-
Notifications
You must be signed in to change notification settings - Fork 687
/
main.go
445 lines (376 loc) · 11.4 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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
package ambex
/**********************************************
* ambex: Ambassador Experimental ADS server
*
* Here's the deal.
*
* go-control-plane, several different classes manage this stuff:
*
* - The root of the world is a SnapshotCache.
* - import github.com/datawire/ambassador/pkg/envoy-control-plane/cache/v2, then refer
* to cache.SnapshotCache.
* - A collection of internally consistent configuration objects is a
* Snapshot (cache.Snapshot).
* - Snapshots are collected in the SnapshotCache.
* - A given SnapshotCache can hold configurations for multiple Envoys,
* identified by the Envoy 'node ID', which must be configured for the
* Envoy.
* - The SnapshotCache can only hold go-control-plane configuration objects,
* so you have to build these up to hand to the SnapshotCache.
* - The gRPC stuff is handled by a Server.
* - import github.com/datawire/ambassador/pkg/envoy-control-plane/server, then refer
* to server.Server.
* - Our runManagementServer (largely ripped off from the go-control-plane
* tests) gets this running. It takes a SnapshotCache (cleverly called a
* "config" for no reason I understand) and a gRPCServer as arguments.
* - _ALL_ the gRPC madness is handled by the Server, with the assistance
* of the methods in a callback object.
* - Once the Server is running, Envoy can open a gRPC stream to it.
* - On connection, Envoy will get handed the most recent Snapshot that
* the Server's SnapshotCache knows about.
* - Whenever a newer Snapshot is added to the SnapshotCache, that Snapshot
* will get sent to the Envoy.
* - We manage the SnapshotCache by loading envoy configuration from
* json and/or protobuf files on disk.
* - By default when we get a SIGHUP, we reload configuration.
* - When passed the -watch argument we reload whenever any file in
* the directory changes.
*/
import (
"context"
"flag"
"fmt"
"io/ioutil"
"net"
"os"
"os/signal"
"path/filepath"
"reflect"
"strings"
"syscall"
"github.com/fsnotify/fsnotify"
"github.com/sirupsen/logrus"
"google.golang.org/grpc"
// protobuf library
"github.com/golang/protobuf/jsonpb"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes"
"github.com/golang/protobuf/ptypes/any"
// envoy control plane
ctypes "github.com/datawire/ambassador/pkg/envoy-control-plane/cache/types"
"github.com/datawire/ambassador/pkg/envoy-control-plane/cache/v2"
"github.com/datawire/ambassador/pkg/envoy-control-plane/server/v2"
// envoy protobuf -- Be sure to import the package of any types that the Python
// emits a "@type" of in the generated config, even if that package is otherwise
// not used by ambex.
v2 "github.com/datawire/ambassador/pkg/api/envoy/api/v2"
_ "github.com/datawire/ambassador/pkg/api/envoy/api/v2/auth"
core "github.com/datawire/ambassador/pkg/api/envoy/api/v2/core"
_ "github.com/datawire/ambassador/pkg/api/envoy/config/accesslog/v2"
bootstrap "github.com/datawire/ambassador/pkg/api/envoy/config/bootstrap/v2"
_ "github.com/datawire/ambassador/pkg/api/envoy/config/filter/network/http_connection_manager/v2"
discovery "github.com/datawire/ambassador/pkg/api/envoy/service/discovery/v2"
)
const (
localhost = "127.0.0.1"
)
var (
debug bool
watch bool
adsNetwork string
adsAddress string
legacyAdsPort uint
// Version is inserted at build using --ldflags -X
Version = "-no-version-"
)
func init() {
flag.BoolVar(&debug, "debug", false, "Use debug logging")
flag.BoolVar(&watch, "watch", false, "Watch for file changes")
// TODO(lukeshu): Consider changing the default here so we don't need to put it in entrypoint.sh
flag.StringVar(&adsNetwork, "ads-listen-network", "tcp", "network for ADS to listen on")
flag.StringVar(&adsAddress, "ads-listen-address", ":18000", "address (on --ads-listen-network) for ADS to listen on")
flag.UintVar(&legacyAdsPort, "ads", 0, "port number for ADS to listen on--deprecated, use --ads-listen-address=:1234 instead")
}
// Hasher returns node ID as an ID
type Hasher struct {
}
// ID function
func (h Hasher) ID(node *core.Node) string {
if node == nil {
return "unknown"
}
return node.Id
}
// end Hasher stuff
// This feels kinda dumb.
type logger struct {
*logrus.Logger
}
var log = &logger{
Logger: logrus.StandardLogger(),
}
// run stuff
// RunManagementServer starts an xDS server at the given port.
func runManagementServer(ctx context.Context, server server.Server, adsNetwork, adsAddress string) {
grpcServer := grpc.NewServer()
lis, err := net.Listen(adsNetwork, adsAddress)
if err != nil {
log.WithError(err).Panic("failed to listen")
}
// register services
discovery.RegisterAggregatedDiscoveryServiceServer(grpcServer, server)
v2.RegisterEndpointDiscoveryServiceServer(grpcServer, server)
v2.RegisterClusterDiscoveryServiceServer(grpcServer, server)
v2.RegisterRouteDiscoveryServiceServer(grpcServer, server)
v2.RegisterListenerDiscoveryServiceServer(grpcServer, server)
log.WithFields(logrus.Fields{"addr": adsNetwork + ":" + adsAddress}).Info("Listening")
go func() {
go func() {
err := grpcServer.Serve(lis)
if err != nil {
log.WithFields(logrus.Fields{"error": err}).Error("Management server exited")
}
}()
<-ctx.Done()
grpcServer.GracefulStop()
}()
}
// Decoders for unmarshalling our config
var decoders = map[string](func(string, proto.Message) error){
".json": jsonpb.UnmarshalString,
".pb": proto.UnmarshalText,
}
func isDecodable(name string) bool {
if strings.HasPrefix(name, ".") {
return false
}
ext := filepath.Ext(name)
_, ok := decoders[ext]
return ok
}
// Not sure if there is a better way to do this, but we cast to this
// so we can call the generated Validate method.
type Validatable interface {
proto.Message
Validate() error
}
func decode(name string) (proto.Message, error) {
any := &any.Any{}
contents, err := ioutil.ReadFile(name)
if err != nil {
return nil, err
}
ext := filepath.Ext(name)
decoder := decoders[ext]
err = decoder(string(contents), any)
if err != nil {
return nil, err
}
var m ptypes.DynamicAny
err = ptypes.UnmarshalAny(any, &m)
if err != nil {
return nil, err
}
var v = m.Message.(Validatable)
err = v.Validate()
if err != nil {
return nil, err
}
log.Infof("Loaded file %s", name)
return v, nil
}
func Merge(to, from proto.Message) {
str, err := (&jsonpb.Marshaler{}).MarshalToString(from)
if err != nil {
panic(err)
}
err = jsonpb.UnmarshalString(str, to)
if err != nil {
panic(err)
}
}
func Clone(src proto.Message) proto.Message {
in := reflect.ValueOf(src)
if in.IsNil() {
return src
}
out := reflect.New(in.Type().Elem())
dst := out.Interface().(proto.Message)
Merge(dst, src)
return dst
}
func update(config cache.SnapshotCache, generation *int, dirs []string) {
clusters := []ctypes.Resource{} // v2.Cluster
endpoints := []ctypes.Resource{} // v2.ClusterLoadAssignment
routes := []ctypes.Resource{} // v2.RouteConfiguration
listeners := []ctypes.Resource{} // v2.Listener
runtimes := []ctypes.Resource{} // discovery.Runtime
var filenames []string
for _, dir := range dirs {
files, err := ioutil.ReadDir(dir)
if err != nil {
log.WithError(err).Warnf("Error listing %v", dir)
continue
}
for _, file := range files {
name := file.Name()
if isDecodable(name) {
filenames = append(filenames, filepath.Join(dir, name))
}
}
}
for _, name := range filenames {
m, e := decode(name)
if e != nil {
log.Warnf("%s: %v", name, e)
continue
}
var dst *[]ctypes.Resource
switch m.(type) {
case *v2.Cluster:
dst = &clusters
case *v2.ClusterLoadAssignment:
dst = &endpoints
case *v2.RouteConfiguration:
dst = &routes
case *v2.Listener:
dst = &listeners
case *discovery.Runtime:
dst = &runtimes
case *bootstrap.Bootstrap:
bs := m.(*bootstrap.Bootstrap)
sr := bs.StaticResources
for _, lst := range sr.Listeners {
listeners = append(listeners, Clone(lst).(ctypes.Resource))
}
for _, cls := range sr.Clusters {
clusters = append(clusters, Clone(cls).(ctypes.Resource))
}
continue
default:
log.Warnf("Unrecognized resource %s: %v", name, e)
continue
}
*dst = append(*dst, m.(ctypes.Resource))
}
version := fmt.Sprintf("v%d", *generation)
*generation++
snapshot := cache.NewSnapshot(
version,
endpoints,
clusters,
routes,
listeners,
runtimes)
err := snapshot.Consistent()
if err != nil {
log.Errorf("Snapshot inconsistency: %+v", snapshot)
} else {
err = config.SetSnapshot("test-id", snapshot)
}
if err != nil {
log.Panicf("Snapshot error %q for %+v", err, snapshot)
} else {
// log.Infof("Snapshot %+v", snapshot)
log.Infof("Pushing snapshot %+v", version)
}
}
func warn(err error) bool {
if err != nil {
log.Warn(err)
return true
} else {
return false
}
}
// OnStreamOpen is called once an xDS stream is open with a stream ID and the type URL (or "" for ADS).
func (l logger) OnStreamOpen(_ context.Context, sid int64, stype string) error {
l.Infof("Stream open[%v]: %v", sid, stype)
return nil
}
// OnStreamClosed is called immediately prior to closing an xDS stream with a stream ID.
func (l logger) OnStreamClosed(sid int64) {
l.Infof("Stream closed[%v]", sid)
}
// OnStreamRequest is called once a request is received on a stream.
func (l logger) OnStreamRequest(sid int64, req *v2.DiscoveryRequest) error {
l.Infof("Stream request[%v]: %v", sid, req)
return nil
}
// OnStreamResponse is called immediately prior to sending a response on a stream.
func (l logger) OnStreamResponse(sid int64, req *v2.DiscoveryRequest, res *v2.DiscoveryResponse) {
l.Infof("Stream response[%v]: %v -> %v", sid, req, res)
}
// OnFetchRequest is called for each Fetch request
func (l logger) OnFetchRequest(_ context.Context, r *v2.DiscoveryRequest) error {
l.Infof("Fetch request: %v", r)
return nil
}
// OnFetchResponse is called immediately prior to sending a response.
func (l logger) OnFetchResponse(req *v2.DiscoveryRequest, res *v2.DiscoveryResponse) {
l.Infof("Fetch response: %v -> %v", req, res)
}
func Main() {
MainContext(context.Background())
}
func MainContext(parent context.Context) {
if !flag.Parsed() {
flag.Parse()
}
if legacyAdsPort != 0 {
adsAddress = fmt.Sprintf(":%v", legacyAdsPort)
}
if debug {
log.SetLevel(logrus.DebugLevel)
} else {
log.SetLevel(logrus.WarnLevel)
}
log.Infof("Ambex %s starting...", Version)
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.WithError(err).Panic()
}
defer watcher.Close()
dirs := flag.Args()
if len(dirs) == 0 {
dirs = []string{"."}
}
if watch {
for _, d := range dirs {
watcher.Add(d)
}
}
ch := make(chan os.Signal)
signal.Notify(ch, syscall.SIGHUP, os.Interrupt, syscall.SIGTERM)
ctx, cancel := context.WithCancel(parent)
defer cancel()
config := cache.NewSnapshotCache(true, Hasher{}, log)
srv := server.NewServer(ctx, config, log)
runManagementServer(ctx, srv, adsNetwork, adsAddress)
pid := os.Getpid()
file := "ambex.pid"
if !warn(ioutil.WriteFile(file, []byte(fmt.Sprintf("%v", pid)), 0644)) {
log.WithFields(logrus.Fields{"pid": pid, "file": file}).Info("Wrote PID")
}
generation := 0
update(config, &generation, dirs)
OUTER:
for {
select {
case sig := <-ch:
switch sig {
case syscall.SIGHUP:
update(config, &generation, dirs)
case os.Interrupt, syscall.SIGTERM:
break OUTER
}
case <-watcher.Events:
update(config, &generation, dirs)
case err := <-watcher.Errors:
log.WithError(err).Warn("Watcher error")
case <-parent.Done():
break OUTER
}
}
log.Info("Done")
}