-
Notifications
You must be signed in to change notification settings - Fork 156
/
handlemetrics.go
1818 lines (1630 loc) · 65.1 KB
/
handlemetrics.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-2018 Zededa, Inc.
// SPDX-License-Identifier: Apache-2.0
// Push metrics to zedcloud
package zedagent
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"fmt"
"net"
"net/http"
"os"
"runtime"
"strings"
"time"
"github.com/golang/protobuf/ptypes"
"github.com/lf-edge/eve-api/go/evecommon"
"github.com/lf-edge/eve-api/go/info"
"github.com/lf-edge/eve-api/go/metrics"
zmet "github.com/lf-edge/eve-api/go/metrics" // zinfo and zmet here
"github.com/lf-edge/eve/pkg/pillar/flextimer"
"github.com/lf-edge/eve/pkg/pillar/types"
"github.com/lf-edge/eve/pkg/pillar/utils"
"github.com/lf-edge/eve/pkg/pillar/utils/persist"
"github.com/lf-edge/eve/pkg/pillar/zedcloud"
"github.com/shirou/gopsutil/host"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/timestamppb"
)
func handleDiskMetricCreate(ctxArg interface{}, key string,
statusArg interface{}) {
handleDiskMetricImpl(ctxArg, key, statusArg)
}
func handleDiskMetricModify(ctxArg interface{}, key string,
statusArg interface{}, oldStatusArg interface{}) {
handleDiskMetricImpl(ctxArg, key, statusArg)
}
func handleDiskMetricImpl(ctxArg interface{}, key string,
statusArg interface{}) {
status := statusArg.(types.DiskMetric)
path := status.DiskPath
log.Functionf("handleDiskMetricImpl: %s", path)
}
func handleDiskMetricDelete(ctxArg interface{}, key string, statusArg interface{}) {
status := statusArg.(types.DiskMetric)
path := status.DiskPath
log.Functionf("handleDiskMetricModify: %s", path)
}
func lookupDiskMetric(ctx *zedagentContext, diskPath string) *types.DiskMetric {
diskPath = types.PathToKey(diskPath)
sub := ctx.subDiskMetric
m, _ := sub.Get(diskPath)
if m == nil {
return nil
}
metric := m.(types.DiskMetric)
return &metric
}
func getAllDiskMetrics(ctx *zedagentContext) []*types.DiskMetric {
var retList []*types.DiskMetric
log.Tracef("getAllDiskMetrics")
sub := ctx.subDiskMetric
items := sub.GetAll()
for _, st := range items {
status := st.(types.DiskMetric)
retList = append(retList, &status)
}
log.Tracef("getAllDiskMetrics: Done")
return retList
}
func handleAppDiskMetricCreate(ctxArg interface{}, key string, _ interface{}) {
ctx := ctxArg.(*zedagentContext)
// if AppDiskMetric create event come after VolumeStatus available
// we should publish updated numbers based on AppDiskMetric
volumeStatusList := ctx.getconfigCtx.subVolumeStatus.GetAll()
for _, s := range volumeStatusList {
volumeStatus, ok := s.(types.VolumeStatus)
if !ok {
log.Error("unexpected type in subVolumeStatus")
continue
}
if volumeStatus.FileLocation == "" {
continue
}
if key != types.PathToKey(volumeStatus.FileLocation) {
continue
}
uuidStr := volumeStatus.VolumeID.String()
PublishVolumeToZedCloud(ctx, uuidStr, &volumeStatus,
ctx.iteration, AllDest)
}
log.Functionf("handleAppDiskMetricCreate: %s", key)
}
func lookupAppDiskMetric(ctx *zedagentContext, diskPath string) *types.AppDiskMetric {
diskPath = types.PathToKey(diskPath)
sub := ctx.subAppDiskMetric
m, _ := sub.Get(diskPath)
if m == nil {
return nil
}
metric := m.(types.AppDiskMetric)
return &metric
}
func encodeErrorInfo(et types.ErrorDescription) *info.ErrorInfo {
if et.ErrorTime.IsZero() {
// No Success / Error to report
return nil
}
errInfo := new(info.ErrorInfo)
errInfo.Description = et.Error
protoTime, err := ptypes.TimestampProto(et.ErrorTime)
if err == nil {
errInfo.Timestamp = protoTime
} else {
log.Errorf("Failed to convert timestamp (%+v) for ErrorStr (%s) "+
"into TimestampProto. err: %s", et.ErrorTime, et.Error, err)
}
errInfo.Severity = info.Severity(et.ErrorSeverity)
errInfo.RetryCondition = et.ErrorRetryCondition
errInfo.Entities = make([]*info.DeviceEntity, len(et.ErrorEntities))
for i, el := range et.ErrorEntities {
errInfo.Entities[i] = &info.DeviceEntity{EntityId: el.EntityID, Entity: info.Entity(el.EntityType)}
}
return errInfo
}
// We reuse the info.ErrorInfo to pass both failure and success. If success
// the Description is left empty
func encodeTestResults(tr types.TestResults) *info.ErrorInfo {
errInfo := new(info.ErrorInfo)
var timestamp time.Time
if tr.HasError() {
timestamp = tr.LastFailed
errInfo.Description = tr.LastError
errInfo.Severity = info.Severity_SEVERITY_ERROR
} else {
timestamp = tr.LastSucceeded
}
if !timestamp.IsZero() {
protoTime, err := ptypes.TimestampProto(timestamp)
if err == nil {
errInfo.Timestamp = protoTime
} else {
log.Errorf("Failed to convert timestamp (%+v) for ErrorStr (%s) "+
"into TimestampProto. err: %s", timestamp, tr.LastError, err)
}
}
return errInfo
}
// Run a periodic post of the metrics and info to an LOC if we have one
func metricsAndInfoTimerTask(ctx *zedagentContext, handleChannel chan interface{}) {
iteration := 0
log.Functionln("starting report metrics/info timer task")
publishMetrics(ctx, iteration)
interval := time.Duration(ctx.globalConfig.GlobalValueInt(types.MetricInterval)) * time.Second
max := float64(interval)
min := max * 0.3
ticker := flextimer.NewRangeTicker(time.Duration(min), time.Duration(max))
// Return handle to caller
handleChannel <- ticker
wdName := agentName + "metrics"
// Run a periodic timer so we always update StillRunning
stillRunning := time.NewTicker(25 * time.Second)
ctx.ps.StillRunning(wdName, warningTime, errorTime)
ctx.ps.RegisterFileWatchdog(wdName)
for {
select {
case <-ticker.C:
start := time.Now()
iteration++
publishMetrics(ctx, iteration)
ctx.ps.CheckMaxTimeTopic(wdName, "publishMetrics", start,
warningTime, errorTime)
locConfig := ctx.getconfigCtx.sideController.locConfig
if locConfig != nil {
// Publish all info by timer only for LOC
triggerPublishAllInfo(ctx, LOCDest)
}
case <-stillRunning.C:
}
ctx.ps.StillRunning(wdName, warningTime, errorTime)
}
}
// maybeUpdateMetricsTimer is responsible of calling updateMetricsTimer.
// This method handles 2 scenarios:
// 1. Current metrics publish interval > new metrics publish interval in GlobalConfig
// For instance, if currentMetricInterval = 300s and latestMetricTickerInterval = 200s,
// the controller will be expecting a metrics every 300s. So increasing the frequency
// immediately to 200s will not result in controller marking the edge-node as suspect
// in between.
// 2. Current metrics publish interval < new metrics publish interval in GlobalConfig
// For instance, if currentMetricInterval = 200s and latestMetricTickerInterval = 300s,
// the controller will be expecting a metrics every 200s. So decreasing the frequency to
// 300s can result in controller marking the edge-node as suspect in between. To avoid this,
// we have to make sure that the controller is notified to expect a metrics every 300s before
// updating our publish frequency. forceUpdate should be true only after we've successfully
// notified new frequency to the controller.
func maybeUpdateMetricsTimer(ctx *getconfigContext, forceUpdate bool) {
latestMetricsInterval := ctx.zedagentCtx.globalConfig.GlobalValueInt(types.MetricInterval)
log.Functionf("maybeUpdateMetricsTimer: currentMetricInterval %v, latestMetricsInterval %v, forceUpdate: %v",
ctx.currentMetricInterval, latestMetricsInterval, forceUpdate)
if ctx.currentMetricInterval > latestMetricsInterval {
log.Tracef("maybeUpdateMetricsTimer: updating metrics publish interval %v seconds",
latestMetricsInterval)
updateMetricsTimer(ctx, latestMetricsInterval)
} else if ctx.currentMetricInterval < latestMetricsInterval {
if forceUpdate {
log.Tracef("maybeUpdateMetricsTimer: updating metrics publish interval %v seconds",
latestMetricsInterval)
updateMetricsTimer(ctx, latestMetricsInterval)
} else {
// Force an immediate timeout to publish metrics.
if ctx.metricsTickerHandle != nil {
flextimer.TickNow(ctx.metricsTickerHandle)
}
}
}
}
// Called when globalConfig changes
// Assumes the caller has verifier that the interval has changed
func updateMetricsTimer(ctx *getconfigContext, metricInterval uint32) {
if ctx.metricsTickerHandle == nil {
log.Warnf("updateMetricsTimer: no metricsTickerHandle yet")
return
}
interval := time.Duration(metricInterval) * time.Second
log.Functionf("updateMetricsTimer() change to %v", interval)
max := float64(interval)
min := max * 0.3
flextimer.UpdateRangeTicker(ctx.metricsTickerHandle,
time.Duration(min), time.Duration(max))
ctx.currentMetricInterval = metricInterval
// Force an immediate timeout since timer could have decreased
flextimer.TickNow(ctx.metricsTickerHandle)
}
// Key is device UUID for host and app instance UUID for app instances
// Returns DomainMetric
func lookupDomainMetric(ctx *zedagentContext, uuidStr string) *types.DomainMetric {
sub := ctx.getconfigCtx.subDomainMetric
m, _ := sub.Get(uuidStr)
if m == nil {
log.Functionf("lookupDomainMetric(%s) not found", uuidStr)
return nil
}
metric := m.(types.DomainMetric)
return &metric
}
func lookupAppContainerMetric(ctx *zedagentContext, uuidStr string) *types.AppContainerMetrics {
sub := ctx.subAppContainerMetrics
m, _ := sub.Get(uuidStr)
if m == nil {
return nil
}
metric := m.(types.AppContainerMetrics)
return &metric
}
func publishMetrics(ctx *zedagentContext, iteration int) {
var ReportMetrics = &metrics.ZMetricMsg{}
startPubTime := time.Now()
ReportDeviceMetric := new(metrics.DeviceMetric)
ReportDeviceMetric.Memory = new(metrics.MemoryMetric)
ReportDeviceMetric.CpuMetric = new(metrics.AppCpuMetric)
ReportMetrics.DevID = *proto.String(devUUID.String())
ReportZmetric := new(metrics.ZmetricTypes)
*ReportZmetric = metrics.ZmetricTypes_ZmDevice
// This will be overridden with the timestamp for the CPU metrics
// below to make CPU usage calculations more accurate
ReportMetrics.AtTimeStamp = ptypes.TimestampNow()
info, err := host.Info()
if err != nil {
log.Fatalf("host.Info(): %s", err)
}
log.Tracef("uptime %d = %d days",
info.Uptime, info.Uptime/(3600*24))
log.Tracef("Booted at %v", time.Unix(int64(info.BootTime), 0).UTC())
// Note that uptime is seconds we've been up. We're converting
// to a timestamp. That better not be interpreted as a time since
// the epoch
uptime, _ := ptypes.TimestampProto(
time.Unix(int64(info.Uptime), 0).UTC())
ReportDeviceMetric.CpuMetric.UpTime = uptime
// Memory related info for the device
var totalMemory, freeMemory, usedEveMB uint64
sub := ctx.getconfigCtx.subHostMemory
m, _ := sub.Get("global")
if m != nil {
metric := m.(types.HostMemory)
totalMemory = metric.TotalMemoryMB
freeMemory = metric.FreeMemoryMB
usedEveMB = metric.UsedEveMB + metric.KmemUsedEveMB
}
// total_memory and free_memory is in MBytes
used := totalMemory - freeMemory
ReportDeviceMetric.Memory.UsedMem = uint32(used)
ReportDeviceMetric.Memory.AvailMem = uint32(freeMemory)
var usedPercent float64
if totalMemory != 0 {
usedPercent = float64(100) * float64(used) / float64(totalMemory)
}
ReportDeviceMetric.Memory.UsedPercentage = usedPercent
ReportDeviceMetric.Memory.AvailPercentage = 100.0 - (usedPercent)
log.Tracef("Device Memory from xl info: %v %v %v %v",
ReportDeviceMetric.Memory.UsedMem,
ReportDeviceMetric.Memory.AvailMem,
ReportDeviceMetric.Memory.UsedPercentage,
ReportDeviceMetric.Memory.AvailPercentage)
// Use the network metrics from zedrouter subscription
// Only report stats for the ports in DeviceNetworkStatus
for _, p := range deviceNetworkStatus.Ports {
var metric *types.NetworkMetric
if !p.IsL3Port {
// metrics for ports from lower layers are not reported
continue
}
if p.IfName == "" {
// Cannot associate metrics with the port until interface name is known.
continue
}
for _, m := range networkMetrics.MetricList {
if p.IfName == m.IfName {
metric = &m
break
}
}
if metric == nil {
continue
}
networkDetails := new(metrics.NetworkMetric)
networkDetails.LocalName = metric.IfName
networkDetails.IName = p.Logicallabel
networkDetails.Alias = p.Alias
networkDetails.TxPkts = metric.TxPkts
networkDetails.RxPkts = metric.RxPkts
networkDetails.TxBytes = metric.TxBytes
networkDetails.RxBytes = metric.RxBytes
networkDetails.TxDrops = metric.TxDrops
networkDetails.RxDrops = metric.RxDrops
networkDetails.TxErrors = metric.TxErrors
networkDetails.RxErrors = metric.RxErrors
networkDetails.TxAclDrops = metric.TxAclDrops
networkDetails.RxAclDrops = metric.RxAclDrops
networkDetails.TxAclRateLimitDrops = metric.TxAclRateLimitDrops
networkDetails.RxAclRateLimitDrops = metric.RxAclRateLimitDrops
ReportDeviceMetric.Network = append(ReportDeviceMetric.Network,
networkDetails)
}
aclMetric := new(metrics.AclMetric)
aclMetric.TotalRuleCount = networkMetrics.TotalRuleCount
ReportDeviceMetric.Acl = aclMetric
ReportDeviceMetric.Cellular = getCellularMetrics(ctx)
zedboxStats := new(metrics.ZedboxStats)
zedboxStats.NumGoRoutines = uint32(runtime.NumGoroutine()) // number of zedbox goroutines
ReportDeviceMetric.Zedbox = zedboxStats
// Transfer to a local copy in since metrics updates are done concurrently
cms := types.MetricsMap{}
ctx.zedcloudMetrics.AddInto(log, cms)
clientMetrics.AddInto(cms)
downloaderMetrics.AddInto(cms)
loguploaderMetrics.AddInto(cms)
diagMetrics.AddInto(cms)
nimMetrics.AddInto(cms)
zrouterMetrics.AddInto(cms)
for ifname, cm := range cms {
metric := metrics.ZedcloudMetric{IfName: ifname,
Failures: cm.FailureCount,
Success: cm.SuccessCount,
AuthVerifyFailure: cm.AuthFailCount,
}
if !cm.LastFailure.IsZero() {
lf, _ := ptypes.TimestampProto(cm.LastFailure)
metric.LastFailure = lf
}
if !cm.LastSuccess.IsZero() {
ls, _ := ptypes.TimestampProto(cm.LastSuccess)
metric.LastSuccess = ls
}
for url, um := range cm.URLCounters {
log.Tracef("CloudMetrics[%s] url %s %v",
ifname, url, um)
urlMet := new(metrics.UrlcloudMetric)
urlMet.Url = url
urlMet.TryMsgCount = um.TryMsgCount
urlMet.TryByteCount = um.TryByteCount
urlMet.SentMsgCount = um.SentMsgCount
urlMet.SentByteCount = um.SentByteCount
urlMet.RecvMsgCount = um.RecvMsgCount
urlMet.RecvByteCount = um.RecvByteCount
urlMet.TotalTimeSpent = um.TotalTimeSpent
urlMet.SessResumeCount = um.SessionResume
metric.UrlMetrics = append(metric.UrlMetrics, urlMet)
}
ReportDeviceMetric.Zedcloud = append(ReportDeviceMetric.Zedcloud,
&metric)
}
nlm := &zmet.NewlogMetric{
FailedToSend: newlogMetrics.FailedToSend,
TotalBytesUpload: newlogMetrics.TotalBytesUpload,
Num4XxResponses: newlogMetrics.Num4xxResponses,
CurrentUploadIntv: newlogMetrics.CurrUploadIntvSec,
LogfileTimeout: newlogMetrics.LogfileTimeoutSec,
MaxGzipFileSize: newlogMetrics.MaxGzipSize,
AvgGzipFileSize: newlogMetrics.AvgGzipSize,
MimUploadMsec: newlogMetrics.Latency.MinUploadMsec,
MaxUploadMsec: newlogMetrics.Latency.MaxUploadMsec,
AvgUploadMsec: newlogMetrics.Latency.AvgUploadMsec,
LastUploadMsec: newlogMetrics.Latency.CurrUploadMsec,
CurrentCPULoadPct: newlogMetrics.ServerStats.CurrCPULoadPCT,
AverageCPULoadPct: newlogMetrics.ServerStats.AvgCPULoadPCT,
CurrentProcessDelay: newlogMetrics.ServerStats.CurrProcessMsec,
AverageProcessDelay: newlogMetrics.ServerStats.AvgProcessMsec,
GzipFilesRemoved: newlogMetrics.NumGZipFileRemoved,
TooManyRequest: newlogMetrics.NumTooManyRequest,
SkipUploadAppFile: newlogMetrics.NumSkipUploadAppFile,
}
if !newlogMetrics.FailSentStartTime.IsZero() {
nlm.FailSentStartTime, _ = ptypes.TimestampProto(newlogMetrics.FailSentStartTime)
}
devM := &zmet.LogfileMetrics{
NumGzipFileSent: newlogMetrics.DevMetrics.NumGZipFilesSent,
NumGzipBytesWrite: newlogMetrics.DevMetrics.NumGZipBytesWrite,
NumBytesWrite: newlogMetrics.DevMetrics.NumBytesWrite,
NumGzipFileInDir: newlogMetrics.DevMetrics.NumGzipFileInDir,
NumInputEvent: newlogMetrics.DevMetrics.NumInputEvent,
NumGzipFileRetry: newlogMetrics.DevMetrics.NumGZipFileRetry,
NumGzipFileKeptLocal: newlogMetrics.DevMetrics.NumGZipFileKeptLocal,
}
if !newlogMetrics.DevMetrics.RecentUploadTimestamp.IsZero() {
devM.RecentGzipFileTime, _ = ptypes.TimestampProto(newlogMetrics.DevMetrics.RecentUploadTimestamp)
}
if !newlogMetrics.DevMetrics.LastGZipFileSendTime.IsZero() {
devM.LastGzipFileSendTime, _ = ptypes.TimestampProto(newlogMetrics.DevMetrics.LastGZipFileSendTime)
}
nlm.DeviceMetrics = devM
appM := &zmet.LogfileMetrics{
NumGzipFileSent: newlogMetrics.AppMetrics.NumGZipFilesSent,
NumGzipBytesWrite: newlogMetrics.AppMetrics.NumGZipBytesWrite,
NumBytesWrite: newlogMetrics.AppMetrics.NumBytesWrite,
NumGzipFileInDir: newlogMetrics.AppMetrics.NumGzipFileInDir,
NumInputEvent: newlogMetrics.AppMetrics.NumInputEvent,
NumGzipFileRetry: newlogMetrics.AppMetrics.NumGZipFileRetry,
NumGzipFileKeptLocal: newlogMetrics.AppMetrics.NumGZipFileKeptLocal,
}
if !newlogMetrics.AppMetrics.RecentUploadTimestamp.IsZero() {
appM.RecentGzipFileTime, _ = ptypes.TimestampProto(newlogMetrics.AppMetrics.RecentUploadTimestamp)
}
if !newlogMetrics.AppMetrics.LastGZipFileSendTime.IsZero() {
appM.LastGzipFileSendTime, _ = ptypes.TimestampProto(newlogMetrics.AppMetrics.LastGZipFileSendTime)
}
nlm.AppMetrics = appM
nlm.Top10InputSources = make(map[string]uint32)
for source, val := range newlogMetrics.DevTop10InputBytesPCT {
nlm.Top10InputSources[source] = val
}
ReportDeviceMetric.Newlog = nlm
log.Tracef("publishMetrics: newlog-metrics %+v", nlm)
// combine CipherMetric from all agents and report
cipherMetrics := []types.CipherMetrics{
cipherMetricsDL,
cipherMetricsDM,
cipherMetricsNim,
cipherMetricsZR,
cipherMetricsWwan,
}
for _, cm := range cipherMetrics {
log.Functionf("Cipher metrics for %s: %+v", cm.AgentName, cm)
metric := metrics.CipherMetric{AgentName: cm.AgentName,
FailureCount: cm.FailureCount,
SuccessCount: cm.SuccessCount,
}
if !cm.LastFailure.IsZero() {
lf, _ := ptypes.TimestampProto(cm.LastFailure)
metric.LastFailure = lf
}
if !cm.LastSuccess.IsZero() {
ls, _ := ptypes.TimestampProto(cm.LastSuccess)
metric.LastSuccess = ls
}
for i := range cm.TypeCounters {
tc := metrics.TypeCounter{
ErrorCode: metrics.CipherError(i),
Count: cm.TypeCounters[i],
}
if tc.Count != 0 {
metric.Tc = append(metric.Tc, &tc)
}
}
ReportDeviceMetric.Cipher = append(ReportDeviceMetric.Cipher,
&metric)
}
var persistUsage uint64
for _, diskMetric := range getAllDiskMetrics(ctx) {
var diskPath, mountPath string
if diskMetric.IsDir {
mountPath = diskMetric.DiskPath
} else {
diskPath = diskMetric.DiskPath
}
metric := metrics.DiskMetric{
Disk: diskPath,
MountPath: mountPath,
ReadBytes: utils.RoundToMbytes(diskMetric.ReadBytes),
WriteBytes: utils.RoundToMbytes(diskMetric.WriteBytes),
ReadCount: diskMetric.ReadCount,
WriteCount: diskMetric.WriteCount,
Total: utils.RoundToMbytes(diskMetric.TotalBytes),
Used: utils.RoundToMbytes(diskMetric.UsedBytes),
Free: utils.RoundToMbytes(diskMetric.FreeBytes),
}
ReportDeviceMetric.Disk = append(ReportDeviceMetric.Disk, &metric)
if diskMetric.DiskPath == types.PersistDir {
persistUsage = diskMetric.UsedBytes
}
}
log.Tracef("DirPaths in persist, elapse sec %v", time.Since(startPubTime).Seconds())
// Determine how much we use in /persist and how much of it is
// for the benefits of applications
var persistAppUsage uint64
for _, path := range types.AppPersistPaths {
diskMetric := lookupDiskMetric(ctx, path)
if diskMetric != nil {
persistAppUsage += diskMetric.UsedBytes
}
}
log.Tracef("persistAppUsage %d, elapse sec %v", persistAppUsage, time.Since(startPubTime).Seconds())
persistOverhead := persistUsage - persistAppUsage
// Convert to MB
runtimeStorageOverhead := types.RoundupToKB(types.RoundupToKB(persistOverhead))
appRunTimeStorage := types.RoundupToKB(types.RoundupToKB(persistAppUsage))
log.Tracef("runtimeStorageOverhead %d MB, appRunTimeStorage %d MB",
runtimeStorageOverhead, appRunTimeStorage)
ReportDeviceMetric.RuntimeStorageOverheadMB = runtimeStorageOverhead
ReportDeviceMetric.AppRunTimeStorageMB = appRunTimeStorage
const nanoSecToSec uint64 = 1000000000
// Get device info using nil UUID
dm := lookupDomainMetric(ctx, nilUUID.String())
if dm != nil {
log.Tracef("host CPU: %d, at %v, percent used %d",
dm.CPUTotalNs, dm.LastHeard, (100*dm.CPUTotalNs)/uint64(info.Uptime))
// Override the time of the report with the time from
// domainmgr
if !dm.LastHeard.IsZero() {
lh, _ := ptypes.TimestampProto(dm.LastHeard)
ReportMetrics.AtTimeStamp = lh
}
ReportDeviceMetric.CpuMetric.Total = *proto.Uint64(dm.CPUTotalNs / nanoSecToSec)
ReportDeviceMetric.CpuMetric.TotalNs = dm.CPUTotalNs
// Report new DeviceMemoryMetric
ReportDeviceMetric.DeviceMemory = new(metrics.DeviceMemoryMetric)
ReportDeviceMetric.DeviceMemory.MemoryMB = uint32(totalMemory)
// Loop over AppInstanceConfig to get sum for AllocatedAppsMB
// independent of status; use DomainMetric if it exists since
// it has the number which includes the qemu overhead.
var sumKB uint64
pub := ctx.getconfigCtx.pubAppInstanceConfig
items := pub.GetAll()
for _, c := range items {
aiConfig := c.(types.AppInstanceConfig)
dm := lookupDomainMetric(ctx, aiConfig.Key())
if dm != nil {
sumKB += 1024 * uint64(dm.AllocatedMB)
} else {
sumKB += uint64(aiConfig.FixedResources.Memory)
}
}
ReportDeviceMetric.DeviceMemory.AllocatedAppsMB = uint32((sumKB + 1023) / 1024)
allocatedEve, err := types.GetEveMemoryLimitInBytes()
if err != nil {
log.Errorf("GetEveMemoryLimitInBytes failed: %v", err)
} else {
ReportDeviceMetric.DeviceMemory.AllocatedEveMB =
uint32((allocatedEve + 1024*1024 - 1) / (1024 * 1024))
}
ReportDeviceMetric.DeviceMemory.UsedEveMB = uint32(usedEveMB)
// SystemServicesMemoryMB is deprecated and replaced by DeviceMemoryMetric.
// Report to support there are old controllers
ReportDeviceMetric.SystemServicesMemoryMB = new(metrics.MemoryMetric)
ReportDeviceMetric.SystemServicesMemoryMB.UsedMem = dm.UsedMemory
ReportDeviceMetric.SystemServicesMemoryMB.AvailMem = dm.AvailableMemory
ReportDeviceMetric.SystemServicesMemoryMB.UsedPercentage = dm.UsedMemoryPercent
ReportDeviceMetric.SystemServicesMemoryMB.AvailPercentage = 100.0 - (dm.UsedMemoryPercent)
log.Tracef("host Memory: %v %v %v %v",
ReportDeviceMetric.SystemServicesMemoryMB.UsedMem,
ReportDeviceMetric.SystemServicesMemoryMB.AvailMem,
ReportDeviceMetric.SystemServicesMemoryMB.UsedPercentage,
ReportDeviceMetric.SystemServicesMemoryMB.AvailPercentage)
}
if !ctx.getconfigCtx.lastReceivedConfig.IsZero() {
protoTime, err := ptypes.TimestampProto(ctx.getconfigCtx.lastReceivedConfig)
if err == nil {
ReportDeviceMetric.LastReceivedConfig = protoTime
} else {
log.Errorf("Failed to convert timestamp (%+v) for LastReceivedConfig into TimestampProto. err: %s",
ctx.getconfigCtx.lastReceivedConfig, err)
}
}
if !ctx.getconfigCtx.lastProcessedConfig.IsZero() {
protoTime, err := ptypes.TimestampProto(ctx.getconfigCtx.lastProcessedConfig)
if err == nil {
ReportDeviceMetric.LastProcessedConfig = protoTime
} else {
log.Errorf("Failed to convert timestamp (%+v) for LastProcessedConfig into TimestampProto. err: %s",
ctx.getconfigCtx.lastProcessedConfig, err)
}
}
ReportDeviceMetric.DormantTimeInSeconds = getDormantTime(ctx)
// Report metrics from ZFS
if persist.ReadPersistType() == types.PersistZFS {
for _, el := range ctx.subZFSPoolMetrics.GetAll() {
zfsPoolMetrics := el.(types.ZFSPoolMetrics)
ReportDeviceMetric.StorageMetrics = append(ReportDeviceMetric.StorageMetrics,
fillStorageMetrics(&zfsPoolMetrics))
}
}
// Report flowlog metrics.
ctx.flowLogMetrics.Lock()
ReportDeviceMetric.Flowlog = &metrics.FlowlogMetric{
Messages: protoEncodeFlowlogCounters(ctx.flowLogMetrics.Messages),
Flows: protoEncodeFlowlogCounters(ctx.flowLogMetrics.Flows),
DnsRequests: protoEncodeFlowlogCounters(ctx.flowLogMetrics.DNSReqs),
}
ctx.flowLogMetrics.Unlock()
ReportMetrics.MetricContent = new(metrics.ZMetricMsg_Dm)
if x, ok := ReportMetrics.GetMetricContent().(*metrics.ZMetricMsg_Dm); ok {
x.Dm = ReportDeviceMetric
}
// Loop over AppInstanceStatus so we report before the instance has booted
sub = ctx.getconfigCtx.subAppInstanceStatus
items := sub.GetAll()
for _, st := range items {
aiStatus := st.(types.AppInstanceStatus)
ReportAppMetric := new(metrics.AppMetric)
ReportAppMetric.Cpu = new(metrics.AppCpuMetric)
// New AppMemoryMetric
ReportAppMetric.AppMemory = new(metrics.AppMemoryMetric)
// MemoryMetric is deprecated; keep for old controllers for now
ReportAppMetric.Memory = new(metrics.MemoryMetric)
ReportAppMetric.AppName = aiStatus.DisplayName
ReportAppMetric.AppID = aiStatus.Key()
ReportAppMetric.PatchEnvelope = composePatchEnvelopeUsage(aiStatus.Key(), ctx)
if !aiStatus.BootTime.IsZero() && aiStatus.Activated {
elapsed := time.Since(aiStatus.BootTime)
uptime, _ := ptypes.TimestampProto(
time.Unix(0, elapsed.Nanoseconds()).UTC())
ReportAppMetric.Cpu.UpTime = uptime
}
dm := lookupDomainMetric(ctx, aiStatus.Key())
if dm != nil {
log.Tracef("metrics for %s CPU %d, usedMem %v, availMem %v, availMemPercent %v",
aiStatus.DomainName, dm.CPUTotalNs, dm.UsedMemory,
dm.AvailableMemory, dm.UsedMemoryPercent)
// Deprecated filed in seconds
ReportAppMetric.Cpu.Total = *proto.Uint64(dm.CPUTotalNs / nanoSecToSec)
// New field in nanosec.
ReportAppMetric.Cpu.TotalNs = dm.CPUTotalNs
// New AppMemoryMetric fields
ReportAppMetric.AppMemory.AllocatedMB = dm.AllocatedMB
ReportAppMetric.AppMemory.UsedMB = dm.UsedMemory
// Deprecated MemoryMetric fields
ReportAppMetric.Memory.UsedMem = dm.UsedMemory
ReportAppMetric.Memory.AvailMem = dm.AvailableMemory
ReportAppMetric.Memory.UsedPercentage = dm.UsedMemoryPercent
availableMemoryPercent := 100.0 - dm.UsedMemoryPercent
ReportAppMetric.Memory.AvailPercentage = availableMemoryPercent
}
appInterfaceList := aiStatus.GetAppInterfaceList()
log.Tracef("ReportMetrics: domainName %s ifs %v",
aiStatus.DomainName, appInterfaceList)
// Use the network metrics from zedrouter subscription
for _, ifName := range appInterfaceList {
var metric *types.NetworkMetric
for _, m := range networkMetrics.MetricList {
if ifName == m.IfName {
metric = &m
break
}
}
if metric == nil {
continue
}
networkDetails := new(metrics.NetworkMetric)
name := appIfnameToName(&aiStatus, metric.IfName)
log.Tracef("app %s/%s localname %s name %s",
aiStatus.Key(), aiStatus.DisplayName,
metric.IfName, name)
networkDetails.IName = name
networkDetails.LocalName = metric.IfName
// Counters not swapped on vif
if strings.HasPrefix(ifName, "nbn") ||
strings.HasPrefix(ifName, "nbu") ||
strings.HasPrefix(ifName, "nbo") {
networkDetails.TxPkts = metric.TxPkts
networkDetails.RxPkts = metric.RxPkts
networkDetails.TxBytes = metric.TxBytes
networkDetails.RxBytes = metric.RxBytes
networkDetails.TxDrops = metric.TxDrops
networkDetails.RxDrops = metric.RxDrops
networkDetails.TxErrors = metric.TxErrors
networkDetails.RxErrors = metric.RxErrors
networkDetails.TxAclDrops = metric.TxAclDrops
networkDetails.RxAclDrops = metric.RxAclDrops
networkDetails.TxAclRateLimitDrops = metric.TxAclRateLimitDrops
networkDetails.RxAclRateLimitDrops = metric.RxAclRateLimitDrops
} else {
// Note that the packets received on bu* and bo* where sent
// by the domU and vice versa, hence we swap here
networkDetails.TxPkts = metric.RxPkts
networkDetails.RxPkts = metric.TxPkts
networkDetails.TxBytes = metric.RxBytes
networkDetails.RxBytes = metric.TxBytes
networkDetails.TxDrops = metric.RxDrops
networkDetails.RxDrops = metric.TxDrops
networkDetails.TxErrors = metric.RxErrors
networkDetails.RxErrors = metric.TxErrors
networkDetails.TxAclDrops = metric.RxAclDrops
networkDetails.RxAclDrops = metric.TxAclDrops
networkDetails.TxAclRateLimitDrops = metric.RxAclRateLimitDrops
networkDetails.RxAclRateLimitDrops = metric.TxAclRateLimitDrops
}
ReportAppMetric.Network = append(ReportAppMetric.Network,
networkDetails)
}
for _, vrs := range aiStatus.VolumeRefStatusList {
appDiskDetails := new(metrics.AppDiskMetric)
if vrs.ActiveFileLocation == "" {
log.Functionf("ActiveFileLocation is empty for %s", vrs.Key())
continue
}
err := getDiskInfo(ctx, vrs, appDiskDetails)
if err != nil {
logData := fmt.Sprintf("getDiskInfo(%s) failed %v",
vrs.ActiveFileLocation, err)
if vrs.State >= types.CREATED_VOLUME {
log.Warn(logData)
} else {
log.Function(logData)
}
continue
}
ReportAppMetric.Disk = append(ReportAppMetric.Disk,
appDiskDetails)
}
acMetric := lookupAppContainerMetric(ctx, aiStatus.UUIDandVersion.UUID.String())
// the new protocol is always fill in at least the module name to indicate
// it has not disappeared yet, even we don't have new info on metrics
if acMetric != nil {
for _, stats := range acMetric.StatsList { // go through each container
appContainerMetric := new(metrics.AppContainerMetric)
appContainerMetric.AppContainerName = stats.ContainerName
// fill in the new metrics info for each module
if acMetric.CollectTime.Sub(ctx.appContainerStatsTime) > 0 {
appContainerMetric.Status = stats.Status
appContainerMetric.PIDs = stats.Pids
appContainerMetric.Cpu = new(metrics.AppCpuMetric)
uptime, _ := ptypes.TimestampProto(time.Unix(0, stats.Uptime).UTC())
appContainerMetric.Cpu.UpTime = uptime
// convert to seconds
appContainerMetric.Cpu.Total = stats.CPUTotal / nanoSecToSec
appContainerMetric.Cpu.SystemTotal = stats.SystemCPUTotal / nanoSecToSec
appContainerMetric.Cpu.TotalNs = stats.CPUTotal
// New AppMemoryMetric
appContainerMetric.AppContainerMemory = new(metrics.AppMemoryMetric)
appContainerMetric.AppContainerMemory.AllocatedMB = stats.AllocatedMem
appContainerMetric.AppContainerMemory.UsedMB = stats.UsedMem
// MemoryMetric is deprecated; keep for old controllers for now
appContainerMetric.Memory = new(metrics.MemoryMetric)
appContainerMetric.Memory.UsedMem = stats.UsedMem
// We report the Allocated aka Limit
// in the AvailMem field, which is confusing
// but this MemoryMetric is deprecated.
appContainerMetric.Memory.AvailMem = stats.AllocatedMem
appContainerMetric.Network = new(metrics.NetworkMetric)
appContainerMetric.Network.TxBytes = stats.TxBytes
appContainerMetric.Network.RxBytes = stats.RxBytes
appContainerMetric.Disk = new(metrics.DiskMetric)
appContainerMetric.Disk.ReadBytes = stats.ReadBytes
appContainerMetric.Disk.WriteBytes = stats.WriteBytes
}
ReportAppMetric.Container = append(ReportAppMetric.Container, appContainerMetric)
}
ctx.appContainerStatsTime = acMetric.CollectTime
}
ReportMetrics.Am = append(ReportMetrics.Am, ReportAppMetric)
}
createNetworkInstanceMetrics(ctx, ReportMetrics)
createVolumeInstanceMetrics(ctx, ReportMetrics)
createProcessMetrics(ctx, ReportMetrics)
log.Tracef("PublishMetricsToZedCloud sending %s", ReportMetrics)
sendMetricsProtobuf(ctx.getconfigCtx, ReportMetrics, iteration)
log.Tracef("publishMetrics: after send, total elapse sec %v", time.Since(startPubTime).Seconds())
// publish the cloud MetricsMap for zedagent for device debugging purpose
if ctx.zedcloudMetrics != nil {
ctx.zedcloudMetrics.Publish(log, ctx.pubMetricsMap, "global")
}
}
func getCellularMetrics(ctx *zedagentContext) (cellularMetrics []*metrics.CellularMetric) {
m, err := ctx.subWwanMetrics.Get("global")
if err != nil {
log.Errorf("subWwanMetrics.Get failed: %v", err)
return
}
wwanMetrics, ok := m.(types.WwanMetrics)
if !ok {
log.Errorln("unexpected type of wwan metrics")
return
}
for _, network := range wwanMetrics.Networks {
if network.LogicalLabel == "" {
// skip unmanaged modems for now
continue
}
cellularMetrics = append(cellularMetrics,
&metrics.CellularMetric{
Logicallabel: network.LogicalLabel,
SignalStrength: &metrics.CellularSignalStrength{
Rssi: network.SignalInfo.RSSI,
Rsrq: network.SignalInfo.RSRQ,
Rsrp: network.SignalInfo.RSRP,
Snr: network.SignalInfo.SNR,
},
PacketStats: &metrics.CellularPacketStats{
Rx: &metrics.NetworkStats{
TotalPackets: network.PacketStats.RxPackets,
Drops: network.PacketStats.RxDrops,
TotalBytes: network.PacketStats.RxBytes,
},
Tx: &metrics.NetworkStats{
TotalPackets: network.PacketStats.TxPackets,
Drops: network.PacketStats.TxDrops,
TotalBytes: network.PacketStats.TxBytes,
},
},
})
}
return cellularMetrics
}
func getDiskInfo(ctx *zedagentContext, vrs types.VolumeRefStatus, appDiskDetails *metrics.AppDiskMetric) error {
appDiskMetric := lookupAppDiskMetric(ctx, vrs.ActiveFileLocation)
if appDiskMetric == nil {
return fmt.Errorf("getDiskInfo: No AppDiskMetric found for %s", vrs.ActiveFileLocation)
}
appDiskDetails.Disk = vrs.ActiveFileLocation
appDiskDetails.Used = utils.RoundToMbytes(appDiskMetric.UsedBytes)
appDiskDetails.Provisioned = utils.RoundToMbytes(appDiskMetric.ProvisionedBytes)
appDiskDetails.DiskType = appDiskMetric.DiskType
appDiskDetails.Dirty = appDiskMetric.Dirty
return nil
}
func getVolumeResourcesInfo(ctx *zedagentContext, volStatus *types.VolumeStatus, volumeResourcesDetails *info.VolumeResources) error {
appDiskMetric := lookupAppDiskMetric(ctx, volStatus.FileLocation)
if appDiskMetric == nil {
err := fmt.Errorf("getVolumeResourcesInfo: No AppDiskMetric found for %s", volStatus.FileLocation)
log.Error(err)
return err
}
volumeResourcesDetails.CurSizeBytes = appDiskMetric.UsedBytes
volumeResourcesDetails.MaxSizeBytes = appDiskMetric.ProvisionedBytes
return nil
}
func getSecurityInfo(ctx *zedagentContext) *info.SecurityInfo {
si := new(info.SecurityInfo)
// Deterime sha of the root CA cert used for object signing and
// encryption
caCert1, err := os.ReadFile(types.RootCertFileName)
if err != nil {
log.Error(err)
} else {
hasher := sha256.New()
hasher.Write(caCert1)
si.ShaRootCa = hasher.Sum(nil)
}
// Add the sha of the root CAs used for TLS
// Note that we have the sha in a logical symlink so we
// just read that file.
line, err := os.ReadFile(types.V2TLSCertShaFilename)
if err != nil {
log.Error(err)
} else {
shaStr := strings.TrimSpace(string(line))
sha, err := hex.DecodeString(shaStr)
if err != nil {
log.Errorf("DecodeString %s failed: %s", shaStr, err)
} else {
si.ShaTlsRootCa = sha
}
}
log.Tracef("getSecurityInfo returns %+v", si)
return si
}
func setMetricAnyValue(item *metrics.MetricItem, val interface{}) {
switch t := val.(type) {
case uint32:
u := val.(uint32)
item.MetricItemValue = new(metrics.MetricItem_Uint32Value)
if x, ok := item.GetMetricItemValue().(*metrics.MetricItem_Uint32Value); ok {
x.Uint32Value = u
}
case uint64:
u := val.(uint64)
item.MetricItemValue = new(metrics.MetricItem_Uint64Value)
if x, ok := item.GetMetricItemValue().(*metrics.MetricItem_Uint64Value); ok {
x.Uint64Value = u
}
case bool:
b := val.(bool)
item.MetricItemValue = new(metrics.MetricItem_BoolValue)
if x, ok := item.GetMetricItemValue().(*metrics.MetricItem_BoolValue); ok {
x.BoolValue = b
}
case float32:
f := val.(float32)
item.MetricItemValue = new(metrics.MetricItem_FloatValue)