forked from fabiolb/fabio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
412 lines (367 loc) · 9.97 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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
package main
import (
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"runtime"
"runtime/debug"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/wowsoso/fabioz/admin"
"github.com/wowsoso/fabioz/cert"
"github.com/wowsoso/fabioz/config"
"github.com/wowsoso/fabioz/exit"
"github.com/wowsoso/fabioz/logger"
"github.com/wowsoso/fabioz/metrics"
"github.com/wowsoso/fabioz/proxy"
"github.com/wowsoso/fabioz/proxy/tcp"
"github.com/wowsoso/fabioz/registry"
"github.com/wowsoso/fabioz/registry/consul"
"github.com/wowsoso/fabioz/registry/file"
"github.com/wowsoso/fabioz/registry/static"
"github.com/wowsoso/fabioz/route"
"github.com/pkg/profile"
dmp "github.com/sergi/go-diff/diffmatchpatch"
)
// version contains the version number
//
// It is set by build/release.sh for tagged releases
// so that 'go get' just works.
//
// It is also set by the linker when fabio
// is built via the Makefile or the build/docker.sh
// script to ensure the correct version nubmer
var version = "1.4.4"
var shuttingDown int32
func main() {
cfg, err := config.Load(os.Args, os.Environ())
if err != nil {
exit.Fatalf("[FATAL] %s. %s", version, err)
}
if cfg == nil {
fmt.Println(version)
return
}
log.Printf("[INFO] Runtime config\n" + toJSON(cfg))
log.Printf("[INFO] Version %s starting", version)
log.Printf("[INFO] Go runtime is %s", runtime.Version())
// setup profiling if enabled
var prof interface {
Stop()
}
if cfg.ProfileMode != "" {
var mode func(*profile.Profile)
switch cfg.ProfileMode {
case "":
// do nothing
case "cpu":
mode = profile.CPUProfile
case "mem":
mode = profile.MemProfile
case "mutex":
mode = profile.MutexProfile
case "block":
mode = profile.BlockProfile
default:
log.Fatalf("[FATAL] Invalid profile mode %q", cfg.ProfileMode)
}
prof = profile.Start(mode, profile.ProfilePath(cfg.ProfilePath), profile.NoShutdownHook)
log.Printf("[INFO] Profile mode %q", cfg.ProfileMode)
log.Printf("[INFO] Profile path %q", cfg.ProfilePath)
}
exit.Listen(func(s os.Signal) {
atomic.StoreInt32(&shuttingDown, 1)
proxy.Shutdown(cfg.Proxy.ShutdownWait)
if prof != nil {
prof.Stop()
}
if registry.Default == nil {
return
}
registry.Default.Deregister()
})
// init metrics early since that create the global metric registries
// that are used by other parts of the code.
initMetrics(cfg)
initRuntime(cfg)
initBackend(cfg)
startAdmin(cfg)
first := make(chan bool)
go watchBackend(cfg, first)
log.Print("[INFO] Waiting for first routing table")
<-first
// create proxies after metrics since they use the metrics registry.
startServers(cfg)
exit.Wait()
log.Print("[INFO] Down")
}
func newHTTPProxy(cfg *config.Config) http.Handler {
var w io.Writer
switch cfg.Log.AccessTarget {
case "":
log.Printf("[INFO] Access logging disabled")
case "stdout":
log.Printf("[INFO] Writing access log to stdout")
w = os.Stdout
default:
exit.Fatal("[FATAL] Invalid access log target ", cfg.Log.AccessTarget)
}
format := cfg.Log.AccessFormat
switch format {
case "common":
format = logger.CommonFormat
case "combined":
format = logger.CombinedFormat
}
l, err := logger.New(w, format)
if err != nil {
exit.Fatal("[FATAL] Invalid log format: ", err)
}
pick := route.Picker[cfg.Proxy.Strategy]
match := route.Matcher[cfg.Proxy.Matcher]
notFound := metrics.DefaultRegistry.GetCounter("notfound")
log.Printf("[INFO] Using routing strategy %q", cfg.Proxy.Strategy)
log.Printf("[INFO] Using route matching %q", cfg.Proxy.Matcher)
newTransport := func(tlscfg *tls.Config) *http.Transport {
return &http.Transport{
ResponseHeaderTimeout: cfg.Proxy.ResponseHeaderTimeout,
MaxIdleConnsPerHost: cfg.Proxy.MaxConn,
Dial: (&net.Dialer{
Timeout: cfg.Proxy.DialTimeout,
KeepAlive: cfg.Proxy.KeepAliveTimeout,
}).Dial,
TLSClientConfig: tlscfg,
}
}
return &proxy.HTTPProxy{
Config: cfg.Proxy,
Transport: newTransport(nil),
InsecureTransport: newTransport(&tls.Config{InsecureSkipVerify: true}),
Lookup: func(r *http.Request) *route.Target {
t := route.GetTable().Lookup(r, r.Header.Get("trace"), pick, match)
if t == nil {
notFound.Inc(1)
log.Print("[WARN] No route for ", r.Host, r.URL)
}
return t
},
Requests: metrics.DefaultRegistry.GetTimer("requests"),
Noroute: metrics.DefaultRegistry.GetCounter("notfound"),
Logger: l,
}
}
func lookupHostFn(cfg *config.Config) func(string) string {
pick := route.Picker[cfg.Proxy.Strategy]
notFound := metrics.DefaultRegistry.GetCounter("notfound")
return func(host string) string {
t := route.GetTable().LookupHost(host, pick)
if t == nil {
notFound.Inc(1)
log.Print("[WARN] No route for ", host)
return ""
}
return t.URL.Host
}
}
func makeTLSConfig(l config.Listen) *tls.Config {
if l.CertSource.Name == "" {
return nil
}
src, err := cert.NewSource(l.CertSource)
if err != nil {
exit.Fatalf("[FATAL] Failed to create cert source %s. %s", l.CertSource.Name, err)
}
tlscfg, err := cert.TLSConfig(src, l.StrictMatch)
if err != nil {
exit.Fatalf("[FATAL] Failed to create TLS config for cert source %s. %s", l.CertSource.Name, err)
}
return tlscfg
}
func startAdmin(cfg *config.Config) {
log.Printf("[INFO] Admin server access mode %q", cfg.UI.Access)
log.Printf("[INFO] Admin server listening on %q", cfg.UI.Listen.Addr)
go func() {
l := cfg.UI.Listen
tlscfg := makeTLSConfig(l)
srv := &admin.Server{
Access: cfg.UI.Access,
Color: cfg.UI.Color,
Title: cfg.UI.Title,
Version: version,
Commands: route.Commands,
Cfg: cfg,
}
if err := srv.ListenAndServe(l, tlscfg); err != nil {
exit.Fatal("[FATAL] ui: ", err)
}
}()
}
func startServers(cfg *config.Config) {
for _, l := range cfg.Listen {
l := l // capture loop var for go routines below
tlscfg := makeTLSConfig(l)
log.Printf("[INFO] %s proxy listening on %s", strings.ToUpper(l.Proto), l.Addr)
if tlscfg != nil && tlscfg.ClientAuth == tls.RequireAndVerifyClientCert {
log.Printf("[INFO] Client certificate authentication enabled on %s", l.Addr)
}
switch l.Proto {
case "http", "https":
go func() {
h := newHTTPProxy(cfg)
if err := proxy.ListenAndServeHTTP(l, h, tlscfg); err != nil {
exit.Fatal("[FATAL] ", err)
}
}()
case "tcp":
go func() {
h := &tcp.Proxy{cfg.Proxy.DialTimeout, lookupHostFn(cfg)}
if err := proxy.ListenAndServeTCP(l, h, tlscfg); err != nil {
exit.Fatal("[FATAL] ", err)
}
}()
case "tcp+sni":
go func() {
h := &tcp.SNIProxy{cfg.Proxy.DialTimeout, lookupHostFn(cfg)}
if err := proxy.ListenAndServeTCP(l, h, tlscfg); err != nil {
exit.Fatal("[FATAL] ", err)
}
}()
default:
exit.Fatal("[FATAL] Invalid protocol ", l.Proto)
}
}
}
func initMetrics(cfg *config.Config) {
if cfg.Metrics.Target == "" {
log.Printf("[INFO] Metrics disabled")
return
}
var err error
if metrics.DefaultRegistry, err = metrics.NewRegistry(cfg.Metrics); err != nil {
exit.Fatal("[FATAL] ", err)
}
if route.ServiceRegistry, err = metrics.NewRegistry(cfg.Metrics); err != nil {
exit.Fatal("[FATAL] ", err)
}
}
func initRuntime(cfg *config.Config) {
if os.Getenv("GOGC") == "" {
log.Print("[INFO] Setting GOGC=", cfg.Runtime.GOGC)
debug.SetGCPercent(cfg.Runtime.GOGC)
} else {
log.Print("[INFO] Using GOGC=", os.Getenv("GOGC"), " from env")
}
if os.Getenv("GOMAXPROCS") == "" {
log.Print("[INFO] Setting GOMAXPROCS=", cfg.Runtime.GOMAXPROCS)
runtime.GOMAXPROCS(cfg.Runtime.GOMAXPROCS)
} else {
log.Print("[INFO] Using GOMAXPROCS=", os.Getenv("GOMAXPROCS"), " from env")
}
}
func initBackend(cfg *config.Config) {
var deadline = time.Now().Add(cfg.Registry.Timeout)
var err error
for {
switch cfg.Registry.Backend {
case "file":
registry.Default, err = file.NewBackend(cfg.Registry.File.Path)
case "static":
registry.Default, err = static.NewBackend(cfg.Registry.Static.Routes)
case "consul":
registry.Default, err = consul.NewBackend(&cfg.Registry.Consul)
default:
exit.Fatal("[FATAL] Unknown registry backend ", cfg.Registry.Backend)
}
if err == nil {
if err = registry.Default.Register(); err == nil {
return
}
}
log.Print("[WARN] Error initializing backend. ", err)
if time.Now().After(deadline) {
exit.Fatal("[FATAL] Timeout registering backend.")
}
time.Sleep(cfg.Registry.Retry)
if atomic.LoadInt32(&shuttingDown) > 0 {
exit.Exit(1)
}
}
}
func watchBackend(cfg *config.Config, first chan bool) {
var (
last string
svccfg string
mancfg string
once sync.Once
)
svc := registry.Default.WatchServices()
man := registry.Default.WatchManual()
for {
select {
case svccfg = <-svc:
case mancfg = <-man:
}
// manual config overrides service config
// order matters
next := svccfg + "\n" + mancfg
if next == last {
continue
}
t, err := route.NewTable(next)
if err != nil {
log.Printf("[WARN] %s", err)
continue
}
route.SetTable(t)
logRoutes(last, next, cfg.Log.RoutesFormat)
last = next
once.Do(func() { close(first) })
}
}
func logRoutes(last, next, format string) {
fmtDiff := func(diffs []dmp.Diff) string {
var b bytes.Buffer
for _, d := range diffs {
t := strings.TrimSpace(d.Text)
if t == "" {
continue
}
switch d.Type {
case dmp.DiffDelete:
b.WriteString("- ")
b.WriteString(strings.Replace(t, "\n", "\n- ", -1))
case dmp.DiffInsert:
b.WriteString("+ ")
b.WriteString(strings.Replace(t, "\n", "\n+ ", -1))
}
}
return b.String()
}
const defFormat = "delta"
switch format {
case "delta":
if delta := fmtDiff(dmp.New().DiffMain(last, next, true)); delta != "" {
log.Printf("[INFO] Config updates\n%s", delta)
}
case "all":
log.Printf("[INFO] Updated config to\n%s", next)
default:
log.Printf("[WARN] Invalid route format %q. Defaulting to %q", format, defFormat)
logRoutes(last, next, defFormat)
}
}
func toJSON(v interface{}) string {
data, err := json.MarshalIndent(v, "", " ")
if err != nil {
panic("json: " + err.Error())
}
return string(data)
}