/
main.go
308 lines (270 loc) · 7.58 KB
/
main.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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"strconv"
"time"
log "github.com/Sirupsen/logrus"
"github.com/nu7hatch/gouuid"
"gopkg.in/yaml.v2"
)
// requestMessage represents an http event to be repeated to eventTargets
// This is, in essence, an http.Request, but those aren't very clean to pass around
type requestMessage struct {
UUID string
URL string
Method string
Source string
Headers http.Header
Body []byte
}
func defaultHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, "{ \"error\": \"No such queue\" }\n")
}
func metricsHandler(w http.ResponseWriter, r *http.Request) {
mapB, _ := json.Marshal(counters) // meh @ error handling here :)
w.Write(mapB)
}
func makeIncomingHandler(queueItems QueueItems) http.HandlerFunc {
// I'm doing it like this so my IDE highlighting doesn't get stupid
h := func(w http.ResponseWriter, r *http.Request) {
// get a UUID for this transaction
u5, err := uuid.NewV4()
if err != nil {
log.WithFields(log.Fields{
"error": err.Error(),
}).Error("failed-to-generate-uuid")
return
}
body, _ := ioutil.ReadAll(r.Body)
requestObj := requestMessage{
UUID: u5.String(),
URL: r.URL.Path[1:], // trim the leading /
Method: r.Method,
Source: r.RemoteAddr,
Headers: r.Header,
Body: body,
}
queue := requestObj.URL
for name, eventTarget := range queueItems {
qu := Queue{queue, name, eventTarget.URL}
addchan <- qu
// this select/case/default is a non-blocking chan push
select {
case requestBuffers[qu] <- requestObj:
default:
// metricize that we're dropping messages
dellchan <- qu
// kill off the oldest, not-in-flight message
// todo: it could possibly make sense to kill the inflight message, but...have to think on that more
<-requestBuffers[qu]
// we attempt to send the current message one last time, but this is still not guaranteed to work
select {
case requestBuffers[qu] <- requestObj:
default:
// well, we tried our damndest, log it and move on
log.WithFields(log.Fields{
"id": u5,
"queue": queue,
"url": eventTarget.URL,
}).Info("queue-full-message-lost")
}
}
}
// to lazy to do a real json.Marshal, etc
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "{ \"id\":\"%s\" }\n", u5)
}
return h
}
func sendEvent(client *http.Client, qu Queue, req requestMessage, workerId uint) {
log.WithFields(log.Fields{
"queue": qu,
"req": req,
"wid": workerId,
}).Debug("sending")
start := time.Now()
var sent bool
sent = false
attempts := 0
sleepDuration := time.Millisecond * 100
for {
attempts++
httpReq, _ := http.NewRequest(req.Method, qu.OutboundURL, bytes.NewBuffer(req.Body))
for headerName, values := range req.Headers {
for _, value := range values {
httpReq.Header.Add(headerName, value)
}
}
httpReq.Header.Set("X-Capacitor-Id", req.UUID)
resp, err := client.Do(httpReq)
if err == nil {
// get rid of the response, we don't care
// but we do need to clean it out, so the client can reuse the same connection
io.Copy(ioutil.Discard, resp.Body)
resp.Body.Close()
}
if err == nil && resp.StatusCode == 200 {
sent = true
break
}
// max duration, ever
// todo: make this configurable
if time.Since(start) > time.Second*60 {
break
}
// oops, didn't work; have a pause and try again in a bit
time.Sleep(sleepDuration)
// slowly ramp up our sleep interval, shall we? But cap it too
if sleepDuration < time.Duration(time.Second*15) {
sleepDuration = time.Duration(float64(sleepDuration) * 1.5)
} else {
sleepDuration = time.Duration(time.Second * 15)
}
}
elapsed := time.Since(start)
if sent {
deltchan <- qu
} else {
delfchan <- qu
}
log.WithFields(log.Fields{
"id": req.UUID,
"queue": qu.InboundName,
"outbound": qu.OutboundName,
"wid": workerId,
"attempts": attempts,
"sent": sent,
"duration": elapsed.Seconds() * 1e3, /* ms hack */
}).Info("relay-end")
}
// queueUrl is a structure for uniqu'ifying tracking maps
type Queue struct {
InboundName string
OutboundName string
OutboundURL string
}
type counterVals struct {
Current uint64 `json:"current"`
Total uint64 `json:"total"`
Success uint64 `json:"success"`
Failure uint64 `json:"failure"`
Lost uint64 `json:"lost"`
}
func (u StatsMap) MarshalJSON() ([]byte, error) {
fmt.Println("marshalling StatsMap")
var v = make(map[string]counterVals)
for i, e := range u {
v[i.InboundName+":"+i.OutboundName] = e
}
return json.Marshal(v)
}
type StatsMap map[Queue]counterVals
var counters = make(StatsMap)
var addchan = make(chan Queue, 100)
var deltchan = make(chan Queue, 100)
var delfchan = make(chan Queue, 100)
var dellchan = make(chan Queue, 100)
func StartWorker(incoming chan requestMessage, queue Queue, id uint) {
client := &http.Client{
// todo: reasonable default?
Timeout: 10 * time.Second,
// no cookies, please
Jar: nil,
}
for {
work := <-incoming
sendEvent(client, queue, work, id)
}
}
var requestBuffers = make(map[Queue]chan requestMessage)
func main() {
log.SetFormatter(&log.TextFormatter{
FullTimestamp: true,
TimestampFormat: time.RFC3339Nano,
})
configFile := flag.String("config", "config.yml", "Path to the config file")
debug := flag.Bool("debug", false, "Enable debug logging")
port := flag.Uint("port", uint(8000), "Listen port")
flag.Parse()
if *debug {
log.SetLevel(log.DebugLevel)
}
if _, err := os.Stat(*configFile); os.IsNotExist(err) {
log.Errorf("Config must be specified and must exist: %s", *configFile)
os.Exit(1)
}
yamlFile, err := ioutil.ReadFile(*configFile)
if err != nil {
panic(err)
}
var config Config
err = yaml.Unmarshal(yamlFile, &config)
if err != nil {
panic(err)
}
// TODO: add config file validation, such as:
//if target.QueueLength <= 0 {
// panic("Buffer length must be > 0")
//}
// TODO: `/api` is reserved as a root for the app
// Setup workers and initialize counters to zero
for inbound, targets := range config {
for targetid, target := range targets {
qu := Queue{inbound, targetid, target.URL}
counters[qu] = counterVals{0, 0, 0, 0, 0}
requestBuffers[qu] = make(chan requestMessage, target.QueueLength)
for i := uint(1); i <= target.MaxParallel; i++ {
go StartWorker(requestBuffers[qu], qu, i)
}
}
}
// goroutine to keep the counters up-to-date
go func() {
for {
// watch each channel as items rolls in and modify the counters as needed
select {
// you can't do counters[control].Current++ in go, so this mess is what results
case control := <-addchan:
tmp := counters[control]
tmp.Current++
tmp.Total++
counters[control] = tmp
case control := <-deltchan:
tmp := counters[control]
tmp.Current--
tmp.Success++
counters[control] = tmp
case control := <-delfchan:
tmp := counters[control]
tmp.Current--
tmp.Failure++
counters[control] = tmp
case control := <-dellchan:
tmp := counters[control]
tmp.Current--
tmp.Lost++
counters[control] = tmp
}
}
}()
// A dumb goroutine to watch memory usage and counter metrics
go stats()
// Oh, hey, there's the webserver!
portStr := strconv.Itoa(int(*port))
log.Info("Starting server on port "+portStr)
for inbound, queueItems := range config {
log.Info("Registering queue @ /" + inbound)
http.HandleFunc("/"+inbound, makeIncomingHandler(queueItems))
}
http.HandleFunc("/", defaultHandler)
http.HandleFunc("/api/metrics", metricsHandler)
log.Fatal("ListenAndServe: ", http.ListenAndServe(":"+portStr, nil))
}