forked from martensson/nixy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnixy.go
248 lines (227 loc) · 5.66 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
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"
)
// Task struct
type Task struct {
Host string
Ports []int64
ServicePorts []int64
StagedAt string
StartedAt string
Version string
}
// PortDefinitions struct
type PortDefinitions struct {
Port int64
Protocol string
Labels map[string]string
}
// PortMapping struct
type PortMapping struct {
ContainerPort int64
HostPort int64
Protocol string
Labels map[string]string
}
// App struct
type App struct {
Tasks []Task
Labels map[string]string
Env map[string]string
Hosts []string
PortDefinitions []PortDefinitions
PortMappings []PortMapping
}
// 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 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, _ = setupStatsd()
mux := mux.NewRouter()
mux.HandleFunc("/", nixyVersion)
mux.HandleFunc("/v1/reload", nixyReload)
mux.HandleFunc("/v1/config", nixyConfig)
mux.HandleFunc("/v1/health", nixyHealth)
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)
}
}