-
Notifications
You must be signed in to change notification settings - Fork 155
/
parseconfig.go
2955 lines (2713 loc) · 97.1 KB
/
parseconfig.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 (c) 2017-2022 Zededa, Inc.
// SPDX-License-Identifier: Apache-2.0
package zedagent
import (
"bytes"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"hash"
"net"
"net/url"
"os"
"sort"
"strings"
"time"
"github.com/google/go-cmp/cmp"
zconfig "github.com/lf-edge/eve-api/go/config"
zevecommon "github.com/lf-edge/eve-api/go/evecommon"
"github.com/lf-edge/eve/pkg/pillar/objtonum"
"github.com/lf-edge/eve/pkg/pillar/sriov"
"github.com/lf-edge/eve/pkg/pillar/types"
fileutils "github.com/lf-edge/eve/pkg/pillar/utils/file"
"github.com/lf-edge/eve/pkg/pillar/utils/netutils"
uuid "github.com/satori/go.uuid"
)
const (
MaxBaseOsCount = 2
BaseOsImageCount = 1
rebootConfigFilename = types.PersistStatusDir + "/rebootConfig"
shutdownConfigFilename = types.PersistStatusDir + "/shutdownConfig"
// interface name length limit as imposed by Linux kernel.
ifNameMaxLength = 15
// range of valid VLAN IDs
minVlanID = 1
maxVlanID = 4094
)
func parseConfig(getconfigCtx *getconfigContext, config *zconfig.EdgeDevConfig,
source configSource) configProcessingRetval {
// Do not accept new commands from side controller while new config
// from the primary controller is being applied. Or vice versa.
getconfigCtx.sideController.Lock()
defer getconfigCtx.sideController.Unlock()
// Make sure we do not accidentally revert to an older configuration.
// This depends on the controller attaching config timestamp.
// If not provided, the check is skipped.
if config.ConfigTimestamp.IsValid() {
configTimestamp := config.ConfigTimestamp.AsTime()
if getconfigCtx.lastConfigTimestamp.After(configTimestamp) {
log.Warnf("Skipping obsolete device configuration "+
"(source: %v, timestamp: %v, currently applied: %v)",
source, configTimestamp, getconfigCtx.lastConfigTimestamp)
return obsoleteConfig
}
getconfigCtx.lastConfigTimestamp = configTimestamp
}
// Update lastReceivedConfig even if the config processing is skipped below.
if config.ConfigTimestamp.IsValid() {
getconfigCtx.lastReceivedConfig = config.ConfigTimestamp.AsTime()
} else {
getconfigCtx.lastReceivedConfig = time.Now()
}
ctx := getconfigCtx.zedagentCtx
// XXX - DO NOT LOG entire config till secrets are in encrypted blobs
//log.Tracef("parseConfig: EdgeDevConfig: %v", *config)
// Prepare LOC structure before everything to be ready to
// publish info
parseLocConfig(getconfigCtx, config)
// Look for timers and other settings in configItems
// Process Config items even when configProcessingSkipFlagReboot is set.
// Allows us to recover if the system got stuck after setting
// configProcessingSkipFlagReboot
parseConfigItems(getconfigCtx, config, source)
// Did MaintenanceMode change?
if ctx.apiMaintenanceMode != config.MaintenanceMode {
ctx.apiMaintenanceMode = config.MaintenanceMode
mergeMaintenanceMode(ctx)
}
// Did the ForceFallbackCounter change? If so we publish for
// baseosmgr to take a look
newForceFallbackCounter := int(ctx.globalConfig.GlobalValueInt(types.ForceFallbackCounter))
if newForceFallbackCounter != ctx.forceFallbackCounter {
log.Noticef("ForceFallbackCounter update from %d to %d",
ctx.forceFallbackCounter, newForceFallbackCounter)
ctx.forceFallbackCounter = newForceFallbackCounter
publishZedAgentStatus(ctx.getconfigCtx)
}
if source == fromController {
rebootFlag, shutdownFlag := parseOpCmds(getconfigCtx, config)
// Any new reboot command?
if rebootFlag {
log.Noticeln("Reboot flag set, skipping config processing")
return skipConfigReboot
}
// Any new shutdown command?
if shutdownFlag {
log.Noticeln("Shutdown flag set, skipping config processing")
return skipConfigReboot
}
}
if getconfigCtx.configProcessingRV == skipConfigReboot || ctx.deviceReboot || ctx.deviceShutdown {
log.Noticef("parseConfig: Ignoring config as reboot/shutdown flag set")
return skipConfigReboot
} else if ctx.maintenanceMode {
log.Noticef("parseConfig: Ignoring config due to maintenanceMode")
} else {
// We do not ignore config if we are in the baseOS upgrade process, as we need to check the volumes
// and the baseOS image configs
if source != fromBootstrap {
handleControllerCertsSha(ctx, config)
parseCipherContext(getconfigCtx, config)
parseDatastoreConfig(getconfigCtx, config)
}
// DeviceIoList has some defaults for Usage and UsagePolicy
// used by systemAdapters
physioChanged := parseDeviceIoListConfig(getconfigCtx, config)
// It is important to parse Bonds before VLANs.
bondsChanged := parseBonds(getconfigCtx, config)
vlansChanged := parseVlans(getconfigCtx, config)
// Network objects are used for systemAdapters
networksChanged := parseNetworkXObjectConfig(getconfigCtx, config)
sourceChanged := getconfigCtx.lastConfigSource != source
// system adapter configuration that we publish, depends
// on Physio, VLAN, Bond and Networks configuration.
// If any of these change, we should re-parse system adapters and
// publish updated configuration.
forceSystemAdaptersParse := physioChanged || networksChanged || vlansChanged ||
bondsChanged || sourceChanged
parseSystemAdapterConfig(getconfigCtx, config, source, forceSystemAdaptersParse)
if source != fromBootstrap {
activateNewBaseOS := parseBaseOS(getconfigCtx, config)
parseNetworkInstanceConfig(getconfigCtx, config)
parseContentInfoConfig(getconfigCtx, config)
parseVolumeConfig(getconfigCtx, config)
parseEvConfig(getconfigCtx, config)
// We have handled the volumes, so we can now process the app instances. But we need to check if
// we are in the middle of a baseOS upgrade, and if so, we need to skip processing the app instances.
if (source == fromController && activateNewBaseOS) ||
(getconfigCtx.configProcessingRV == skipConfigUpdate) {
// We need to activate the new baseOS
// before we can process the app instances
// which depend on the new baseOS
log.Noticef("parseConfig: Ignoring config as a new baseOS image is being activated")
return skipConfigUpdate
}
// parseProfile must be called before processing of app instances from config
parseProfile(getconfigCtx, config)
parseAppInstanceConfig(getconfigCtx, config)
parseDisksConfig(getconfigCtx, config)
parseEdgeNodeInfo(getconfigCtx, config)
parsePatchEnvelopes(getconfigCtx, config)
}
getconfigCtx.lastProcessedConfig = getconfigCtx.lastReceivedConfig
getconfigCtx.lastConfigSource = source
}
return configOK
}
// Walk published AppInstanceConfig's and set Activate=false
// Note that we don't currently wait for the shutdown to complete.
// If withLocalServer is set we skip the app instances which are running
// a Local Profile Server, and return the number of Local Profile Server apps
func shutdownApps(getconfigCtx *getconfigContext, withLocalServer bool) (lpsCount uint) {
pub := getconfigCtx.pubAppInstanceConfig
items := pub.GetAll()
for _, c := range items {
config := c.(types.AppInstanceConfig)
if config.Activate {
if config.HasLocalServer && !withLocalServer {
log.Noticef("shutdownApps: defer for %s uuid %s",
config.DisplayName, config.Key())
lpsCount++
continue
}
log.Functionf("shutdownApps: clearing Activate for %s uuid %s",
config.DisplayName, config.Key())
config.Activate = false
pub.Publish(config.Key(), config)
}
}
return lpsCount
}
// countRunningApps returns the number of app instances which are booting,
// running, or halting.
func countRunningApps(getconfigCtx *getconfigContext) (runningCount uint) {
sub := getconfigCtx.subAppInstanceStatus
items := sub.GetAll()
for _, s := range items {
status := s.(types.AppInstanceStatus)
switch status.State {
case types.BOOTING, types.RUNNING, types.HALTING:
runningCount++
}
}
return runningCount
}
// Defer shutting down app instances with HasLocalServer until all other app
// instances has halted
func shutdownAppsGlobal(ctx *zedagentContext) {
lpsCount := shutdownApps(ctx.getconfigCtx, false)
if lpsCount == 0 {
log.Noticef("shutDownAppsGlobal: no Local Profile Server apps")
return
}
startTime := time.Now()
go func() {
for {
runningCount := countRunningApps(ctx.getconfigCtx)
log.Noticef("shutdownAppsGlobal: %d LPS apps, %d running, waited %v",
lpsCount, runningCount, time.Since(startTime))
if runningCount > lpsCount {
waitTimer := time.NewTimer(10 * time.Second)
<-waitTimer.C
continue
}
log.Noticef("shutdownAppsGlobal: defer done after %v",
time.Since(startTime))
shutdownApps(ctx.getconfigCtx, true)
break
}
}()
}
var baseOSPrevConfigHash []byte
func parseBaseOS(getconfigCtx *getconfigContext,
config *zconfig.EdgeDevConfig) (activateNewBaseOSFlag bool) {
// activateNewBaseOSFlag is set to true if we need to activate a new baseOS:
// 1. If the config has a new baseOS image with the activate flag set to true
// 2. If the config has a previous baseOS image, but the activate flag is _switched_ from false to true
// We don't care if the active flag already was true, as that means that the process of activating has already started.
activateNewBaseOSFlag = false
baseOS := config.GetBaseos()
if baseOS == nil {
log.Function("parseBaseOS: nil config received")
items := getconfigCtx.pubBaseOsConfig.GetAll()
for idStr := range items {
log.Functionf("parseBaseOS: deleting %s\n", idStr)
unpublishBaseOsConfig(getconfigCtx, idStr)
}
baseOSPrevConfigHash = []byte{}
return
}
h := sha256.New()
computeConfigElementSha(h, baseOS)
configHash := h.Sum(nil)
same := bytes.Equal(configHash, baseOSPrevConfigHash)
if same {
return
}
log.Functionf("parseBaseOS: Applying updated config "+
"prevSha: % x, "+
"NewSha : % x, "+
"baseOS: %v",
baseOSPrevConfigHash, configHash, baseOS)
baseOSPrevConfigHash = configHash
if baseOS.GetRetryUpdate() != nil {
if getconfigCtx.configRetryUpdateCounter != baseOS.GetRetryUpdate().GetCounter() {
log.Noticef("configRetryUpdateCounter update from %d to %d",
getconfigCtx.configRetryUpdateCounter, baseOS.GetRetryUpdate().GetCounter())
getconfigCtx.configRetryUpdateCounter = baseOS.GetRetryUpdate().GetCounter()
}
}
cfg := &types.BaseOsConfig{
ContentTreeUUID: baseOS.ContentTreeUuid,
BaseOsVersion: baseOS.BaseOsVersion,
RetryUpdateCounter: getconfigCtx.configRetryUpdateCounter,
Activate: baseOS.Activate,
}
// Check if baseOS version has changed and the new baseOS is set to be activated
partName := getZbootCurrentPartition(getconfigCtx.zedagentCtx)
status := getZbootPartitionStatus(getconfigCtx.zedagentCtx, partName)
if status.ShortVersion != cfg.BaseOsVersion && cfg.Activate {
activateNewBaseOSFlag = true
log.Functionf("BaseOS version has changed. Previous version: %s, New version: %s", status.ShortVersion, cfg.BaseOsVersion)
log.Functionf("Activate flag is set to true. BaseOS will be activated.")
} else {
log.Functionf("BaseOS version has not changed or Activate flag is not set to true.")
}
// Go through all published BaseOsConfig's and delete the ones which are not in the config
items := getconfigCtx.pubBaseOsConfig.GetAll()
for idStr := range items {
if idStr != cfg.Key() {
log.Functionf("parseBaseOS: deleting %s\n", idStr)
unpublishBaseOsConfig(getconfigCtx, idStr)
}
}
// publish new one
publishBaseOsConfig(getconfigCtx, cfg)
return
}
var networkConfigPrevConfigHash []byte
func parseNetworkXObjectConfig(getconfigCtx *getconfigContext,
config *zconfig.EdgeDevConfig) bool {
h := sha256.New()
nets := config.GetNetworks()
for _, n := range nets {
computeConfigElementSha(h, n)
}
configHash := h.Sum(nil)
same := bytes.Equal(configHash, networkConfigPrevConfigHash)
if same {
return false
}
log.Functionf("parseNetworkXObjectConfig: Applying updated config "+
"prevSha: % x, "+
"NewSha : % x, "+
"networks: %v",
networkConfigPrevConfigHash, configHash, nets)
networkConfigPrevConfigHash = configHash
// Export NetworkXObjectConfig for ourselves; systemAdapter
// XXX
// System Adapter points to network for Proxy configuration.
// There could be a situation where networks change, but
// systerm adapters do not change. When we see the networks
// change, we should parse systerm adapters again.
publishNetworkXObjectConfig(getconfigCtx, nets)
return true
}
func unpublishDeletedNetworkInstanceConfig(ctx *getconfigContext,
networkInstances []*zconfig.NetworkInstanceConfig) {
currentEntries := ctx.pubNetworkInstanceConfig.GetAll()
for key, entry := range currentEntries {
networkInstanceEntry := lookupNetworkInstanceById(key, networkInstances)
if networkInstanceEntry != nil {
// Entry not deleted.
log.Functionf("NetworkInstance %s (Name: %s) still exists",
key, networkInstanceEntry.Displayname)
continue
}
config := entry.(types.NetworkInstanceConfig)
log.Functionf("unpublishing NetworkInstance %s (Name: %s)",
key, config.DisplayName)
if err := ctx.pubNetworkInstanceConfig.Unpublish(key); err != nil {
log.Fatalf("Network Instance UnPublish (key:%s, name:%s) FAILED: %s",
key, config.DisplayName, err)
}
}
}
func parseDnsNameToIpList(
apiConfigEntry *zconfig.NetworkInstanceConfig,
config *types.NetworkInstanceConfig) {
// Parse and store DNSNameToIPList form Network configuration
dnsEntries := apiConfigEntry.GetDns()
// Parse and populate the DNSNameToIP list
// This is what we will publish to zedrouter
nameToIPs := []types.DNSNameToIP{}
for _, dnsEntry := range dnsEntries {
hostName := dnsEntry.HostName
ips := []net.IP{}
for _, strAddr := range dnsEntry.Address {
ip := net.ParseIP(strAddr)
if ip != nil {
ips = append(ips, ip)
} else {
log.Errorf("Bad dnsEntry %s ignored",
strAddr)
}
}
nameToIP := types.DNSNameToIP{
HostName: hostName,
IPs: ips,
}
nameToIPs = append(nameToIPs, nameToIP)
}
config.DnsNameToIPList = nameToIPs
}
func parseStaticRoute(route *zconfig.IPRoute, config *types.NetworkInstanceConfig) error {
if route.DestinationNetwork == "" {
return errors.New("missing destination network address")
}
_, dstNetwork, err := net.ParseCIDR(route.DestinationNetwork)
if err != nil {
return fmt.Errorf("destination network is invalid: %w", err)
}
if route.Gateway == "" {
return errors.New("missing gateway IP address")
}
gatewayIP := net.ParseIP(route.Gateway)
if gatewayIP == nil {
return errors.New("gateway IP address is invalid")
}
if gatewayIP.IsUnspecified() {
return errors.New("gateway IP address is all-zeroes")
}
config.StaticRoutes = append(config.StaticRoutes, types.IPRoute{
DstNetwork: dstNetwork,
Gateway: gatewayIP,
})
return nil
}
func publishNetworkInstanceConfig(ctx *getconfigContext,
networkInstances []*zconfig.NetworkInstanceConfig) {
log.Functionf("Publish NetworkInstance Config: %+v", networkInstances)
unpublishDeletedNetworkInstanceConfig(ctx, networkInstances)
for _, apiConfigEntry := range networkInstances {
id, err := uuid.FromString(apiConfigEntry.Uuidandversion.Uuid)
version := apiConfigEntry.Uuidandversion.Version
if err != nil {
log.Errorf("NetworkInstanceConfig: Malformed UUID %s. ignored. Err: %s",
apiConfigEntry.Uuidandversion.Uuid, err)
// XXX - We should propagate this error to Cloud.
// Why ignore only for this specific Check?
// Shouldn't we reject the config if any of the fields have errors?
// Or may be identify some fields as imp. fields and reject them only?
// Either way, it is good to propagate the error to Cloud.
continue
}
networkInstanceConfig := types.NetworkInstanceConfig{
UUIDandVersion: types.UUIDandVersion{UUID: id, Version: version},
DisplayName: apiConfigEntry.Displayname,
Type: types.NetworkInstanceType(apiConfigEntry.InstType),
Activate: apiConfigEntry.Activate,
PropagateConnRoutes: apiConfigEntry.PropagateConnectedRoutes,
}
log.Functionf("publishNetworkInstanceConfig: processing %s %s type %d activate %v",
networkInstanceConfig.UUID.String(), networkInstanceConfig.DisplayName,
networkInstanceConfig.Type, networkInstanceConfig.Activate)
if apiConfigEntry.Port != nil {
networkInstanceConfig.PortLogicalLabel = apiConfigEntry.Port.Name
}
networkInstanceConfig.IpType = types.AddressType(apiConfigEntry.IpType)
if networkInstanceConfig.Type == types.NetworkInstanceTypeSwitch {
// XXX controller should send AddressTypeNone type for switch
// network instances
if networkInstanceConfig.IpType != types.AddressTypeNone {
log.Errorf("Switch network instance %s %s with invalid IpType %d should be %d",
networkInstanceConfig.UUID.String(),
networkInstanceConfig.DisplayName,
networkInstanceConfig.IpType,
types.AddressTypeNone)
// Let's relax the requirement until cloud side update the right IpType
networkInstanceConfig.IpType = types.AddressTypeNone
}
}
// other than switch-type(l2)
// if ip type is l3, do the needful
if networkInstanceConfig.IpType != types.AddressTypeNone {
err := parseIpspec(apiConfigEntry.Ip, &networkInstanceConfig)
if err != nil {
errStr := fmt.Sprintf("Network Instance %s parameter parse failed: %s",
networkInstanceConfig.Key(), err)
log.Error(errStr)
networkInstanceConfig.SetErrorNow(errStr)
// Proceed to send error back to controller
}
parseDnsNameToIpList(apiConfigEntry,
&networkInstanceConfig)
for _, route := range apiConfigEntry.StaticRoutes {
err := parseStaticRoute(route, &networkInstanceConfig)
if err != nil {
err = fmt.Errorf("network Instance %s IP route %v parsing failed: %w",
networkInstanceConfig.Key(), route, err)
log.Error(err)
networkInstanceConfig.SetErrorNow(err.Error())
// Proceed to send error back to controller
}
}
}
ctx.pubNetworkInstanceConfig.Publish(networkInstanceConfig.UUID.String(),
networkInstanceConfig)
}
}
var networkInstancePrevConfigHash []byte
func parseNetworkInstanceConfig(getconfigCtx *getconfigContext,
config *zconfig.EdgeDevConfig) {
networkInstances := config.GetNetworkInstances()
h := sha256.New()
for _, n := range networkInstances {
computeConfigElementSha(h, n)
}
configHash := h.Sum(nil)
same := bytes.Equal(configHash, networkInstancePrevConfigHash)
if same {
return
}
log.Functionf("parseNetworkInstanceConfig: Applying updated config "+
"prevSha: % x, "+
"NewSha : % x, "+
"networkInstances: %v",
networkInstancePrevConfigHash, configHash, networkInstances)
networkInstancePrevConfigHash = configHash
// Export NetworkInstanceConfig to zedrouter
publishNetworkInstanceConfig(getconfigCtx, networkInstances)
}
var appinstancePrevConfigHash []byte
func parseAppInstanceConfig(getconfigCtx *getconfigContext,
config *zconfig.EdgeDevConfig) {
Apps := config.GetApps()
h := sha256.New()
for _, a := range Apps {
computeConfigElementSha(h, a)
}
configHash := h.Sum(nil)
same := bytes.Equal(configHash, appinstancePrevConfigHash)
if same {
return
}
log.Functionf("parseAppInstanceConfig: Applying updated config "+
"prevSha: % x, "+
"NewSha : % x, "+
"Apps: %v",
appinstancePrevConfigHash, configHash, Apps)
appinstancePrevConfigHash = configHash
// First look for deleted ones
items := getconfigCtx.pubAppInstanceConfig.GetAll()
for uuidStr := range items {
found := false
for _, app := range Apps {
if app.Uuidandversion.Uuid == uuidStr {
found = true
break
}
}
if !found {
log.Functionf("Remove app config %s", uuidStr)
getconfigCtx.pubAppInstanceConfig.Unpublish(uuidStr)
delLocalAppConfig(getconfigCtx, uuidStr)
}
}
for _, cfgApp := range Apps {
// Note that we repeat this even if the app config didn't
// change but something else in the EdgeDeviceConfig did
log.Tracef("New/updated app instance %v", cfgApp)
var appInstance types.AppInstanceConfig
appInstance.UUIDandVersion.UUID, _ = uuid.FromString(cfgApp.Uuidandversion.Uuid)
appInstance.UUIDandVersion.Version = cfgApp.Uuidandversion.Version
appInstance.DisplayName = cfgApp.Displayname
appInstance.Activate = cfgApp.Activate
appInstance.FixedResources.Kernel = cfgApp.Fixedresources.Kernel
appInstance.FixedResources.BootLoader = cfgApp.Fixedresources.Bootloader
appInstance.FixedResources.Ramdisk = cfgApp.Fixedresources.Ramdisk
appInstance.FixedResources.MaxMem = int(cfgApp.Fixedresources.Maxmem)
appInstance.FixedResources.VMMMaxMem = int(cfgApp.Fixedresources.VmmMaxmem)
appInstance.FixedResources.Memory = int(cfgApp.Fixedresources.Memory)
appInstance.FixedResources.RootDev = cfgApp.Fixedresources.Rootdev
appInstance.FixedResources.VCpus = int(cfgApp.Fixedresources.Vcpus)
appInstance.FixedResources.MaxCpus = int(cfgApp.Fixedresources.Maxcpus)
appInstance.FixedResources.VirtualizationMode = types.VmMode(cfgApp.Fixedresources.VirtualizationMode)
appInstance.FixedResources.EnableVnc = cfgApp.Fixedresources.EnableVnc
appInstance.FixedResources.EnableVncShimVM = cfgApp.Fixedresources.EnableVncShimVm
appInstance.FixedResources.VncDisplay = cfgApp.Fixedresources.VncDisplay
appInstance.FixedResources.VncPasswd = cfgApp.Fixedresources.VncPasswd
appInstance.DisableLogs = cfgApp.Fixedresources.DisableLogs
appInstance.MetaDataType = types.MetaDataType(cfgApp.MetaDataType)
appInstance.Delay = time.Duration(cfgApp.StartDelayInSeconds) * time.Second
appInstance.Service = cfgApp.Service
appInstance.CloudInitVersion = cfgApp.CloudInitVersion
appInstance.FixedResources.CPUsPinned = cfgApp.Fixedresources.PinCpu
// Parse the snapshot related fields
if cfgApp.Snapshot != nil {
parseSnapshotConfig(&appInstance.Snapshot, cfgApp.Snapshot)
}
appInstance.VolumeRefConfigList = make([]types.VolumeRefConfig,
len(cfgApp.VolumeRefList))
parseVolumeRefList(appInstance.VolumeRefConfigList, cfgApp.GetVolumeRefList())
// fill in the collect stats IP address of the App
appInstance.CollectStatsIPAddr = net.ParseIP(cfgApp.GetCollectStatsIPAddr())
// fill the app adapter config
parseAppNetworkConfig(&appInstance, cfgApp, config.Networks,
config.NetworkInstances)
// I/O adapters
appInstance.IoAdapterList = nil
for _, adapter := range cfgApp.Adapters {
log.Tracef("Processing adapter type %d name %s",
adapter.Type, adapter.Name)
ioa := types.IoAdapter{Type: types.IoType(adapter.Type), Name: adapter.Name}
if ioa.Type == types.IoNetEthVF && adapter.EthVf != nil {
// not checking lower bound, since it's zero if VlanId is not specified
if adapter.EthVf.VlanId > maxVlanID {
log.Errorf("Incorrect VlanID %d for adapter %s", adapter.EthVf.VlanId, adapter)
continue
}
hwaddr, err := net.ParseMAC(adapter.EthVf.Mac)
if err != nil {
log.Errorf("Failed to parse hardware address for adapter %s: %s", adapter.Name, err)
}
ioa.EthVf = sriov.EthVF{
Mac: hwaddr.String(),
VlanID: uint16(adapter.EthVf.VlanId)}
} else if ioa.Type == types.IoCAN || ioa.Type == types.IoVCAN || ioa.Type == types.IoLCAN {
log.Functionf("Got CAN adapter")
}
appInstance.IoAdapterList = append(appInstance.IoAdapterList, ioa)
}
log.Functionf("Got adapters %v", appInstance.IoAdapterList)
cmd := cfgApp.GetRestart()
if cmd != nil {
appInstance.RestartCmd.Counter = cmd.Counter
appInstance.RestartCmd.ApplyTime = cmd.OpsTime
}
cmd = cfgApp.GetPurge()
if cmd != nil {
appInstance.PurgeCmd.Counter = cmd.Counter
appInstance.PurgeCmd.ApplyTime = cmd.OpsTime
}
userData := cfgApp.GetUserData()
if userData != "" {
appInstance.CloudInitUserData = &userData
}
appInstance.RemoteConsole = cfgApp.GetRemoteConsole()
appInstance.CipherBlockStatus = parseCipherBlock(getconfigCtx, appInstance.Key(), cfgApp.GetCipherData())
appInstance.ProfileList = cfgApp.ProfileList
// Add config submitted via local profile server.
addLocalAppConfig(getconfigCtx, &appInstance)
// Verify that it fits and if not publish with error
checkAndPublishAppInstanceConfig(getconfigCtx, appInstance)
}
}
func parseSnapshotConfig(appInstanceSnapshot *types.SnapshotConfig, cfgAppSnapshot *zconfig.SnapshotConfig) {
appInstanceSnapshot.ActiveSnapshot = cfgAppSnapshot.ActiveSnapshot
appInstanceSnapshot.MaxSnapshots = cfgAppSnapshot.MaxSnapshots
if cfgAppSnapshot.RollbackCmd != nil {
appInstanceSnapshot.RollbackCmd.ApplyTime = cfgAppSnapshot.RollbackCmd.OpsTime
appInstanceSnapshot.RollbackCmd.Counter = cfgAppSnapshot.RollbackCmd.Counter
}
appInstanceSnapshot.Snapshots = make([]types.SnapshotDesc, len(cfgAppSnapshot.Snapshots))
parseSnapshots(appInstanceSnapshot.Snapshots, cfgAppSnapshot.Snapshots)
}
func parseSnapshots(snapshots []types.SnapshotDesc, cfgSnapshots []*zconfig.SnapshotDesc) {
for i, cfgSnapshot := range cfgSnapshots {
snapshots[i].SnapshotID = cfgSnapshot.Id
snapshots[i].SnapshotType = types.SnapshotType(cfgSnapshot.Type)
}
}
var systemAdaptersPrevConfigHash []byte
func parseSystemAdapterConfig(getconfigCtx *getconfigContext, config *zconfig.EdgeDevConfig,
source configSource, forceParse bool) {
sysAdapters := config.GetSystemAdapterList()
h := sha256.New()
for _, a := range sysAdapters {
computeConfigElementSha(h, a)
}
configHash := h.Sum(nil)
same := bytes.Equal(configHash, systemAdaptersPrevConfigHash)
if same && !forceParse {
return
}
// XXX secrets like wifi credentials in here
if false {
log.Functionf("parseSystemAdapterConfig: Applying updated config "+
"prevSha: % x, "+
"NewSha : % x, "+
"sysAdapters: %v, "+
"Forced parsing: %v",
systemAdaptersPrevConfigHash, configHash, sysAdapters, forceParse)
}
systemAdaptersPrevConfigHash = configHash
// Check if we have any with Uplink/IsMgmt set, in which case we
// infer the version
// XXX should we have a version in the proto file? Will end up with
// a collapsed systemAdapter with network info inlined soon.
version := types.DPCInitial
for _, sysAdapter := range sysAdapters {
if sysAdapter.Uplink {
version = types.DPCIsMgmt
}
}
portConfig := &types.DevicePortConfig{}
portConfig.Version = version
if source == fromBootstrap {
portConfig.Key = "bootstrap" // Instead of "zedagent".
}
var newPorts []*types.NetworkPortConfig
for _, sysAdapter := range sysAdapters {
ports, err := parseOneSystemAdapterConfig(getconfigCtx, sysAdapter, version)
if err != nil {
portConfig.RecordFailure(err.Error())
}
newPorts = append(newPorts, ports...)
}
validateAndAssignNetPorts(portConfig, newPorts)
// Check if all management ports have errors
// Propagate any parse errors for all ports to the DPC
// since controller expects LastError and LastFailed for the DPC
ok := false
mgmtCount := 0
errStr := ""
for _, p := range portConfig.Ports {
if !p.IsMgmt {
continue
}
mgmtCount++
if !p.HasError() {
ok = true
break
}
errStr += p.LastError + "\n"
}
if !ok {
if errStr == "" && portConfig.HasError() {
errStr = portConfig.LastError
}
if errStr != "" {
errStr = "All management ports failed to parse: " + errStr
} else if mgmtCount == 0 {
errStr = "No management interfaces"
} else {
errStr = "All management ports failed parser"
}
portConfig.RecordFailure(errStr)
}
// Any content change?
// Even if only ErrorAndTime changed we publish so
// the change can be sent back to the controller using ctx.devicePortConfigList
if cmp.Equal(getconfigCtx.devicePortConfig.Ports, portConfig.Ports) &&
cmp.Equal(getconfigCtx.devicePortConfig.TestResults, portConfig.TestResults) &&
getconfigCtx.devicePortConfig.Version == portConfig.Version &&
getconfigCtx.devicePortConfig.Key == portConfig.Key {
log.Functionf("parseSystemAdapterConfig: DevicePortConfig - " +
"Done with no change")
return
}
log.Functionf("parseSystemAdapterConfig: version %d/%d differs",
getconfigCtx.devicePortConfig.Version, portConfig.Version)
if config.ConfigTimestamp.IsValid() {
portConfig.TimePriority = config.ConfigTimestamp.AsTime()
} else {
// This is suboptimal after a reboot since the config will be the same
// yet the timestamp be new. HandleDPCModify takes care of that.
portConfig.TimePriority = time.Now()
}
getconfigCtx.devicePortConfig = *portConfig
getconfigCtx.pubDevicePortConfig.Publish("zedagent", *portConfig)
log.Functionf("parseSystemAdapterConfig: Done")
}
// Validate parsed network ports and assign non-duplicates to DevicePortConfig.
func validateAndAssignNetPorts(dpc *types.DevicePortConfig, newPorts []*types.NetworkPortConfig) {
var validatedPorts []*types.NetworkPortConfig
// 1. check for collisions
for _, port := range newPorts {
var skip bool
for _, port2 := range validatedPorts {
// With VLANs the same physicalIO or bond may be used by multiple system adapters.
// So it is OK to get duplicates but they should be completely equal.
if cmp.Equal(port, port2) {
skip = true
break
}
if port.Logicallabel == port2.Logicallabel {
errStr := fmt.Sprintf(
"Port collides with another port with the same logical label (%s)",
port.Logicallabel)
log.Error(errStr)
port.RecordFailure(errStr)
port2.RecordFailure(errStr)
break
}
if port.IfName != "" && port.IfName == port2.IfName {
errStr := fmt.Sprintf(
"Port collides with another port with the same interface name (%s)",
port.IfName)
log.Error(errStr)
port.RecordFailure(errStr)
port2.RecordFailure(errStr)
break
}
}
if skip {
continue
}
validatedPorts = append(validatedPorts, port)
}
// 2. validate L2 references
type l2References struct {
vlanSubIntfs []*types.NetworkPortConfig
bondMasters []*types.NetworkPortConfig
}
// key = logical name, value = inverted references from higher layers
invertedRefs := make(map[string]*l2References)
// build map of inverted L2 references, used for validation purposes below
for _, port := range validatedPorts {
switch port.L2LinkConfig.L2Type {
case types.L2LinkTypeVLAN:
parent := port.L2LinkConfig.VLAN.ParentPort
if _, exist := invertedRefs[parent]; !exist {
invertedRefs[parent] = &l2References{}
}
l2Refs := invertedRefs[parent]
l2Refs.vlanSubIntfs = append(l2Refs.vlanSubIntfs, port)
case types.L2LinkTypeBond:
aggrPorts := port.L2LinkConfig.Bond.AggregatedPorts
for _, aggrPort := range aggrPorts {
if _, exist := invertedRefs[aggrPort]; !exist {
invertedRefs[aggrPort] = &l2References{}
}
l2Refs := invertedRefs[aggrPort]
l2Refs.bondMasters = append(l2Refs.bondMasters, port)
}
}
}
for _, port := range validatedPorts {
l2Refs := invertedRefs[port.Logicallabel]
if l2Refs == nil {
continue
}
if len(l2Refs.bondMasters) > 1 {
errStr := fmt.Sprintf(
"Port %s is aggregated by multiple bond interfaces (%s, %s, ...)",
port.Logicallabel,
l2Refs.bondMasters[0].Logicallabel,
l2Refs.bondMasters[1].Logicallabel)
log.Error(errStr)
port.RecordFailure(errStr)
continue
}
if len(l2Refs.bondMasters) > 0 && len(l2Refs.vlanSubIntfs) > 0 {
errStr := fmt.Sprintf(
"Port %s is referenced by both bond (%s) and VLAN (%s)",
port.Logicallabel, l2Refs.bondMasters[0].Logicallabel,
l2Refs.vlanSubIntfs[0].Logicallabel)
log.Error(errStr)
port.RecordFailure(errStr)
continue
}
for i, vlanSubIntf := range l2Refs.vlanSubIntfs {
for j := 0; j < i; j++ {
if vlanSubIntf.VLAN.ID == l2Refs.vlanSubIntfs[j].VLAN.ID {
errStr := fmt.Sprintf(
"Port %s has duplicate VLAN sub-interfaces (VLAN ID = %d)",
port.Logicallabel, vlanSubIntf.VLAN.ID)
log.Error(errStr)
port.RecordFailure(errStr)
continue
}
}
}
}
// 3. Propagate errors up to system adapters
propagateFrom := validatedPorts
for len(propagateFrom) > 0 {
var propagateFromNext []*types.NetworkPortConfig
for _, port := range propagateFrom {
if port.IsL3Port || !port.HasError() {
continue
}
l2Refs := invertedRefs[port.Logicallabel]
if l2Refs == nil {
continue
}
for _, vlanSubIntf := range l2Refs.vlanSubIntfs {
if !vlanSubIntf.HasError() {
propagateError(vlanSubIntf, port)
propagateFromNext = append(propagateFromNext, vlanSubIntf)
}
}
for _, bondMaster := range l2Refs.bondMasters {
if !bondMaster.HasError() {
propagateError(bondMaster, port)
propagateFromNext = append(propagateFromNext, bondMaster)
}
}
}
propagateFrom = propagateFromNext
}
// 4. Assign all non-duplicate, validated ports.
for _, port := range validatedPorts {
dpc.Ports = append(dpc.Ports, *port)
}
}
// Propagate error from a lower-layer adapter to a higher-layer adapter.
func propagateError(higherLayerPort, lowerLayerPort *types.NetworkPortConfig) {
if lowerLayerPort.HasError() {
// Inherit error from the lower-layer adapter if there is any
errStr := fmt.Sprintf("Lower-layer adapter %s has an error (%s)",
lowerLayerPort.Logicallabel, lowerLayerPort.LastError)
higherLayerPort.RecordFailure(errStr)
}
}
func propagatePhyioAttrsToPort(port *types.NetworkPortConfig, phyio *types.PhysicalIOAdapter) {
port.Phylabel = phyio.Phylabel
port.IfName = phyio.Phyaddr.Ifname
port.USBAddr = phyio.Phyaddr.UsbAddr
port.PCIAddr = phyio.Phyaddr.PciLong
if port.IfName == "" {
// Inside device model, network adapter may be referenced by PCI or USB address
// instead of the interface name. In fact, with multiple network ports, interface naming
// is not necessary deterministic and may depend on the order of network adapter
// initialization and discovery by the kernel.
// Moreover, once EVE supports userspace vswitch, interface names of ports will differ
// depending on if they are assigned to the kernel or vswitch.
// For the reasons above, it is preferred to reference network adapters by PCI/USB
// addresses going forward.
// For now, we will allow network port configs without interface name at least for
// cellular modems.
// TODO: Allow any type of network port to be defined in PhysicalIOAdapter without
// interface name.
switch types.IoType(phyio.Ptype) {
case types.IoNetWWAN:
if port.USBAddr == "" && port.PCIAddr == "" {
log.Warnf("Physical IO %s (Phylabel %s) has no physical address",
phyio.Logicallabel, phyio.Phylabel)
handleMissingIfname(port, phyio)
}
default:
log.Warnf("Physical IO %s (Phylabel %s) has no ifname",
phyio.Logicallabel, phyio.Phylabel)
handleMissingIfname(port, phyio)
}
}
}
func handleMissingIfname(port *types.NetworkPortConfig, phyio *types.PhysicalIOAdapter) {
// Try to use logical or physical label as interface name.
// If such interface name is not valid, NIM will report error in DeviceNetworkStatus
// under the port's TestResults.
if phyio.Logicallabel != "" {
port.IfName = phyio.Logicallabel
} else {