forked from fabiolb/fabio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
629 lines (565 loc) · 16.3 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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
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/fabiolb/fabio/admin"
"github.com/fabiolb/fabio/auth"
"github.com/fabiolb/fabio/cert"
"github.com/fabiolb/fabio/config"
"github.com/fabiolb/fabio/exit"
"github.com/fabiolb/fabio/logger"
"github.com/fabiolb/fabio/metrics"
"github.com/fabiolb/fabio/noroute"
"github.com/fabiolb/fabio/proxy"
"github.com/fabiolb/fabio/proxy/tcp"
"github.com/fabiolb/fabio/registry"
"github.com/fabiolb/fabio/registry/consul"
"github.com/fabiolb/fabio/registry/custom"
"github.com/fabiolb/fabio/registry/file"
"github.com/fabiolb/fabio/registry/static"
"github.com/fabiolb/fabio/route"
"github.com/fabiolb/fabio/trace"
grpc_proxy "github.com/mwitkow/grpc-proxy/proxy"
"github.com/pkg/profile"
dmp "github.com/sergi/go-diff/diffmatchpatch"
"google.golang.org/grpc"
)
// 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 number
var version = "1.5.12"
var shuttingDown int32
func main() {
logOutput := logger.NewLevelWriter(os.Stderr, "INFO", "2017/01/01 00:00:00 ")
log.SetOutput(logOutput)
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] Setting log level to %s", logOutput.Level())
if !logOutput.SetLevel(cfg.Log.Level) {
log.Printf("[INFO] Cannot set log level to %s", cfg.Log.Level)
}
log.Printf("[INFO] Runtime config\n" + toJSON(cfg))
log.Printf("[INFO] Version %s starting", version)
log.Printf("[INFO] Go runtime is %s", runtime.Version())
// warn once so that it is at the beginning of the log
// this will also start the reminder go routine if necessary.
WarnIfRunAsRoot(cfg.Insecure)
// 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
case "trace":
mode = profile.TraceProfile
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.DeregisterAll()
})
// 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)
// init OpenTracing, if enabled
trace.InitializeTracer(&cfg.Tracing)
startAdmin(cfg)
go watchNoRouteHTML(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)
// warn again so that it is visible in the terminal
WarnIfRunAsRoot(cfg.Insecure)
exit.Wait()
log.Print("[INFO] Down")
}
func newGrpcProxy(cfg *config.Config, tlscfg *tls.Config) []grpc.ServerOption {
//Init Glob Cache
globCache := route.NewGlobCache(cfg.GlobCacheSize)
statsHandler := &proxy.GrpcStatsHandler{
Connect: metrics.DefaultRegistry.GetCounter("grpc.conn"),
Request: metrics.DefaultRegistry.GetTimer("grpc.requests"),
NoRoute: metrics.DefaultRegistry.GetCounter("grpc.noroute"),
}
proxyInterceptor := proxy.GrpcProxyInterceptor{
Config: cfg,
StatsHandler: statsHandler,
GlobCache: globCache,
}
handler := grpc_proxy.TransparentHandler(proxy.GetGRPCDirector(tlscfg))
return []grpc.ServerOption{
grpc.CustomCodec(grpc_proxy.Codec()),
grpc.UnknownServiceHandler(handler),
grpc.StreamInterceptor(proxyInterceptor.Stream),
grpc.StatsHandler(statsHandler),
}
}
func newHTTPProxy(cfg *config.Config) http.Handler {
var w io.Writer
//Init Glob Cache
globCache := route.NewGlobCache(cfg.GlobCacheSize)
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,
}
}
authSchemes, err := auth.LoadAuthSchemes(cfg.Proxy.AuthSchemes)
if err != nil {
exit.Fatal("[FATAL] ", err)
}
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, globCache, cfg.GlobMatchingDisabled)
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,
TracerCfg: cfg.Tracing,
AuthSchemes: authSchemes,
}
}
func lookupHostFn(cfg *config.Config) func(string) *route.Target {
pick := route.Picker[cfg.Proxy.Strategy]
notFound := metrics.DefaultRegistry.GetCounter("notfound")
return func(host string) *route.Target {
t := route.GetTable().LookupHost(host, pick)
if t == nil {
notFound.Inc(1)
log.Print("[WARN] No route for ", host)
}
return t
}
}
func makeTLSConfig(l config.Listen) (*tls.Config, error) {
if l.CertSource.Name == "" {
return nil, nil
}
src, err := cert.NewSource(l.CertSource)
if err != nil {
return nil, fmt.Errorf("Failed to create cert source %s. %s", l.CertSource.Name, err)
}
tlscfg, err := cert.TLSConfig(src, l.StrictMatch, l.TLSMinVersion, l.TLSMaxVersion, l.TLSCiphers)
if err != nil {
return nil, fmt.Errorf("[FATAL] Failed to create TLS config for cert source %s. %s", l.CertSource.Name, err)
}
return tlscfg, nil
}
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, err := makeTLSConfig(l)
if err != nil {
exit.Fatal("[FATAL] ", err)
}
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, err := makeTLSConfig(l)
if err != nil {
exit.Fatal("[FATAL] ", err)
}
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 "grpc", "grpcs":
go func() {
h := newGrpcProxy(cfg, tlscfg)
if err := proxy.ListenAndServeGRPC(l, h, tlscfg); err != nil {
exit.Fatal("[FATAL] ", err)
}
}()
case "tcp":
go func() {
h := &tcp.Proxy{
DialTimeout: cfg.Proxy.DialTimeout,
Lookup: lookupHostFn(cfg),
Conn: metrics.DefaultRegistry.GetCounter("tcp.conn"),
ConnFail: metrics.DefaultRegistry.GetCounter("tcp.connfail"),
Noroute: metrics.DefaultRegistry.GetCounter("tcp.noroute"),
}
if err := proxy.ListenAndServeTCP(l, h, tlscfg); err != nil {
exit.Fatal("[FATAL] ", err)
}
}()
case "tcp+sni":
go func() {
h := &tcp.SNIProxy{
DialTimeout: cfg.Proxy.DialTimeout,
Lookup: lookupHostFn(cfg),
Conn: metrics.DefaultRegistry.GetCounter("tcp_sni.conn"),
ConnFail: metrics.DefaultRegistry.GetCounter("tcp_sni.connfail"),
Noroute: metrics.DefaultRegistry.GetCounter("tcp_sni.noroute"),
}
if err := proxy.ListenAndServeTCP(l, h, tlscfg); err != nil {
exit.Fatal("[FATAL] ", err)
}
}()
case "tcp-dynamic":
go func() {
var buffer strings.Builder
for {
time.Sleep(l.Refresh)
table := route.GetTable()
ports := []string{}
for target, rts := range table {
if strings.Contains(target, ":") {
buffer.WriteString(":")
buffer.WriteString(strings.Split(target, ":")[1])
schemes := tableSchemes(rts)
if len(schemes) == 1 && schemes[0] == "tcp" {
ports = append(ports, buffer.String())
}
buffer.Reset()
}
ports = unique(ports)
}
for _, port := range ports {
l := l
port := port
conn, err := net.Listen("tcp", port)
if err != nil {
log.Printf("[DEBUG] Dynamic TCP port %s in use", port)
continue
}
conn.Close()
log.Printf("[INFO] Starting dynamic TCP listener on port %s ", port)
go func() {
h := &tcp.DynamicProxy{
DialTimeout: cfg.Proxy.DialTimeout,
Lookup: lookupHostFn(cfg),
Conn: metrics.DefaultRegistry.GetCounter("tcp.conn"),
ConnFail: metrics.DefaultRegistry.GetCounter("tcp.connfail"),
Noroute: metrics.DefaultRegistry.GetCounter("tcp.noroute"),
}
l.Addr = port
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 deadline = time.Now().Add(cfg.Metrics.Timeout)
var err error
for {
metrics.DefaultRegistry, err = metrics.NewRegistry(cfg.Metrics)
if err == nil {
route.ServiceRegistry, err = metrics.NewRegistry(cfg.Metrics)
}
if err == nil {
return
}
if time.Now().After(deadline) {
exit.Fatal("[FATAL] ", err)
}
log.Print("[WARN] Error initializing metrics. ", err)
time.Sleep(cfg.Metrics.Retry)
if atomic.LoadInt32(&shuttingDown) > 0 {
exit.Exit(1)
}
}
}
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)
case "static":
registry.Default, err = static.NewBackend(&cfg.Registry.Static)
case "consul":
registry.Default, err = consul.NewBackend(&cfg.Registry.Consul)
case "custom":
registry.Default, err = custom.NewBackend(&cfg.Registry.Custom)
default:
exit.Fatal("[FATAL] Unknown registry backend ", cfg.Registry.Backend)
}
if err == nil {
if err = registry.Default.Register(nil); 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 (
nextTable string
lastTable string
svccfg string
mancfg string
customBE string
once sync.Once
tableBuffer = new(bytes.Buffer) // fix crash on reset before used (#650)
)
switch cfg.Registry.Backend {
// custom back end receives JSON from a remote source that contains a slice of route.RouteDef
// the route table is created directly from that input
case "custom":
svc := registry.Default.WatchServices()
for {
customBE = <-svc
if customBE != "OK" {
log.Printf("[ERROR] error during update from custom back end - %s", customBE)
}
once.Do(func() { close(first) })
}
// all other backend types
default:
svc := registry.Default.WatchServices()
man := registry.Default.WatchManual()
for {
select {
case svccfg = <-svc:
case mancfg = <-man:
}
// manual config overrides service config - order matters
tableBuffer.Reset()
tableBuffer.WriteString(svccfg)
tableBuffer.WriteString("\n")
tableBuffer.WriteString(mancfg)
// set nextTable here to preserve the state. The buffer is altered
// when calling route.NewTable and we lose change logging (#737)
if nextTable = tableBuffer.String(); nextTable == lastTable {
continue
}
aliases, err := route.ParseAliases(nextTable)
if err != nil {
log.Printf("[WARN]: %s", err)
}
registry.Default.Register(aliases)
t, err := route.NewTable(tableBuffer)
if err != nil {
log.Printf("[WARN] %s", err)
continue
}
route.SetTable(t)
logRoutes(t, lastTable, nextTable, cfg.Log.RoutesFormat)
lastTable = nextTable
once.Do(func() { close(first) })
}
}
}
func watchNoRouteHTML(cfg *config.Config) {
html := registry.Default.WatchNoRouteHTML()
for {
next := <-html
if next == noroute.GetHTML() {
continue
}
noroute.SetHTML(next)
if next == "" {
log.Print("[INFO] Unset noroute HTML")
} else {
log.Printf("[INFO] Set noroute HTML (%d bytes)", len(next))
}
}
}
func logRoutes(t route.Table, 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 "detail":
log.Printf("[INFO] Updated config to\n%s", t.Dump())
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(t, last, next, defFormat)
}
}
func toJSON(v interface{}) string {
data, err := json.MarshalIndent(v, "", " ")
if err != nil {
panic("json: " + err.Error())
}
return string(data)
}
func unique(strSlice []string) []string {
keys := make(map[string]bool)
list := []string{}
for _, entry := range strSlice {
if _, value := keys[entry]; !value {
keys[entry] = true
list = append(list, entry)
}
}
return list
}
func tableSchemes(r route.Routes) []string {
schemes := []string{}
for _, rt := range r {
for _, target := range rt.Targets {
schemes = append(schemes, target.URL.Scheme)
}
}
return unique(schemes)
}