-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
98 lines (88 loc) · 2.43 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
package main
import (
"flag"
"fmt"
"time"
log "github.com/sirupsen/logrus"
)
var (
advertised = false // advertised holds a bool value to show whether the service ip is bgp advertised
flagConfig = flag.String("config", "/etc/bgp-lb/config.json", "Config file path")
flagLogLevel = flag.String("log-level", "info", "Log level (debug|info|warning|error)")
flagNetworkSetup = flag.Bool("network-setup", true, "Whether to try setting up net interfaces and ipvs rules on the host")
flagMetricsAddr = flag.String("metrics-address", ":8081", "Metrics server address")
)
func initLogger(logLevel string) {
log.SetFormatter(&log.TextFormatter{})
switch logLevel {
case "debug":
log.SetLevel(log.DebugLevel)
case "info":
log.SetLevel(log.InfoLevel)
case "warning":
log.SetLevel(log.WarnLevel)
case "error":
log.SetLevel(log.ErrorLevel)
default:
log.WithFields(log.Fields{
"level": logLevel}).Fatal("Unsupported log level")
}
}
func main() {
flag.Parse()
initLogger(*flagLogLevel)
config, err := readConfig(*flagConfig)
if err != nil {
log.WithFields(log.Fields{
"error": err,
}).Fatal("Failed to read config file")
}
bgp := bgpSetup(config.Bgp)
if *flagNetworkSetup {
netlinkSetup(config.Service, config.Bgp.Local.RouterId)
}
go startMetricsServer(*flagMetricsAddr)
// init metric with 0 value, in case healthcheck fails
unsetBGPPathAdvertisementMetric(config.Service.IP, fmt.Sprint(config.Service.PrefixLength), config.Bgp.Local.RouterId)
h := healthCheckSetup(config.Service)
if h == nil {
log.Fatal("Need to set one healthcheck")
}
for t := time.Tick(time.Second * time.Duration(1)); ; <-t {
res := h.Check()
if res.err != "" {
log.Warn(fmt.Sprintf("Healthcheck error: %s", res.err))
}
if res.healthy && !advertised {
ServiceOn(bgp, config)
}
if !res.healthy && advertised {
if res.output != "" {
log.Warn(fmt.Sprintf("Healthcheck failed: %s", res.output))
}
ServiceOff(bgp, config)
}
}
}
func ServiceOn(bgp *BgpServer, config *config) {
if err := bgp.AddV4Path(
config.Service.IP,
uint32(config.Service.PrefixLength),
config.Bgp.Local.RouterId,
); err != nil {
log.Fatal(err)
}
bgp.ListV4Paths()
advertised = true
}
func ServiceOff(bgp *BgpServer, config *config) {
if err := bgp.DeleteV4Path(
config.Service.IP,
uint32(config.Service.PrefixLength),
config.Bgp.Local.RouterId,
); err != nil {
log.Fatal(err)
}
advertised = false
bgp.ListV4Paths()
}