forked from networkservicemesh/cmd-nse-icmp-responder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
200 lines (176 loc) · 7.99 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
// Copyright (c) 2020 Doc.ai and/or its affiliates.
//
// SPDX-License-Identifier: Apache-2.0
//
// 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"
"net"
"net/url"
"os"
"time"
nested "github.com/antonfisher/nested-logrus-formatter"
"github.com/golang/protobuf/ptypes/timestamp"
"github.com/kelseyhightower/envconfig"
"github.com/sirupsen/logrus"
"github.com/spiffe/go-spiffe/v2/spiffetls/tlsconfig"
"github.com/spiffe/go-spiffe/v2/workloadapi"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"github.com/networkservicemesh/api/pkg/api/registry"
"github.com/networkservicemesh/sdk/pkg/networkservice/chains/endpoint"
"github.com/networkservicemesh/sdk/pkg/networkservice/common/authorize"
"github.com/networkservicemesh/sdk/pkg/networkservice/common/mechanisms/kernel"
"github.com/networkservicemesh/sdk/pkg/networkservice/ipam/point2pointipam"
"github.com/networkservicemesh/sdk/pkg/tools/debug"
"github.com/networkservicemesh/sdk/pkg/tools/grpcutils"
"github.com/networkservicemesh/sdk/pkg/tools/log"
"github.com/networkservicemesh/sdk/pkg/tools/signalctx"
"github.com/networkservicemesh/sdk/pkg/tools/spiffejwt"
)
// Config holds configuration parameters from environment variables
type Config struct {
Name string `default:"icmp-server" desc:"Name of ICMP Server"`
BaseDir string `default:"./" desc:"base directory" split_words:"true"`
ListenOn url.URL `default:"unix:///listen.on.socket" desc:"url to listen on" split_words:"true"`
ConnectTo url.URL `default:"unix:///connect.to.socket" desc:"url to connect to" split_words:"true"`
MaxTokenLifetime time.Duration `default:"24h" desc:"maximum lifetime of tokens" split_words:"true"`
EndpointName string `default:"icmp-responder-nse" desc:"url to the local registry to register this NSE"`
CidrPrefix string `default:"169.254.0.0/16" desc:"CIDR Prefix to assign IPs from"`
}
func main() {
// ********************************************************************************
// setup context to catch signals
// ********************************************************************************
ctx := signalctx.WithSignals(context.Background())
ctx, cancel := context.WithCancel(ctx)
// ********************************************************************************
// setup logging
// ********************************************************************************
logrus.SetFormatter(&nested.Formatter{})
logrus.SetLevel(logrus.TraceLevel)
ctx = log.WithField(ctx, "cmd", os.Args[0])
if err := debug.Self(); err != nil {
log.Entry(ctx).Infof("%s", err)
}
// enumerating phases
log.Entry(ctx).Infof("there are 6 phases which will be executed followed by a success message:")
log.Entry(ctx).Infof("the phases include:")
log.Entry(ctx).Infof("1: get config from environment")
log.Entry(ctx).Infof("2: retrieve spiffe svid")
log.Entry(ctx).Infof("3: create icmp server ipam")
log.Entry(ctx).Infof("4: create icmp server nse")
log.Entry(ctx).Infof("5: create grpc and mount nse")
log.Entry(ctx).Infof("6: register nse with nsm")
log.Entry(ctx).Infof("a final success message with start time duration")
starttime := time.Now()
// ********************************************************************************
log.Entry(ctx).Infof("executing phase 1: get config from environment")
// ********************************************************************************
config := &Config{}
if err := envconfig.Usage("nse", config); err != nil {
logrus.Fatal(err)
}
if err := envconfig.Process("nse", config); err != nil {
logrus.Fatalf("error processing config from env: %+v", err)
}
log.Entry(ctx).Infof("Config: %#v", config)
// ********************************************************************************
log.Entry(ctx).Infof("executing phase 2: retrieving svid, check spire agent logs if this is the last line you see")
// ********************************************************************************
source, err := workloadapi.NewX509Source(ctx)
if err != nil {
logrus.Fatalf("error getting x509 source: %+v", err)
}
svid, err := source.GetX509SVID()
if err != nil {
logrus.Fatalf("error getting x509 svid: %+v", err)
}
log.Entry(ctx).Infof("SVID: %q", svid.ID)
// ********************************************************************************
log.Entry(ctx).Infof("executing phase 3: creating icmp server ipam")
// ********************************************************************************
_, ipnet, err := net.ParseCIDR(config.CidrPrefix)
if err != nil {
log.Entry(ctx).Fatalf("error parsing cidr: %+v", err)
}
prefixes := []*net.IPNet{
ipnet,
}
ipamServer := point2pointipam.NewServer(prefixes...)
// ********************************************************************************
log.Entry(ctx).Infof("executing phase 4: create icmp-server network service endpoint")
// ********************************************************************************
responderEndpoint := endpoint.NewServer(
ctx,
config.Name,
authorize.NewServer(),
spiffejwt.TokenGeneratorFunc(source, config.MaxTokenLifetime),
ipamServer,
kernel.NewServer())
// ********************************************************************************
log.Entry(ctx).Infof("executing phase 5: create grpc server and register icmp-server")
// TODO add serveroptions for tracing
// ********************************************************************************
server := grpc.NewServer(grpc.Creds(credentials.NewTLS(tlsconfig.MTLSServerConfig(source, source, tlsconfig.AuthorizeAny()))))
responderEndpoint.Register(server)
srvErrCh := grpcutils.ListenAndServe(ctx, &config.ListenOn, server)
exitOnErr(ctx, cancel, srvErrCh)
log.Entry(ctx).Infof("grpc server started")
var nsmTarget string
switch scheme := config.ConnectTo.Scheme; scheme {
case "tcp":
nsmTarget = config.ConnectTo.Host
default:
nsmTarget = config.ConnectTo.String()
}
// ********************************************************************************
log.Entry(ctx).Infof("executing phase 6: register nse with nsm")
// ********************************************************************************
cc, err := grpc.DialContext(ctx,
nsmTarget,
grpc.WithBlock(),
grpc.WithTransportCredentials(credentials.NewTLS(tlsconfig.MTLSClientConfig(source, source, tlsconfig.AuthorizeAny()))))
if err != nil {
log.Entry(ctx).Fatalf("error establishing grpc connection to registry server %+v", err)
}
nse, err := registry.NewNetworkServiceEndpointRegistryClient(cc).Register(context.Background(), ®istry.NetworkServiceEndpoint{
Name: config.EndpointName,
NetworkServiceNames: []string{config.Name},
ExpirationTime: ×tamp.Timestamp{Seconds: time.Now().Add(time.Hour * 24).Unix()},
})
logrus.Infof("nse: %+v", nse)
if err != nil {
log.Entry(ctx).Fatalf("unable to register nse %+v", err)
}
// ********************************************************************************
log.Entry(ctx).Infof("startup completed in %v", time.Since(starttime))
// ********************************************************************************
// wait for server to exit
<-ctx.Done()
}
func exitOnErr(ctx context.Context, cancel context.CancelFunc, errCh <-chan error) {
// If we already have an error, log it and exit
select {
case err := <-errCh:
log.Entry(ctx).Fatal(err)
default:
}
// Otherwise wait for an error in the background to log and cancel
go func(ctx context.Context, errCh <-chan error) {
err := <-errCh
log.Entry(ctx).Error(err)
cancel()
}(ctx, errCh)
}