You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
1.6 KiB

10 years ago
10 years ago
10 years ago
10 years ago
  1. package alert
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/sfreiberg/gotwilio"
  6. . "github.com/tendermint/tendermint/config"
  7. )
  8. var lastAlertUnix int64 = 0
  9. var alertCountSince int = 0
  10. // Sends a critical alert message to administrators.
  11. func Alert(message string) {
  12. log.Error("<!> ALERT <!>\n" + message)
  13. now := time.Now().Unix()
  14. if now-lastAlertUnix > int64(Config.Alert.MinInterval) {
  15. message = fmt.Sprintf("%v:%v", Config.Network, message)
  16. if alertCountSince > 0 {
  17. message = fmt.Sprintf("%v (+%v more since)", message, alertCountSince)
  18. alertCountSince = 0
  19. }
  20. if len(Config.Alert.TwilioSid) > 0 {
  21. go sendTwilio(message)
  22. }
  23. if len(Config.Alert.EmailRecipients) > 0 {
  24. go sendEmail(message)
  25. }
  26. } else {
  27. alertCountSince++
  28. }
  29. }
  30. func sendTwilio(message string) {
  31. defer func() {
  32. if err := recover(); err != nil {
  33. log.Error("sendTwilio error", "error", err)
  34. }
  35. }()
  36. if len(message) > 50 {
  37. message = message[:50]
  38. }
  39. twilio := gotwilio.NewTwilioClient(Config.Alert.TwilioSid, Config.Alert.TwilioToken)
  40. res, exp, err := twilio.SendSMS(Config.Alert.TwilioFrom, Config.Alert.TwilioTo, message, "", "")
  41. if exp != nil || err != nil {
  42. log.Error("sendTwilio error", "res", res, "exp", exp, "error", err)
  43. }
  44. }
  45. func sendEmail(message string) {
  46. defer func() {
  47. if err := recover(); err != nil {
  48. log.Error("sendEmail error", "error", err)
  49. }
  50. }()
  51. subject := message
  52. if len(subject) > 80 {
  53. subject = subject[:80]
  54. }
  55. err := SendEmail(subject, message, Config.Alert.EmailRecipients)
  56. if err != nil {
  57. log.Error("sendEmail error", "error", err, "message", message)
  58. }
  59. }