-
Notifications
You must be signed in to change notification settings - Fork 164
/
zedagent.go
2731 lines (2428 loc) · 86.8 KB
/
zedagent.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
// zedAgent interfaces with zedcloud for
// * config sync
// * metric/info publish
// app instance config is published to zedmanager for orchestration
// baseos/certs config is published to baseosmgr for orchestration
// datastore config is published for downloader consideration
// event based baseos/app instance/device info published to ZedCloud
// periodic status/metric published to zedCloud
// zedagent handles the following configuration
// * app instance config/status <zedagent> / <appimg> / <config | status>
// * base os config/status <zedagent> / <baseos> / <config | status>
// * certs config/status <zedagent> / certs> / <config | status>
// <base os>
// <zedagent> <baseos> <config> --> <baseosmgr> <baseos> <status>
// <certs>
// <zedagent> <certs> <config> --> <baseosmgr> <certs> <status>
// <app image>
// <zedagent> <appimage> <config> --> <zedmanager> <appimage> <status>
// <datastore>
// <zedagent> <datastore> <config> --> <downloader>
package zedagent
import (
"bytes"
"flag"
"fmt"
"os"
"time"
"github.com/eriknordmark/ipinfo"
"github.com/google/go-cmp/cmp"
"github.com/lf-edge/eve-api/go/attest"
"github.com/lf-edge/eve-api/go/flowlog"
"github.com/lf-edge/eve-api/go/info"
"github.com/lf-edge/eve/pkg/pillar/agentbase"
"github.com/lf-edge/eve/pkg/pillar/agentlog"
"github.com/lf-edge/eve/pkg/pillar/base"
"github.com/lf-edge/eve/pkg/pillar/netdump"
"github.com/lf-edge/eve/pkg/pillar/pubsub"
"github.com/lf-edge/eve/pkg/pillar/types"
"github.com/lf-edge/eve/pkg/pillar/zedcloud"
uuid "github.com/satori/go.uuid"
"github.com/sirupsen/logrus"
)
const (
agentName = "zedagent"
restartCounterFile = types.PersistStatusDir + "/restartcounter"
lastDevCmdTimestampFile = types.PersistStatusDir + "/lastdevcmdtimestamp"
// checkpointDirname - location of config checkpoint
checkpointDirname = types.PersistDir + "/checkpoint"
// Time limits for event loop handlers
errorTime = 3 * time.Minute
warningTime = 40 * time.Second
// Maximum allowed number of flow messages enqueued and waiting to be published.
flowlogQueueCap = 100
// Factor by which the dormant time needs to be scaled up.
dormantTimeScaleFactor = 3
)
// XXX move to a context? Which? Used in handleconfig and handlemetrics!
var deviceNetworkStatus = &types.DeviceNetworkStatus{}
// XXX globals filled in by subscription handlers and read by handlemetrics
// XXX could alternatively access sub object when adding them.
var clientMetrics types.MetricsMap
var loguploaderMetrics types.MetricsMap
var newlogMetrics types.NewlogMetrics
var downloaderMetrics types.MetricsMap
var networkMetrics types.NetworkMetrics
var cipherMetricsDL types.CipherMetrics
var cipherMetricsDM types.CipherMetrics
var cipherMetricsNim types.CipherMetrics
var cipherMetricsZR types.CipherMetrics
var cipherMetricsWwan types.CipherMetrics
var diagMetrics types.MetricsMap
var nimMetrics types.MetricsMap
var zrouterMetrics types.MetricsMap
// Context for handleDNSModify
type DNSContext struct {
DNSinitialized bool // Received DeviceNetworkStatus
subDeviceNetworkStatus pubsub.Subscription
triggerGetConfig bool
triggerDeviceInfo bool
triggerHandleDeferred bool
triggerRadioPOST bool
}
type zedagentContext struct {
agentbase.AgentBase
ps *pubsub.PubSub
getconfigCtx *getconfigContext // Cross link
cipherCtx *cipherContext // Cross link
attestCtx *attestContext // Cross link
dnsCtx *DNSContext
assignableAdapters *types.AssignableAdapters
subAssignableAdapters pubsub.Subscription
iteration int
subNetworkInstanceStatus pubsub.Subscription
subCertObjConfig pubsub.Subscription
flowlogQueue chan<- *flowlog.FlowMessage
triggerDeviceInfo chan<- destinationBitset
triggerHwInfo chan<- destinationBitset
triggerLocationInfo chan<- destinationBitset
triggerNTPSourcesInfo chan<- destinationBitset
triggerObjectInfo chan<- infoForObjectKey
zbootRestarted bool // published by baseosmgr
subOnboardStatus pubsub.Subscription
subBaseOsStatus pubsub.Subscription
subBaseOsMgrStatus pubsub.Subscription
subNetworkInstanceMetrics pubsub.Subscription
subAppFlowMonitor pubsub.Subscription
pubGlobalConfig pubsub.Publication
pubMetricsMap pubsub.Publication
subGlobalConfig pubsub.Subscription
subEdgeNodeCert pubsub.Subscription
subVaultStatus pubsub.Subscription
subAttestQuote pubsub.Subscription
subEncryptedKeyFromDevice pubsub.Subscription
subNewlogMetrics pubsub.Subscription
subBlobStatus pubsub.Subscription
GCInitialized bool // Received initial GlobalConfig
subZbootStatus pubsub.Subscription
subAppContainerMetrics pubsub.Subscription
subDiskMetric pubsub.Subscription
subAppDiskMetric pubsub.Subscription
subCapabilities pubsub.Subscription
subAppInstMetaData pubsub.Subscription
subWwanMetrics pubsub.Subscription
subWwanStatus pubsub.Subscription
subLocationInfo pubsub.Subscription
subZFSPoolStatus pubsub.Subscription
subZFSPoolMetrics pubsub.Subscription
subEdgeviewStatus pubsub.Subscription
subNetworkMetrics pubsub.Subscription
subClientMetrics pubsub.Subscription
subLoguploaderMetrics pubsub.Subscription
subDownloaderMetrics pubsub.Subscription
subDiagMetrics pubsub.Subscription
subNimMetrics pubsub.Subscription
subZRouterMetrics pubsub.Subscription
subCipherMetricsDL pubsub.Subscription
subCipherMetricsDM pubsub.Subscription
subCipherMetricsNim pubsub.Subscription
subCipherMetricsZR pubsub.Subscription
subCipherMetricsWwan pubsub.Subscription
subPatchEnvelopeUsage pubsub.Subscription
zedcloudMetrics *zedcloud.AgentMetrics
fatalFlag bool // From command line arguments
hangFlag bool // From command line arguments
rebootCmd bool
rebootCmdDeferred bool
deviceReboot bool // From nodeagent
shutdownCmd bool
shutdownCmdDeferred bool
deviceShutdown bool // From nodeagent
poweroffCmd bool
poweroffCmdDeferred bool
devicePoweroff bool // From nodeagent
allDomainsHalted bool
requestedRebootReason string // Set by zedagent
requestedBootReason types.BootReason // Set by zedagent
rebootReason string // Previous reboot from nodeagent
bootReason types.BootReason // Previous reboot from nodeagent
rebootStack string // Previous reboot from nodeagent
rebootTime time.Time // Previous reboot from nodeagent
// restartCounter - counts number of reboots of the device by Eve
restartCounter uint32
// rebootConfigCounter - reboot counter sent by the cloud in its config.
// This is the value of counter that triggered reboot. This is sent in
// device info msg. Can be used to verify device is caught up on all
// outstanding reboot commands from cloud.
rebootConfigCounter uint32
shutdownConfigCounter uint32
// Part of the fields above (the reboot ones) are initialized only once the NodeAgent status is received
// This flag is used to make sure we initialize them before continuing with the rest of the agent's initialization
initializedFromNodeAgentStatus bool
subDevicePortConfigList pubsub.Subscription
DevicePortConfigList *types.DevicePortConfigList
remainingTestTime time.Duration
physicalIoAdapterMap map[string]types.PhysicalIOAdapter
globalConfig types.ConfigItemValueMap
globalConfigPublished bool // was last globalConfig successfully published
specMap types.ConfigItemSpecMap
globalStatus types.GlobalStatus
flowLogMetrics types.FlowlogMetrics
appContainerStatsTime time.Time // last time the App Container stats uploaded
// The MaintenanceMode can come from GlobalConfig and from the config
// API. Those are merged into maintenanceMode
// TBD will be also decide locally to go into maintenanceMode based
// on out of disk space etc?
maintenanceMode bool //derived state, after consolidating all inputs
maintModeReason types.MaintenanceModeReason //reason for setting derived maintenance mode
gcpMaintenanceMode types.TriState
apiMaintenanceMode bool
localMaintenanceMode bool //maintenance mode triggered by local failure
localMaintModeReason types.MaintenanceModeReason //local failure reason for maintenance mode
devState types.DeviceState
attestState types.AttestState
attestError string
vaultStatus info.DataSecAtRestStatus
pcrStatus info.PCRStatus
vaultErr string
// Track the counter from force.fallback.counter to detect changes
forceFallbackCounter int
// Used for retry of EdgeNodeCerts
publishedEdgeNodeCerts bool
// Used for retry of SendAttestEscrow
publishedAttestEscrow bool
attestationTryCount int
// cli options
parsePtr *string
validatePtr *bool
fatalPtr *bool
hangPtr *bool
// Is Kubevirt eve
hvTypeKube bool
// Netdump
netDumper *netdump.NetDumper // nil if netdump is disabled
netdumpInterval time.Duration
lastConfigNetdumpPub time.Time // last call to publishConfigNetdump
lastInfoNetdumpPub time.Time // last call to publishInfoNetdump
startTime time.Time
}
// AddAgentSpecificCLIFlags adds CLI options
func (zedagentCtx *zedagentContext) AddAgentSpecificCLIFlags(flagSet *flag.FlagSet) {
zedagentCtx.parsePtr = flagSet.String("p", "", "parse checkpoint file")
zedagentCtx.validatePtr = flagSet.Bool("V", false, "validate UTF-8 in checkpoint")
zedagentCtx.fatalPtr = flagSet.Bool("F", false, "Cause log.Fatal fault injection")
zedagentCtx.hangPtr = flagSet.Bool("H", false, "Cause watchdog .touch fault injection")
}
var logger *logrus.Logger
var log *base.LogObject
var zedcloudCtx *zedcloud.ZedCloudContext
// Destination bitset as unsigned integer
type destinationBitset uint
// Destination types, where info should be sent
const (
ControllerDest destinationBitset = (1 << 0)
LPSDest = (1 << 1)
LOCDest = (1 << 2)
AllDest = ControllerDest | LPSDest | LOCDest
// Request should be send in any case
ForceSend = (1 << 8)
)
// queueInfoToDest - queues "info" requests according to the specified
//
// destination. Once deferred item has been added the queue is kicked
// to start processing requests immediately from a separate task.
//
// @forcePeriodic forces all deferred requests to be added
// to the deferred queue and errors will be ignored.
func queueInfoToDest(ctx *zedagentContext, dest destinationBitset,
key string, buf *bytes.Buffer, size int64, bailOnHTTPErr,
withNetTracing, forcePeriodic bool, itemType interface{}) {
locConfig := ctx.getconfigCtx.sideController.locConfig
if dest&ControllerDest != 0 {
url := zedcloud.URLPathString(serverNameAndPort, zedcloudCtx.V2API,
devUUID, "info")
// Ignore all errors in case of periodic
ignoreErr := forcePeriodic
deferredCtx := zedcloudCtx.DeferredEventCtx
if forcePeriodic {
deferredCtx = zedcloudCtx.DeferredPeriodicCtx
}
deferredCtx.SetDeferred(key, buf, size, url,
bailOnHTTPErr, withNetTracing, ignoreErr, itemType)
}
if dest&LOCDest != 0 && locConfig != nil {
url := zedcloud.URLPathString(locConfig.LocURL, zedcloudCtx.V2API,
devUUID, "info")
// Ignore errors for all the LOC info messages
const ignoreErr = true
zedcloudCtx.DeferredLOCPeriodicCtx.SetDeferred(key, buf, size, url,
bailOnHTTPErr, withNetTracing, ignoreErr, itemType)
}
}
// object to trigger sending of info with infoType for objectKey
type infoForObjectKey struct {
infoType info.ZInfoTypes
objectKey string
infoDest destinationBitset
}
func Run(ps *pubsub.PubSub, loggerArg *logrus.Logger, logArg *base.LogObject, arguments []string, baseDir string) int {
logger = loggerArg
log = logArg
zedagentCtx := &zedagentContext{}
agentbase.Init(zedagentCtx, logger, log, agentName,
agentbase.WithPidFile(),
agentbase.WithBaseDir(baseDir),
agentbase.WithArguments(arguments))
var err error
parse := *zedagentCtx.parsePtr
validate := *zedagentCtx.validatePtr
if validate && parse == "" {
fmt.Printf("Setting -V requires -p\n")
return 1
}
// Initialize zedagent context.
zedagentCtx.init()
zedagentCtx.ps = ps
zedagentCtx.hangFlag = *zedagentCtx.hangPtr
zedagentCtx.fatalFlag = *zedagentCtx.fatalPtr
zedagentCtx.startTime = time.Now()
flowlogQueue := make(chan *flowlog.FlowMessage, flowlogQueueCap)
triggerDeviceInfo := make(chan destinationBitset, 1)
triggerHwInfo := make(chan destinationBitset, 1)
triggerLocationInfo := make(chan destinationBitset, 1)
triggerNTPSourcesInfo := make(chan destinationBitset, 1)
triggerObjectInfo := make(chan infoForObjectKey, 1)
zedagentCtx.flowlogQueue = flowlogQueue
zedagentCtx.triggerDeviceInfo = triggerDeviceInfo
zedagentCtx.triggerHwInfo = triggerHwInfo
zedagentCtx.triggerLocationInfo = triggerLocationInfo
zedagentCtx.triggerNTPSourcesInfo = triggerNTPSourcesInfo
zedagentCtx.triggerObjectInfo = triggerObjectInfo
// Initialize all zedagent publications.
initPublications(zedagentCtx)
// Run a periodic timer so we always update StillRunning
stillRunning := time.NewTicker(25 * time.Second)
ps.StillRunning(agentName, warningTime, errorTime)
initializeDirs()
// Load bootstrap configuration if present.
getconfigCtx := zedagentCtx.getconfigCtx
maybeLoadBootstrapConfig(getconfigCtx)
// Get GlobalConfig.
// If not present (e.g. loading of bootstrap config failed), use default values.
item, err := zedagentCtx.pubGlobalConfig.Get("global")
if err == nil {
zedagentCtx.globalConfig = item.(types.ConfigItemValueMap)
} else {
log.Warnf("GlobalConfig is missing, publishing default values")
zedagentCtx.globalConfig = *types.DefaultConfigItemValueMap()
err = zedagentCtx.pubGlobalConfig.Publish("global", zedagentCtx.globalConfig)
if err != nil {
// Could fail if no space left in the filesystem.
log.Fatalf("Failed to publish default globalConfig: %s", err)
}
}
// GlobalConfig is guaranteed to have been published by this point
// (otherwise the log.Fatalf above exits zedagent).
zedagentCtx.globalConfigPublished = true
log.Noticef("Initialized GlobalConfig: %v", zedagentCtx.globalConfig)
// Apply saved radio config ASAP.
initializeRadioConfig(getconfigCtx)
// Wait until we have been onboarded aka know our own UUID.
// Onboarding is done by client (pillar/cmd/client).
// Activate in the next step so that zedagentCtx.subOnboardStatus is set
// before Modify handler is called by SubscriptionImpl.populate()
// (only needed for persistent subs).
zedagentCtx.subOnboardStatus, err = ps.NewSubscription(pubsub.SubscriptionOptions{
AgentName: "zedclient",
MyAgentName: agentName,
TopicImpl: types.OnboardingStatus{},
Activate: false,
Persistent: true,
Ctx: zedagentCtx,
CreateHandler: handleOnboardStatusCreate,
ModifyHandler: handleOnboardStatusModify,
WarningTime: warningTime,
ErrorTime: errorTime,
})
if err != nil {
log.Fatal(err)
}
zedagentCtx.subOnboardStatus.Activate()
if parse == "" {
waitUntilOnboarded(zedagentCtx, stillRunning)
}
// Netdumper uses different publish period after onboarding.
reinitNetdumper(zedagentCtx)
// We know our own UUID; prepare for communication with controller
zedcloudCtx = initZedcloudContext(getconfigCtx,
zedagentCtx.globalConfig.GlobalValueInt(types.NetworkSendTimeout),
zedagentCtx.globalConfig.GlobalValueInt(types.NetworkDialTimeout),
zedagentCtx.zedcloudMetrics)
if parse != "" {
res, config := readValidateConfig(parse)
if !res {
fmt.Printf("Failed to parse %s\n", parse)
return 1
}
fmt.Printf("parsed proto <%v>\n", config)
if validate {
valid := validateConfigUTF8(config)
if !valid {
fmt.Printf("Found some invalid UTF-8\n")
return 1
}
}
return 0
}
// Timer for deferred sends of info messages
zedcloudCtx.DeferredEventCtx = zedcloud.CreateDeferredCtx(zedcloudCtx,
zedagentCtx.ps, agentName, "DeferredEvent",
warningTime, errorTime,
getDeferredSentHandlerFunction(zedagentCtx),
getDeferredPriorityFunctions()...)
zedcloudCtx.DeferredPeriodicCtx = zedcloud.CreateDeferredCtx(zedcloudCtx,
zedagentCtx.ps, agentName, "DeferredPeriodic",
warningTime, errorTime, nil)
zedcloudCtx.DeferredLOCPeriodicCtx = zedcloud.CreateDeferredCtx(zedcloudCtx,
zedagentCtx.ps, agentName, "DeferredLOCPeriodic",
warningTime, errorTime, nil)
// XXX defer this until we have some config from cloud or saved copy
getconfigCtx.pubAppInstanceConfig.SignalRestarted()
// Initialize remote attestation context. Do this before we get events
// from the AttestQuote and EncryptedKeyFromDevice subscriptions
attestModuleInitialize(zedagentCtx)
// With device UUID, zedagent is ready to initialize and activate all subscriptions.
initPostOnboardSubs(zedagentCtx)
// Wait until we initialize the context from node agent status.
// At least we need to be sure the bootReason field is set properly, as it's used during fetching local config,
// when it's necessary (necessary or not is determined exactly by the bootReason).
waitUntilInitializedFromNodeAgentStatus(zedagentCtx, stillRunning)
//initialize cipher processing block
cipherModuleInitialize(zedagentCtx)
// Pick up debug aka log level before we start real work
waitUntilGCReady(zedagentCtx, stillRunning)
// wait till, zboot status is ready
waitUntilZbootReady(zedagentCtx, stillRunning)
// wait until NIM reports Device Network Status
waitUntilDNSReady(zedagentCtx, stillRunning)
// Parse SMART data
go parseSMARTData()
// Use go routines to make sure we have wait/timeout without
// blocking the main select loop
log.Functionf("Creating %s at %s", "deviceInfoTask", agentlog.GetMyStack())
go deviceInfoTask(zedagentCtx, triggerDeviceInfo)
log.Functionf("Creating %s at %s", "objectInfoTask", agentlog.GetMyStack())
go objectInfoTask(zedagentCtx, triggerObjectInfo)
log.Functionf("Creating %s at %s", "flowLogTask", agentlog.GetMyStack())
go flowlogTask(zedagentCtx, flowlogQueue)
log.Functionf("Creating %s at %s", "hardwareInfoTask", agentlog.GetMyStack())
go hardwareInfoTask(zedagentCtx, triggerHwInfo)
// Publish initial device info.
triggerPublishDevInfo(zedagentCtx)
// Publish initial hardware info.
triggerPublishHwInfo(zedagentCtx)
// start the metrics reporting task
handleChannel := make(chan interface{})
log.Functionf("Creating %s at %s", "metricsAndInfoTimerTask", agentlog.GetMyStack())
go metricsAndInfoTimerTask(zedagentCtx, handleChannel)
metricsTickerHandle := <-handleChannel
getconfigCtx.metricsTickerHandle = metricsTickerHandle
// start the location reporting task
log.Functionf("Creating %s at %s", "locationTimerTask", agentlog.GetMyStack())
go locationTimerTask(zedagentCtx, handleChannel, triggerLocationInfo)
getconfigCtx.locationCloudTickerHandle = <-handleChannel
getconfigCtx.locationAppTickerHandle = <-handleChannel
// start the NTP sources reporting task
log.Functionf("Creating %s at %s", "ntpTimerTask", agentlog.GetMyStack())
go ntpSourcesTimerTask(zedagentCtx, handleChannel, triggerNTPSourcesInfo)
getconfigCtx.ntpSourcesTickerHandle = <-handleChannel
//trigger channel for localProfile state machine
getconfigCtx.sideController.localProfileTrigger = make(chan Notify, 1)
//process saved local profile
processSavedProfile(getconfigCtx)
// initialize localInfo
initializeLocalAppInfo(getconfigCtx)
go localAppInfoPOSTTask(getconfigCtx)
initializeLocalCommands(getconfigCtx)
initializeLocalDevCmdTimestamp(getconfigCtx)
initializeLocalDevInfo(getconfigCtx)
go localDevInfoPOSTTask(getconfigCtx)
// start the config fetch tasks, when zboot status is ready
log.Functionf("Creating %s at %s", "configTimerTask", agentlog.GetMyStack())
go configTimerTask(getconfigCtx, handleChannel)
configTickerHandle := <-handleChannel
// XXX close handleChannels?
getconfigCtx.configTickerHandle = configTickerHandle
// start the local profile fetch tasks
log.Functionf("Creating %s at %s", "localProfileTimerTask", agentlog.GetMyStack())
go localProfileTimerTask(handleChannel, getconfigCtx)
localProfileTickerHandle := <-handleChannel
getconfigCtx.localProfileTickerHandle = localProfileTickerHandle
// start task fetching radio config from local server
go radioPOSTTask(getconfigCtx)
// start cipher module tasks
cipherModuleStart(zedagentCtx)
// start remote attestation task
attestModuleStart(zedagentCtx)
// Enter main zedagent event loop.
mainEventLoop(zedagentCtx, stillRunning) // never exits
return 0
}
func waitUntilInitializedFromNodeAgentStatus(ctx *zedagentContext, running *time.Ticker) {
log.Functionf("waitUntilInitializedFromNodeAgentStatus()")
for !ctx.initializedFromNodeAgentStatus {
select {
case change := <-ctx.getconfigCtx.subNodeAgentStatus.MsgChan():
ctx.getconfigCtx.subNodeAgentStatus.ProcessChange(change)
case <-running.C:
}
ctx.ps.StillRunning(agentName, warningTime, errorTime)
}
log.Functionf("waitUntilInitializedFromNodeAgentStatus() done")
}
func (zedagentCtx *zedagentContext) init() {
zedagentCtx.zedcloudMetrics = zedcloud.NewAgentMetrics()
zedagentCtx.specMap = types.NewConfigItemSpecMap()
zedagentCtx.globalConfig = *types.DefaultConfigItemValueMap()
zedagentCtx.globalStatus.ConfigItems = make(
map[string]types.ConfigItemStatus)
zedagentCtx.globalStatus.UpdateItemValuesFromGlobalConfig(
zedagentCtx.globalConfig)
zedagentCtx.globalStatus.UnknownConfigItems = make(
map[string]types.ConfigItemStatus)
rebootConfig := readDeviceOpsCmdConfig(types.DeviceOperationReboot)
if rebootConfig != nil {
zedagentCtx.rebootConfigCounter = rebootConfig.Counter
log.Functionf("Zedagent Run - rebootConfigCounter at init is %d",
zedagentCtx.rebootConfigCounter)
}
shutdownConfig := readDeviceOpsCmdConfig(types.DeviceOperationShutdown)
if shutdownConfig != nil {
zedagentCtx.shutdownConfigCounter = shutdownConfig.Counter
log.Functionf("Zedagent Run - shutdownConfigCounter at init is %d",
zedagentCtx.shutdownConfigCounter)
}
zedagentCtx.physicalIoAdapterMap = make(map[string]types.PhysicalIOAdapter)
// Pick up (mostly static) AssignableAdapters before we report
// any device info
aa := types.AssignableAdapters{}
zedagentCtx.assignableAdapters = &aa
// Initialize context used to get and parse device configuration.
getconfigCtx := &getconfigContext{
// default value of currentMetricInterval
currentMetricInterval: zedagentCtx.globalConfig.GlobalValueInt(types.MetricInterval),
// edge-view configure
configEdgeview: &types.EdgeviewConfig{},
}
getconfigCtx.sideController.localServerMap = &localServerMap{}
cipherCtx := &cipherContext{}
attestCtx := &attestContext{}
dnsCtx := &DNSContext{}
zedagentCtx.dnsCtx = dnsCtx
// Cross links between contexts.
getconfigCtx.zedagentCtx = zedagentCtx
zedagentCtx.getconfigCtx = getconfigCtx
cipherCtx.zedagentCtx = zedagentCtx
zedagentCtx.cipherCtx = cipherCtx
attestCtx.zedagentCtx = zedagentCtx
zedagentCtx.attestCtx = attestCtx
zedagentCtx.hvTypeKube = base.IsHVTypeKube()
}
func initializeDirs() {
// create persistent holder directory
if _, err := os.Stat(types.PersistDir); err != nil {
log.Tracef("Create %s", types.PersistDir)
if err := os.MkdirAll(types.PersistDir, 0700); err != nil {
log.Fatal(err)
}
}
if _, err := os.Stat(types.CertificateDirname); err != nil {
log.Tracef("Create %s", types.CertificateDirname)
if err := os.MkdirAll(types.CertificateDirname, 0700); err != nil {
log.Fatal(err)
}
}
if _, err := os.Stat(checkpointDirname); err != nil {
log.Tracef("Create %s", checkpointDirname)
if err := os.MkdirAll(checkpointDirname, 0700); err != nil {
log.Fatal(err)
}
}
}
func waitUntilOnboarded(zedagentCtx *zedagentContext, stillRunning *time.Ticker) {
nilUUID := uuid.UUID{}
for devUUID == nilUUID {
log.Functionf("Waiting for OnboardStatus UUID")
select {
case change := <-zedagentCtx.subOnboardStatus.MsgChan():
zedagentCtx.subOnboardStatus.ProcessChange(change)
case <-stillRunning.C:
}
zedagentCtx.ps.StillRunning(agentName, warningTime, errorTime)
}
}
func waitUntilGCReady(zedagentCtx *zedagentContext, stillRunning *time.Ticker) {
getconfigCtx := zedagentCtx.getconfigCtx
for !zedagentCtx.GCInitialized {
log.Functionf("Waiting for GCInitialized")
select {
case change := <-zedagentCtx.subOnboardStatus.MsgChan():
zedagentCtx.subOnboardStatus.ProcessChange(change)
case change := <-zedagentCtx.subGlobalConfig.MsgChan():
zedagentCtx.subGlobalConfig.ProcessChange(change)
case change := <-getconfigCtx.subNodeAgentStatus.MsgChan():
getconfigCtx.subNodeAgentStatus.ProcessChange(change)
case <-stillRunning.C:
}
zedagentCtx.ps.StillRunning(agentName, warningTime, errorTime)
}
log.Functionf("processed GlobalConfig")
}
func waitUntilZbootReady(zedagentCtx *zedagentContext, stillRunning *time.Ticker) {
getconfigCtx := zedagentCtx.getconfigCtx
for !zedagentCtx.zbootRestarted {
select {
case change := <-zedagentCtx.subOnboardStatus.MsgChan():
zedagentCtx.subOnboardStatus.ProcessChange(change)
case change := <-zedagentCtx.subZbootStatus.MsgChan():
zedagentCtx.subZbootStatus.ProcessChange(change)
if zedagentCtx.zbootRestarted {
log.Functionf("Zboot reported restarted")
}
case change := <-getconfigCtx.subNodeAgentStatus.MsgChan():
getconfigCtx.subNodeAgentStatus.ProcessChange(change)
case <-stillRunning.C:
// Fault injection
if zedagentCtx.fatalFlag {
log.Fatal("Requested fault injection to cause watchdog")
}
}
if zedagentCtx.hangFlag {
log.Functionf("Requested to not touch to cause watchdog")
} else {
zedagentCtx.ps.StillRunning(agentName, warningTime, errorTime)
}
}
}
func waitUntilDNSReady(zedagentCtx *zedagentContext, stillRunning *time.Ticker) {
getconfigCtx := zedagentCtx.getconfigCtx
dnsCtx := zedagentCtx.dnsCtx
log.Functionf("Waiting until we have DeviceNetworkStatus")
for !dnsCtx.DNSinitialized {
log.Functionf("Waiting for DeviceNetworkStatus %v",
dnsCtx.DNSinitialized)
select {
case change := <-zedagentCtx.subOnboardStatus.MsgChan():
zedagentCtx.subOnboardStatus.ProcessChange(change)
case change := <-zedagentCtx.subGlobalConfig.MsgChan():
zedagentCtx.subGlobalConfig.ProcessChange(change)
case change := <-dnsCtx.subDeviceNetworkStatus.MsgChan():
dnsCtx.subDeviceNetworkStatus.ProcessChange(change)
if dnsCtx.triggerHandleDeferred {
// Connectivity has been restored so kick the queue
// in order to process all deferred requests faster,
// within minute. We don't bother to kick the periodic
// queue, because failed requests will be dropped from
// the queue anyway.
zedcloudCtx.DeferredEventCtx.KickTimerWithinMinute()
dnsCtx.triggerHandleDeferred = false
}
case change := <-zedagentCtx.subAssignableAdapters.MsgChan():
zedagentCtx.subAssignableAdapters.ProcessChange(change)
case change := <-zedagentCtx.subDevicePortConfigList.MsgChan():
zedagentCtx.subDevicePortConfigList.ProcessChange(change)
case change := <-getconfigCtx.subNodeAgentStatus.MsgChan():
getconfigCtx.subNodeAgentStatus.ProcessChange(change)
case change := <-zedagentCtx.subVaultStatus.MsgChan():
zedagentCtx.subVaultStatus.ProcessChange(change)
case change := <-zedagentCtx.subAttestQuote.MsgChan():
zedagentCtx.subAttestQuote.ProcessChange(change)
case change := <-zedagentCtx.subEncryptedKeyFromDevice.MsgChan():
zedagentCtx.subEncryptedKeyFromDevice.ProcessChange(change)
case change := <-getconfigCtx.subAppNetworkStatus.MsgChan():
getconfigCtx.sideController.localServerMap.upToDate = false
getconfigCtx.subAppNetworkStatus.ProcessChange(change)
case change := <-zedagentCtx.subWwanStatus.MsgChan():
zedagentCtx.subWwanStatus.ProcessChange(change)
case change := <-zedagentCtx.subWwanMetrics.MsgChan():
zedagentCtx.subWwanMetrics.ProcessChange(change)
case change := <-zedagentCtx.subLocationInfo.MsgChan():
zedagentCtx.subLocationInfo.ProcessChange(change)
case <-stillRunning.C:
// Fault injection
if zedagentCtx.fatalFlag {
log.Fatal("Requested fault injection to cause watchdog")
}
}
if zedagentCtx.hangFlag {
log.Functionf("Requested to not touch to cause watchdog")
} else {
zedagentCtx.ps.StillRunning(agentName, warningTime, errorTime)
}
}
}
func mainEventLoop(zedagentCtx *zedagentContext, stillRunning *time.Ticker) {
getconfigCtx := zedagentCtx.getconfigCtx
dnsCtx := zedagentCtx.dnsCtx
hwInfoTiker := time.NewTicker(3 * time.Hour)
for {
select {
case change := <-zedagentCtx.subOnboardStatus.MsgChan():
zedagentCtx.subOnboardStatus.ProcessChange(change)
case change := <-zedagentCtx.subZbootStatus.MsgChan():
zedagentCtx.subZbootStatus.ProcessChange(change)
case change := <-zedagentCtx.subGlobalConfig.MsgChan():
zedagentCtx.subGlobalConfig.ProcessChange(change)
case change := <-getconfigCtx.subAppInstanceStatus.MsgChan():
getconfigCtx.subAppInstanceStatus.ProcessChange(change)
case change := <-getconfigCtx.subContentTreeStatus.MsgChan():
getconfigCtx.subContentTreeStatus.ProcessChange(change)
case change := <-getconfigCtx.subVolumeStatus.MsgChan():
getconfigCtx.subVolumeStatus.ProcessChange(change)
case change := <-getconfigCtx.subDomainMetric.MsgChan():
getconfigCtx.subDomainMetric.ProcessChange(change)
case change := <-getconfigCtx.subProcessMetric.MsgChan():
getconfigCtx.subProcessMetric.ProcessChange(change)
case change := <-getconfigCtx.subHostMemory.MsgChan():
getconfigCtx.subHostMemory.ProcessChange(change)
case change := <-zedagentCtx.subBaseOsStatus.MsgChan():
zedagentCtx.subBaseOsStatus.ProcessChange(change)
case change := <-zedagentCtx.subBlobStatus.MsgChan():
zedagentCtx.subBlobStatus.ProcessChange(change)
case change := <-getconfigCtx.subNodeAgentStatus.MsgChan():
getconfigCtx.subNodeAgentStatus.ProcessChange(change)
case change := <-getconfigCtx.subAppNetworkStatus.MsgChan():
getconfigCtx.sideController.localServerMap.upToDate = false
getconfigCtx.subAppNetworkStatus.ProcessChange(change)
case change := <-dnsCtx.subDeviceNetworkStatus.MsgChan():
dnsCtx.subDeviceNetworkStatus.ProcessChange(change)
if dnsCtx.triggerGetConfig {
triggerGetConfig(getconfigCtx.configTickerHandle)
dnsCtx.triggerGetConfig = false
}
if dnsCtx.triggerDeviceInfo {
// IP/DNS in device info could have changed
log.Functionf("NetworkStatus triggered PublishDeviceInfo")
triggerPublishDevInfo(zedagentCtx)
dnsCtx.triggerDeviceInfo = false
}
if dnsCtx.triggerHandleDeferred {
// Connectivity has been restored so kick the queue
// in order to process all deferred requests faster,
// within minute. We don't bother to kick the periodic
// queue, because failed requests will be dropped from
// the queue anyway.
zedcloudCtx.DeferredEventCtx.KickTimerWithinMinute()
dnsCtx.triggerHandleDeferred = false
}
if dnsCtx.triggerRadioPOST {
triggerRadioPOST(getconfigCtx)
dnsCtx.triggerRadioPOST = false
}
case change := <-zedagentCtx.subAssignableAdapters.MsgChan():
zedagentCtx.subAssignableAdapters.ProcessChange(change)
case change := <-zedagentCtx.subNetworkMetrics.MsgChan():
zedagentCtx.subNetworkMetrics.ProcessChange(change)
m, err := zedagentCtx.subNetworkMetrics.Get("global")
if err != nil {
log.Errorf("subNetworkMetrics.Get failed: %s",
err)
} else {
networkMetrics = m.(types.NetworkMetrics)
}
case change := <-zedagentCtx.subClientMetrics.MsgChan():
zedagentCtx.subClientMetrics.ProcessChange(change)
m, err := zedagentCtx.subClientMetrics.Get("global")
if err != nil {
log.Errorf("subClientMetrics.Get failed: %s",
err)
} else {
clientMetrics = m.(types.MetricsMap)
}
case change := <-zedagentCtx.subLoguploaderMetrics.MsgChan():
zedagentCtx.subLoguploaderMetrics.ProcessChange(change)
m, err := zedagentCtx.subLoguploaderMetrics.Get("global")
if err != nil {
log.Errorf("subLoguploaderMetrics.Get failed: %s",
err)
} else {
loguploaderMetrics = m.(types.MetricsMap)
}
case change := <-zedagentCtx.subDiagMetrics.MsgChan():
zedagentCtx.subDiagMetrics.ProcessChange(change)
m, err := zedagentCtx.subDiagMetrics.Get("global")
if err != nil {
log.Errorf("subDiagMetrics.Get failed: %s",
err)
} else {
diagMetrics = m.(types.MetricsMap)
}
case change := <-zedagentCtx.subNimMetrics.MsgChan():
zedagentCtx.subNimMetrics.ProcessChange(change)
m, err := zedagentCtx.subNimMetrics.Get("global")
if err != nil {
log.Errorf("subNimMetrics.Get failed: %s",
err)
} else {
nimMetrics = m.(types.MetricsMap)
}
case change := <-zedagentCtx.subZRouterMetrics.MsgChan():
zedagentCtx.subZRouterMetrics.ProcessChange(change)
m, err := zedagentCtx.subZRouterMetrics.Get("global")
if err != nil {
log.Errorf("subZRouterMetrics.Get failed: %s",
err)
} else {
zrouterMetrics = m.(types.MetricsMap)
}
case change := <-zedagentCtx.subNewlogMetrics.MsgChan():
zedagentCtx.subNewlogMetrics.ProcessChange(change)
m, err := zedagentCtx.subNewlogMetrics.Get("global")
if err != nil {
log.Errorf("subNewlogMetrics.Get failed: %s",
err)
} else {
newlogMetrics = m.(types.NewlogMetrics)
}
case change := <-zedagentCtx.subDownloaderMetrics.MsgChan():
zedagentCtx.subDownloaderMetrics.ProcessChange(change)
m, err := zedagentCtx.subDownloaderMetrics.Get("global")
if err != nil {
log.Errorf("subDownloaderMetrics.Get failed: %s",
err)
} else {
downloaderMetrics = m.(types.MetricsMap)
}
case change := <-zedagentCtx.subCipherMetricsDL.MsgChan():
zedagentCtx.subCipherMetricsDL.ProcessChange(change)
m, err := zedagentCtx.subCipherMetricsDL.Get("global")
if err != nil {
log.Errorf("subCipherMetricsDL.Get failed: %s",
err)
} else {
cipherMetricsDL = m.(types.CipherMetrics)
}
case change := <-zedagentCtx.subCipherMetricsDM.MsgChan():
zedagentCtx.subCipherMetricsDM.ProcessChange(change)
m, err := zedagentCtx.subCipherMetricsDM.Get("global")
if err != nil {
log.Errorf("subCipherMetricsDM.Get failed: %s",
err)
} else {
cipherMetricsDM = m.(types.CipherMetrics)
}
case change := <-zedagentCtx.subCipherMetricsNim.MsgChan():
zedagentCtx.subCipherMetricsNim.ProcessChange(change)
m, err := zedagentCtx.subCipherMetricsNim.Get("global")
if err != nil {
log.Errorf("subCipherMetricsNim.Get failed: %s",
err)
} else {
cipherMetricsNim = m.(types.CipherMetrics)
}
case change := <-zedagentCtx.subCipherMetricsZR.MsgChan():
zedagentCtx.subCipherMetricsZR.ProcessChange(change)
m, err := zedagentCtx.subCipherMetricsZR.Get("global")
if err != nil {
log.Errorf("subCipherMetricsZR.Get failed: %s",
err)
} else {
cipherMetricsZR = m.(types.CipherMetrics)
}
case change := <-zedagentCtx.subCipherMetricsWwan.MsgChan():
zedagentCtx.subCipherMetricsWwan.ProcessChange(change)
m, err := zedagentCtx.subCipherMetricsWwan.Get("global")
if err != nil {
log.Errorf("subCipherMetricsWwan.Get failed: %s", err)
} else {
cipherMetricsWwan = m.(types.CipherMetrics)
}
case change := <-zedagentCtx.subNetworkInstanceStatus.MsgChan():
zedagentCtx.subNetworkInstanceStatus.ProcessChange(change)
case change := <-zedagentCtx.subNetworkInstanceMetrics.MsgChan():
zedagentCtx.subNetworkInstanceMetrics.ProcessChange(change)
case change := <-zedagentCtx.subDevicePortConfigList.MsgChan():
zedagentCtx.subDevicePortConfigList.ProcessChange(change)
case change := <-zedagentCtx.subAppFlowMonitor.MsgChan():
log.Tracef("FlowStats: change called")
zedagentCtx.subAppFlowMonitor.ProcessChange(change)
case change := <-zedagentCtx.subEdgeNodeCert.MsgChan():
zedagentCtx.subEdgeNodeCert.ProcessChange(change)