This repository has been archived by the owner on Jan 21, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathmain.go
322 lines (270 loc) · 7.69 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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
package main
import (
"flag"
"fmt"
"github.com/dgrijalva/jwt-go"
"github.com/gorilla/mux"
"github.com/sokil/go-statsd-client"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"time"
)
// Version is a current git commit hash and tag
// Injected by compilation flag
var Version = "Unknown"
// BuildNumber is a current commit hash
// Injected by compilation flag
var BuildNumber = "Unknown"
// BuildDate is a date of build
// Injected by compilation flag
var BuildDate = "Unknown"
// HTTP connection params
const defaultHTTPHost = "127.0.0.1"
const defaultHTTPPort = 80
// StatsD connection params
const defaultStatsDHost = "127.0.0.1"
const defaultStatsDPort = 8125
// JWT params
const jwtHeaderName = "X-JWT-Token"
const jwtQueryStringKeyName = "token"
// declare command line options
var httpHost = flag.String("http-host", defaultHTTPHost, "HTTP Host")
var httpPort = flag.Int("http-port", defaultHTTPPort, "HTTP Port")
var statsdHost = flag.String("statsd-host", defaultStatsDHost, "StatsD Host")
var statsdPort = flag.Int("statsd-port", defaultStatsDPort, "StatsD Port")
var metricPrefix = flag.String("metric-prefix", "", "Prefix of metric name")
var tokenSecret = flag.String("jwt-secret", "", "Secret to encrypt JWT")
var verbose = flag.Bool("verbose", false, "Verbose")
var version = flag.Bool("version", false, "Show version")
// statsd client
var statsdClient *statsd.Client
func main() {
// get flags
flag.Parse()
// show version and exit
if *version == true {
showVersion()
os.Exit(0)
}
// configure verbosity of logging
if *verbose == true {
log.SetOutput(os.Stderr)
} else {
log.SetOutput(ioutil.Discard)
}
// prepare metric prefix
if *metricPrefix != "" && (*metricPrefix)[len(*metricPrefix)-1:] != "." {
*metricPrefix = *metricPrefix + "."
}
// create HTTP router
router := mux.NewRouter().StrictSlash(true)
// register http request handlers
router.Handle(
"/heartbeat",
validateCORS(http.HandlerFunc(handleHeartbeatRequest)),
).Methods("GET")
router.Handle(
"/count/{key}",
validateCORS(validateJWT(http.HandlerFunc(handleCountRequest))),
).Methods("POST")
router.Handle(
"/gauge/{key}",
validateCORS(validateJWT(http.HandlerFunc(handleGaugeRequest))),
).Methods("POST")
router.Handle(
"/timing/{key}",
validateCORS(validateJWT(http.HandlerFunc(handleTimingRequest))),
).Methods("POST")
router.Handle(
"/set/{key}",
validateCORS(validateJWT(http.HandlerFunc(handleSetRequest))),
).Methods("POST")
router.PathPrefix("/").Methods("OPTIONS").HandlerFunc(handlePreFlightCORSRequest);
// Create a new StatsD connection
statsdClient = statsd.NewClient(*statsdHost, *statsdPort)
statsdClient.Open()
defer statsdClient.Close()
// get server address to bind
httpAddress := fmt.Sprintf("%s:%d", *httpHost, *httpPort)
log.Printf("Starting HTTP server at %s", httpAddress)
// create http server
s := &http.Server{
Addr: httpAddress,
Handler: router,
ReadTimeout: 1 * time.Second,
WriteTimeout: 1 * time.Second,
MaxHeaderBytes: 1 << 20,
}
// start http server
err := s.ListenAndServe()
if err != nil {
log.Fatal(err)
os.Exit(1)
}
}
// validate CORS headers
func validateCORS(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if origin != "" {
w.Header().Add("Access-Control-Allow-Origin", origin)
}
next.ServeHTTP(w, r)
})
}
// validate JWT middleware
func validateJWT(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if *tokenSecret == "" {
next.ServeHTTP(w, r)
} else {
// get JWT from header
tokenString := r.Header.Get(jwtHeaderName)
// get JWT from query string
if tokenString == "" {
tokenString = r.URL.Query().Get(jwtQueryStringKeyName)
}
if tokenString == "" {
http.Error(w, "Token not specified", 401)
return
}
// parse JWT
_, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return []byte(*tokenSecret), nil
})
if err != nil {
http.Error(w, "Error parsing token", 403)
return
}
// accept request
next.ServeHTTP(w, r)
}
})
}
// Handle heartbeat request
func handleHeartbeatRequest(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "OK")
}
// Handle StatsD Count request
func handleCountRequest(w http.ResponseWriter, r *http.Request) {
// get key
vars := mux.Vars(r)
key := *metricPrefix + vars["key"]
// get count value
var value = 1
valuePostFormValue := r.PostFormValue("value")
if valuePostFormValue != "" {
var err error
value, err = strconv.Atoi(valuePostFormValue)
if err != nil {
http.Error(w, "Invalid value specified", 400)
}
}
// get sample rate
var sampleRate float64 = 1
sampleRatePostFormValue := r.PostFormValue("sampleRate")
if sampleRatePostFormValue != "" {
var err error
sampleRate, err = strconv.ParseFloat(sampleRatePostFormValue, 32)
if err != nil {
http.Error(w, "Invalid sample rate specified", 400)
}
}
// send request
statsdClient.Count(key, value, float32(sampleRate))
}
// Handle StatsD Gauge request
func handleGaugeRequest(w http.ResponseWriter, r *http.Request) {
// get key
vars := mux.Vars(r)
key := *metricPrefix + vars["key"]
// get gauge shift
shiftPostFormValue := r.PostFormValue("shift")
if shiftPostFormValue != "" {
// get value
value, err := strconv.Atoi(shiftPostFormValue)
if err != nil {
http.Error(w, "Invalid gauge shift specified", 400)
}
// send request
statsdClient.GaugeShift(key, value)
return
}
// get gauge value
var value = 1
valuePostFormValue := r.PostFormValue("value")
if valuePostFormValue != "" {
// get value
var err error
value, err = strconv.Atoi(valuePostFormValue)
if err != nil {
http.Error(w, "Invalid gauge value specified", 400)
}
}
// send gauge value request
statsdClient.Gauge(key, value)
}
// Handle StatsD Timing request
func handleTimingRequest(w http.ResponseWriter, r *http.Request) {
// get key
vars := mux.Vars(r)
key := *metricPrefix + vars["key"]
// get timing
time, err := strconv.ParseInt(r.PostFormValue("time"), 10, 64)
if err != nil {
http.Error(w, "Invalid time specified", 400)
}
// get sample rate
var sampleRate float64 = 1
sampleRatePostFormValue := r.PostFormValue("sampleRate")
if sampleRatePostFormValue != "" {
var err error
sampleRate, err = strconv.ParseFloat(sampleRatePostFormValue, 32)
if err != nil {
http.Error(w, "Invalid sample rate specified", 400)
}
}
// send request
statsdClient.Timing(key, time, float32(sampleRate))
}
// Handle StatsD Set request
func handleSetRequest(w http.ResponseWriter, r *http.Request) {
// get key
vars := mux.Vars(r)
key := *metricPrefix + vars["key"]
// get set value
var value = 1
valuePostFormValue := r.PostFormValue("value")
if valuePostFormValue != "" {
var err error
value, err = strconv.Atoi(valuePostFormValue)
if err != nil {
http.Error(w, "Invalid set value specified", 400)
}
}
// send request
statsdClient.Set(key, value)
}
// Handle PreFlight CORS request with OPTIONS method
func handlePreFlightCORSRequest(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if origin != "" {
w.Header().Add("Access-Control-Allow-Origin", origin)
w.Header().Add("Access-Control-Allow-Headers", jwtHeaderName+", X-Requested-With, Origin, Accept, Content-Type, Authentication")
w.Header().Add("Access-Control-Allow-Methods", "GET, POST, HEAD, OPTIONS")
}
}
func showVersion() {
fmt.Printf(
"StatsD HTTP Proxy v.%s, build %s from %s\n",
Version,
BuildNumber,
BuildDate,
)
}