forked from envoyproxy/go-control-plane
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
309 lines (266 loc) · 7.46 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
package main
import (
"bufio"
"context"
"flag"
"fmt"
"github.com/envoyproxy/go-control-plane/envoy/api/v2/endpoint"
"net"
"os"
"sync"
"sync/atomic"
"time"
"github.com/envoyproxy/go-control-plane/pkg/cache"
xds "github.com/envoyproxy/go-control-plane/pkg/server"
log "github.com/sirupsen/logrus"
"google.golang.org/grpc"
"github.com/envoyproxy/go-control-plane/envoy/api/v2"
"github.com/envoyproxy/go-control-plane/envoy/api/v2/auth"
"github.com/envoyproxy/go-control-plane/envoy/api/v2/core"
"github.com/envoyproxy/go-control-plane/envoy/api/v2/listener"
"github.com/envoyproxy/go-control-plane/envoy/api/v2/route"
discovery "github.com/envoyproxy/go-control-plane/envoy/service/discovery/v2"
hcm "github.com/envoyproxy/go-control-plane/envoy/config/filter/network/http_connection_manager/v2"
"github.com/envoyproxy/go-control-plane/pkg/util"
)
var (
debug bool
onlyLogging bool
port uint
gatewayPort uint
alsPort uint
mode string
version int32
config cache.SnapshotCache
)
const (
Ads = "ads"
Xds = "xds"
Rest = "rest"
)
func init() {
flag.BoolVar(&debug, "debug", true, "Use debug logging")
flag.BoolVar(&onlyLogging, "onlyLogging", false, "Only demo AccessLogging Service")
flag.UintVar(&port, "port", 18000, "Management server port")
flag.UintVar(&gatewayPort, "gateway", 18001, "Management server port for HTTP gateway")
flag.UintVar(&alsPort, "als", 18090, "Accesslog server port")
flag.StringVar(&mode, "ads", Ads, "Management server type (ads, xds, rest)")
}
type logger struct{}
func (logger logger) Infof(format string, args ...interface{}) {
log.Infof(format, args...)
}
func (logger logger) Errorf(format string, args ...interface{}) {
log.Errorf(format, args...)
}
func (cb *callbacks) Report() {
cb.mu.Lock()
defer cb.mu.Unlock()
log.WithFields(log.Fields{"fetches": cb.fetches, "requests": cb.requests}).Info("cb.Report() callbacks")
}
func (cb *callbacks) OnStreamOpen(c context.Context, i int64, s string) error {
log.Infof("OnStreamOpen %d open for %s", i, s)
return nil
}
func (cb *callbacks) OnStreamClosed(id int64) {
log.Infof("OnStreamClosed %d closed", id)
}
func (cb *callbacks) OnStreamRequest(i int64, req *v2.DiscoveryRequest) {
log.Debugf("stream request received for %s", req.TypeUrl)
cb.mu.Lock()
defer cb.mu.Unlock()
cb.requests++
if cb.signal != nil {
close(cb.signal)
cb.signal = nil
}
}
func (cb *callbacks) OnStreamResponse(i int64, req *v2.DiscoveryRequest, resp *v2.DiscoveryResponse) {
cb.Report()
}
func (cb *callbacks) OnFetchRequest(ctx context.Context, req *v2.DiscoveryRequest) error {
log.Infof("OnFetchRequest...")
cb.mu.Lock()
defer cb.mu.Unlock()
cb.fetches++
if cb.signal != nil {
close(cb.signal)
cb.signal = nil
}
return nil
}
func (cb *callbacks) OnFetchResponse(*v2.DiscoveryRequest, *v2.DiscoveryResponse) {
cb.Report()
}
type callbacks struct {
signal chan struct{}
fetches int
requests int
mu sync.Mutex
}
const grpcMaxConcurrentStreams = 1000000
// RunManagementServer starts an xDS server at the given port.
func RunManagementServer(ctx context.Context, server xds.Server, port uint) {
var grpcOptions []grpc.ServerOption
grpcOptions = append(grpcOptions, grpc.MaxConcurrentStreams(grpcMaxConcurrentStreams))
grpcServer := grpc.NewServer(grpcOptions...)
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
if err != nil {
log.WithError(err).Fatal("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(log.Fields{"port": port}).Info("management server listening")
go func() {
if err = grpcServer.Serve(lis); err != nil {
log.Error(err)
}
}()
<-ctx.Done()
grpcServer.GracefulStop()
}
type hasher2 struct {
}
func (h hasher2) ID(node *core.Node) string {
if node == nil {
return "unknown"
}
return node.Id
}
func main() {
flag.Parse()
if debug {
log.SetLevel(log.DebugLevel)
}
ctx := context.Background()
log.Printf("Starting control plane")
signal := make(chan struct{})
cb := &callbacks{
signal: signal,
fetches: 0,
requests: 0,
}
h := new(hasher2)
config = cache.NewSnapshotCache(mode == Ads, h, logger{})
srv := xds.NewServer(config, cb)
if onlyLogging {
cc := make(chan struct{})
<-cc
os.Exit(0)
}
// start the xDS server
go RunManagementServer(ctx, srv, port)
<-signal
cb.Report()
for {
atomic.AddInt32(&version, 1)
nodeId := config.GetStatusKeys()[1]
var clusterName = "service_google"
var remoteHost = "google.com"
var fullRemoteHost = "www." + remoteHost
loadAssignment := &v2.ClusterLoadAssignment{
ClusterName: clusterName,
Endpoints: []endpoint.LocalityLbEndpoints{{
LbEndpoints: []endpoint.LbEndpoint{{
Endpoint: &endpoint.Endpoint{
Address: &core.Address{
Address: &core.Address_SocketAddress{
SocketAddress: &core.SocketAddress{
Protocol: core.TCP,
Address: remoteHost,
PortSpecifier: &core.SocketAddress_PortValue{
PortValue: uint32(443),
},
},
},
},
},
}},
}},
}
cluster := []cache.Resource{
&v2.Cluster{
Name: clusterName,
ConnectTimeout: 1 * time.Second,
Type: v2.Cluster_LOGICAL_DNS,
DnsLookupFamily: v2.Cluster_V4_ONLY,
LbPolicy: v2.Cluster_ROUND_ROBIN,
LoadAssignment:loadAssignment,
TlsContext: &auth.UpstreamTlsContext{
Sni: fullRemoteHost,
},
},
}
virtualHost := route.VirtualHost{
Name: "local_service",
Domains: []string{"*"},
Routes: []route.Route{{
Match: route.RouteMatch{
PathSpecifier: &route.RouteMatch_Prefix{
Prefix: "/",
},
},
Action: &route.Route_Route{
Route: &route.RouteAction{
HostRewriteSpecifier: &route.RouteAction_HostRewrite{
HostRewrite: fullRemoteHost,
},
ClusterSpecifier: &route.RouteAction_Cluster{
Cluster: clusterName,
},
},
},
}}}
connectionManager := &hcm.HttpConnectionManager{
CodecType: hcm.AUTO,
StatPrefix: "ingress_http",
RouteSpecifier: &hcm.HttpConnectionManager_RouteConfig{
RouteConfig: &v2.RouteConfiguration{
Name: "local_route",
VirtualHosts: []route.VirtualHost{virtualHost},
},
},
HttpFilters: []*hcm.HttpFilter{{
Name: util.Router,
}},
}
cmStruct, err := util.MessageToStruct(connectionManager)
if err != nil {
panic(err)
}
listenr := []cache.Resource{
&v2.Listener{
Name: "listener_0",
Address: core.Address{
Address: &core.Address_SocketAddress{
SocketAddress: &core.SocketAddress{
Protocol: core.TCP,
Address: "0.0.0.0",
PortSpecifier: &core.SocketAddress_PortValue{
PortValue: 10000,
},
},
},
},
FilterChains: []listener.FilterChain{{
Filters: []listener.Filter{{
Name: util.HTTPConnectionManager,
ConfigType: &listener.Filter_Config{
Config: cmStruct,
},
}},
}},
}}
log.Infof("creating snapshot Version %s for node %s", fmt.Sprint(version), nodeId)
snap := cache.NewSnapshot(fmt.Sprint(version), nil, cluster, nil, listenr)
if err = config.SetSnapshot(nodeId, snap); err != nil {
log.Error(err)
}
reader := bufio.NewReader(os.Stdin)
_, _ = reader.ReadString('\n')
}
}