forked from Nordix/Meridio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
223 lines (197 loc) · 5.95 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
/*
Copyright (c) 2021 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"
"google.golang.org/grpc"
feConfig "github.com/lioneljouin/meridio/cmd/frontend/internal/config"
"github.com/lioneljouin/meridio/cmd/frontend/internal/env"
"github.com/lioneljouin/meridio/cmd/frontend/internal/frontend"
nspAPI "github.com/nordix/meridio/api/nsp/v1"
"github.com/nordix/meridio/pkg/health"
"github.com/nordix/meridio/pkg/health/connection"
"github.com/nordix/meridio/pkg/log"
"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")
help := flag.Bool("help", false, "Print help and quit")
flag.Parse()
if *ver {
fmt.Println(version)
os.Exit(0)
}
if *help {
printHelp()
os.Exit(0)
}
config := &env.Config{}
if err := envconfig.Usage("nfe", config); err != nil {
panic(err)
}
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()
// create and start health server
ctx = health.CreateChecker(ctx)
if err := health.RegisterReadinesSubservices(ctx, health.FEReadinessServices...); err != nil {
logger.Error(err, "RegisterReadinesSubservices")
}
// connect NSP
logger.Info("Dial NSP", "NSPService", config.NSPService)
conn, err := grpc.DialContext(ctx,
config.NSPService,
grpc.WithTransportCredentials(
credentials.GetClient(context.Background()),
),
grpc.WithDefaultCallOptions(
grpc.WaitForReady(true),
))
if err != nil {
log.Fatal(logger, "Dial NSP", "error", err)
}
defer 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")
}
// create and start frontend service
c := &feConfig.Config{
Config: config,
NSPConn: conn,
}
fe := frontend.NewFrontEndService(ctx, c)
defer fe.CleanUp()
health.SetServingStatus(ctx, health.TargetRegistryCliSvc, true) // NewFrontEndService() creates Target Registry Client
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)
<-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 err
}
for {
attractorResponse, err := watchAttractor.Recv()
if err == io.EOF {
break
}
if err != nil {
logger.Info("Attractor watcher closing down")
return err
}
logger.Info("Attractor config change event")
if err := fe.SetNewConfig(ctx, attractorResponse.Attractors); err != nil {
return err
}
}
return nil
}