-
Notifications
You must be signed in to change notification settings - Fork 164
/
newlogd.go
1967 lines (1719 loc) · 56.6 KB
/
newlogd.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
package main
import (
"bufio"
"bytes"
"compress/gzip"
"encoding/json"
"flag"
"fmt"
"io"
"net"
"os"
"path"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"unicode"
"github.com/euank/go-kmsg-parser/kmsgparser"
"github.com/golang/protobuf/ptypes/timestamp"
"github.com/google/go-cmp/cmp"
"github.com/lf-edge/eve-api/go/logs"
"github.com/lf-edge/eve/pkg/pillar/agentlog"
"github.com/lf-edge/eve/pkg/pillar/base"
"github.com/lf-edge/eve/pkg/pillar/flextimer"
"github.com/lf-edge/eve/pkg/pillar/pidfile"
"github.com/lf-edge/eve/pkg/pillar/pubsub"
"github.com/lf-edge/eve/pkg/pillar/pubsub/socketdriver"
"github.com/lf-edge/eve/pkg/pillar/types"
"github.com/sirupsen/logrus"
)
const (
agentName = "newlogd"
errorTime = 3 * time.Minute
warningTime = 40 * time.Second
metricsPublishInterval = 300 * time.Second
logfileDelay = 300 // maximum delay 5 minutes for log file collection
fastlogfileDelay = 10 // faster to close log file if fastUpload is enabled
stillRunningInerval = 25 * time.Second
devPrefix = types.DevPrefix
devPrefixKeep = types.DevPrefixKeep
devPrefixUpload = types.DevPrefixUpload
appPrefix = types.AppPrefix
tmpPrefix = "TempFile"
skipUpload = "skipTx."
maxLogFileSize int32 = 550000 // maximum collect file size in bytes
maxGzipFileSize int64 = 50000 // maximum gzipped file size for upload in bytes
gzipFileFooter int64 = 12 // size of gzip footer to use in calculations
defaultSyncCount = 30 // default log events flush/sync to disk file
maxToSendMbytes uint32 = 2048 // default 2 Gbytes for log files remains on disk
ansi = "[\u0009\u001B\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[a-zA-Z\\d]*)*)?\u0007)|(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))"
)
var (
logger *logrus.Logger
log *base.LogObject
collectDir = types.NewlogCollectDir
uploadDevDir = types.NewlogUploadDevDir
uploadAppDir = types.NewlogUploadAppDir
keepSentDir = types.NewlogKeepSentQueueDir
failSendDir = types.NewlogDir + "/failedUpload"
panicFileDir = types.NewlogDir + "/panicStacks"
symlinkFile = collectDir + "/current.device.log"
tmpSymlink = collectDir + "/tmp-sym.dev.log"
msgIDDevCnt uint64 = 1 // every log message increments the msg-id by 1
logmetrics types.NewlogMetrics // the log metric, publishes to zedagent
devMetaData devMeta
syncToFileCnt int // every 'N' log event count flush to log file
persistMbytes uint64 // '/persist' disk space total in Mbytes
gzipFilesCnt int64 // total gzip files written
panicBuf []byte // buffer to save panic crash stack
limitGzipFilesMbyts uint32 // maximum Mbytes for gzip files remain to be sent up
enableFastUpload bool // enable fast upload to controller similar to previous log operation
lastLogNum int // last number used for file name generation
subGlobalConfig pubsub.Subscription
schedResetTimer *time.Timer // after detect log has watchdog going down message, reset the file flush count
panicWriteTimer *time.Timer // after detect pillar panic, in case no other log comes in, write the panic files
// per app writelog stats
appStatsMap map[string]statsLogFile
// device source input bytes written to log file
devSourceBytes *base.LockedStringMap
// last number of bytes from call to calculate ranks
lastDevNumBytesWrite uint64
//domainUUID
domainUUID *base.LockedStringMap // App log, from domain-id to appDomain
// Default log levels for some subsystems. Variables are updated and used
// from different goroutines, so in order to push the changes out of the
// goroutines local caches and correctly observe changed values in another
// goroutine sync/atomic synchronization is used. You've been warned.
syslogPrio = types.SyslogKernelLogLevelNum[types.SyslogKernelDefaultLogLevel]
kernelPrio = types.SyslogKernelLogLevelNum[types.SyslogKernelDefaultLogLevel]
syslogRemotePrio = types.SyslogKernelLogLevelNum[types.SyslogKernelDefaultLogLevel]
kernelRemotePrio = types.SyslogKernelLogLevelNum[types.SyslogKernelDefaultLogLevel]
agentDefaultRemoteLogLevel atomic.Value // logrus.Level
agentsRemoteLogLevel sync.Map // map of agentName to logrus.Level
)
func init() {
// domain-name to UUID and App-name mapping
domainUUID = base.NewLockedStringMap()
agentDefaultRemoteLogLevel.Store(logrus.InfoLevel)
}
// for app Domain-ID mapping into UUID and DisplayName
type appDomain struct {
appUUID string
appName string
msgIDAppCnt uint64
disableLogs bool
trigMove bool
}
type inputEntry struct {
severity string
source string
content string // One line
pid string
filename string // file name that generated the logmsg
function string // function name that generated the log msg
timestamp string
appUUID string // App UUID
acName string // App Container Name
acLogTime string // App Container log time
sendToRemote bool // this log entry needs to be sent to remote
}
// collection time device/app temp file stats for file size and time limit
type statsLogFile struct {
index int
file *os.File
size int32
starttime time.Time
notUpload bool
}
// file info passing from collection to compression threads
type fileChanInfo struct {
tmpfile string
header string
inputSize int32
isApp bool
notUpload bool // app log is configured not to upload
}
// device Meta Data
type devMeta struct {
uuid string
imageVer string
curPart string
}
// parse log level string
func parseSyslogLogLevel(loglevel string) uint32 {
prio, ok := types.SyslogKernelLogLevelNum[loglevel]
if !ok {
prio = types.SyslogKernelLogLevelNum[types.SyslogKernelDefaultLogLevel]
}
return prio
}
// newlogd program
func main() {
restartPtr := flag.Bool("r", false, "Restart")
flag.Parse()
restarted := *restartPtr
logger, log = agentlog.Init(agentName)
if !restarted {
if err := pidfile.CheckAndCreatePidfile(log, agentName); err != nil {
log.Fatal(err)
}
syncToFileCnt = defaultSyncCount
} else {
// sync every log event in restart mode, going down in less than 5 min
syncToFileCnt = 1
}
persistMbytes = getPersistSpace()
limitGzipFilesMbyts = maxToSendMbytes
log.Functionf("newlogd: starting... restarted %v", restarted)
loggerChan := make(chan inputEntry, 10)
movefileChan := make(chan fileChanInfo, 5)
panicFileChan := make(chan []byte, 2)
ps := *pubsub.New(&socketdriver.SocketDriver{Logger: logger, Log: log}, logger, log)
// create the necessary directories upfront
for _, dir := range []string{collectDir, uploadDevDir, uploadAppDir, keepSentDir, panicFileDir} {
if _, err := os.Stat(dir); os.IsNotExist(err) {
if err := os.MkdirAll(dir, 0755); err != nil {
log.Fatal(err)
}
}
}
// handle the write log messages to /persist/newlog/collect/ logfiles
go writelogFile(loggerChan, movefileChan)
// handle the kernel messages
go getKmessages(loggerChan)
// handle collect other container log messages from memlogd
go getMemlogMsg(loggerChan, panicFileChan)
// handle linux Syslog /dev/log messages
go getSyslogMsg(loggerChan)
stillRunning := time.NewTicker(stillRunningInerval)
ps.StillRunning(agentName, warningTime, errorTime)
// Publish newlog metrics
metricsPub, err := ps.NewPublication(
pubsub.PublicationOptions{
AgentName: agentName,
TopicType: types.NewlogMetrics{},
})
if err != nil {
log.Fatal(err)
}
err = metricsPub.ClearRestarted()
if err != nil {
log.Fatal(err)
}
// Get DomainStatus from domainmgr
subDomainStatus, err := ps.NewSubscription(pubsub.SubscriptionOptions{
AgentName: "domainmgr",
TopicImpl: types.DomainStatus{},
Activate: true,
CreateHandler: handleDomainStatusCreate,
ModifyHandler: handleDomainStatusModify,
DeleteHandler: handleDomainStatusDelete,
WarningTime: warningTime,
ErrorTime: errorTime,
})
if err != nil {
log.Fatal(err)
}
subOnboardStatus, err := ps.NewSubscription(pubsub.SubscriptionOptions{
AgentName: "zedclient",
CreateHandler: handleOnboardStatusCreate,
ModifyHandler: handleOnboardStatusModify,
WarningTime: warningTime,
ErrorTime: errorTime,
TopicImpl: types.OnboardingStatus{},
Activate: true,
Persistent: true,
})
if err != nil {
log.Fatal(err)
}
// Look for global config such as log levels
subGlobalConfig, err = ps.NewSubscription(pubsub.SubscriptionOptions{
AgentName: "zedagent",
TopicImpl: types.ConfigItemValueMap{},
Persistent: true,
Activate: false,
CreateHandler: handleGlobalConfigCreate,
ModifyHandler: handleGlobalConfigModify,
WarningTime: warningTime,
ErrorTime: errorTime,
})
if err != nil {
log.Fatal(err)
}
err = subGlobalConfig.Activate()
if err != nil {
log.Fatal(err)
}
subUploadMetrics, err := ps.NewSubscription(pubsub.SubscriptionOptions{
AgentName: "loguploader",
CreateHandler: handleUploadMetricsCreate,
ModifyHandler: handleUploadMetricsModify,
WarningTime: warningTime,
ErrorTime: errorTime,
TopicImpl: types.NewlogMetrics{},
Activate: true,
})
if err != nil {
log.Fatal(err)
}
// newlog Metrics publish timer. Publish log metrics every 5 minutes.
interval := time.Duration(metricsPublishInterval)
max := float64(interval)
min := max * 0.3
metricsPublishTimer := flextimer.NewRangeTicker(time.Duration(min),
time.Duration(max))
schedResetTimer = time.NewTimer(1 * time.Second)
schedResetTimer.Stop()
panicWriteTimer = time.NewTimer(1 * time.Second)
panicWriteTimer.Stop()
// set default timeout of logfile delay
if enableFastUpload {
logmetrics.LogfileTimeoutSec = uint32(fastlogfileDelay)
} else {
logmetrics.LogfileTimeoutSec = uint32(logfileDelay)
}
for {
select {
case <-metricsPublishTimer.C:
getDevTop10Inputs()
err = metricsPub.Publish("global", logmetrics)
if err != nil {
log.Error(err)
}
log.Tracef("newlodg main: Published newlog metrics at %s", time.Now().String())
// check and handle if logfile quota exceeded
checkKeepQuota()
case change := <-subDomainStatus.MsgChan():
subDomainStatus.ProcessChange(change)
case change := <-subUploadMetrics.MsgChan():
subUploadMetrics.ProcessChange(change)
case change := <-subGlobalConfig.MsgChan():
subGlobalConfig.ProcessChange(change)
case change := <-subOnboardStatus.MsgChan():
subOnboardStatus.ProcessChange(change)
case tmpLogfileInfo := <-movefileChan:
// handle logfile to gzip conversion work
doMoveCompressFile(&ps, tmpLogfileInfo)
case panicBuf := <-panicFileChan:
// save panic stack into files
savePanicFiles(panicBuf)
case <-panicWriteTimer.C:
if len(panicBuf) > 0 {
savePanicFiles(panicBuf)
panicBuf = nil
}
case <-schedResetTimer.C:
syncToFileCnt = defaultSyncCount
case <-stillRunning.C:
}
ps.StillRunning(agentName, warningTime, errorTime)
}
}
// Handles upload side of Newlog metrics
func handleUploadMetricsCreate(ctxArg interface{}, key string, statusArg interface{}) {
handleUploadMetricsImp(ctxArg, key, statusArg)
}
// Handles upload side of Newlog metrics
func handleUploadMetricsModify(ctxArg interface{}, key string,
statusArg interface{}, oldStatusArg interface{}) {
handleUploadMetricsImp(ctxArg, key, statusArg)
}
// Handles and combine loguploader side of Newlog metrics
func handleUploadMetricsImp(ctxArg interface{}, key string, statusArg interface{}) {
status := statusArg.(types.NewlogMetrics)
logmetrics.TotalBytesUpload = status.TotalBytesUpload
logmetrics.Num4xxResponses = status.Num4xxResponses
logmetrics.NumTooManyRequest = status.NumTooManyRequest
logmetrics.Latency.MinUploadMsec = status.Latency.MinUploadMsec
logmetrics.Latency.MaxUploadMsec = status.Latency.MaxUploadMsec
logmetrics.Latency.AvgUploadMsec = status.Latency.AvgUploadMsec
logmetrics.Latency.CurrUploadMsec = status.Latency.CurrUploadMsec
logmetrics.CurrUploadIntvSec = status.CurrUploadIntvSec
logmetrics.ServerStats.CurrCPULoadPCT = status.ServerStats.CurrCPULoadPCT
logmetrics.ServerStats.AvgCPULoadPCT = status.ServerStats.AvgCPULoadPCT
logmetrics.ServerStats.CurrProcessMsec = status.ServerStats.CurrProcessMsec
logmetrics.ServerStats.AvgProcessMsec = status.ServerStats.AvgProcessMsec
// loguplader signal to newlogd on upload fail status
logmetrics.FailedToSend = status.FailedToSend
logmetrics.FailSentStartTime = status.FailSentStartTime
logmetrics.LastTooManyReqTime = status.LastTooManyReqTime
logmetrics.DevMetrics.NumGZipFilesSent = status.DevMetrics.NumGZipFilesSent
logmetrics.DevMetrics.NumGzipFileInDir = status.DevMetrics.NumGzipFileInDir
logmetrics.DevMetrics.NumGZipFileRetry = status.DevMetrics.NumGZipFileRetry
logmetrics.DevMetrics.RecentUploadTimestamp = status.DevMetrics.RecentUploadTimestamp
logmetrics.DevMetrics.LastGZipFileSendTime = status.DevMetrics.LastGZipFileSendTime
logmetrics.DevMetrics.NumGZipFileKeptLocal = status.DevMetrics.NumGZipFileKeptLocal
logmetrics.AppMetrics.NumGZipFilesSent = status.AppMetrics.NumGZipFilesSent
logmetrics.AppMetrics.NumGzipFileInDir = status.AppMetrics.NumGzipFileInDir
logmetrics.AppMetrics.NumGZipFileRetry = status.AppMetrics.NumGZipFileRetry
logmetrics.AppMetrics.RecentUploadTimestamp = status.AppMetrics.RecentUploadTimestamp
logmetrics.AppMetrics.LastGZipFileSendTime = status.AppMetrics.LastGZipFileSendTime
logmetrics.AppMetrics.NumGZipFileKeptLocal = status.AppMetrics.NumGZipFileKeptLocal
log.Tracef("newlogd handleUploadMetricsModify changed to %+v", status)
}
// Handles UUID change from process client
func handleOnboardStatusCreate(ctxArg interface{}, key string, statusArg interface{}) {
handleOnboardStatusImp(ctxArg, key, statusArg)
}
// Handles UUID change from process client
func handleOnboardStatusModify(ctxArg interface{}, key string,
statusArg interface{}, oldStatusArg interface{}) {
handleOnboardStatusImp(ctxArg, key, statusArg)
}
// Handles UUID change from process client
func handleOnboardStatusImp(ctxArg interface{}, key string, statusArg interface{}) {
status := statusArg.(types.OnboardingStatus)
if cmp.Equal(devMetaData.uuid, status.DeviceUUID.String()) {
log.Tracef("newlogd handleOnboardStatusModify no change to %s", devMetaData.uuid)
return
}
devMetaData.uuid = status.DeviceUUID.String()
log.Functionf("newlogd handleOnboardStatusModify changed to %+v", devMetaData)
}
func handleDomainStatusCreate(ctxArg interface{}, key string, statusArg interface{}) {
handleDomainStatusImp(ctxArg, key, statusArg)
}
func handleDomainStatusModify(ctxArg interface{}, key string,
statusArg interface{}, oldStatusArg interface{}) {
handleDomainStatusImp(ctxArg, key, statusArg)
}
func handleDomainStatusImp(ctxArg interface{}, key string, statusArg interface{}) {
log.Tracef("handleDomainStatusModify: for %s", key)
status := statusArg.(types.DomainStatus)
// Record the domainName even if Pending* is set
log.Tracef("handleDomainStatusModify: add %s to %s",
status.DomainName, status.UUIDandVersion.UUID.String())
appD := appDomain{
appUUID: status.UUIDandVersion.UUID.String(),
appName: status.DisplayName,
disableLogs: status.DisableLogs,
msgIDAppCnt: 1,
}
// close the app log file if already opened due to app log policy change
if val, ok := domainUUID.Load(appD.appUUID); ok {
d := val.(appDomain)
if d.disableLogs != appD.disableLogs {
appD.trigMove = true
} else {
appD.trigMove = d.trigMove
}
appD.msgIDAppCnt = d.msgIDAppCnt // inherit the counter for the app
}
domainUUID.Store(appD.appUUID, appD)
log.Tracef("handleDomainStatusModify: done for %s", key)
}
func handleDomainStatusDelete(ctxArg interface{}, key string, statusArg interface{}) {
log.Tracef("handleDomainStatusDelete: for %s", key)
status := statusArg.(types.DomainStatus)
appUUID := status.UUIDandVersion.UUID.String()
if _, ok := domainUUID.Load(appUUID); !ok {
return
}
log.Tracef("handleDomainStatusDelete: remove %s", appUUID)
domainUUID.Delete(appUUID)
log.Tracef("handleDomainStatusDelete: done for %s", key)
}
// Handles create events
func handleGlobalConfigCreate(ctxArg interface{}, key string, statusArg interface{}) {
handleGlobalConfigImp(ctxArg, key, statusArg)
}
// Handles modify events
func handleGlobalConfigModify(ctxArg interface{}, key string,
statusArg interface{}, oldStatusArg interface{}) {
handleGlobalConfigImp(ctxArg, key, statusArg)
}
func handleGlobalConfigImp(ctxArg interface{}, key string, statusArg interface{}) {
if key != "global" {
log.Tracef("handleGlobalConfigModify: ignoring %s", key)
return
}
gcp := agentlog.HandleGlobalConfig(log, subGlobalConfig, agentName, false, logger)
if gcp != nil {
enabled := gcp.GlobalValueBool(types.AllowLogFastupload)
if enableFastUpload != enabled {
if enabled {
logmetrics.LogfileTimeoutSec = uint32(fastlogfileDelay)
} else {
logmetrics.LogfileTimeoutSec = uint32(logfileDelay)
}
}
enableFastUpload = enabled
// get user specified disk quota for logs and cap at 10% of /persist space
limitGzipFilesMbyts = gcp.GlobalValueInt(types.LogRemainToSendMBytes)
if limitGzipFilesMbyts > uint32(persistMbytes/10) {
limitGzipFilesMbyts = uint32(persistMbytes / 10)
}
// parse agent's individual remote log levels
for agentName := range gcp.AgentSettings {
loglevel := getRemoteLogLevelImpl(gcp, agentName)
agentsRemoteLogLevel.Store(agentName, parseAgentLogLevel(loglevel))
}
// parse agent's default remote log level
loglevel := gcp.GlobalValueString(types.DefaultRemoteLogLevel)
agentDefaultRemoteLogLevel.Store(parseAgentLogLevel(loglevel))
// parse syslog log level
syslogPrioStr := gcp.GlobalValueString(types.SyslogLogLevel)
atomic.StoreUint32(&syslogPrio, parseSyslogLogLevel(syslogPrioStr))
// parse kernel log level
kernelPrioStr := gcp.GlobalValueString(types.KernelLogLevel)
atomic.StoreUint32(&kernelPrio, parseSyslogLogLevel(kernelPrioStr))
// parse syslog remote log level
syslogRemotePrioStr := gcp.GlobalValueString(types.SyslogRemoteLogLevel)
atomic.StoreUint32(&syslogRemotePrio, parseSyslogLogLevel(syslogRemotePrioStr))
// parse kernel remote log level
kernelRemotePrioStr := gcp.GlobalValueString(types.KernelRemoteLogLevel)
atomic.StoreUint32(&kernelRemotePrio, parseSyslogLogLevel(kernelRemotePrioStr))
}
log.Tracef("handleGlobalConfigModify done for %s, fastupload enabled %v", key, enableFastUpload)
}
func parseAgentLogLevel(loglevel string) logrus.Level {
switch loglevel {
case "none":
// TODO: this should suppress most logs, but needs to be later replaced with a better solution
return logrus.PanicLevel
case "all":
return logrus.TraceLevel
default:
level, err := logrus.ParseLevel(loglevel)
if err != nil {
log.Errorf("parseAgentLogLevel: invalid log level %s for %s", loglevel, agentName)
}
return level
}
}
func getRemoteLogLevelImpl(gc *types.ConfigItemValueMap, agentName string) string {
// Do we have an entry for this agent?
loglevel := gc.AgentSettingStringValue(agentName, types.RemoteLogLevel)
if loglevel != "" {
log.Tracef("getRemoteLogLevelImpl: loglevel=%s", loglevel)
return loglevel
}
// Agent specific setting not available. Get it from Global Setting
loglevel = gc.GlobalValueString(types.DefaultRemoteLogLevel)
if loglevel != "" {
log.Tracef("getRemoteLogLevelImpl: returning DefaultRemoteLogLevel (%s)",
loglevel)
return loglevel
}
log.Errorf("***getRemoteLogLevelImpl: DefaultRemoteLogLevel not found. " +
"returning info")
return "info"
}
func suppressMsg(entry inputEntry, cfgPrio uint32) bool {
pri := parseSyslogLogLevel(entry.severity)
return pri > cfgPrio
}
// getKmessages - goroutine to get from /dev/kmsg
func getKmessages(loggerChan chan inputEntry) {
parser, err := kmsgparser.NewParser()
if err != nil {
log.Fatalf("unable to create kmsg parser: %v", err)
}
defer parser.Close()
kmsg := parser.Parse()
for msg := range kmsg {
entry := inputEntry{
source: "kernel",
severity: types.SyslogKernelDefaultLogLevel,
content: msg.Message,
timestamp: msg.Timestamp.Format(time.RFC3339Nano),
}
if msg.Priority >= 0 {
entry.severity = types.SyslogKernelLogLevelStr[msg.Priority%8]
}
if suppressMsg(entry, atomic.LoadUint32(&kernelPrio)) {
continue
}
entry.sendToRemote = types.SyslogKernelLogLevelNum[entry.severity] <= atomic.LoadUint32(&kernelRemotePrio)
logmetrics.NumKmessages++
logmetrics.DevMetrics.NumInputEvent++
log.Tracef("getKmessages (%d) entry msg %s", logmetrics.NumKmessages, entry.content)
loggerChan <- entry
}
}
// getMemlogMsg - goroutine to get messages from memlogd queue
func getMemlogMsg(logChan chan inputEntry, panicFileChan chan []byte) {
sockName := fmt.Sprintf("/run/%s.sock", "memlogdq")
s, err := net.Dial("unix", sockName)
if err != nil {
log.Fatal("getMemlogMsg: Dial:", err)
}
defer s.Close()
log.Functionf("getMemlogMsg: got socket for memlogdq")
var writeByte byte = 2
readTimeout := 30 * time.Second
// have to write byte value 2 to trigger memlogd queue streaming
_, err = s.Write([]byte{writeByte})
if err != nil {
log.Fatal("getMemlogMsg: write to memlogd failed:", err)
}
var panicStackCount int
bufReader := bufio.NewReader(s)
for {
if err = s.SetDeadline(time.Now().Add(readTimeout)); err != nil {
log.Fatal("getMemlogMsg: SetDeadline:", err)
}
bytes, err := bufReader.ReadBytes('\n')
if err != nil {
if err != io.EOF && !strings.HasSuffix(err.Error(), "i/o timeout") {
log.Fatal("getMemlogMsg: bufRead Read:", err)
}
}
if len(bytes) == 0 {
time.Sleep(5 * time.Second)
continue
}
var pidStr string
// Everything is json, in some cases with an embedded json Msg
var logEntry MemlogLogEntry
if err := json.Unmarshal(bytes, &logEntry); err != nil {
log.Warnf("Received non-json from memlogd: %s\n",
string(bytes))
continue
}
// Is the Msg itself json?
var logInfo Loginfo
if err := json.Unmarshal([]byte(logEntry.Msg), &logInfo); err == nil {
// Use the inner JSON struct
// Go back to the envelope for anything not in the inner JSON
if logInfo.Time == "" {
logInfo.Time = logEntry.Time
}
if logInfo.Source == "" {
logInfo.Source = logEntry.Source
}
// and keep the original message text and fields
logInfo.Msg = logEntry.Msg
} else {
// Start with the envelope
logInfo.Source = logEntry.Source
logInfo.Time = logEntry.Time
logInfo.Msg = logEntry.Msg
// Some messages have attr=val syntax
// If the inner message has Level, Time or Msg set they take
// precedence over the envelope
level, timeStr, msg := parseLevelTimeMsg(logEntry.Msg)
if level != "" {
logInfo.Level = level
}
if timeStr != "" {
logInfo.Time = timeStr
}
if msg != "" {
logInfo.Msg = msg
}
}
// all logs must have the level field
if logInfo.Level == "" {
logInfo.Level = logrus.InfoLevel.String()
}
logFromApp := strings.Contains(logInfo.Source, "guest_vm") || logInfo.Containername != ""
if logFromApp {
logmetrics.AppMetrics.NumInputEvent++
} else {
logmetrics.DevMetrics.NumInputEvent++
}
if logInfo.Pid != 0 {
pidStr = strconv.Itoa(logInfo.Pid)
}
// not to upload 'kube' container logs, one can find in /persist/kubelog for detail
if logInfo.Source == "kube" {
continue
}
sendToRemote := false
if !logFromApp { // there are no granularity nobs for the edge apps' log levels
loglevel, err := logrus.ParseLevel(logInfo.Level)
if err != nil {
log.Errorf("getMemlogMsg: found invalid log level %s in message from %s", logInfo.Level, logInfo.Source)
} else {
// see if we have an agent specific log level
if remoteLogLevel, ok := agentsRemoteLogLevel.Load(logInfo.Source); ok {
sendToRemote = loglevel <= remoteLogLevel.(logrus.Level)
} else {
sendToRemote = loglevel <= agentDefaultRemoteLogLevel.Load().(logrus.Level)
}
}
}
entry := inputEntry{
source: logInfo.Source,
content: logInfo.Msg,
pid: pidStr,
timestamp: logInfo.Time,
function: logInfo.Function,
filename: logInfo.Filename,
severity: logInfo.Level,
appUUID: logInfo.Appuuid,
acName: logInfo.Containername,
acLogTime: logInfo.Eventtime,
sendToRemote: sendToRemote,
}
// if we are in watchdog going down. fsync often
checkWatchdogRestart(&entry, &panicStackCount, string(bytes), panicFileChan)
logChan <- entry
}
}
// Returns level, time and msg if the string contains those attr=val
func parseLevelTimeMsg(content string) (level string, timeStr string, msg string) {
content = remNonPrintable(content)
if strings.Contains(content, ",\"msg\":") {
// Json or something - bail
return
}
level1 := strings.SplitN(content, "level=", 2)
if len(level1) == 2 {
level2 := strings.Split(level1[1], " ")
level = level2[0]
}
time1 := strings.SplitN(content, "time=", 2)
if len(time1) == 2 {
time2 := strings.Split(time1[1], "\"")
if len(time2) == 3 {
timeStr = time2[1]
}
}
msg1 := strings.SplitN(content, "msg=", 2)
if len(msg1) == 2 {
msg2 := strings.Split(msg1[1], "\"")
if len(msg2) == 3 {
msg = msg2[1]
}
}
return
}
func createLogTmpfile(dirname, filename string) *os.File {
tmpFile, err := os.CreateTemp(dirname, filename)
if err != nil {
log.Fatal(err)
}
err = tmpFile.Chmod(0600)
if err != nil {
log.Fatal(err)
}
log.Function("Created new temp log file: ", tmpFile.Name())
// make symbolic link for device log file to keep
if filename == devPrefixKeep {
if err := os.Remove(tmpSymlink); err != nil && !os.IsNotExist(err) { // remove a stale one
log.Error(err)
}
err = os.Symlink(path.Base(tmpFile.Name()), tmpSymlink)
if err != nil {
log.Error(err)
}
err = os.Rename(tmpSymlink, symlinkFile)
if err != nil {
log.Error(err)
}
log.Function("Pointed symlink ", symlinkFile, " to ", tmpFile.Name())
}
return tmpFile
}
func remNonPrintable(str string) string {
var re = regexp.MustCompile(ansi)
myStr := re.ReplaceAllString(str, "")
myStr = strings.Trim(myStr, "\r")
return strings.Trim(myStr, "\n")
}
// writelogFile - a goroutine to format and write log entries into dev/app logfiles
func writelogFile(logChan <-chan inputEntry, moveChan chan fileChanInfo) {
// get EVE version and partition, UUID may not be available yet
getEveInfo()
// move and gzip the existing logfiles first
findMovePrevLogFiles(moveChan)
// new file to collect device logs for upload
devStatsUpload := initNewLogfile(collectDir, devPrefixUpload, "")
defer devStatsUpload.file.Close()
devStatsUpload.notUpload = false
// new file to collect device logs to keep on device
devStatsKeep := initNewLogfile(collectDir, devPrefixKeep, "")
defer devStatsKeep.file.Close()
devStatsKeep.notUpload = true
oldestLogEntry, err := getOldestLog()
if err != nil {
log.Errorf("could not set OldestSavedDeviceLog metric due to getLatestLog error: %v", err)
} else {
if oldestLogEntry == nil {
// no log entry found, set the oldest log time to now
logmetrics.OldestSavedDeviceLog = time.Now()
} else {
logmetrics.OldestSavedDeviceLog = time.Unix(oldestLogEntry.Timestamp.Seconds, int64(oldestLogEntry.Timestamp.Nanos))
}
}
devSourceBytes = base.NewLockedStringMap()
appStatsMap = make(map[string]statsLogFile)
checklogTimer := time.NewTimer(5 * time.Second)
timeIdx := 0
for {
select {
case <-checklogTimer.C:
timeIdx++
checkLogTimeExpire(&devStatsUpload, moveChan) // only check the upload log file, there is no need to hurry moving the keep log file
checklogTimer = time.NewTimer(5 * time.Second) // check the file time limit every 5 seconds
case entry := <-logChan:
appuuid := checkAppEntry(&entry)
var appM statsLogFile
if appuuid != "" {
appM = getAppStatsMap(appuuid)
}
timeS, _ := getPtypeTimestamp(entry.timestamp)
mapLog := logs.LogEntry{
Severity: entry.severity,
Source: entry.source,
Content: entry.content,
Iid: entry.pid,
Filename: entry.filename,
Msgid: updateLogMsgID(appuuid),
Function: entry.function,
Timestamp: timeS,
}
mapJentry, _ := json.Marshal(&mapLog)
logline := string(mapJentry) + "\n"
if appuuid != "" {
len := writelogEntry(&appM, logline)
logmetrics.AppMetrics.NumBytesWrite += uint64(len)
appStatsMap[appuuid] = appM
trigMoveToGzip(&appM, appuuid, moveChan, false)
} else {
if entry.sendToRemote {
writelogEntry(&devStatsUpload, logline)
trigMoveToGzip(&devStatsUpload, "", moveChan, false)
}
// write all log entries to the log file to keep
len := writelogEntry(&devStatsKeep, logline)
updateDevInputlogStats(entry.source, uint64(len))
trigMoveToGzip(&devStatsKeep, "", moveChan, false)
}
}
}
}
func checkAppEntry(entry *inputEntry) string {
appuuid := ""
var appVMlog bool
var appSplitArr []string
if entry.appUUID != "" {
appuuid = entry.appUUID
entry.content = "{\"container\":\"" + entry.acName + "\",\"time\":\"" + entry.acLogTime + "\",\"msg\":\"" + entry.content + "\"}"
} else if strings.HasPrefix(entry.source, "guest_vm-") {
appSplitArr = strings.SplitN(entry.source, "guest_vm-", 2)
appVMlog = true
} else if strings.HasPrefix(entry.source, "guest_vm_err-") {
appSplitArr = strings.SplitN(entry.source, "guest_vm_err-", 2)
appVMlog = true
}
if appVMlog {
if len(appSplitArr) == 2 {
if appSplitArr[0] == "" && appSplitArr[1] != "" {
// entry.source is the 'domainName' in the format
// of app-uuid.restart-num.app-num
entry.source = appSplitArr[1]
appsource := strings.Split(entry.source, ".")
if val, ok := domainUUID.Load(appsource[0]); ok {
du := val.(appDomain)
appuuid = du.appUUID
} else {
log.Tracef("entry.source not in right format %s", entry.source)
}
}
}
}
return appuuid
}
// updateLogMsgID - handles the msgID for log for both dev and apps
// dev log does not have app-uuid, thus domainName passed in is ""
func updateLogMsgID(appUUID string) uint64 {
var msgid uint64
if appUUID == "" {
msgid = msgIDDevCnt
msgIDDevCnt++
} else {
if val, ok := domainUUID.Load(appUUID); ok {
appD := val.(appDomain)
msgid = appD.msgIDAppCnt
appD.msgIDAppCnt++
domainUUID.Store(appUUID, appD)
}
}
return msgid
}
func getAppStatsMap(appuuid string) statsLogFile {
if _, ok := appStatsMap[appuuid]; !ok {
applogname := appPrefix + appuuid + ".log"
appM := initNewLogfile(collectDir, applogname, appuuid)
val, found := domainUUID.Load(appuuid)
if found {
appD := val.(appDomain)
appM.notUpload = appD.disableLogs
if appD.trigMove {
appD.trigMove = false // reset this since we start a new file
domainUUID.Store(appuuid, appD)
}
}
appStatsMap[appuuid] = appM
}
return appStatsMap[appuuid]