-
Notifications
You must be signed in to change notification settings - Fork 242
/
Copy pathmain.go
1339 lines (1197 loc) · 47.5 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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2017 Microsoft. All rights reserved.
// MIT License
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/fs"
"net/http"
"os"
"os/signal"
"runtime"
"strconv"
"strings"
"syscall"
"time"
"github.com/Azure/azure-container-networking/aitelemetry"
"github.com/Azure/azure-container-networking/cnm/ipam"
"github.com/Azure/azure-container-networking/cnm/network"
"github.com/Azure/azure-container-networking/cns"
cnsclient "github.com/Azure/azure-container-networking/cns/client"
cnscli "github.com/Azure/azure-container-networking/cns/cmd/cli"
"github.com/Azure/azure-container-networking/cns/cniconflist"
"github.com/Azure/azure-container-networking/cns/cnireconciler"
"github.com/Azure/azure-container-networking/cns/common"
"github.com/Azure/azure-container-networking/cns/configuration"
"github.com/Azure/azure-container-networking/cns/fsnotify"
"github.com/Azure/azure-container-networking/cns/healthserver"
"github.com/Azure/azure-container-networking/cns/hnsclient"
"github.com/Azure/azure-container-networking/cns/ipampool"
cssctrl "github.com/Azure/azure-container-networking/cns/kubecontroller/clustersubnetstate"
nncctrl "github.com/Azure/azure-container-networking/cns/kubecontroller/nodenetworkconfig"
"github.com/Azure/azure-container-networking/cns/logger"
"github.com/Azure/azure-container-networking/cns/multitenantcontroller"
"github.com/Azure/azure-container-networking/cns/multitenantcontroller/multitenantoperator"
"github.com/Azure/azure-container-networking/cns/restserver"
cnstypes "github.com/Azure/azure-container-networking/cns/types"
"github.com/Azure/azure-container-networking/cns/wireserver"
acn "github.com/Azure/azure-container-networking/common"
"github.com/Azure/azure-container-networking/crd"
"github.com/Azure/azure-container-networking/crd/clustersubnetstate/api/v1alpha1"
"github.com/Azure/azure-container-networking/crd/nodenetworkconfig"
"github.com/Azure/azure-container-networking/crd/nodenetworkconfig/api/v1alpha"
acnfs "github.com/Azure/azure-container-networking/internal/fs"
"github.com/Azure/azure-container-networking/log"
"github.com/Azure/azure-container-networking/nmagent"
"github.com/Azure/azure-container-networking/platform"
"github.com/Azure/azure-container-networking/processlock"
localtls "github.com/Azure/azure-container-networking/server/tls"
"github.com/Azure/azure-container-networking/store"
"github.com/Azure/azure-container-networking/telemetry"
"github.com/avast/retry-go/v4"
"github.com/pkg/errors"
"go.uber.org/zap"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
kuberuntime "k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/healthz"
)
const (
// Service name.
name = "azure-cns"
pluginName = "azure-vnet"
endpointStoreName = "azure-endpoints"
endpointStoreLocation = "/var/run/azure-cns/"
defaultCNINetworkConfigFileName = "10-azure.conflist"
dncApiVersion = "?api-version=2018-03-01"
poolIPAMRefreshRateInMilliseconds = 1000
// 720 * acn.FiveSeconds sec sleeps = 1Hr
maxRetryNodeRegister = 720
initCNSInitalDelay = 10 * time.Second
// envVarEnableCNIConflistGeneration enables cni conflist generation if set (value doesn't matter)
envVarEnableCNIConflistGeneration = "CNS_ENABLE_CNI_CONFLIST_GENERATION"
cnsReqTimeout = 15 * time.Second
)
type cniConflistScenario string
const (
scenarioV4Overlay cniConflistScenario = "v4overlay"
scenarioOverlay cniConflistScenario = "overlay"
scenarioCilium cniConflistScenario = "cilium"
scenarioSWIFT cniConflistScenario = "swift"
)
var (
rootCtx context.Context
rootErrCh chan error
)
// Version is populated by make during build.
var version string
// Command line arguments for CNS.
var args = acn.ArgumentList{
{
Name: acn.OptEnvironment,
Shorthand: acn.OptEnvironmentAlias,
Description: "Set the operating environment",
Type: "string",
DefaultValue: acn.OptEnvironmentAzure,
ValueMap: map[string]interface{}{
acn.OptEnvironmentAzure: 0,
acn.OptEnvironmentMAS: 0,
acn.OptEnvironmentFileIpam: 0,
},
},
{
Name: acn.OptAPIServerURL,
Shorthand: acn.OptAPIServerURLAlias,
Description: "Set the API server URL",
Type: "string",
DefaultValue: "",
},
{
Name: acn.OptLogLevel,
Shorthand: acn.OptLogLevelAlias,
Description: "Set the logging level",
Type: "int",
DefaultValue: acn.OptLogLevelInfo,
ValueMap: map[string]interface{}{
acn.OptLogLevelInfo: log.LevelInfo,
acn.OptLogLevelDebug: log.LevelDebug,
},
},
{
Name: acn.OptLogTarget,
Shorthand: acn.OptLogTargetAlias,
Description: "Set the logging target",
Type: "int",
DefaultValue: acn.OptLogTargetFile,
ValueMap: map[string]interface{}{
acn.OptLogTargetSyslog: log.TargetSyslog,
acn.OptLogTargetStderr: log.TargetStderr,
acn.OptLogTargetFile: log.TargetLogfile,
acn.OptLogStdout: log.TargetStdout,
acn.OptLogMultiWrite: log.TargetStdOutAndLogFile,
},
},
{
Name: acn.OptLogLocation,
Shorthand: acn.OptLogLocationAlias,
Description: "Set the directory location where logs will be saved",
Type: "string",
DefaultValue: "",
},
{
Name: acn.OptIpamQueryUrl,
Shorthand: acn.OptIpamQueryUrlAlias,
Description: "Set the IPAM query URL",
Type: "string",
DefaultValue: "",
},
{
Name: acn.OptIpamQueryInterval,
Shorthand: acn.OptIpamQueryIntervalAlias,
Description: "Set the IPAM plugin query interval",
Type: "int",
DefaultValue: "",
},
{
Name: acn.OptCnsURL,
Shorthand: acn.OptCnsURLAlias,
Description: "Set the URL for CNS to listen on",
Type: "string",
DefaultValue: "",
},
{
Name: acn.OptStartAzureCNM,
Shorthand: acn.OptStartAzureCNMAlias,
Description: "Start Azure-CNM if flag is set",
Type: "bool",
DefaultValue: false,
},
{
Name: acn.OptVersion,
Shorthand: acn.OptVersionAlias,
Description: "Print version information",
Type: "bool",
DefaultValue: false,
},
{
Name: acn.OptNetPluginPath,
Shorthand: acn.OptNetPluginPathAlias,
Description: "Set network plugin binary absolute path to parent (of azure-vnet and azure-vnet-ipam)",
Type: "string",
DefaultValue: platform.K8SCNIRuntimePath,
},
{
Name: acn.OptNetPluginConfigFile,
Shorthand: acn.OptNetPluginConfigFileAlias,
Description: "Set network plugin configuration file absolute path",
Type: "string",
DefaultValue: platform.K8SNetConfigPath + string(os.PathSeparator) + defaultCNINetworkConfigFileName,
},
{
Name: acn.OptCreateDefaultExtNetworkType,
Shorthand: acn.OptCreateDefaultExtNetworkTypeAlias,
Description: "Create default external network for windows platform with the specified type (l2bridge or l2tunnel)",
Type: "string",
DefaultValue: "",
},
{
Name: acn.OptTelemetry,
Shorthand: acn.OptTelemetryAlias,
Description: "Set to false to disable telemetry. This is deprecated in favor of cns_config.json",
Type: "bool",
DefaultValue: true,
},
{
Name: acn.OptHttpConnectionTimeout,
Shorthand: acn.OptHttpConnectionTimeoutAlias,
Description: "Set HTTP connection timeout in seconds to be used by http client in CNS",
Type: "int",
DefaultValue: "5",
},
{
Name: acn.OptHttpResponseHeaderTimeout,
Shorthand: acn.OptHttpResponseHeaderTimeoutAlias,
Description: "Set HTTP response header timeout in seconds to be used by http client in CNS",
Type: "int",
DefaultValue: "120",
},
{
Name: acn.OptStoreFileLocation,
Shorthand: acn.OptStoreFileLocationAlias,
Description: "Set store file absolute path",
Type: "string",
DefaultValue: platform.CNMRuntimePath,
},
{
Name: acn.OptPrivateEndpoint,
Shorthand: acn.OptPrivateEndpointAlias,
Description: "Set private endpoint",
Type: "string",
DefaultValue: "",
},
{
Name: acn.OptInfrastructureNetworkID,
Shorthand: acn.OptInfrastructureNetworkIDAlias,
Description: "Set infrastructure network ID",
Type: "string",
DefaultValue: "",
},
{
Name: acn.OptNodeID,
Shorthand: acn.OptNodeIDAlias,
Description: "Set node name/ID",
Type: "string",
DefaultValue: "",
},
{
Name: acn.OptManaged,
Shorthand: acn.OptManagedAlias,
Description: "Set to true to enable managed mode. This is deprecated in favor of cns_config.json",
Type: "bool",
DefaultValue: false,
},
{
Name: acn.OptDebugCmd,
Shorthand: acn.OptDebugCmdAlias,
Description: "Debug flag to retrieve IPconfigs, available values: assigned, available, all",
Type: "string",
DefaultValue: "",
},
{
Name: acn.OptDebugArg,
Shorthand: acn.OptDebugArgAlias,
Description: "Argument flag to be paired with the 'debugcmd' flag.",
Type: "string",
DefaultValue: "",
},
{
Name: acn.OptCNSConfigPath,
Shorthand: acn.OptCNSConfigPathAlias,
Description: "Path to cns config file",
Type: "string",
DefaultValue: "",
},
{
Name: acn.OptTelemetryService,
Shorthand: acn.OptTelemetryServiceAlias,
Description: "Flag to start telemetry service to receive telemetry events from CNI. Default, disabled.",
Type: "bool",
DefaultValue: false,
},
{
Name: acn.OptCNIConflistFilepath,
Shorthand: acn.OptCNIConflistFilepathAlias,
Description: "Filepath to write CNI conflist when CNI conflist generation is enabled",
Type: "string",
DefaultValue: "",
},
{
Name: acn.OptCNIConflistScenario,
Shorthand: acn.OptCNIConflistScenarioAlias,
Description: "Scenario to generate CNI conflist for",
Type: "string",
DefaultValue: "",
},
}
// init() is executed before main() whenever this package is imported
// to do pre-run setup of things like exit signal handling and building
// the root context.
func init() {
var cancel context.CancelFunc
rootCtx, cancel = context.WithCancel(context.Background())
rootErrCh = make(chan error, 1)
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM)
go func() {
// Wait until receiving a signal.
select {
case sig := <-sigCh:
log.Errorf("caught exit signal %v, exiting", sig)
case err := <-rootErrCh:
log.Errorf("unhandled error %v, exiting", err)
}
cancel()
}()
}
// Prints description and version information.
func printVersion() {
fmt.Printf("Azure Container Network Service\n")
fmt.Printf("Version %v\n", version)
}
// NodeInterrogator is functionality necessary to read information about nodes.
// It is intended to be strictly read-only.
type NodeInterrogator interface {
SupportedAPIs(context.Context) ([]string, error)
}
// RegisterNode - Tries to register node with DNC when CNS is started in managed DNC mode
func registerNode(httpc *http.Client, httpRestService cns.HTTPService, dncEP, infraVnet, nodeID string, ni NodeInterrogator) error {
logger.Printf("[Azure CNS] Registering node %s with Infrastructure Network: %s PrivateEndpoint: %s", nodeID, infraVnet, dncEP)
var (
numCPU = runtime.NumCPU()
url = fmt.Sprintf(acn.RegisterNodeURLFmt, dncEP, infraVnet, nodeID, dncApiVersion)
nodeRegisterRequest cns.NodeRegisterRequest
)
nodeRegisterRequest.NumCores = numCPU
supportedApis, retErr := ni.SupportedAPIs(context.TODO())
if retErr != nil {
logger.Errorf("[Azure CNS] Failed to retrieve SupportedApis from NMagent of node %s with Infrastructure Network: %s PrivateEndpoint: %s",
nodeID, infraVnet, dncEP)
return retErr
}
// To avoid any null-pointer deferencing errors.
if supportedApis == nil {
supportedApis = []string{}
}
nodeRegisterRequest.NmAgentSupportedApis = supportedApis
// CNS tries to register Node for maximum of an hour.
err := retry.Do(func() error {
return sendRegisterNodeRequest(httpc, httpRestService, nodeRegisterRequest, url)
}, retry.Delay(acn.FiveSeconds), retry.Attempts(maxRetryNodeRegister), retry.DelayType(retry.FixedDelay))
return errors.Wrap(err, fmt.Sprintf("[Azure CNS] Failed to register node %s after maximum reties for an hour with Infrastructure Network: %s PrivateEndpoint: %s",
nodeID, infraVnet, dncEP))
}
// sendRegisterNodeRequest func helps in registering the node until there is an error.
func sendRegisterNodeRequest(httpc *http.Client, httpRestService cns.HTTPService, nodeRegisterRequest cns.NodeRegisterRequest, registerURL string) error {
var body bytes.Buffer
err := json.NewEncoder(&body).Encode(nodeRegisterRequest)
if err != nil {
log.Errorf("[Azure CNS] Failed to register node while encoding json failed with non-retriable err %v", err)
return errors.Wrap(retry.Unrecoverable(err), "failed to sendRegisterNodeRequest")
}
response, err := httpc.Post(registerURL, "application/json", &body)
if err != nil {
logger.Errorf("[Azure CNS] Failed to register node with retriable err: %+v", err)
return errors.Wrap(err, "failed to sendRegisterNodeRequest")
}
defer response.Body.Close()
if response.StatusCode != http.StatusCreated {
err = fmt.Errorf("[Azure CNS] Failed to register node, DNC replied with http status code %s", strconv.Itoa(response.StatusCode))
logger.Errorf(err.Error())
return errors.Wrap(err, "failed to sendRegisterNodeRequest")
}
var req cns.SetOrchestratorTypeRequest
err = json.NewDecoder(response.Body).Decode(&req)
if err != nil {
log.Errorf("[Azure CNS] decoding Node Resgister response json failed with err %v", err)
return errors.Wrap(err, "failed to sendRegisterNodeRequest")
}
httpRestService.SetNodeOrchestrator(&req)
logger.Printf("[Azure CNS] Node Registered")
return nil
}
func startTelemetryService(ctx context.Context) {
var config aitelemetry.AIConfig
err := telemetry.CreateAITelemetryHandle(config, false, false, false)
if err != nil {
log.Errorf("AI telemetry handle creation failed..:%w", err)
return
}
tbtemp := telemetry.NewTelemetryBuffer()
//nolint:errcheck // best effort to cleanup leaked pipe/socket before start
tbtemp.Cleanup(telemetry.FdName)
tb := telemetry.NewTelemetryBuffer()
err = tb.StartServer()
if err != nil {
log.Errorf("Telemetry service failed to start: %w", err)
return
}
tb.PushData(rootCtx)
}
// Main is the entry point for CNS.
func main() {
// Initialize and parse command line arguments.
acn.ParseArgs(&args, printVersion)
environment := acn.GetArg(acn.OptEnvironment).(string)
url := acn.GetArg(acn.OptAPIServerURL).(string)
cniPath := acn.GetArg(acn.OptNetPluginPath).(string)
cniConfigFile := acn.GetArg(acn.OptNetPluginConfigFile).(string)
cnsURL := acn.GetArg(acn.OptCnsURL).(string)
logLevel := acn.GetArg(acn.OptLogLevel).(int)
logTarget := acn.GetArg(acn.OptLogTarget).(int)
logDirectory := acn.GetArg(acn.OptLogLocation).(string)
ipamQueryUrl := acn.GetArg(acn.OptIpamQueryUrl).(string)
ipamQueryInterval := acn.GetArg(acn.OptIpamQueryInterval).(int)
startCNM := acn.GetArg(acn.OptStartAzureCNM).(bool)
vers := acn.GetArg(acn.OptVersion).(bool)
createDefaultExtNetworkType := acn.GetArg(acn.OptCreateDefaultExtNetworkType).(string)
telemetryEnabled := acn.GetArg(acn.OptTelemetry).(bool)
httpConnectionTimeout := acn.GetArg(acn.OptHttpConnectionTimeout).(int)
httpResponseHeaderTimeout := acn.GetArg(acn.OptHttpResponseHeaderTimeout).(int)
storeFileLocation := acn.GetArg(acn.OptStoreFileLocation).(string)
privateEndpoint := acn.GetArg(acn.OptPrivateEndpoint).(string)
infravnet := acn.GetArg(acn.OptInfrastructureNetworkID).(string)
nodeID := acn.GetArg(acn.OptNodeID).(string)
clientDebugCmd := acn.GetArg(acn.OptDebugCmd).(string)
clientDebugArg := acn.GetArg(acn.OptDebugArg).(string)
cmdLineConfigPath := acn.GetArg(acn.OptCNSConfigPath).(string)
telemetryDaemonEnabled := acn.GetArg(acn.OptTelemetryService).(bool)
cniConflistFilepathArg := acn.GetArg(acn.OptCNIConflistFilepath).(string)
cniConflistScenarioArg := acn.GetArg(acn.OptCNIConflistScenario).(string)
if vers {
printVersion()
os.Exit(0)
}
// Initialize CNS.
var (
err error
config common.ServiceConfig
endpointStateStore store.KeyValueStore
)
config.Version = version
config.Name = name
// Create a channel to receive unhandled errors from CNS.
config.ErrChan = rootErrCh
// Create logging provider.
logger.InitLogger(name, logLevel, logTarget, logDirectory)
if clientDebugCmd != "" {
err := cnscli.HandleCNSClientCommands(rootCtx, clientDebugCmd, clientDebugArg)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
os.Exit(0)
}
if !telemetryEnabled {
logger.Errorf("[Azure CNS] Cannot disable telemetry via cmdline. Update cns_config.json to disable telemetry.")
}
cnsconfig, err := configuration.ReadConfig(cmdLineConfigPath)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
logger.Warnf("config file does not exist, using default")
cnsconfig = &configuration.CNSConfig{}
} else {
logger.Errorf("fatal: failed to read cns config: %v", err)
os.Exit(1)
}
}
configuration.SetCNSConfigDefaults(cnsconfig)
logger.Printf("[Azure CNS] Using config: %+v", cnsconfig)
_, envEnableConflistGeneration := os.LookupEnv(envVarEnableCNIConflistGeneration)
var conflistGenerator restserver.CNIConflistGenerator
if cnsconfig.EnableCNIConflistGeneration || envEnableConflistGeneration {
conflistFilepath := cnsconfig.CNIConflistFilepath
if cniConflistFilepathArg != "" {
// allow the filepath to get overidden by command line arg
conflistFilepath = cniConflistFilepathArg
}
writer, newWriterErr := acnfs.NewAtomicWriter(conflistFilepath)
if newWriterErr != nil {
logger.Errorf("unable to create atomic writer to generate cni conflist: %v", newWriterErr)
os.Exit(1)
}
// allow the scenario to get overridden by command line arg
scenarioString := cnsconfig.CNIConflistScenario
if cniConflistScenarioArg != "" {
scenarioString = cniConflistScenarioArg
}
switch scenario := cniConflistScenario(scenarioString); scenario {
case scenarioV4Overlay:
conflistGenerator = &cniconflist.V4OverlayGenerator{Writer: writer}
case scenarioCilium:
conflistGenerator = &cniconflist.CiliumGenerator{Writer: writer}
case scenarioSWIFT:
conflistGenerator = &cniconflist.SWIFTGenerator{Writer: writer}
default:
logger.Errorf("unable to generate cni conflist for unknown scenario: %s", scenario)
os.Exit(1)
}
}
// start the health server
z, _ := zap.NewProduction()
go healthserver.Start(z, cnsconfig.MetricsBindAddress)
nmaConfig, err := nmagent.NewConfig(cnsconfig.WireserverIP)
if err != nil {
logger.Errorf("[Azure CNS] Failed to produce NMAgent config from the supplied wireserver ip: %v", err)
return
}
nmaClient, err := nmagent.NewClient(nmaConfig)
if err != nil {
logger.Errorf("[Azure CNS] Failed to start nmagent client due to error: %v", err)
return
}
homeAzMonitor := restserver.NewHomeAzMonitor(nmaClient, time.Duration(cnsconfig.PopulateHomeAzCacheRetryIntervalSecs)*time.Second)
logger.Printf("start the goroutine for refreshing homeAz")
homeAzMonitor.Start()
if cnsconfig.ChannelMode == cns.Managed {
config.ChannelMode = cns.Managed
privateEndpoint = cnsconfig.ManagedSettings.PrivateEndpoint
infravnet = cnsconfig.ManagedSettings.InfrastructureNetworkID
nodeID = cnsconfig.ManagedSettings.NodeID
} else if cnsconfig.ChannelMode == cns.CRD {
config.ChannelMode = cns.CRD
} else if cnsconfig.ChannelMode == cns.MultiTenantCRD {
config.ChannelMode = cns.MultiTenantCRD
} else if acn.GetArg(acn.OptManaged).(bool) {
config.ChannelMode = cns.Managed
}
disableTelemetry := cnsconfig.TelemetrySettings.DisableAll
if !disableTelemetry {
ts := cnsconfig.TelemetrySettings
aiConfig := aitelemetry.AIConfig{
AppName: name,
AppVersion: version,
BatchSize: ts.TelemetryBatchSizeBytes,
BatchInterval: ts.TelemetryBatchIntervalInSecs,
RefreshTimeout: ts.RefreshIntervalInSecs,
DisableMetadataRefreshThread: ts.DisableMetadataRefreshThread,
DebugMode: ts.DebugMode,
}
if aiKey := cnsconfig.TelemetrySettings.AppInsightsInstrumentationKey; aiKey != "" {
logger.InitAIWithIKey(aiConfig, aiKey, ts.DisableTrace, ts.DisableMetric, ts.DisableEvent)
} else {
logger.InitAI(aiConfig, ts.DisableTrace, ts.DisableMetric, ts.DisableEvent)
}
}
if telemetryDaemonEnabled {
go startTelemetryService(rootCtx)
}
// Log platform information.
logger.Printf("Running on %v", platform.GetOSInfo())
err = platform.CreateDirectory(storeFileLocation)
if err != nil {
logger.Errorf("Failed to create File Store directory %s, due to Error:%v", storeFileLocation, err.Error())
return
}
lockclient, err := processlock.NewFileLock(platform.CNILockPath + name + store.LockExtension)
if err != nil {
log.Printf("Error initializing file lock:%v", err)
return
}
// Create the key value store.
storeFileName := storeFileLocation + name + ".json"
config.Store, err = store.NewJsonFileStore(storeFileName, lockclient)
if err != nil {
logger.Errorf("Failed to create store file: %s, due to error %v\n", storeFileName, err)
return
}
// Initialize endpoint state store if cns is managing endpoint state.
if cnsconfig.ManageEndpointState {
log.Printf("[Azure CNS] Configured to manage endpoints state")
endpointStoreLock, err := processlock.NewFileLock(platform.CNILockPath + endpointStoreName + store.LockExtension) // nolint
if err != nil {
log.Printf("Error initializing endpoint state file lock:%v", err)
return
}
defer endpointStoreLock.Unlock() // nolint
err = platform.CreateDirectory(endpointStoreLocation)
if err != nil {
logger.Errorf("Failed to create File Store directory %s, due to Error:%v", storeFileLocation, err.Error())
return
}
// Create the key value store.
storeFileName := endpointStoreLocation + endpointStoreName + ".json"
endpointStateStore, err = store.NewJsonFileStore(storeFileName, endpointStoreLock)
if err != nil {
logger.Errorf("Failed to create endpoint state store file: %s, due to error %v\n", storeFileName, err)
return
}
}
wsProxy := wireserver.Proxy{
Host: cnsconfig.WireserverIP,
HTTPClient: &http.Client{},
}
httpRestService, err := restserver.NewHTTPRestService(&config, &wireserver.Client{HTTPClient: &http.Client{}}, &wsProxy, nmaClient,
endpointStateStore, conflistGenerator, homeAzMonitor)
if err != nil {
logger.Errorf("Failed to create CNS object, err:%v.\n", err)
return
}
// Set CNS options.
httpRestService.SetOption(acn.OptCnsURL, cnsURL)
httpRestService.SetOption(acn.OptNetPluginPath, cniPath)
httpRestService.SetOption(acn.OptNetPluginConfigFile, cniConfigFile)
httpRestService.SetOption(acn.OptCreateDefaultExtNetworkType, createDefaultExtNetworkType)
httpRestService.SetOption(acn.OptHttpConnectionTimeout, httpConnectionTimeout)
httpRestService.SetOption(acn.OptHttpResponseHeaderTimeout, httpResponseHeaderTimeout)
httpRestService.SetOption(acn.OptProgramSNATIPTables, cnsconfig.ProgramSNATIPTables)
httpRestService.SetOption(acn.OptManageEndpointState, cnsconfig.ManageEndpointState)
// Create default ext network if commandline option is set
if len(strings.TrimSpace(createDefaultExtNetworkType)) > 0 {
if err := hnsclient.CreateDefaultExtNetwork(createDefaultExtNetworkType); err == nil {
logger.Printf("[Azure CNS] Successfully created default ext network")
} else {
logger.Printf("[Azure CNS] Failed to create default ext network due to error: %v", err)
return
}
}
logger.Printf("[Azure CNS] Initialize HTTPRestService")
if httpRestService != nil {
if cnsconfig.UseHTTPS {
config.TlsSettings = localtls.TlsSettings{
TLSSubjectName: cnsconfig.TLSSubjectName,
TLSCertificatePath: cnsconfig.TLSCertificatePath,
TLSPort: cnsconfig.TLSPort,
KeyVaultURL: cnsconfig.KeyVaultSettings.URL,
KeyVaultCertificateName: cnsconfig.KeyVaultSettings.CertificateName,
MSIResourceID: cnsconfig.MSISettings.ResourceID,
KeyVaultCertificateRefreshInterval: time.Duration(cnsconfig.KeyVaultSettings.RefreshIntervalInHrs) * time.Hour,
}
}
err = httpRestService.Init(&config)
if err != nil {
logger.Errorf("Failed to init HTTPService, err:%v.\n", err)
return
}
}
// Setting the remote ARP MAC address to 12-34-56-78-9a-bc on windows for external traffic
err = platform.SetSdnRemoteArpMacAddress()
if err != nil {
logger.Errorf("Failed to set remote ARP MAC address: %v", err)
return
}
// We are only setting the PriorityVLANTag in 'cns.Direct' mode, because it neatly maps today, to 'isUsingMultitenancy'
// In the future, we would want to have a better CNS flag, to explicitly say, this CNS is using multitenancy
if config.ChannelMode == cns.Direct {
// Set Mellanox adapter's PriorityVLANTag value to 3 if adapter exists
// reg key value for PriorityVLANTag = 3 --> Packet priority and VLAN enabled
// for more details goto https://docs.nvidia.com/networking/display/winof2v230/Configuring+the+Driver+Registry+Keys#ConfiguringtheDriverRegistryKeys-GeneralRegistryKeysGeneralRegistryKeys
if platform.HasMellanoxAdapter() {
go platform.MonitorAndSetMellanoxRegKeyPriorityVLANTag(rootCtx, cnsconfig.MellanoxMonitorIntervalSecs)
}
}
// Initialze state in if CNS is running in CRD mode
// State must be initialized before we start HTTPRestService
if config.ChannelMode == cns.CRD {
// Check the CNI statefile mount, and if the file is empty
// stub an empty JSON object
if err := cnireconciler.WriteObjectToCNIStatefile(); err != nil {
logger.Errorf("Failed to write empty object to CNI state: %v", err)
return
}
// We might be configured to reinitialize state from the CNI instead of the apiserver.
// If so, we should check that the the CNI is new enough to support the state commands,
// otherwise we fall back to the existing behavior.
if cnsconfig.InitializeFromCNI {
var isGoodVer bool
isGoodVer, err = cnireconciler.IsDumpStateVer()
if err != nil {
logger.Errorf("error checking CNI ver: %v", err)
}
// override the prior config flag with the result of the ver check.
cnsconfig.InitializeFromCNI = isGoodVer
if cnsconfig.InitializeFromCNI {
// Set the PodInfoVersion by initialization type, so that the
// PodInfo maps use the correct key schema
cns.GlobalPodInfoScheme = cns.InterfaceIDPodInfoScheme
}
}
// If cns manageendpointstate is true, then cns maintains its own state and reconciles from it.
// in this case, cns maintains state with containerid as key and so in-memory cache can lookup
// and update based on container id.
if cnsconfig.ManageEndpointState {
cns.GlobalPodInfoScheme = cns.InterfaceIDPodInfoScheme
}
logger.Printf("Set GlobalPodInfoScheme %v (InitializeFromCNI=%t)", cns.GlobalPodInfoScheme, cnsconfig.InitializeFromCNI)
err = InitializeCRDState(rootCtx, httpRestService, cnsconfig)
if err != nil {
logger.Errorf("Failed to start CRD Controller, err:%v.\n", err)
return
}
}
// Initialize multi-tenant controller if the CNS is running in MultiTenantCRD mode.
// It must be started before we start HTTPRestService.
if config.ChannelMode == cns.MultiTenantCRD {
err = InitializeMultiTenantController(rootCtx, httpRestService, *cnsconfig)
if err != nil {
logger.Errorf("Failed to start multiTenantController, err:%v.\n", err)
return
}
}
logger.Printf("[Azure CNS] Start HTTP listener")
if httpRestService != nil {
if cnsconfig.EnablePprof {
httpRestService.RegisterPProfEndpoints()
}
err = httpRestService.Start(&config)
if err != nil {
logger.Errorf("Failed to start CNS, err:%v.\n", err)
return
}
}
if cnsconfig.EnableAsyncPodDelete {
// Start fs watcher here
cnsclient, err := cnsclient.New("", cnsReqTimeout) //nolint
if err != nil {
z.Error("failed to create cnsclient", zap.Error(err))
}
go func() {
_ = retry.Do(func() error {
z.Info("starting fsnotify watcher to process missed Pod deletes")
w, err := fsnotify.New(cnsclient, cnsconfig.AsyncPodDeletePath, z)
if err != nil {
z.Error("failed to create fsnotify watcher", zap.Error(err))
return errors.Wrap(err, "failed to create fsnotify watcher, will retry")
}
if err := w.Start(rootCtx); err != nil {
z.Error("failed to start fsnotify watcher, will retry", zap.Error(err))
return errors.Wrap(err, "failed to start fsnotify watcher, will retry")
}
return nil
}, retry.DelayType(retry.BackOffDelay), retry.Attempts(0), retry.Context(rootCtx)) // infinite cancellable exponential backoff retrier
}()
}
if !disableTelemetry {
go logger.SendHeartBeat(rootCtx, cnsconfig.TelemetrySettings.HeartBeatIntervalInMins)
go httpRestService.SendNCSnapShotPeriodically(rootCtx, cnsconfig.TelemetrySettings.SnapshotIntervalInMins)
}
// If CNS is running on managed DNC mode
if config.ChannelMode == cns.Managed {
if privateEndpoint == "" || infravnet == "" || nodeID == "" {
logger.Errorf("[Azure CNS] Missing required values to run in managed mode: PrivateEndpoint: %s InfrastructureNetworkID: %s NodeID: %s",
privateEndpoint,
infravnet,
nodeID)
return
}
httpRestService.SetOption(acn.OptPrivateEndpoint, privateEndpoint)
httpRestService.SetOption(acn.OptInfrastructureNetworkID, infravnet)
httpRestService.SetOption(acn.OptNodeID, nodeID)
registerErr := registerNode(acn.GetHttpClient(), httpRestService, privateEndpoint, infravnet, nodeID, nmaClient)
if registerErr != nil {
logger.Errorf("[Azure CNS] Resgistering Node failed with error: %v PrivateEndpoint: %s InfrastructureNetworkID: %s NodeID: %s",
registerErr,
privateEndpoint,
infravnet,
nodeID)
return
}
go func(ep, vnet, node string) {
// Periodically poll DNC for node updates
tickerChannel := time.Tick(time.Duration(cnsconfig.ManagedSettings.NodeSyncIntervalInSeconds) * time.Second)
for {
<-tickerChannel
httpRestService.SyncNodeStatus(ep, vnet, node, json.RawMessage{})
}
}(privateEndpoint, infravnet, nodeID)
}
var (
netPlugin network.NetPlugin
ipamPlugin ipam.IpamPlugin
lockclientCnm processlock.Interface
)
if startCNM {
var pluginConfig acn.PluginConfig
pluginConfig.Version = version
// Create a channel to receive unhandled errors from the plugins.
pluginConfig.ErrChan = make(chan error, 1)
// Create network plugin.
netPlugin, err = network.NewPlugin(&pluginConfig)
if err != nil {
logger.Errorf("Failed to create network plugin, err:%v.\n", err)
return
}
// Create IPAM plugin.
ipamPlugin, err = ipam.NewPlugin(&pluginConfig)
if err != nil {
logger.Errorf("Failed to create IPAM plugin, err:%v.\n", err)
return
}
lockclientCnm, err = processlock.NewFileLock(platform.CNILockPath + pluginName + store.LockExtension)
if err != nil {
log.Printf("Error initializing file lock:%v", err)
return
}
// Create the key value store.
pluginStoreFile := storeFileLocation + pluginName + ".json"
pluginConfig.Store, err = store.NewJsonFileStore(pluginStoreFile, lockclientCnm)
if err != nil {
logger.Errorf("Failed to create plugin store file %s, due to error : %v\n", pluginStoreFile, err)
return
}
// Set plugin options.
netPlugin.SetOption(acn.OptAPIServerURL, url)
logger.Printf("Start netplugin\n")
if err := netPlugin.Start(&pluginConfig); err != nil {
logger.Errorf("Failed to create network plugin, err:%v.\n", err)
return
}
ipamPlugin.SetOption(acn.OptEnvironment, environment)
ipamPlugin.SetOption(acn.OptAPIServerURL, url)
ipamPlugin.SetOption(acn.OptIpamQueryUrl, ipamQueryUrl)
ipamPlugin.SetOption(acn.OptIpamQueryInterval, ipamQueryInterval)
if err := ipamPlugin.Start(&pluginConfig); err != nil {
logger.Errorf("Failed to create IPAM plugin, err:%v.\n", err)
return
}
}
// block until process exiting
<-rootCtx.Done()
if len(strings.TrimSpace(createDefaultExtNetworkType)) > 0 {
if err := hnsclient.DeleteDefaultExtNetwork(); err == nil {
logger.Printf("[Azure CNS] Successfully deleted default ext network")
} else {
logger.Printf("[Azure CNS] Failed to delete default ext network due to error: %v", err)
}
}
logger.Printf("end the goroutine for refreshing homeAz")
homeAzMonitor.Stop()
logger.Printf("stop cns service")
// Cleanup.
if httpRestService != nil {
httpRestService.Stop()
}
if startCNM {
logger.Printf("stop cnm plugin")
if netPlugin != nil {
netPlugin.Stop()
}
if ipamPlugin != nil {
logger.Printf("stop ipam plugin")
ipamPlugin.Stop()
}
if err = lockclientCnm.Unlock(); err != nil {
log.Errorf("lockclient cnm unlock error:%v", err)
}
}
if err = lockclient.Unlock(); err != nil {
log.Errorf("lockclient cns unlock error:%v", err)
}
logger.Printf("CNS exited")
logger.Close()
}
func InitializeMultiTenantController(ctx context.Context, httpRestService cns.HTTPService, cnsconfig configuration.CNSConfig) error {
var multiTenantController multitenantcontroller.RequestController
kubeConfig, err := ctrl.GetConfig()
kubeConfig.UserAgent = fmt.Sprintf("azure-cns-%s", version)
if err != nil {
return err
}
// convert interface type to implementation type
httpRestServiceImpl, ok := httpRestService.(*restserver.HTTPRestService)
if !ok {
logger.Errorf("Failed to convert interface httpRestService to implementation: %v", httpRestService)
return fmt.Errorf("Failed to convert interface httpRestService to implementation: %v",
httpRestService)
}
// Set orchestrator type
orchestrator := cns.SetOrchestratorTypeRequest{
OrchestratorType: cns.Kubernetes,
}
httpRestServiceImpl.SetNodeOrchestrator(&orchestrator)
// Create multiTenantController.
multiTenantController, err = multitenantoperator.New(httpRestServiceImpl, kubeConfig)
if err != nil {
logger.Errorf("Failed to create multiTenantController:%v", err)
return err
}
// Wait for multiTenantController to start.
go func() {
for {
if err := multiTenantController.Start(ctx); err != nil {
logger.Errorf("Failed to start multiTenantController: %v", err)
} else {
logger.Printf("Exiting multiTenantController")
return