-
Notifications
You must be signed in to change notification settings - Fork 41
/
nixy.go
332 lines (305 loc) · 7.58 KB
/
nixy.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
323
324
325
326
327
328
329
330
331
332
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"sync"
"time"
"github.com/BurntSushi/toml"
"github.com/Sirupsen/logrus"
"github.com/gorilla/mux"
"github.com/peterbourgon/g2s"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// Task struct
type Task struct {
AppID string
Host string
ID string
Ports []int64
ServicePorts []int64
SlaveID string
StagedAt string
StartedAt string
State string
Version string
Labels map[string]string
}
// PortDefinitions struct
type PortDefinitions struct {
Port int64
Protocol string
Name string
Labels map[string]string
}
// PortMappings struct
type PortMappings struct {
ContainerPort int64
HostPort int64
Labels map[string]string
Protocol string
ServicePort int64
}
// Container struct
type Container struct {
PortMappings []PortMappings
}
// HealthCheck struct
type HealthCheck struct {
Path string
}
// App struct
type App struct {
Tasks []Task
Labels map[string]string
Env map[string]string
Hosts []string
PortDefinitions []PortDefinitions
HealthChecks []HealthCheck
Container Container
}
// Config struct used by the template engine
type Config struct {
sync.RWMutex
Xproxy string
Realm string
Port string `json:"-"`
Marathon []string `json:"-"`
User string `json:"-"`
Pass string `json:"-"`
NginxConfig string `json:"-" toml:"nginx_config"`
NginxTemplate string `json:"-" toml:"nginx_template"`
NginxCmd string `json:"-" toml:"nginx_cmd"`
NginxIgnoreCheck bool `json:"-" toml:"nginx_ignore_check"`
LeftDelimiter string `json:"-" toml:"left_delimiter"`
RightDelimiter string `json:"-" toml:"right_delimiter"`
Statsd StatsdConfig
LastUpdates Updates
Apps map[string]App
}
// Updates timings used for metrics
type Updates struct {
LastSync time.Time
LastConfigRendered time.Time
LastConfigValid time.Time
LastNginxReload time.Time
}
// StatsdConfig statsd stuct
type StatsdConfig struct {
Addr string
Namespace string
SampleRate int `toml:"sample_rate"`
}
// Status health status struct
type Status struct {
Healthy bool
Message string
}
// EndpointStatus health status struct
type EndpointStatus struct {
Endpoint string
Healthy bool
Message string
}
// Health struct
type Health struct {
Config Status
Template Status
Endpoints []EndpointStatus
}
// Global variables
var version = "master" //set by ldflags
var date string //set by ldflags
var commit string //set by ldflags
var config = Config{LeftDelimiter: "{{", RightDelimiter: "}}"}
var statsd g2s.Statter
var health Health
var lastConfig string
var logger = logrus.New()
// Eventqueue with buffer of two, because we dont really need more.
var eventqueue = make(chan bool, 2)
// Global http transport for connection reuse
var tr = &http.Transport{MaxIdleConnsPerHost: 10}
func (c *Config) MergeAppsByLabel(label string) map[string]App {
apps := make(map[string]App, 0)
labeledApps := make(map[string][]App, 0)
for appID, app := range c.Apps {
if labelValue, has := app.Labels[label]; has {
labeledApps[labelValue] = append(labeledApps[labelValue], app)
} else {
apps[appID] = app
}
}
for id, appGroup := range labeledApps {
apps[id] = mergeApps(appGroup)
}
return apps
}
func mergeApps(apps []App) App {
tasks := make([]Task, 0)
labels := make(map[string]string, 0)
env := make(map[string]string, 0)
hosts := make([]string, 0)
portDefs := make([]PortDefinitions, 0)
seenPorts := make(map[int64]bool, 0)
for _, app := range apps {
for k, v := range app.Labels {
labels[k] = v
}
for k, v := range app.Env {
env[k] = v
}
for _, h := range app.Hosts {
hosts = append(hosts, h)
}
for _, t := range app.Tasks {
t.Labels = app.Labels
tasks = append(tasks, t)
}
for _, def := range app.PortDefinitions {
if _, seen := seenPorts[def.Port]; !seen {
seenPorts[def.Port] = true
portDefs = append(portDefs, def)
}
}
}
return App{
Tasks: tasks,
Labels: labels,
Env: env,
Hosts: hosts,
PortDefinitions: portDefs,
HealthChecks: apps[0].HealthChecks,
Container: Container{},
}
}
func newHealth() Health {
var h Health
for _, ep := range config.Marathon {
var s EndpointStatus
s.Endpoint = ep
s.Healthy = true
s.Message = "OK"
h.Endpoints = append(h.Endpoints, s)
}
return h
}
func nixyReload(w http.ResponseWriter, r *http.Request) {
logger.WithFields(logrus.Fields{
"client": r.RemoteAddr,
}).Info("marathon reload triggered")
select {
case eventqueue <- true: // Add reload to our queue channel, unless it is full of course.
w.WriteHeader(202)
fmt.Fprintln(w, "queued")
return
default:
w.WriteHeader(202)
fmt.Fprintln(w, "queue is full")
return
}
}
func nixyHealth(w http.ResponseWriter, r *http.Request) {
err := checkTmpl()
if err != nil {
health.Template.Message = err.Error()
health.Template.Healthy = false
w.WriteHeader(http.StatusInternalServerError)
} else {
health.Template.Message = "OK"
health.Template.Healthy = true
}
err = checkConf(lastConfig)
if err != nil {
health.Config.Message = err.Error()
health.Config.Healthy = false
w.WriteHeader(http.StatusInternalServerError)
} else {
health.Config.Message = "OK"
health.Config.Healthy = true
}
allBackendsDown := true
for _, endpoint := range health.Endpoints {
if endpoint.Healthy {
allBackendsDown = false
break
}
}
if allBackendsDown {
w.WriteHeader(http.StatusInternalServerError)
}
w.Header().Add("Content-Type", "application/json; charset=utf-8")
b, _ := json.MarshalIndent(health, "", " ")
w.Write(b)
return
}
func nixyConfig(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json; charset=utf-8")
b, _ := json.MarshalIndent(&config, "", " ")
w.Write(b)
return
}
func nixyVersion(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "version: "+version)
fmt.Fprintln(w, "commit: "+commit)
fmt.Fprintln(w, "date: "+date)
return
}
func main() {
configtoml := flag.String("f", "nixy.toml", "Path to config. (default nixy.toml)")
versionflag := flag.Bool("v", false, "prints current nixy version")
flag.Parse()
if *versionflag {
fmt.Printf("version: %s\n", version)
fmt.Printf("commit: %s\n", commit)
fmt.Printf("date: %s\n", date)
os.Exit(0)
}
file, err := ioutil.ReadFile(*configtoml)
if err != nil {
logger.WithFields(logrus.Fields{
"error": err.Error(),
}).Fatal("problem opening toml config")
}
err = toml.Unmarshal(file, &config)
if err != nil {
logger.WithFields(logrus.Fields{
"error": err.Error(),
}).Fatal("problem parsing config")
}
// Lets default empty Xproxy to hostname.
if config.Xproxy == "" {
config.Xproxy, _ = os.Hostname()
}
statsd, err = setupStatsd()
if err != nil {
logger.WithFields(logrus.Fields{
"error": err.Error(),
}).Error("unable to Dial statsd")
statsd = g2s.Noop() //fallback to Noop.
}
setupPrometheusMetrics()
mux := mux.NewRouter()
mux.HandleFunc("/", nixyVersion)
mux.HandleFunc("/v1/reload", nixyReload)
mux.HandleFunc("/v1/config", nixyConfig)
mux.HandleFunc("/v1/health", nixyHealth)
mux.Handle("/v1/metrics", promhttp.Handler())
s := &http.Server{
Addr: ":" + config.Port,
Handler: mux,
}
health = newHealth()
endpointHealth()
eventStream()
eventWorker()
logger.Info("starting nixy on :" + config.Port)
err = s.ListenAndServe()
if err != nil {
log.Fatal(err)
}
}