From 5e72e1c5283583ec889a77b7fb105065ae43e730 Mon Sep 17 00:00:00 2001 From: DanB Date: Wed, 22 Jan 2014 22:14:06 +0100 Subject: [PATCH] Adding mail_async action --- config/config.go | 2 +- engine/action.go | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/config/config.go b/config/config.go index 65bea79ba..b2890550b 100644 --- a/config/config.go +++ b/config/config.go @@ -234,7 +234,7 @@ func (self *CGRConfig) setDefaults() error { self.HistoryListen = "127.0.0.1:2013" self.HistoryDir = "/var/log/cgrates/history" self.HistorySaveInterval = time.Duration(1) * time.Second - self.MailerServer = "localhost" + self.MailerServer = "localhost:25" self.MailerAuthUser = "cgrates" self.MailerAuthPass = "CGRateS.org" self.MailerFromAddr = "cgr-mailer@localhost.localdomain" diff --git a/engine/action.go b/engine/action.go index 1518ba071..5459ca5b8 100644 --- a/engine/action.go +++ b/engine/action.go @@ -22,9 +22,14 @@ import ( "bytes" "encoding/json" "fmt" + "errors" "net/http" + "net/smtp" "sort" "time" + "strings" + "github.com/cgrates/cgrates/config" + "github.com/cgrates/cgrates/utils" ) /* @@ -55,6 +60,7 @@ const ( RESET_COUNTERS = "*reset_counters" CALL_URL = "*call_url" CALL_URL_ASYNC = "*call_url_async" + MAIL_ASYNC = "*mail_async" UNLIMITED = "*unlimited" ) @@ -88,6 +94,8 @@ func getActionFunc(typ string) (actionTypeFunc, bool) { return callUrl, true case CALL_URL_ASYNC: return callUrlAsync, true + case MAIL_ASYNC: + return mailAsync, true } return nil, false } @@ -211,6 +219,36 @@ func callUrlAsync(ub *UserBalance, a *Action) error { return nil } +// Mails the balance hitting the threshold towards predefined list of addresses +func mailAsync(ub *UserBalance, a *Action) error { + ubJson, err := json.Marshal(ub) + if err != nil { + return err + } + cgrCfg := config.CgrConfig() + params := strings.Split(a.ExtraParameters, string(utils.CSV_SEP)) + if len(params) == 0 { + return errors.New("Unconfigured parameters for mail action") + } + toAddrs := strings.Split(params[0], string(utils.FALLBACK_SEP)) + message := []byte(fmt.Sprintf("[CGR Notification]: Threshold hit on balance: %s\n\nTime: \n\t%s\n\nBalance:\n\t%s\n\nYour faithful CGR Balance Monitor\n", + ub.Id, time.Now(), ubJson)) + auth := smtp.PlainAuth("", cgrCfg.MailerAuthUser, cgrCfg.MailerAuthPass, strings.Split(cgrCfg.MailerServer,":")[0]) // We only need host part, so ignore port + go func() { + for i := 0; i < 5; i++ { // Loop so we can increase the success rate on best effort + if err := smtp.SendMail(cgrCfg.MailerServer, auth, cgrCfg.MailerFromAddr, toAddrs, message); err == nil { + break + } else if i == 4 { + Logger.Warning(fmt.Sprintf(" WARNING: Failed emailing, params: [%s], error: [%s], balance: %s", a.ExtraParameters, err.Error(), ubJson)) + break + } + time.Sleep(time.Duration(i) * time.Minute) + } + }() + return nil +} + + // Structure to store actions according to weight type Actions []*Action