-
Notifications
You must be signed in to change notification settings - Fork 0
/
maelstrom.go
292 lines (258 loc) · 5.97 KB
/
maelstrom.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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
package main
import (
"encoding/json"
"flag"
"fmt"
"google.golang.org/cloud/compute/metadata"
"gopkg.in/mgo.v2/bson"
"io"
"log"
"net/http"
"os"
"time"
)
var config Config
var Debug bool
var gce bool
var Password string
var quit chan struct{}
var Servers map[MailSender]bool
var emailRegex string = "\\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}\\b"
var indexHtml = "resources/html/index.html"
var throttle chan int
var datastore Datastore
var InfoLog *log.Logger
var ErrorLog *log.Logger
func init() {
// Read Config file
config = Config{}
file, err := os.Open("conf.json")
if err != nil {
fmt.Println("No config file found. Using Defaults")
config.PingPeriod = 60
config.EmailThrottle = 5
} else {
decoder := json.NewDecoder(file)
err = decoder.Decode(&config)
check(err)
}
// Check if running on GCE
if metadata.OnGCE() {
if Debug {
fmt.Println("Running on GCE. Pulling attributes.")
}
gce = true
} else {
if Debug {
fmt.Println("Not running on GCE.")
}
gce = false
}
// init loggers
var writer io.Writer
if len(config.LogFileName) > 0 {
// Create Directory
// os.MkdirAll(, 0777)
logFile, err := os.OpenFile(config.LogFileName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
fmt.Println("Error opening log file: ", err)
writer = os.Stdout
} else {
defer logFile.Close()
writer = logFile
}
} else {
writer = os.Stdout
}
InfoLog = log.New(writer, "INFO: ", log.LstdFlags)
ErrorLog = log.New(writer, "ERROR: ", log.LstdFlags)
}
func main() {
// Parse command line args
flag.BoolVar(&Debug, "debug", true, "Turn on debug logging.")
flag.StringVar(&Password, "password", "", "Password needed by users to send emails.")
flag.Parse()
// Check GCE for Password
if gce {
pw, _ := metadata.InstanceAttributeValue("emailPW")
if len(pw) > 0 {
Password = pw
}
}
// Initiate throttle
throttle = make(chan int, config.EmailThrottle)
buildServersMap()
initiatePing()
// Create Database
datastore = &MongoDatastore{}
if datastore.Ping() {
InfoLog.Println("MongoDB running.")
} else {
ErrorLog.Println("MongoDB connection unsuccessful.")
}
http.HandleFunc("/", errorHandler(rootHandler))
http.HandleFunc("/messages/", errorHandler(messageHandler))
http.HandleFunc("/status", errorHandler(statusHandler))
http.HandleFunc("/contacts/", errorHandler(contactsHandler))
// To Serve CSS and JS files
http.Handle("/resources/", http.StripPrefix("/resources/", http.FileServer(http.Dir("resources"))))
// Read Port from Env
port := os.Getenv("PORT")
if port == "" {
port = "8123"
}
if Debug {
InfoLog.Println("Server running on Port:", port)
}
http.ListenAndServe(":"+port, nil)
}
// Generic Interface for a Mail Server
type MailSender interface {
Send(Message) int
Ping() bool
GetName() string
SetKey(string)
}
// Select a MailServer which is currently 'up'
// TODO allow specifying of Server?
func chooseMailSender() MailSender {
// Weighted Ranking? Random?
for serv, status := range Servers {
if status {
if Debug {
InfoLog.Printf("Selected Mail Server: %s\n", serv.GetName())
}
return serv
}
}
if Debug {
ErrorLog.Println("No MailServers are currently available")
}
return nil
}
// Build list of Servers as defined in the Configuration
func buildServersMap() {
Servers = make(map[MailSender]bool)
for _, conf := range config.MailServers {
if Debug {
InfoLog.Println("Adding Server: " + conf.Name)
}
var server MailSender
if conf.Name == "MailGun" {
server = &MailGunServer{conf}
} else if conf.Name == "SendGrid" {
server = &SendGridServer{conf}
} else if conf.Name == "Mandrill" {
server = &MandrillServer{conf}
} else if conf.Name == "AWS" {
server = &AwsServer{conf}
} else {
if Debug {
ErrorLog.Println("Unknown MailServer: " + conf.Name)
}
continue
}
var apiKey string
if gce {
apiKey, _ = metadata.InstanceAttributeValue(conf.Name)
} else {
apiKey = conf.ApiKey
}
server.SetKey(apiKey)
Servers[server] = false
}
checkServers()
}
// Starts a periodic Ping for the Mail Servers
func initiatePing() {
pinger := time.NewTicker(time.Duration(config.PingPeriod) * time.Second)
quit = make(chan struct{})
go func() {
for {
select {
case <-pinger.C:
checkServers()
case <-quit:
pinger.Stop()
return
}
}
}()
}
// Check and update the status for all Mail Servers
func checkServers() {
for server, _ := range Servers {
status := server.Ping()
if Debug {
InfoLog.Printf("Mail Server: %s status: %t\n", server.GetName(), status)
}
Servers[server] = status
}
}
// Enforce Throttling by requiring a 'slot' to send
func requestSlot() bool {
if len(throttle) >= cap(throttle) {
if Debug {
InfoLog.Println("Request blocked. No open slots.")
}
return false
}
throttle <- 1
slotTimer := time.NewTimer(time.Second * 1)
go func() {
<-slotTimer.C
_ = <-throttle
}()
return true
}
// Standard error check function
func check(err error) {
if err != nil {
ErrorLog.Println("Panicking: ", err)
panic(err)
}
}
type Datastore interface {
Status() bool
StoreContact(Contact) Contact
DeleteContact(string) bool
UpdateContact(Contact) Contact
RetrieveContactsBy(string, string) []Contact
Ping() bool
}
type Contact struct {
Id bson.ObjectId `json:"id" bson:"_id,omitempty"`
Email string `json:"email"`
Name string `json:"name"`
Tags []string `json:"tags"`
}
// Generic Message object
type Message struct {
Id int `json:"id"`
To []string `json:"to"`
Subject string `json:"subject"`
From string `json:"from"`
Text string `json:"text"`
}
// Generic Mail Server Configuration
type MailServer struct {
Name string
Url string
PingUrl string
ApiKey string
PingKey string
}
// Structure for Applications Configuration
type Config struct {
MailServers []MailServer
PingPeriod int
EmailThrottle int
LogFileName string
}
// Structure of Server Status
type Status struct {
ServerStatus []struct {
Name string
Status bool
}
}