-
Notifications
You must be signed in to change notification settings - Fork 3
/
dispatch.go
183 lines (157 loc) · 4.86 KB
/
dispatch.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"path"
"path/filepath"
"reflect"
"text/template"
"github.com/Masterminds/sprig/v3"
log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v2"
)
// DispatchMap is a AuthToken to DispatchTarget map
type DispatchMap map[string]DispatchTarget
// DispatchRequest is the expected message submission
type DispatchRequest map[string]string
// DispatchRequest is values provided in headers
type DispatchHeaders map[string]string
// Dispatch is the central point for the dispatches
type Dispatch struct {
dispatchMap DispatchMap
smtpSettings SMTPSettings
messageTemplate *template.Template
}
// NewDispatch create a new dispatch
func NewDispatch(targetDir string, smtpSettings SMTPSettings) *Dispatch {
d := new(Dispatch)
d.dispatchMap = make(DispatchMap)
d.smtpSettings = smtpSettings
msg := `
{{ printf "%-12s" "Timestamp:"}}{{ index . "timestamp" }}
{{ range $key, $value := . -}}
{{ if eq $key "message" "auth-token" "timestamp" }}{{ else -}}
{{title $key | printf "%s:" | printf "%-12s"}}{{$value}}
{{ end }}{{ end -}}
-----------------------------------------------------------
{{ index . "message"}}
`
d.messageTemplate = template.Must(template.New("request").Funcs(sprig.TxtFuncMap()).Parse(msg))
d.LoadTargets(targetDir)
return d
}
// LoadTargets Loads all of the configs in the target config dir
func (d *Dispatch) LoadTargets(targetDir string) {
targets, err := getTargetConfigList(targetDir)
if err != nil {
log.Errorf("error: could not load targets: %v", err)
return
}
log.Debugf("Found %d targets in %s", len(targets), targetDir)
for _, target := range targets {
log.Debugf("loading target %s", target)
data, err := ioutil.ReadFile(target)
if err != nil {
log.Errorf("error: could not load %s: %v", target, err)
continue
}
targetConf, err := loadTarget(target, data)
if err != nil {
log.Errorf("error: parsing target %s: %v", target, err)
continue
}
if len(targetConf.To) == 0 {
log.Errorf("error: target %s does not have a destination, skipping", targetConf.Name)
continue
}
d.dispatchMap[targetConf.AuthToken] = targetConf
log.Infof("loaded target %s:%s", targetConf.Name, targetConf.AuthToken)
}
}
// AddTarget adds a target to the dispatch map
func (d *Dispatch) AddTarget(target DispatchTarget) {
d.dispatchMap[target.AuthToken] = target
}
// Send formats and sends the message
func (d *Dispatch) Send(request DispatchRequest) error {
target, found := d.dispatchMap[request["auth-token"]]
if !found {
return errors.New("authentication is not valid")
}
r := mergeRequests(request, target.Defaults)
// format the email subject line
subject := ""
if s, ok := r["subject"]; ok && len(r["subject"]) > 0 {
subject = fmt.Sprintf(" - %s", s)
}
var email Message
// if 'from' field is black, email package will fill in a default
email.FromAddress = target.From
email.ToAddressList = target.To
email.Subject = fmt.Sprintf("[dispatch] %s%s", target.Name, subject)
var msgBuffer bytes.Buffer
d.messageTemplate.Execute(&msgBuffer, request)
email.TextMessage = msgBuffer.String()
log.Infof("sending message: {AuthToken:%s Name:%s}", request["auth-token"], request["name"])
sendMessage(email, d.smtpSettings)
return nil
}
// DispatchTarget is a target to send too
type DispatchTarget struct {
AuthToken string `yaml:"auth-token"`
From string `yaml:"from"`
To []string `yaml:"to"`
Name string `yaml:"name"`
Defaults map[string]string `yaml:"defaults"`
}
func getTargetConfigList(targetDir string) (target []string, err error) {
pattern := fmt.Sprintf("%s/*", targetDir)
log.Debugf("searching %s", pattern)
matches, err := filepath.Glob(pattern)
if err != nil {
log.Errorf("error: %v", err)
return nil, err
}
return matches, nil
}
func loadTarget(target string, data []byte) (DispatchTarget, error) {
t := DispatchTarget{}
err := yaml.Unmarshal(data, &t)
if err != nil {
return t, err
}
if len(t.Name) == 0 {
t.Name = path.Base(target)
}
oldTo := make([]string, len(t.To))
copy(oldTo, t.To)
t.To = t.To[:0] // Clear our slice
for _, addr := range oldTo {
fAddr, err := FormatEmail(addr)
if err != nil {
log.Errorf("error parsing email '%s', skipping", addr)
continue
}
t.To = append(t.To, fAddr)
}
log.Debugf("target=%+v", t)
return t, nil
}
// mergeRequests merges two requests, primary overrides secondary
func mergeRequests(primary, secondary interface{}) map[string]string {
// primary values always override secondary
result := map[string]string{}
vs := reflect.ValueOf(secondary)
for _, key := range vs.MapKeys() {
strct := vs.MapIndex(key)
result[key.Interface().(string)] = strct.Interface().(string)
}
vp := reflect.ValueOf(primary)
for _, key := range vp.MapKeys() {
strct := vp.MapIndex(key)
result[key.Interface().(string)] = strct.Interface().(string)
}
return result
}