-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
117 lines (92 loc) · 2.36 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
package main
import (
"context"
"errors"
"flag"
"net/http"
"os"
"os/signal"
"runtime/debug"
"strconv"
"syscall"
"time"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
var debugFlag bool
var jsonLog bool
var port int
var configPath string
var cycleInterval int
var prefixes []*Prefix
func init() {
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
flag.IntVar(&port, "port", 2113, "port")
flag.BoolVar(&debugFlag, "debug", false, "debug")
flag.BoolVar(&jsonLog, "json", false, "json logging")
flag.StringVar(&configPath, "config", "config.toml", "config file")
flag.IntVar(&cycleInterval, "i", 10, "cycle interval")
}
func main() {
flag.Parse()
if !jsonLog {
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stdout})
}
if debugFlag {
zerolog.SetGlobalLevel(zerolog.DebugLevel)
log.Debug().Msg("Debug log enabled")
} else {
zerolog.SetGlobalLevel(zerolog.InfoLevel)
}
if err := loadConfig(); err != nil {
log.Fatal().Err(err).Msg("error loading config")
return
}
bgpInit()
log.Info().
Msg("Starting PEERINGMON Controller")
prefixes = prefixesInit()
http.Handle("/metrics", promhttp.Handler())
done := make(chan os.Signal, 1)
signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
srv := &http.Server{
Addr: ":" + strconv.Itoa(port),
}
go func() {
cycle()
ticker := time.NewTicker(time.Duration(cycleInterval) * time.Minute)
defer ticker.Stop()
for range ticker.C {
cycle()
}
}()
go func() {
if err := srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
log.Fatal().Err(err).Msg("Failed to start HTTP server")
}
}()
log.Info().
Int("port", port).
Int("cycle_interval", cycleInterval).
Msg("Started controller")
go startMemoryCleanup()
<-done
log.Info().Msg("Stopping")
shutdownCtx, shutdownRelease := context.WithTimeout(context.Background(), 10*time.Second)
defer shutdownRelease()
if err := bgpStop(shutdownCtx); err != nil {
log.Fatal().Err(err).Msg("Failed to gracefully stop bgp instance")
}
if err := srv.Shutdown(shutdownCtx); err != nil {
log.Fatal().Err(err).Msg("Failed to gracefully stop http server")
}
log.Info().Msg("Graceful Shutdown Successful, bye")
}
func startMemoryCleanup() {
ticker := time.NewTicker(1 * time.Minute)
defer ticker.Stop()
for range ticker.C {
debug.FreeOSMemory()
}
}