-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathmain.go
356 lines (318 loc) · 9.48 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
/*
Copyright (c) 2021-2024 Nordix Foundation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"context"
"flag"
"fmt"
"io"
"os"
"os/signal"
"syscall"
"time"
"github.com/go-logr/logr"
"github.com/kelseyhightower/envconfig"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/metric"
"google.golang.org/grpc"
"google.golang.org/grpc/backoff"
"google.golang.org/grpc/keepalive"
nspAPI "github.com/nordix/meridio/api/nsp/v1"
feConfig "github.com/nordix/meridio/cmd/frontend/internal/config"
"github.com/nordix/meridio/cmd/frontend/internal/env"
"github.com/nordix/meridio/cmd/frontend/internal/frontend"
"github.com/nordix/meridio/pkg/debug"
"github.com/nordix/meridio/pkg/health"
"github.com/nordix/meridio/pkg/health/connection"
linuxKernel "github.com/nordix/meridio/pkg/kernel"
"github.com/nordix/meridio/pkg/log"
"github.com/nordix/meridio/pkg/metrics"
"github.com/nordix/meridio/pkg/retry"
"github.com/nordix/meridio/pkg/security/credentials"
)
func printHelp() {
fmt.Println(`
frontend --
The frontend process in https://github.com/Nordix/Meridio uses BGP (Bird)
to attract traffic to Virtual IP (VIP) addresses.
This program shall be started in a Kubernetes container.`)
}
var version = "(unknown)"
func main() {
ver := flag.Bool("version", false, "Print version and quit")
debugCmd := flag.Bool("debug", false, "Print the debug information and quit")
help := flag.Bool("help", false, "Print help and quit")
flag.Parse()
if *ver {
fmt.Println(version)
os.Exit(0)
}
if *debugCmd {
debug.MeridioVersion = version
fmt.Println(debug.Collect().String())
os.Exit(0)
}
if *help {
printHelp()
os.Exit(0)
}
config := &env.Config{}
if err := envconfig.Process("nfe", config); err != nil {
panic(err)
}
logger := log.New("Meridio-frontend", config.LogLevel)
logger.Info("Config read", "config", config)
rootCtx, cancelRootCtx := context.WithCancel(logr.NewContext(context.Background(), logger))
defer cancelRootCtx()
ctx, cancel := signal.NotifyContext(
rootCtx,
os.Interrupt,
syscall.SIGHUP,
syscall.SIGTERM,
syscall.SIGQUIT,
)
defer cancel()
hostname, err := os.Hostname()
if err != nil {
log.Fatal(logger, "Unable to get hostname", "error", err)
}
// create and start health server
ctx = health.CreateChecker(ctx)
if err := health.RegisterReadinessSubservices(ctx, health.FEReadinessServices...); err != nil {
logger.Error(err, "RegisterReadinesSubservices")
}
// connect NSP
logger.Info("Dial NSP", "NSPService", config.NSPService)
conn, err := connectNSP(ctx, config)
if err != nil {
log.Fatal(logger, "Dial NSP", "error", err)
}
defer func() {
_ = conn.Close()
}()
// monitor status of NSP connection and adjust probe status accordingly
if err := connection.Monitor(ctx, health.NSPCliSvc, conn); err != nil {
logger.Error(err, "NSP connection state monitor")
}
gatewayMetrics := frontend.NewGatewayMetrics([]metric.ObserveOption{
metric.WithAttributes(attribute.String("trench", config.TrenchName)),
metric.WithAttributes(attribute.String("attractor", config.AttractorName)),
})
// connect loadbalancer
logger.Info("Dial loadbalancer", "LBService", config.LBSocket)
lbConn, err := connectLoadbalancer(ctx, config)
if err != nil {
log.Fatal(logger, "Dial loadbalancer", "error", err)
}
defer func() {
_ = lbConn.Close()
}()
// create and start frontend service
c := &feConfig.Config{
Config: config,
NSPConn: conn,
LBConn: lbConn,
Hostname: hostname,
}
fe := frontend.NewFrontEndService(ctx, c, gatewayMetrics)
defer fe.CleanUp()
if err := fe.Init(); err != nil {
cancel()
log.Fatal(logger, "Init failed", "error", err)
}
feErrCh := make(chan error, 1)
defer close(feErrCh)
fe.Start(rootCtx, feErrCh)
defer func() {
deleteCtx, deleteClose := context.WithTimeout(rootCtx, 3*time.Second)
defer deleteClose()
fe.Stop(deleteCtx)
}()
exitOnErrCh(logr.NewContext(ctx, logger.WithValues("func", "Start")), cancel, feErrCh)
// monitor routing sessions
monErrCh := make(chan error, 1)
defer close(monErrCh)
fe.Monitor(ctx, monErrCh)
exitOnErrCh(logr.NewContext(ctx, logger.WithValues("func", "Monitor")), cancel, monErrCh)
// start watching events of interest via NSP
go watchConfig(ctx, cancel, c, fe)
interfaceMetrics := linuxKernel.NewInterfaceMetrics([]metric.ObserveOption{
metric.WithAttributes(attribute.String("trench", config.TrenchName)),
metric.WithAttributes(attribute.String("attractor", config.AttractorName)),
})
interfaceMetrics.Register(config.ExternalInterface)
if config.MetricsEnabled {
func() {
_, err = metrics.Init(ctx)
if err != nil {
logger.Error(err, "Unable to init metrics collector")
cancel()
return
}
err = interfaceMetrics.Collect()
if err != nil {
logger.Error(err, "Unable to start interface metrics collector")
cancel()
return
}
err = gatewayMetrics.Collect()
if err != nil {
logger.Error(err, "Unable to start gateway metrics collector")
cancel()
return
}
metricsServer := metrics.Server{
IP: "",
Port: config.MetricsPort,
}
go func() {
err := metricsServer.Start(ctx)
if err != nil {
logger.Error(err, "Unable to start metrics server")
cancel()
}
}()
}()
}
<-ctx.Done()
logger.Info("FE shutting down")
}
func exitOnErrCh(ctx context.Context, cancel context.CancelFunc, errCh <-chan error) {
logger := log.FromContextOrGlobal(ctx).WithValues("func", "exitOnErrCh")
// If we already have an error, log it and exit
select {
case err, ok := <-errCh:
if ok {
logger.Error(err, "already have an error")
cancel()
}
default:
}
// Otherwise wait for an error in the background to log and cancel
go func(ctx context.Context, errCh <-chan error) {
select {
case <-ctx.Done():
logger.V(1).Info("context closed")
case err, ok := <-errCh:
if ok {
logger.Error(err, "got an error")
cancel()
}
}
}(ctx, errCh)
}
func watchConfig(ctx context.Context, cancel context.CancelFunc, c *feConfig.Config, fe *frontend.FrontEndService) {
logger := log.FromContextOrGlobal(ctx).WithValues("func", "watchConfig")
if err := fe.WaitStart(ctx); err != nil {
logger.Error(err, "WaitStart")
cancel()
}
configurationManagerClient := nspAPI.NewConfigurationManagerClient(c.NSPConn)
attractorToWatch := &nspAPI.Attractor{
Name: c.AttractorName,
Trench: &nspAPI.Trench{
Name: c.TrenchName,
},
}
err := retry.Do(func() error {
return watchAttractor(ctx, configurationManagerClient, attractorToWatch, fe)
}, retry.WithContext(ctx),
retry.WithDelay(500*time.Millisecond),
retry.WithErrorIngnored())
if err != nil {
logger.Error(err, "Attractor watcher")
cancel()
}
}
func watchAttractor(ctx context.Context, cli nspAPI.ConfigurationManagerClient, toWatch *nspAPI.Attractor, fe *frontend.FrontEndService) error {
logger := log.FromContextOrGlobal(ctx)
watchAttractor, err := cli.WatchAttractor(ctx, toWatch)
if err != nil {
return fmt.Errorf("failed to create attractor watcher: %w", err)
}
for {
attractorResponse, err := watchAttractor.Recv()
if err == io.EOF {
break
}
if err != nil {
logger.Info("Attractor watcher closing down")
return fmt.Errorf("attractor watcher recv error: %w", err)
}
logger.Info("Attractor config change event")
if err := fe.SetNewConfig(ctx, attractorResponse.Attractors); err != nil {
return fmt.Errorf("failed to set new Attractor config: %w", err)
}
}
return nil
}
func connectNSP(ctx context.Context, config *env.Config) (*grpc.ClientConn, error) {
grpcBackoffCfg := backoff.DefaultConfig
if grpcBackoffCfg.MaxDelay != config.GRPCMaxBackoff {
grpcBackoffCfg.MaxDelay = config.GRPCMaxBackoff
}
conn, err := grpc.DialContext(ctx,
config.NSPService,
grpc.WithTransportCredentials(
credentials.GetClient(context.Background()),
),
grpc.WithDefaultCallOptions(
grpc.WaitForReady(true),
),
grpc.WithConnectParams(grpc.ConnectParams{
Backoff: grpcBackoffCfg,
}),
grpc.WithKeepaliveParams(keepalive.ClientParameters{
Time: config.GRPCKeepaliveTime,
}),
)
if err != nil {
err = fmt.Errorf("failed to dial NSP: %w", err)
}
return conn, err
}
func connectLoadbalancer(ctx context.Context, config *env.Config) (*grpc.ClientConn, error) {
lbConn, err := grpc.DialContext(ctx,
func() string {
switch config.LBSocket.Scheme {
case "unix":
return config.LBSocket.String()
case "tcp":
return config.LBSocket.Host
}
return config.LBSocket.String()
}(),
grpc.WithTransportCredentials(
credentials.GetClient(context.Background()),
),
grpc.WithDefaultCallOptions(
grpc.WaitForReady(true),
),
grpc.WithConnectParams(grpc.ConnectParams{
Backoff: func() backoff.Config {
grpcBackoffCfg := backoff.DefaultConfig
if grpcBackoffCfg.MaxDelay != config.GRPCMaxBackoff {
grpcBackoffCfg.MaxDelay = config.GRPCMaxBackoff
}
return grpcBackoffCfg
}(),
}),
grpc.WithKeepaliveParams(keepalive.ClientParameters{
Time: config.GRPCKeepaliveTime,
}),
)
if err != nil {
err = fmt.Errorf("failed to dial loadbalancer: %w", err)
}
return lbConn, err
}