-
Notifications
You must be signed in to change notification settings - Fork 156
/
reportinfo.go
1372 lines (1260 loc) · 47.1 KB
/
reportinfo.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) 2020 Zededa, Inc.
// SPDX-License-Identifier: Apache-2.0
// Pushes info to zedcloud
package zedagent
import (
"bytes"
"encoding/json"
"fmt"
"os"
"strings"
"time"
"github.com/containerd/containerd/mount"
"github.com/eriknordmark/ipinfo"
"github.com/golang/protobuf/ptypes"
"github.com/lf-edge/eve-api/go/evecommon"
"github.com/lf-edge/eve-api/go/info"
etpm "github.com/lf-edge/eve/pkg/pillar/evetpm"
"github.com/lf-edge/eve/pkg/pillar/hardware"
"github.com/lf-edge/eve/pkg/pillar/netclone"
"github.com/lf-edge/eve/pkg/pillar/netdump"
"github.com/lf-edge/eve/pkg/pillar/types"
"github.com/lf-edge/eve/pkg/pillar/utils"
fileutils "github.com/lf-edge/eve/pkg/pillar/utils/file"
"github.com/lf-edge/eve/pkg/pillar/utils/persist"
"github.com/lf-edge/eve/pkg/pillar/vault"
uuid "github.com/satori/go.uuid"
"github.com/shirou/gopsutil/host"
"golang.org/x/sys/unix"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/timestamppb"
)
const (
// Topic for zedagent netdumps of successful info msg publications.
netDumpInfoOKTopic = agentName + "-info-ok"
// Topic for zedagent netdumps of failed info msg publications.
netDumpInfoFailTopic = agentName + "-info-fail"
)
var (
nilIPInfo = ipinfo.IPInfo{}
smartData = types.NewSmartDataWithDefaults()
maxSmartCtlSize = 65536 // Limit size of smartctl output files
)
func deviceInfoTask(ctxPtr *zedagentContext, triggerDeviceInfo <-chan destinationBitset) {
wdName := agentName + "devinfo"
// Run a periodic timer so we always update StillRunning
stillRunning := time.NewTicker(25 * time.Second)
ctxPtr.ps.StillRunning(wdName, warningTime, errorTime)
ctxPtr.ps.RegisterFileWatchdog(wdName)
for {
select {
case dest := <-triggerDeviceInfo:
start := time.Now()
log.Function("deviceInfoTask got message")
PublishDeviceInfoToZedCloud(ctxPtr, dest)
ctxPtr.iteration++
log.Function("deviceInfoTask done with message")
ctxPtr.ps.CheckMaxTimeTopic(wdName, "PublishDeviceInfo", start,
warningTime, errorTime)
case <-stillRunning.C:
}
ctxPtr.ps.StillRunning(wdName, warningTime, errorTime)
}
}
// objectInfoTask publishes info for objects, identified by key and type coming from the channel
func objectInfoTask(ctxPtr *zedagentContext, triggerInfo <-chan infoForObjectKey) {
wdName := agentName + "objectinfo"
// Run a periodic timer so we always update StillRunning
stillRunning := time.NewTicker(25 * time.Second)
ctxPtr.ps.StillRunning(wdName, warningTime, errorTime)
ctxPtr.ps.RegisterFileWatchdog(wdName)
for {
select {
case infoForKeyMessage := <-triggerInfo:
infoType := infoForKeyMessage.infoType
infoDest := infoForKeyMessage.infoDest
log.Functionf("objectInfoTask got message for %s", infoType.String())
start := time.Now()
var err error
var c interface{}
switch infoType {
case info.ZInfoTypes_ZiDevice:
// publish device info
PublishDeviceInfoToZedCloud(ctxPtr, infoDest)
ctxPtr.iteration++
case info.ZInfoTypes_ZiApp:
// publish application info
sub := ctxPtr.getconfigCtx.subAppInstanceStatus
if c, err = sub.Get(infoForKeyMessage.objectKey); err == nil {
appStatus := c.(types.AppInstanceStatus)
uuidStr := appStatus.Key()
PublishAppInfoToZedCloud(ctxPtr, uuidStr, &appStatus, ctxPtr.assignableAdapters,
ctxPtr.iteration, infoDest)
ctxPtr.iteration++
}
case info.ZInfoTypes_ZiNetworkInstance:
// publish network instance info
sub := ctxPtr.subNetworkInstanceStatus
if c, err = sub.Get(infoForKeyMessage.objectKey); err == nil {
niStatus := c.(types.NetworkInstanceStatus)
prepareAndPublishNetworkInstanceInfoMsg(ctxPtr, niStatus,
false, infoDest)
ctxPtr.iteration++
}
case info.ZInfoTypes_ZiVolume:
// publish volume info
sub := ctxPtr.getconfigCtx.subVolumeStatus
if c, err = sub.Get(infoForKeyMessage.objectKey); err == nil {
volumeStatus := c.(types.VolumeStatus)
uuidStr := volumeStatus.VolumeID.String()
PublishVolumeToZedCloud(ctxPtr, uuidStr, &volumeStatus,
ctxPtr.iteration, infoDest)
ctxPtr.iteration++
}
case info.ZInfoTypes_ZiContentTree:
// publish content tree info
sub := ctxPtr.getconfigCtx.subContentTreeStatus
if c, err = sub.Get(infoForKeyMessage.objectKey); err == nil {
ctStatus := c.(types.ContentTreeStatus)
uuidStr := ctStatus.Key()
PublishContentInfoToZedCloud(ctxPtr, uuidStr, &ctStatus,
ctxPtr.iteration, infoDest)
ctxPtr.iteration++
}
case info.ZInfoTypes_ZiBlobList:
// publish blob info
sub := ctxPtr.subBlobStatus
if c, err = sub.Get(infoForKeyMessage.objectKey); err == nil {
blobStatus := c.(types.BlobStatus)
uuidStr := blobStatus.Key()
PublishBlobInfoToZedCloud(ctxPtr, uuidStr, &blobStatus,
ctxPtr.iteration, infoDest)
ctxPtr.iteration++
}
case info.ZInfoTypes_ZiAppInstMetaData:
// publish appInst metadata info
sub := ctxPtr.subAppInstMetaData
if c, err = sub.Get(infoForKeyMessage.objectKey); err == nil {
appInstMetaData := c.(types.AppInstMetaData)
PublishAppInstMetaDataToZedCloud(ctxPtr, &appInstMetaData,
false, infoDest)
ctxPtr.iteration++
}
case info.ZInfoTypes_ZiHardware:
PublishHardwareInfoToZedCloud(ctxPtr, infoDest)
ctxPtr.iteration++
case info.ZInfoTypes_ZiEdgeview:
// publish Edgeview info
sub := ctxPtr.subEdgeviewStatus
if c, err = sub.Get(infoForKeyMessage.objectKey); err == nil {
evStatus := c.(types.EdgeviewStatus)
PublishEdgeviewToZedCloud(ctxPtr, &evStatus, infoDest)
}
case info.ZInfoTypes_ZiLocation:
locInfo := getLocationInfo(ctxPtr)
if locInfo != nil {
// Note that we use a zero iteration
// counter here.
publishLocationToDest(ctxPtr, locInfo, 0, infoDest)
}
}
if err != nil {
log.Functionf("objectInfoTask not found %s for key %s: %s",
infoType.String(), infoForKeyMessage.objectKey, err)
}
log.Function("objectInfoTask done with message")
ctxPtr.ps.CheckMaxTimeTopic(wdName, "PublishInfo", start,
warningTime, errorTime)
case <-stillRunning.C:
}
ctxPtr.ps.StillRunning(wdName, warningTime, errorTime)
}
}
func fillStorageChildren(children []*types.StorageChildren) []*info.StorageChildren {
var infoChildren []*info.StorageChildren
for _, child := range children {
childInfo := new(info.StorageChildren)
childInfo.CurrentRaid = info.StorageRaidType(child.CurrentRaid)
childInfo.GUID = child.GUID
childInfo.DisplayName = child.DisplayName
for _, disk := range child.Disks {
diskInfo := new(info.StorageDiskState)
diskInfo.Status = info.StorageStatus(disk.Status)
if disk.DiskName != nil {
diskInfo.DiskName = new(evecommon.DiskDescription)
diskInfo.DiskName.Name = disk.DiskName.Name
diskInfo.DiskName.LogicalName = disk.DiskName.LogicalName
diskInfo.DiskName.Serial = disk.DiskName.Serial
}
childInfo.Disks = append(childInfo.Disks, diskInfo)
}
childInfo.Children = fillStorageChildren(child.Children)
infoChildren = append(infoChildren, childInfo)
}
return infoChildren
}
// PublishDeviceInfoToZedCloud This function is called per change, hence needs to try over all management ports
func PublishDeviceInfoToZedCloud(ctx *zedagentContext, dest destinationBitset) {
aa := ctx.assignableAdapters
subBaseOsStatus := ctx.subBaseOsStatus
var ReportInfo = &info.ZInfoMsg{}
deviceType := new(info.ZInfoTypes)
*deviceType = info.ZInfoTypes_ZiDevice
ReportInfo.Ztype = *deviceType
deviceUUID := devUUID.String()
ReportInfo.DevId = *proto.String(deviceUUID)
ReportInfo.AtTimeStamp = ptypes.TimestampNow()
log.Functionf("PublishDeviceInfoToZedCloud uuid %s", deviceUUID)
ReportDeviceInfo := new(info.ZInfoDevice)
// Get the remote access status
ReportDeviceInfo.RemoteAccessDisabled = utils.RemoteAccessDisabled()
var uname unix.Utsname
err := unix.Uname(&uname)
if err != nil {
log.Errorf("get info from uname failed %s", err)
} else {
ReportDeviceInfo.MachineArch = *proto.String(unix.ByteSliceToString(uname.Machine[:]))
ReportDeviceInfo.CpuArch = *proto.String(unix.ByteSliceToString(uname.Machine[:]))
ReportDeviceInfo.Platform = *proto.String(unix.ByteSliceToString(uname.Machine[:]))
}
sub := ctx.getconfigCtx.subHostMemory
m, _ := sub.Get("global")
if m != nil {
metric := m.(types.HostMemory)
ReportDeviceInfo.Ncpu = *proto.Uint32(metric.Ncpus)
ReportDeviceInfo.Memory = *proto.Uint64(metric.TotalMemoryMB)
}
ReportDeviceInfo.PowerCycleCounter = smartData.PowerCycleCount
// Find all disks and partitions
for _, diskMetric := range getAllDiskMetrics(ctx) {
var diskPath, mountPath string
if diskMetric.IsDir {
mountPath = diskMetric.DiskPath
} else {
diskPath = diskMetric.DiskPath
}
is := info.ZInfoStorage{
Device: diskPath,
MountPath: mountPath,
Total: utils.RoundToMbytes(diskMetric.TotalBytes),
}
if diskMetric.DiskPath == types.PersistDir {
is.StorageLocation = true
ReportDeviceInfo.Storage += *proto.Uint64(utils.RoundToMbytes(diskMetric.TotalBytes))
}
ReportDeviceInfo.StorageList = append(ReportDeviceInfo.StorageList, &is)
}
ReportDeviceManufacturerInfo := new(info.ZInfoManufacturer)
productManufacturer, productName, productVersion, productSerial, productUUID := hardware.GetDeviceManufacturerInfo(log)
ReportDeviceManufacturerInfo.Manufacturer = *proto.String(strings.TrimSpace(productManufacturer))
ReportDeviceManufacturerInfo.ProductName = *proto.String(strings.TrimSpace(productName))
ReportDeviceManufacturerInfo.Version = *proto.String(strings.TrimSpace(productVersion))
ReportDeviceManufacturerInfo.SerialNumber = *proto.String(strings.TrimSpace(productSerial))
ReportDeviceManufacturerInfo.UUID = *proto.String(strings.TrimSpace(productUUID))
biosVendor, biosVersion, biosReleaseDate := hardware.GetDeviceBios(log)
ReportDeviceManufacturerInfo.BiosVendor = *proto.String(strings.TrimSpace(biosVendor))
ReportDeviceManufacturerInfo.BiosVersion = *proto.String(strings.TrimSpace(biosVersion))
ReportDeviceManufacturerInfo.BiosReleaseDate = *proto.String(strings.TrimSpace(biosReleaseDate))
compatible := hardware.GetCompatible(log)
ReportDeviceManufacturerInfo.Compatible = *proto.String(compatible)
ReportDeviceInfo.Minfo = ReportDeviceManufacturerInfo
ReportDeviceInfo.BaseosUpdateCounter = getBaseosUpdateCounter(ctx)
// Report BaseOs Status for the two partitions
getBaseOsStatus := func(partLabel string) *types.BaseOsStatus {
// Look for a matching IMGA/IMGB in baseOsStatus
items := subBaseOsStatus.GetAll()
for _, st := range items {
bos := st.(types.BaseOsStatus)
if bos.PartitionLabel == partLabel {
return &bos
}
}
return nil
}
getSwInfo := func(partLabel string) *info.ZInfoDevSW {
swInfo := new(info.ZInfoDevSW)
tooEarly := false
if bos := getBaseOsStatus(partLabel); bos != nil {
// Get current state/version which is different than
// what is on disk
swInfo.Activated = bos.Activated
swInfo.PartitionLabel = bos.PartitionLabel
swInfo.PartitionDevice = bos.PartitionDevice
swInfo.PartitionState = bos.PartitionState
swInfo.Status = bos.State.ZSwState()
swInfo.ShortVersion = bos.BaseOsVersion
swInfo.LongVersion = "" // XXX
ctInterface, _ := ctx.getconfigCtx.subContentTreeStatus.Get(bos.ContentTreeUUID)
if ctInterface != nil {
ct, ok := ctInterface.(types.ContentTreeStatus)
if ok {
swInfo.DownloadProgress = uint32(ct.Progress)
}
}
if !bos.ErrorTime.IsZero() {
log.Tracef("reportMetrics sending error time %v error %v for %s",
bos.ErrorTime, bos.Error,
bos.BaseOsVersion)
swInfo.SwErr = encodeErrorInfo(bos.ErrorAndTime.ErrorDescription)
}
if swInfo.ShortVersion == "" {
swInfo.Status = info.ZSwState_INITIAL
swInfo.DownloadProgress = 0
}
tooEarly = bos.TooEarly
} else {
partStatus := getZbootPartitionStatus(ctx, partLabel)
swInfo.PartitionLabel = partLabel
if partStatus != nil {
swInfo.Activated = partStatus.CurrentPartition
swInfo.PartitionDevice = partStatus.PartitionDevname
swInfo.PartitionState = partStatus.PartitionState
swInfo.ShortVersion = partStatus.ShortVersion
swInfo.LongVersion = partStatus.LongVersion
}
if swInfo.ShortVersion != "" {
swInfo.Status = info.ZSwState_INSTALLED
swInfo.DownloadProgress = 100
} else {
swInfo.Status = info.ZSwState_INITIAL
swInfo.DownloadProgress = 0
}
}
addUserSwInfo(ctx, swInfo, tooEarly)
return swInfo
}
ReportDeviceInfo.SwList = make([]*info.ZInfoDevSW, 2)
ReportDeviceInfo.SwList[0] = getSwInfo(getZbootCurrentPartition(ctx))
ReportDeviceInfo.SwList[1] = getSwInfo(getZbootOtherPartition(ctx))
// Report any other BaseOsStatus which might have errors
items := subBaseOsStatus.GetAll()
for _, st := range items {
bos := st.(types.BaseOsStatus)
if bos.PartitionLabel != "" {
// Already reported above
continue
}
log.Tracef("reportMetrics sending unattached bos for %s",
bos.BaseOsVersion)
swInfo := new(info.ZInfoDevSW)
swInfo.Status = bos.State.ZSwState()
swInfo.ShortVersion = bos.BaseOsVersion
swInfo.LongVersion = "" // XXX
ctInterface, _ := ctx.getconfigCtx.subContentTreeStatus.Get(bos.ContentTreeUUID)
if ctInterface != nil {
ct, ok := ctInterface.(types.ContentTreeStatus)
if ok {
// Assume one - pick first ContentTreeStatus
swInfo.DownloadProgress = uint32(ct.Progress)
}
}
if !bos.ErrorTime.IsZero() {
log.Tracef("reportMetrics sending error time %v error %v for %s",
bos.ErrorTime, bos.Error, bos.BaseOsVersion)
swInfo.SwErr = encodeErrorInfo(bos.ErrorAndTime.ErrorDescription)
}
addUserSwInfo(ctx, swInfo, bos.TooEarly)
ReportDeviceInfo.SwList = append(ReportDeviceInfo.SwList,
swInfo)
}
// Reporting all zpools in Strorage Info
if persist.ReadPersistType() == types.PersistZFS {
zfsPoolStatusMap := ctx.subZFSPoolStatus.GetAll()
for _, el := range zfsPoolStatusMap {
zfsPoolStatus := el.(types.ZFSPoolStatus)
storageInfo := new(info.StorageInfo)
storageInfo.StorageType = info.StorageTypeInfo_STORAGE_TYPE_INFO_ZFS
storageInfo.PoolName = zfsPoolStatus.PoolName
storageInfo.StorageState = info.StorageStatus(zfsPoolStatus.StorageState)
storageInfo.ZfsVersion = zfsPoolStatus.ZfsVersion
storageInfo.CurrentRaid = info.StorageRaidType(zfsPoolStatus.CurrentRaid)
storageInfo.CompressionRatio = zfsPoolStatus.CompressionRatio
storageInfo.ZpoolSize = zfsPoolStatus.ZpoolSize
storageInfo.CountZvols = zfsPoolStatus.CountZvols
storageInfo.PoolStatusMsg = zfsPoolStatus.PoolStatusMsgStr
storageInfo.CollectorErrors = zfsPoolStatus.CollectorErrors
for _, disk := range zfsPoolStatus.Disks {
diskInfo := new(info.StorageDiskState)
diskInfo.Status = info.StorageStatus(disk.Status)
diskInfo.State = disk.AuxStateStr
if disk.DiskName != nil {
diskInfo.DiskName = new(evecommon.DiskDescription)
diskInfo.DiskName.Name = disk.DiskName.Name
diskInfo.DiskName.LogicalName = disk.DiskName.LogicalName
diskInfo.DiskName.Serial = disk.DiskName.Serial
}
storageInfo.Disks = append(storageInfo.Disks, diskInfo)
}
storageInfo.Children = fillStorageChildren(zfsPoolStatus.Children)
ReportDeviceInfo.StorageInfo = append(ReportDeviceInfo.StorageInfo, storageInfo)
log.Tracef("sending info for ZFS zpool %s", zfsPoolStatus.PoolName)
}
} else {
xStorageInfo := new(info.StorageInfo)
xStorageInfo.StorageType = info.StorageTypeInfo_STORAGE_TYPE_INFO_EXT4
xStorageInfo.PoolName = *proto.String(types.PersistDir)
mi, err := mount.Lookup(types.PersistDir)
if err != nil {
log.Errorf("cannot find device with %s mount", types.PersistDir)
xStorageInfo.StorageState = info.StorageStatus_STORAGE_STATUS_OFFLINE
} else {
// If ext4 is mounted its state is considered online
xStorageInfo.StorageState = info.StorageStatus_STORAGE_STATUS_ONLINE
serialNumber, err := hardware.GetSerialNumberForDisk(mi.Source)
if err != nil {
serialNumber = "unknown"
}
rDiskStatus := new(info.StorageDiskState)
rDiskStatus.DiskName = new(evecommon.DiskDescription)
rDiskStatus.DiskName.Name = *proto.String(mi.Source)
rDiskStatus.DiskName.Serial = *proto.String(serialNumber)
rDiskStatus.Status = info.StorageStatus_STORAGE_STATUS_ONLINE
xStorageInfo.Disks = append(xStorageInfo.Disks, rDiskStatus)
}
ReportDeviceInfo.StorageInfo = append(ReportDeviceInfo.StorageInfo, xStorageInfo)
log.Tracef("report metrics sending info for EXT4 storage type")
}
// We report all the ports in DeviceNetworkStatus
// Note that this is deprecated in favour of SystemAdapterInfo.
for _, p := range deviceNetworkStatus.Ports {
ReportDeviceNetworkInfo := encodeNetInfo(p)
// XXX rename DevName to Logicallabel in proto file
ReportDeviceNetworkInfo.DevName = p.Logicallabel
ReportDeviceInfo.Network = append(ReportDeviceInfo.Network,
ReportDeviceNetworkInfo)
}
// Report all SIM cards and cellular modules, including those not in use.
if statusObj, _ := ctx.subWwanStatus.Get("global"); statusObj != nil {
if status, ok := statusObj.(types.WwanStatus); ok {
for _, cellNet := range status.Networks {
ReportDeviceInfo.CellRadios = append(
ReportDeviceInfo.CellRadios,
encodeCellModuleInfo(cellNet.Module))
ReportDeviceInfo.Sims = append(
ReportDeviceInfo.Sims,
encodeSimCards(cellNet.Module.Name, cellNet.SimCards)...)
}
}
}
// Fill in global ZInfoDNS dns from /etc/resolv.conf
// Note that "domain" is returned in search, hence DNSdomain is
// not filled in.
dc := netclone.DnsReadConfig("/etc/resolv.conf")
log.Tracef("resolv.conf servers %v", dc.Servers)
log.Tracef("resolv.conf search %v", dc.Search)
ReportDeviceInfo.Dns = new(info.ZInfoDNS)
ReportDeviceInfo.Dns.DNSservers = dc.Servers
ReportDeviceInfo.Dns.DNSsearch = dc.Search
// Report AssignableAdapters.
// Domainmgr excludes adapters which do not currently exist in
// what it publishes.
// We also mark current management ports as such.
var seenBundles []string
for _, ib := range aa.IoBundleList {
// Report each group once
seen := false
for _, s := range seenBundles {
if s == ib.AssignmentGroup {
seen = true
break
}
}
if seen && ib.AssignmentGroup != "" {
continue
}
seenBundles = append(seenBundles, ib.AssignmentGroup)
reportAA := new(info.ZioBundle)
reportAA.Type = evecommon.PhyIoType(ib.Type)
reportAA.Name = ib.AssignmentGroup
// XXX - Cast is needed because PhyIoMemberUsage was replicated in info
// When this is fixed, we can remove this case.
reportAA.Usage = evecommon.PhyIoMemberUsage(ib.Usage)
list := aa.LookupIoBundleGroup(ib.AssignmentGroup)
if len(list) == 0 {
if ib.AssignmentGroup != "" {
log.Functionf("Nothing to report for %d %s",
ib.Type, ib.AssignmentGroup)
continue
}
// Singleton
list = append(list, &ib)
}
for _, b := range list {
if b == nil {
continue
}
reportAA.Members = append(reportAA.Members,
b.Logicallabel)
if b.MacAddr != "" {
reportMac := new(info.IoAddresses)
reportMac.MacAddress = b.MacAddr
reportAA.IoAddressList = append(reportAA.IoAddressList,
reportMac)
}
}
if ib.UsedByUUID != nilUUID {
reportAA.UsedByAppUUID = ib.UsedByUUID.String()
} else if ib.KeepInHost {
reportAA.UsedByBaseOS = true
}
if ib.Error != "" {
errInfo := new(info.ErrorInfo)
errInfo.Description = ib.Error
errInfo.Severity = info.Severity_SEVERITY_ERROR
if !ib.ErrorTime.IsZero() {
protoTime, err := ptypes.TimestampProto(ib.ErrorTime)
if err == nil {
errInfo.Timestamp = protoTime
}
}
reportAA.Err = errInfo
}
log.Tracef("AssignableAdapters for %s macs %v",
reportAA.Name, reportAA.IoAddressList)
ReportDeviceInfo.AssignableAdapters = append(ReportDeviceInfo.AssignableAdapters,
reportAA)
}
hinfo, err := host.Info()
if err != nil {
log.Fatalf("host.Info(): %s", err)
}
log.Tracef("uptime %d = %d days",
hinfo.Uptime, hinfo.Uptime/(3600*24))
log.Tracef("Booted at %v", time.Unix(int64(hinfo.BootTime), 0).UTC())
bootTime, _ := ptypes.TimestampProto(
time.Unix(int64(hinfo.BootTime), 0).UTC())
ReportDeviceInfo.BootTime = bootTime
hostname, err := os.Hostname()
if err != nil {
log.Errorf("HostName failed: %s", err)
} else {
ReportDeviceInfo.HostName = hostname
}
ReportDeviceInfo.LastRebootReason = ctx.rebootReason
ReportDeviceInfo.LastBootReason = info.BootReason(ctx.bootReason)
if ctx.bootReason != types.BootReasonNone {
// XXX Remove?
log.Tracef("Reporting BootReason %s", ctx.bootReason.String())
log.Tracef("Reporting RebootReason %s", ctx.rebootReason)
}
ReportDeviceInfo.LastRebootStack = ctx.rebootStack
if !ctx.rebootTime.IsZero() {
rebootTime, _ := ptypes.TimestampProto(ctx.rebootTime)
ReportDeviceInfo.LastRebootTime = rebootTime
}
ReportDeviceInfo.SystemAdapter = encodeSystemAdapterInfo(ctx)
ReportDeviceInfo.RestartCounter = ctx.restartCounter
ReportDeviceInfo.RebootConfigCounter = ctx.rebootConfigCounter
ReportDeviceInfo.ShutdownConfigCounter = ctx.shutdownConfigCounter
//Operational information about TPM presence/absence/usage.
ReportDeviceInfo.HSMStatus = etpm.FetchTpmSwStatus()
ReportDeviceInfo.HSMInfo, _ = etpm.FetchTpmHwInfo()
//Operational information about Data Security At Rest
ReportDataSecAtRestInfo := getDataSecAtRestInfo(ctx)
//This will be removed after new fields propagate to Controller.
ReportDataSecAtRestInfo.Status, ReportDataSecAtRestInfo.Info =
vault.GetOperationalInfo(log)
ReportDeviceInfo.DataSecAtRestInfo = ReportDataSecAtRestInfo
if len(ReportDataSecAtRestInfo.VaultList) > 0 {
// We look at the first one since current implementation only
// has the default vault
first := ReportDataSecAtRestInfo.VaultList[0]
var firstErr string
if first.VaultErr != nil {
firstErr = first.VaultErr.Description
}
if ctx.vaultStatus != first.Status ||
ctx.pcrStatus != first.PcrStatus ||
ctx.vaultErr != firstErr {
ctx.vaultStatus = first.Status
ctx.pcrStatus = first.PcrStatus
ctx.vaultErr = firstErr
publishZedAgentStatus(ctx.getconfigCtx)
}
}
// Add SecurityInfo
ReportDeviceInfo.SecInfo = getSecurityInfo(ctx)
// EVE needs to fill deprecated MaintenanceMode until it is removed
ReportDeviceInfo.MaintenanceMode = ctx.maintenanceMode
ReportDeviceInfo.MaintenanceModeReason = info.MaintenanceModeReason(ctx.maintModeReason)
// For backward compatibility added new field
ReportDeviceInfo.MaintenanceModeReasons = append(ReportDeviceInfo.MaintenanceModeReasons,
info.MaintenanceModeReason(ctx.maintModeReason))
// Watchdog
ReportDeviceInfo.HardwareWatchdogPresent = getHarwareWatchdogPresent(ctx)
// This is also reported in State
ReportDeviceInfo.RebootInprogress = ctx.rebootCmd || ctx.deviceReboot
ReportDeviceInfo.Capabilities = getCapabilities(ctx)
ReportDeviceInfo.OptionalCapabilities = getOptionalCapabilities(ctx)
devState := getDeviceState(ctx)
if ctx.devState != devState {
ctx.devState = devState
publishZedAgentStatus(ctx.getconfigCtx)
}
ReportDeviceInfo.State = info.ZDeviceState(devState)
// TODO: Enhance capability reporting with a bitmap-like approach for increased granularity.
// We report the snapshot capability despite the fact that we support snapshots only
// for file-based volumes. If a controller tries to make a snapshot of ZFS-based volume
// device returns a runtime error.
ReportDeviceInfo.ApiCapability = info.APICapability_API_CAPABILITY_NETWORK_INSTANCE_ROUTING
// Report if there is a local override of profile
if ctx.getconfigCtx.sideController.currentProfile !=
ctx.getconfigCtx.sideController.globalProfile {
ReportDeviceInfo.LocalProfile = ctx.getconfigCtx.sideController.currentProfile
}
ReportInfo.InfoContent = new(info.ZInfoMsg_Dinfo)
if x, ok := ReportInfo.GetInfoContent().(*info.ZInfoMsg_Dinfo); ok {
x.Dinfo = ReportDeviceInfo
}
// Add ConfigItems to the DeviceInfo
ReportDeviceInfo.ConfigItemStatus = createConfigItemStatus(ctx.globalStatus)
// Add AppInstances to the DeviceInfo. We send a list of all AppInstances
// currently on the device - even if the corresponding AppInstanceConfig
// is deleted.
createAppInstances(ctx, ReportDeviceInfo)
if ctx.attestCtx != nil && ctx.attestCtx.attestFsmCtx != nil {
ReportDeviceInfo.AttestationInfo = &info.AttestationInfo{
State: info.AttestationState(ctx.attestCtx.attestFsmCtx.GetState()),
}
if ctx.attestCtx.attestFsmCtx.HasError() {
ReportDeviceInfo.AttestationInfo.Error = encodeErrorInfo(ctx.attestCtx.attestFsmCtx.ErrorDescription)
}
if ctx.attestCtx.Started {
attestFsmCtx := ctx.attestCtx.attestFsmCtx
if ctx.attestState != attestFsmCtx.GetState() ||
ctx.attestError != attestFsmCtx.ErrorDescription.Error {
ctx.attestState = attestFsmCtx.GetState()
ctx.attestError = attestFsmCtx.ErrorDescription.Error
publishZedAgentStatus(ctx.getconfigCtx)
}
}
}
log.Tracef("PublishDeviceInfoToZedCloud sending %v", ReportInfo)
data, err := proto.Marshal(ReportInfo)
if err != nil {
log.Fatal("PublishDeviceInfoToZedCloud proto marshaling error: ", err)
}
buf := bytes.NewBuffer(data)
if buf == nil {
log.Fatal("malloc error")
}
size := int64(proto.Size(ReportInfo))
//We queue the message and then get the highest priority message to send.
//If there are no failures and defers we'll send this message,
//but if there is a queue we'll retry sending the highest priority message.
withNetTracing := traceNextInfoReq(ctx)
queueInfoToDest(ctx, dest, deviceUUID, buf, size, true, withNetTracing, false,
info.ZInfoTypes_ZiDevice)
}
// PublishAppInstMetaDataToZedCloud is called when an appInst reports its Metadata to EVE.
// AppInst metadata is relayed to the controller to be processed further.
func PublishAppInstMetaDataToZedCloud(ctx *zedagentContext,
appInstMetadata *types.AppInstMetaData, isDelete bool,
dest destinationBitset) {
metadataType := appInstMetadata.Type
appInstId := appInstMetadata.AppInstUUID.String()
log.Functionf("PublishAppInstMetaDataToZedCloud: appInstID: %v", appInstId)
var ReportInfo = &info.ZInfoMsg{}
contentType := new(info.ZInfoTypes)
*contentType = info.ZInfoTypes_ZiAppInstMetaData
ReportInfo.Ztype = *contentType
ReportInfo.DevId = *proto.String(devUUID.String())
ReportInfo.AtTimeStamp = ptypes.TimestampNow()
ReportAppInstMetaData := new(info.ZInfoAppInstMetaData)
ReportAppInstMetaData.Uuid = appInstId
ReportAppInstMetaData.Type = info.AppInstMetaDataType(metadataType)
if !isDelete {
// The Data size is expected to be <= 32KB. We have a check for that in zedrouter.
ReportAppInstMetaData.Data = appInstMetadata.Data
}
ReportInfo.InfoContent = new(info.ZInfoMsg_Amdinfo)
if reportAppInstMetadata, ok := ReportInfo.GetInfoContent().(*info.ZInfoMsg_Amdinfo); ok {
reportAppInstMetadata.Amdinfo = ReportAppInstMetaData
}
log.Functionf("PublishAppInstMetaDataToZedCloud sending %v", ReportInfo)
data, err := proto.Marshal(ReportInfo)
if err != nil {
log.Fatal("PublishAppInstMetaDataToZedCloud proto marshaling error: ", err)
}
deferKey := "appInstMetadataInfo:" + appInstMetadata.Key()
buf := bytes.NewBuffer(data)
if buf == nil {
log.Fatal("malloc error")
}
size := int64(proto.Size(ReportInfo))
//We queue the message and then get the highest priority message to send.
//If there are no failures and defers we'll send this message,
//but if there is a queue we'll retry sending the highest priority message.
queueInfoToDest(ctx, dest, deferKey, buf, size, true, false, false,
info.ZInfoTypes_ZiAppInstMetaData)
}
// Convert the implementation details to the user-friendly userStatus and subStatus*
func addUserSwInfo(ctx *zedagentContext, swInfo *info.ZInfoDevSW, tooEarly bool) {
log.Functionf("Device swInfo: %s", swInfo.String())
switch swInfo.Status {
case info.ZSwState_INITIAL:
// If Unused and partitionLabel is set them it
// is the uninitialized IMGB partition which we don't report
if swInfo.PartitionState == "unused" &&
swInfo.PartitionLabel != "" {
swInfo.UserStatus = info.BaseOsStatus_NONE
} else if swInfo.ShortVersion == "" {
swInfo.UserStatus = info.BaseOsStatus_NONE
} else {
swInfo.UserStatus = info.BaseOsStatus_UPDATING
swInfo.SubStatus = info.BaseOsSubStatus_UPDATE_INITIALIZING
swInfo.SubStatusStr = "Initializing update"
}
case info.ZSwState_DOWNLOAD_STARTED:
swInfo.UserStatus = info.BaseOsStatus_DOWNLOADING
swInfo.SubStatus = info.BaseOsSubStatus_DOWNLOAD_INPROGRESS
swInfo.SubStatusProgress = swInfo.DownloadProgress
swInfo.SubStatusStr = fmt.Sprintf("Download %d%% done",
swInfo.SubStatusProgress)
case info.ZSwState_DOWNLOADED:
if swInfo.Activated {
swInfo.UserStatus = info.BaseOsStatus_DOWNLOADING
swInfo.SubStatus = info.BaseOsSubStatus_DOWNLOAD_INPROGRESS
swInfo.SubStatusProgress = 100
swInfo.SubStatusStr = "Download 100% done"
} else {
swInfo.UserStatus = info.BaseOsStatus_NONE
}
case info.ZSwState_DELIVERED:
if swInfo.Activated {
swInfo.UserStatus = info.BaseOsStatus_DOWNLOAD_DONE
swInfo.SubStatusStr = "Downloaded and verified"
} else if tooEarly {
swInfo.UserStatus = info.BaseOsStatus_UPDATING
swInfo.SubStatus = info.BaseOsSubStatus_UPDATE_DEFERRED
swInfo.SubStatusStr = "Waiting for current image to finish testing before updating again"
} else {
swInfo.UserStatus = info.BaseOsStatus_NONE
}
case info.ZSwState_INSTALLED:
switch swInfo.PartitionState {
case "active":
if swInfo.Activated {
swInfo.UserStatus = info.BaseOsStatus_UPDATED
} else {
swInfo.UserStatus = info.BaseOsStatus_FALLBACK
}
case "updating":
swInfo.UserStatus = info.BaseOsStatus_UPDATING
swInfo.SubStatus = info.BaseOsSubStatus_UPDATE_REBOOTING
// XXX progress based on time left??
swInfo.SubStatusStr = "About to reboot"
case "inprogress":
if swInfo.Activated {
swInfo.UserStatus = info.BaseOsStatus_UPDATING
swInfo.SubStatus = info.BaseOsSubStatus_UPDATE_TESTING
swInfo.SubStatusProgress = uint32(ctx.remainingTestTime / time.Second)
swInfo.SubStatusStr = fmt.Sprintf("Testing for %d more seconds",
swInfo.SubStatusProgress)
} else {
swInfo.UserStatus = info.BaseOsStatus_FAILED
}
case "unused":
swInfo.UserStatus = info.BaseOsStatus_NONE
}
default:
// The other states are use for app instances not for baseos
swInfo.UserStatus = info.BaseOsStatus_NONE
}
if swInfo.SwErr != nil && swInfo.SwErr.Description != "" {
swInfo.UserStatus = info.BaseOsStatus_FAILED
}
}
// encodeNetInfo encodes info from the port
func encodeNetInfo(port types.NetworkPortStatus) *info.ZInfoNetwork {
networkInfo := new(info.ZInfoNetwork)
networkInfo.LocalName = port.IfName
networkInfo.IPAddrs = make([]string, len(port.AddrInfoList))
for index, ai := range port.AddrInfoList {
networkInfo.IPAddrs[index] = ai.Addr.String()
}
networkInfo.Ipv4Up = port.Up
networkInfo.MacAddr = port.MacAddr.String()
networkInfo.DevName = port.Logicallabel
networkInfo.Alias = port.Alias
// Default routers from kernel whether or not we are using DHCP
networkInfo.DefaultRouters = make([]string, len(port.DefaultRouters))
for index, dr := range port.DefaultRouters {
networkInfo.DefaultRouters[index] = *proto.String(dr.String())
}
networkInfo.Uplink = port.IsMgmt
// fill in ZInfoDNS from what is currently used
networkInfo.Dns = new(info.ZInfoDNS)
networkInfo.Dns.DNSdomain = port.DomainName
for _, server := range port.DNSServers {
networkInfo.Dns.DNSservers = append(networkInfo.Dns.DNSservers,
server.String())
}
// XXX we potentially have geoloc information for each IP
// address.
// For now fill in using the first IP address which has location
// info.
for _, ai := range port.AddrInfoList {
if ai.Geo == nilIPInfo {
continue
}
geo := new(info.GeoLoc)
geo.UnderlayIP = ai.Geo.IP
geo.Hostname = ai.Geo.Hostname
geo.City = ai.Geo.City
geo.Country = ai.Geo.Country
geo.Loc = ai.Geo.Loc
geo.Org = ai.Geo.Org
geo.Postal = ai.Geo.Postal
networkInfo.Location = geo
break
}
// Any error or test result?
networkInfo.NetworkErr = encodeTestResults(port.TestResults)
networkInfo.Proxy = encodeProxyStatus(&port.ProxyConfig)
networkInfo.NtpServers = []string{}
for _, server := range port.NtpServers {
networkInfo.NtpServers = append(networkInfo.NtpServers, server.String())
}
return networkInfo
}
func encodeCellModuleInfo(wwanModule types.WwanCellModule) *info.ZCellularModuleInfo {
var opState info.ZCellularOperatingState
switch wwanModule.OpMode {
case types.WwanOpModeUnspecified:
opState = info.ZCellularOperatingState_Z_CELLULAR_OPERATING_STATE_UNSPECIFIED
case types.WwanOpModeOnline:
opState = info.ZCellularOperatingState_Z_CELLULAR_OPERATING_STATE_ONLINE
case types.WwanOpModeConnected:
opState = info.ZCellularOperatingState_Z_CELLULAR_OPERATING_STATE_ONLINE_AND_CONNECTED
case types.WwanOpModeRadioOff:
opState = info.ZCellularOperatingState_Z_CELLULAR_OPERATING_STATE_RADIO_OFF
case types.WwanOpModeOffline:
opState = info.ZCellularOperatingState_Z_CELLULAR_OPERATING_STATE_OFFLINE
case types.WwanOpModeUnrecognized:
opState = info.ZCellularOperatingState_Z_CELLULAR_OPERATING_STATE_UNRECOGNIZED
default:
log.Errorf("Invalid wwan module operating state: %v", wwanModule.OpMode)
}
var ctrlProto info.ZCellularControlProtocol
switch wwanModule.ControlProtocol {
case types.WwanCtrlProtUnspecified:
ctrlProto = info.ZCellularControlProtocol_Z_CELLULAR_CONTROL_PROTOCOL_UNSPECIFIED
case types.WwanCtrlProtQMI:
ctrlProto = info.ZCellularControlProtocol_Z_CELLULAR_CONTROL_PROTOCOL_QMI
case types.WwanCtrlProtMBIM:
ctrlProto = info.ZCellularControlProtocol_Z_CELLULAR_CONTROL_PROTOCOL_MBIM
default:
log.Errorf("Invalid wwan module control protocol: %v", wwanModule.ControlProtocol)
}
return &info.ZCellularModuleInfo{
Name: wwanModule.Name,
Imei: wwanModule.IMEI,
FirmwareVersion: wwanModule.Revision,
Model: wwanModule.Model,
Manufacturer: wwanModule.Manufacturer,
OperatingState: opState,
ControlProtocol: ctrlProto,
}
}
func encodeSimCards(cellModule string, wwanSimCards []types.WwanSimCard) (simCards []*info.ZSimcardInfo) {
for _, simCard := range wwanSimCards {
simCards = append(simCards, &info.ZSimcardInfo{
Name: simCard.Name,
CellModuleName: cellModule,
Imsi: simCard.IMSI,
Iccid: simCard.ICCID,
Type: info.SimType(simCard.Type),
State: simCard.State,
SlotNumber: uint32(simCard.SlotNumber),
SlotActivated: simCard.SlotActivated,
})
}
return simCards
}
func encodeCellProvider(wwanProvider types.WwanProvider) (provider *info.ZCellularProvider) {
return &info.ZCellularProvider{
Plmn: wwanProvider.PLMN,
Description: wwanProvider.Description,
CurrentServing: wwanProvider.CurrentServing,
Roaming: wwanProvider.Roaming,
Forbidden: wwanProvider.Forbidden,
}
}
func encodeCellProviders(wwanStatus types.WwanNetworkStatus) (providers []*info.ZCellularProvider) {
var includedCurrentProvider bool
for _, provider := range wwanStatus.VisibleProviders {
if provider == wwanStatus.CurrentProvider {
includedCurrentProvider = true
}
providers = append(providers, encodeCellProvider(provider))
}
if !includedCurrentProvider && wwanStatus.CurrentProvider.PLMN != "" {
providers = append(providers, encodeCellProvider(wwanStatus.CurrentProvider))
}
return providers
}
func encodeSystemAdapterInfo(ctx *zedagentContext) *info.SystemAdapterInfo {
dpcl := *ctx.DevicePortConfigList
sainfo := new(info.SystemAdapterInfo)
sainfo.CurrentIndex = uint32(dpcl.CurrentIndex)
sainfo.Status = make([]*info.DevicePortStatus, len(dpcl.PortConfigList))
for i, dpc := range dpcl.PortConfigList {
dps := new(info.DevicePortStatus)
dps.Version = uint32(dpc.Version)
dps.Key = dpc.Key
ts, _ := ptypes.TimestampProto(dpc.TimePriority)
dps.TimePriority = ts
if !dpc.LastFailed.IsZero() {
ts, _ := ptypes.TimestampProto(dpc.LastFailed)
dps.LastFailed = ts
}
if !dpc.LastSucceeded.IsZero() {
ts, _ := ptypes.TimestampProto(dpc.LastSucceeded)
dps.LastSucceeded = ts
}
dps.LastError = dpc.LastError
dps.Ports = make([]*info.DevicePort, len(dpc.Ports))