-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
206 lines (176 loc) · 5.18 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
// CLI to run fault detector service
package main
import (
"context"
"errors"
"flag"
"fmt"
"os"
"os/signal"
"path"
"strings"
"sync"
"syscall"
"time"
"github.com/LiskHQ/op-fault-detector/pkg/api"
"github.com/LiskHQ/op-fault-detector/pkg/config"
"github.com/LiskHQ/op-fault-detector/pkg/faultdetector"
"github.com/LiskHQ/op-fault-detector/pkg/log"
"github.com/LiskHQ/op-fault-detector/pkg/utils/notification"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/collectors"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/spf13/viper"
)
// App encapsulates start and stop logic for the whole application.
type App struct {
ctx context.Context
logger log.Logger
errChan chan error
config *config.Config
wg *sync.WaitGroup
apiServer *api.HTTPServer
faultDetector *faultdetector.FaultDetector
notification *notification.Notification
}
// NewApp returns [App] with all the initialized services and variables.
func NewApp(ctx context.Context, logger log.Logger) (*App, error) {
reg := prometheus.NewRegistry()
// Adding Go process related metric
reg.MustRegister(
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
collectors.NewGoCollector(),
)
configFilepath := flag.String("config", "./config.yaml", "Path to the config file")
flag.Parse()
config, err := getAppConfig(logger, *configFilepath)
if err != nil {
logger.Errorf("Failed at parsing config with error %v", err)
return nil, err
}
wg := sync.WaitGroup{}
errorChan := make(chan error, 1)
// Initialize notification service
var notificationChannel *notification.Notification
if config.Notification.Enable {
notificationChannel, err = notification.NewNotification(
ctx,
logger,
config.Notification,
)
if err != nil {
logger.Errorf("Failed to initialize notification service, error: %v", err)
return nil, err
}
}
// Start Fault Detector
faultDetector, err := faultdetector.NewFaultDetector(
ctx,
logger,
errorChan,
&wg,
config.FaultDetectorConfig,
reg,
notificationChannel,
)
if err != nil {
logger.Errorf("Failed to create fault detector service.")
return nil, err
}
// Start API Server
apiServer := api.NewHTTPServer(ctx, logger, &wg, config, errorChan)
// Register metrics endpoint on the apiServer
apiServer.RegisterHandler("GET", "/metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{Registry: reg, ProcessStartTime: time.Now()}))
return &App{
ctx: ctx,
logger: logger,
errChan: errorChan,
config: config,
wg: &wg,
apiServer: apiServer,
faultDetector: faultDetector,
notification: notificationChannel,
}, nil
}
// This will start the application by starting API Server and Fault Detector services.
func (app *App) Start() {
doneChan := make(chan struct{})
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, os.Interrupt, syscall.SIGTERM)
app.wg.Add(1)
go app.faultDetector.Start()
app.apiServer.RegisterHandlersForVersions(app.faultDetector, app.config.Api.RegisterVersions, app.config.Api.BasePath)
app.wg.Add(1)
go app.apiServer.Start()
go func() {
app.wg.Wait()
close(doneChan)
}()
for {
select {
case <-doneChan:
app.stop()
return
case <-signalChan:
app.stop()
return
case err := <-app.errChan:
app.logger.Errorf("Received error of %v", err)
if app.notification != nil {
if err := app.notification.Notify("Error while starting application"); err != nil {
app.logger.Errorf("Failed to send notification, error: %v", err)
}
}
return
}
}
}
func (app *App) stop() {
app.faultDetector.Stop()
err := app.apiServer.Stop()
if err != nil {
app.logger.Error("Server shutdown not successful: %v", err)
}
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
logger, err := log.NewDefaultProductionLogger()
if err != nil {
logger.Errorf("Failed to create logger, %v", err)
return
}
app, err := NewApp(ctx, logger)
if err != nil {
logger.Errorf("Failed to create app, %v", err)
return
}
logger.Infof("Starting app...")
app.Start()
}
// getAppConfig is the function that takes in the absolute path to the config file, parses the content and returns it.
func getAppConfig(logger log.Logger, configFilepath string) (*config.Config, error) {
configDir := path.Dir(configFilepath)
configFilenameWithExt := path.Base(configFilepath)
splits := strings.FieldsFunc(configFilenameWithExt, func(r rune) bool { return r == '.' })
configType := splits[len(splits)-1] // Config file extension
viper.AddConfigPath(configDir)
viper.AddConfigPath(".")
viper.AddConfigPath("..")
viper.AddConfigPath("$HOME/.op-fault-detector")
viper.SetConfigName(configFilenameWithExt)
viper.SetConfigType(configType)
err := viper.ReadInConfig()
if err != nil {
return nil, fmt.Errorf("failed to load the config from disk: %w", err)
}
var config config.Config
err = viper.Unmarshal(&config)
if err != nil {
return nil, errors.New("failed to unmarshal config. Verify the 'Config' struct definition in 'pkg/config/config.go'")
}
if err := config.Validate(); err != nil {
return nil, err
}
return &config, nil
}