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.

64 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. )
  7. var lastAlertUnix int64 = 0
  8. var alertCountSince int = 0
  9. // Sends a critical alert message to administrators.
  10. func Alert(message string) {
  11. log.Error("<!> ALERT <!>\n" + message)
  12. now := time.Now().Unix()
  13. if now-lastAlertUnix > int64(config.GetInt("alert_min_interval")) {
  14. message = fmt.Sprintf("%v:%v", config.GetString("chain_id"), message)
  15. if alertCountSince > 0 {
  16. message = fmt.Sprintf("%v (+%v more since)", message, alertCountSince)
  17. alertCountSince = 0
  18. }
  19. if len(config.GetString("alert_twilio_sid")) > 0 {
  20. go sendTwilio(message)
  21. }
  22. if len(config.GetString("alert_email_recipients")) > 0 {
  23. go sendEmail(message)
  24. }
  25. } else {
  26. alertCountSince++
  27. }
  28. }
  29. func sendTwilio(message string) {
  30. defer func() {
  31. if err := recover(); err != nil {
  32. log.Error("sendTwilio error", "error", err)
  33. }
  34. }()
  35. if len(message) > 50 {
  36. message = message[:50]
  37. }
  38. twilio := gotwilio.NewTwilioClient(config.GetString("alert_twilio_sid"), config.GetString("alert_twilio_token"))
  39. res, exp, err := twilio.SendSMS(config.GetString("alert_twilio_from"), config.GetString("alert_twilio_to"), message, "", "")
  40. if exp != nil || err != nil {
  41. log.Error("sendTwilio error", "res", res, "exp", exp, "error", err)
  42. }
  43. }
  44. func sendEmail(message string) {
  45. defer func() {
  46. if err := recover(); err != nil {
  47. log.Error("sendEmail error", "error", err)
  48. }
  49. }()
  50. subject := message
  51. if len(subject) > 80 {
  52. subject = subject[:80]
  53. }
  54. err := SendEmail(subject, message, config.GetStringSlice("alert_email_recipients"))
  55. if err != nil {
  56. log.Error("sendEmail error", "error", err, "message", message)
  57. }
  58. }