-
Notifications
You must be signed in to change notification settings - Fork 164
/
Copy pathagent.go
1478 lines (1402 loc) · 46.5 KB
/
agent.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) 2023 Zededa, Inc.
// SPDX-License-Identifier: Apache-2.0
package main
import (
"bytes"
"context"
"errors"
"flag"
"fmt"
"net"
"os"
"path"
"strconv"
"strings"
"time"
"github.com/lf-edge/eve/pkg/pillar/agentbase"
"github.com/lf-edge/eve/pkg/pillar/agentlog"
"github.com/lf-edge/eve/pkg/pillar/base"
"github.com/lf-edge/eve/pkg/pillar/cipher"
"github.com/lf-edge/eve/pkg/pillar/flextimer"
"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"
fileutils "github.com/lf-edge/eve/pkg/pillar/utils/file"
"github.com/lf-edge/eve/pkg/wwan/mmagent/mmdbus"
"github.com/miekg/dns"
"github.com/sirupsen/logrus"
"github.com/tatsushid/go-fastping"
"github.com/vishvananda/netlink"
"golang.org/x/sys/unix"
)
const (
agentName = "wwan"
errorTime = 3 * time.Minute
warningTime = 40 * time.Second
wdTouchPeriod = 25 * time.Second
mmStartTimeout = time.Minute
metricsPublishPeriod = time.Minute
retryPeriod = 1 * time.Minute
suspendReconcilePeriod = retryPeriod >> 1
connProbePeriod = 5 * time.Minute
defRouteBaseMetric = 65000
icmpProbeMaxRTT = time.Second
icmpProbeMaxAttempts = 3
tcpProbeTimeout = 5 * time.Second
dnsProbeTimeout = 5 * time.Second
scanProvidersPeriod = time.Hour
)
const (
// WwanResolvConfDir : directory where wwan microservice stores resolv.conf
// files separately for every interface (named <interface>.dhcp).
// TODO: this is already defined in pillar/devicenetwork, but importing that package
// brings in tons of unnecessary dependencies. It would be better to move this
// constant to pillar/types or to some other small common package.
// Alternatively, CheckAndGetNetworkProxy (which has those many deps) could be
// moved out from devicenetwork to some other place.
WwanResolvConfDir = "/run/wwan/resolv.conf"
)
var (
_, ipv4Any, _ = net.ParseCIDR("0.0.0.0/0")
_, ipv6Any, _ = net.ParseCIDR("::/0")
emptyPhysAddrs = types.WwanPhysAddrs{}
defaultProbeAddr = net.ParseIP("8.8.8.8")
emptyIPSettings = types.WwanIPSettings{}
)
// MMAgent is an EVE microservice controlling ModemManager (https://modemmanager.org/).
type MMAgent struct {
agentbase.AgentBase
logger *logrus.Logger
log *base.LogObject
ps *pubsub.PubSub
// publications
pubWwanStatus pubsub.Publication
pubWwanMetrics pubsub.Publication
pubWwanLocationInfo pubsub.Publication
pubCipherBlockStatus pubsub.Publication
pubCipherMetrics pubsub.Publication
cipherMetrics *cipher.AgentMetrics
// subscriptions
subGlobalConfig pubsub.Subscription
subWwanConfig pubsub.Subscription
subControllerCert pubsub.Subscription
subEdgeNodeCert pubsub.Subscription
// client for communication with MM
mmClient *mmdbus.Client
// global config properties
gcInitialized bool
globalConfig types.ConfigItemValueMap
dpcKey string
dpcTimestamp time.Time
rsConfigTimestamp time.Time
radioSilence bool
locPublishPeriod time.Duration
locTrackingModem string // selected modem for location tracking (DBus path)
scanProviders bool
// config, state data and metrics collected for every cellular modem
modemInfo map[string]*ModemInfo // key: DBus path
missingModems []types.WwanNetworkConfig
// True when modem metrics have been updated and should be published
metricsUpdated bool
}
// ModemInfo : collection of config, state data and metrics stored by the agent
// inside MMAgent.modemInfo for every modem detected by ModemManager.
// Note that modems which have config but are not physically present are recorded
// in MMAgent.missingModems.
type ModemInfo struct {
// State data and metrics received from the ModemManager D-Bus client.
mmdbus.Modem
// Unmanaged modem has empty Config (LogicalLabel is empty string).
config types.WwanNetworkConfig
// Previous config - used only within the applyWwanConfig function.
prevConfig types.WwanNetworkConfig
// IP settings applied for the wwan* interface in the Linux network stack.
appliedIPSettings types.WwanIPSettings
// Last applied user-configured MTU.
appliedUserMTU uint16
// Decrypted username and password (from Config.AccessPoint.EncryptedCredentials).
decryptedUsername string
decryptedPassword string
// Latest errors encountered while managing this modem.
probeError error
connectError error
decryptError error
locTrackingError error
// Modem changes/operations take time to apply.
// After changing any modem settings, we suspend reconcileModem from touching the modem
// for a short period of time (half the retryPeriod).
suspendedReconcileUntil time.Time
}
// IsManaged : modem configured by EVE controller is denoted as "managed".
func (m *ModemInfo) IsManaged() bool {
return m.config.LogicalLabel != ""
}
// AddAgentSpecificCLIFlags defines the version argument.
func (a *MMAgent) AddAgentSpecificCLIFlags(flagSet *flag.FlagSet) {
}
// Init performs initialization of the agent. Should be called before Run.
func (a *MMAgent) Init() (err error) {
a.logger, a.log = agentlog.Init(agentName)
a.ps = pubsub.New(
&socketdriver.SocketDriver{Logger: a.logger, Log: a.log},
a.logger, a.log)
arguments := os.Args[1:]
agentbase.Init(a, a.logger, a.log, agentName,
agentbase.WithArguments(arguments), agentbase.WithPidFile(),
agentbase.WithWatchdog(a.ps, warningTime, errorTime))
a.modemInfo = make(map[string]*ModemInfo)
if err = a.ensureDir(WwanResolvConfDir); err != nil {
return err
}
if err = a.initPublications(); err != nil {
return err
}
if err = a.initSubscriptions(); err != nil {
return err
}
a.cipherMetrics = cipher.NewAgentMetrics(agentName)
a.mmClient, err = mmdbus.NewClient(a.log)
if err != nil {
return err
}
return nil
}
func (a *MMAgent) initPublications() (err error) {
a.pubWwanStatus, err = a.ps.NewPublication(
pubsub.PublicationOptions{
AgentName: agentName,
TopicType: types.WwanStatus{},
})
if err != nil {
return err
}
a.pubWwanMetrics, err = a.ps.NewPublication(
pubsub.PublicationOptions{
AgentName: agentName,
TopicType: types.WwanMetrics{},
})
if err != nil {
return err
}
a.pubWwanLocationInfo, err = a.ps.NewPublication(
pubsub.PublicationOptions{
AgentName: agentName,
TopicType: types.WwanLocationInfo{},
})
if err != nil {
return err
}
a.pubCipherBlockStatus, err = a.ps.NewPublication(
pubsub.PublicationOptions{
AgentName: agentName,
TopicType: types.CipherBlockStatus{},
})
if err != nil {
return err
}
a.pubCipherMetrics, err = a.ps.NewPublication(pubsub.PublicationOptions{
AgentName: agentName,
TopicType: types.CipherMetrics{},
})
if err != nil {
return err
}
return nil
}
func (a *MMAgent) initSubscriptions() (err error) {
a.subGlobalConfig, err = a.ps.NewSubscription(pubsub.SubscriptionOptions{
AgentName: "zedagent",
MyAgentName: agentName,
TopicImpl: types.ConfigItemValueMap{},
Persistent: true,
Activate: false,
CreateHandler: a.handleGlobalConfigCreate,
ModifyHandler: a.handleGlobalConfigModify,
DeleteHandler: a.handleGlobalConfigDelete,
WarningTime: warningTime,
ErrorTime: errorTime,
})
if err != nil {
return err
}
a.subWwanConfig, err = a.ps.NewSubscription(pubsub.SubscriptionOptions{
AgentName: "nim",
MyAgentName: agentName,
TopicImpl: types.WwanConfig{},
Activate: false,
CreateHandler: a.handleWwanConfigCreate,
ModifyHandler: a.handleWwanConfigModify,
DeleteHandler: a.handleWwanConfigDelete,
WarningTime: warningTime,
ErrorTime: errorTime,
})
if err != nil {
return err
}
// Look for controller certs which will be used for decryption.
a.subControllerCert, err = a.ps.NewSubscription(pubsub.SubscriptionOptions{
AgentName: "zedagent",
MyAgentName: agentName,
TopicImpl: types.ControllerCert{},
Persistent: true,
Activate: false,
WarningTime: warningTime,
ErrorTime: errorTime,
})
if err != nil {
return err
}
// Look for edge node certs which will be used for decryption
a.subEdgeNodeCert, err = a.ps.NewSubscription(pubsub.SubscriptionOptions{
AgentName: "tpmmgr",
MyAgentName: agentName,
TopicImpl: types.EdgeNodeCert{},
Persistent: true,
Activate: false,
WarningTime: warningTime,
ErrorTime: errorTime,
})
if err != nil {
return err
}
return nil
}
func (a *MMAgent) ensureDir(dirname string) error {
err := os.MkdirAll(dirname, 0755)
if err != nil {
err = fmt.Errorf("failed to create directory %s: %w", dirname, err)
a.log.Error(err)
return err
}
return nil
}
// Run runs the agent.
// It is a blocking call and returns only when a critical run-time error is detected
// or the context is canceled.
func (a *MMAgent) Run(ctx context.Context) error {
a.log.Noticef("Starting %s", agentName)
// Run a periodic timer so we always update StillRunning
stillRunning := time.NewTicker(wdTouchPeriod)
a.ps.StillRunning(agentName, warningTime, errorTime)
// Wait for ModemManager.
deadline := time.Now().Add(mmStartTimeout)
mmVersion, err := a.mmClient.GetMMVersion()
for err != nil {
if time.Now().After(deadline) {
return fmt.Errorf("ModemManager is not available even %s after start: %v",
mmStartTimeout, err)
}
time.Sleep(time.Second)
a.ps.StillRunning(agentName, warningTime, errorTime)
mmVersion, err = a.mmClient.GetMMVersion()
}
a.log.Noticef("ModemManager version: %s", mmVersion)
// Wait for initial GlobalConfig.
if err := a.subGlobalConfig.Activate(); err != nil {
return err
}
for !a.gcInitialized {
a.log.Noticef("Waiting for GCInitialized")
select {
case change := <-a.subGlobalConfig.MsgChan():
a.subGlobalConfig.ProcessChange(change)
case <-stillRunning.C:
}
a.ps.StillRunning(agentName, warningTime, errorTime)
}
a.log.Noticef("Processed GlobalConfig")
// Periodically reconnect modems where the last attempt to establish
// connection failed.
retryTicker := time.NewTicker(retryPeriod)
// Periodically recheck modem connectivity by talking to a remote endpoint
// using a minimum traffic possible.
probeTicker := time.NewTicker(connProbePeriod)
// If enabled, periodically scan visible providers.
scanTicker := time.NewTicker(scanProvidersPeriod)
// Publish metrics for zedagent
maxInterval := float64(metricsPublishPeriod)
minInterval := maxInterval * 0.3
metricPollInterval := time.Duration(minInterval)
publishMetricsTimer := flextimer.NewRangeTicker(
time.Duration(minInterval), time.Duration(maxInterval))
// Start monitoring state of all detected cellular modems.
modems, modemNotifications := a.mmClient.RunModemMonitoring(metricPollInterval)
for _, modem := range modems {
a.log.Noticef("Modem detected at startup, path: %s, physical addresses: %+v",
modem.Path, modem.Status.PhysAddrs)
modemInfo := &ModemInfo{Modem: modem}
a.modemInfo[modem.Path] = modemInfo
// Unmanaged modems have radio function disabled.
modemInfo.connectError = a.mmClient.DisableRadio(modem.Path)
}
a.publishWwanStatus()
// Start receiving configuration.
if err := a.subWwanConfig.Activate(); err != nil {
return err
}
if err := a.subControllerCert.Activate(); err != nil {
return err
}
if err := a.subEdgeNodeCert.Activate(); err != nil {
return err
}
for {
select {
case change := <-a.subGlobalConfig.MsgChan():
a.subGlobalConfig.ProcessChange(change)
case change := <-a.subWwanConfig.MsgChan():
a.subWwanConfig.ProcessChange(change)
case change := <-a.subControllerCert.MsgChan():
a.subControllerCert.ProcessChange(change)
case change := <-a.subEdgeNodeCert.MsgChan():
a.subEdgeNodeCert.ProcessChange(change)
case notif := <-modemNotifications:
a.processModemNotif(notif)
case <-retryTicker.C:
var statusChanged bool
for _, modem := range a.modemInfo {
statusChanged = a.reconcileModem(modem, false) || statusChanged
}
if statusChanged {
a.publishWwanStatus()
}
case <-probeTicker.C:
a.probeConnectivity()
case <-scanTicker.C:
if !a.scanProviders || a.radioSilence {
break
}
for _, modem := range a.modemInfo {
if !modem.IsManaged() {
continue
}
a.scanVisibleProviders(modem)
}
a.publishWwanStatus()
case <-publishMetricsTimer.C:
a.publishMetrics()
case <-stillRunning.C:
if time.Since(a.mmClient.LastSeenMM()) >= wdTouchPeriod {
if _, err := a.mmClient.GetMMVersion(); err != nil {
a.log.Warnf("Failed to get MM version (process crashed?): %v", err)
}
}
}
// Here we implement watchdog detection for both this agent and the ModemManager.
if time.Since(a.mmClient.LastSeenMM()) < wdTouchPeriod {
a.ps.StillRunning(agentName, warningTime, errorTime)
}
}
}
func (a *MMAgent) ignoreNonGlobalKey(key string) bool {
if key != "global" {
a.log.Warnf("Ignoring pubsub message key=%s", key)
return true
}
return false
}
func (a *MMAgent) handleGlobalConfigCreate(_ interface{}, key string, arg interface{}) {
if a.ignoreNonGlobalKey(key) {
return
}
a.applyGlobalConfig(arg.(types.ConfigItemValueMap))
}
func (a *MMAgent) handleGlobalConfigModify(_ interface{}, key string, arg, _ interface{}) {
if a.ignoreNonGlobalKey(key) {
return
}
a.applyGlobalConfig(arg.(types.ConfigItemValueMap))
}
func (a *MMAgent) handleGlobalConfigDelete(_ interface{}, key string, arg interface{}) {
if a.ignoreNonGlobalKey(key) {
return
}
a.applyGlobalConfig(*types.DefaultConfigItemValueMap())
}
func (a *MMAgent) handleWwanConfigCreate(_ interface{}, key string, arg interface{}) {
if a.ignoreNonGlobalKey(key) {
return
}
a.applyWwanConfig(arg.(types.WwanConfig))
}
func (a *MMAgent) handleWwanConfigModify(_ interface{}, key string, arg, _ interface{}) {
if a.ignoreNonGlobalKey(key) {
return
}
a.applyWwanConfig(arg.(types.WwanConfig))
}
func (a *MMAgent) handleWwanConfigDelete(_ interface{}, key string, _ interface{}) {
if a.ignoreNonGlobalKey(key) {
return
}
a.applyWwanConfig(types.WwanConfig{})
}
func (a *MMAgent) applyGlobalConfig(config types.ConfigItemValueMap) {
a.globalConfig = config
prevLogLevel := a.logger.GetLevel()
agentlog.HandleGlobalConfig(a.log, a.subGlobalConfig, agentName,
a.CLIParams().DebugOverride, a.logger)
if a.logger.GetLevel() != prevLogLevel || !a.gcInitialized {
err := a.mmClient.SetMMLogLevel(a.logger.GetLevel())
if err == nil {
a.log.Noticef("Changed ModemManager log level to %v", a.logger.GetLevel())
} else {
a.log.Warnf("Failed to set ModemManager log level to %v: %v",
a.logger.GetLevel(), err)
}
}
// Publish location info 2x more often (at most) than zedagent publishes
// to applications and controller.
locPublishCloudPeriod := time.Second *
time.Duration(a.globalConfig.GlobalValueInt(types.LocationCloudInterval))
locPublishAppPeriod := time.Second *
time.Duration(a.globalConfig.GlobalValueInt(types.LocationAppInterval))
publishInterval := locPublishAppPeriod
if locPublishCloudPeriod < publishInterval {
// This is quite unlikely config.
publishInterval = locPublishCloudPeriod
}
publishInterval = publishInterval >> 1
if a.locPublishPeriod != publishInterval {
a.locPublishPeriod = publishInterval
if a.locTrackingModem != "" && !a.radioSilence {
modem := a.modemInfo[a.locTrackingModem]
err := a.mmClient.StopLocationTracking(modem.Path)
if err == nil {
err = a.mmClient.StartLocationTracking(
modem.Path, publishInterval)
}
if err == nil {
a.log.Noticef(
"Updated location tracking publish interval for modem %s (%s) to %s",
modem.config.LogicalLabel, modem.Path, a.locPublishPeriod)
} else {
modem.locTrackingError = fmt.Errorf("failed to restart location tracking "+
"to update publish interval for modem %s (%s): %v",
modem.config.LogicalLabel, modem.Path, err)
a.log.Error(modem.locTrackingError.Error())
}
}
}
scanProviders := a.globalConfig.GlobalValueBool(types.WwanQueryVisibleProviders)
if a.scanProviders != scanProviders {
a.scanProviders = scanProviders
if a.scanProviders && !a.radioSilence {
for _, modem := range a.modemInfo {
if !modem.IsManaged() {
continue
}
a.scanVisibleProviders(modem)
}
a.publishWwanStatus()
}
}
a.gcInitialized = true
}
func (a *MMAgent) applyWwanConfig(config types.WwanConfig) {
a.log.Noticef("Applying wwan config, DPC: %s/%v, RS config timestamp: %v",
config.DPCKey, config.DPCTimestamp, config.RSConfigTimestamp)
resumeMonitoring := a.mmClient.PauseModemMonitoring()
for _, modem := range a.modemInfo {
modem.prevConfig = modem.config
modem.config = types.WwanNetworkConfig{}
}
a.dpcKey = config.DPCKey
a.dpcTimestamp = config.DPCTimestamp
a.rsConfigTimestamp = config.RSConfigTimestamp
a.radioSilence = config.RadioSilence
a.missingModems = nil
// Associate config with ModemInfo.
for _, modemConfig := range config.Networks {
var foundModem bool
for _, modem := range a.modemInfo {
if a.configMatchesModem(modemConfig, modem) {
modem.config = modemConfig
foundModem = true
break
}
}
if !foundModem {
a.missingModems = append(a.missingModems, modemConfig)
}
}
// Determine which modem to use for location tracking if enabled.
if a.locTrackingModem != "" &&
!a.modemInfo[a.locTrackingModem].config.LocationTracking {
// Modem used for location tracking should no longer be used for that purpose.
a.locTrackingModem = ""
}
if a.locTrackingModem == "" {
for _, modem := range a.modemInfo {
if modem.config.LocationTracking {
a.locTrackingModem = modem.Path
break
}
}
}
// Apply the new config
var rescanProviders []string
for _, modem := range a.modemInfo {
var forceReconnect bool
// Logical label can appear of disappear but cannot change - it is fixed
// in the device model.
if modem.prevConfig.LogicalLabel != "" && modem.config.LogicalLabel == "" {
a.log.Noticef("Modem at path %s is no longer managed "+
"(previously had logical label %s)", modem.Path,
modem.prevConfig.LogicalLabel)
}
if modem.prevConfig.LogicalLabel == "" && modem.config.LogicalLabel != "" {
a.log.Noticef("Associated modem at path %s with logical label %s",
modem.Path, modem.config.LogicalLabel)
// Previously unmanaged modem now has configuration.
rescanProviders = append(rescanProviders, modem.Path)
}
if !modem.config.AccessPoint.Equal(modem.prevConfig.AccessPoint) {
modem.decryptedUsername, modem.decryptedPassword, modem.decryptError =
a.decryptAPCredentials(&modem.config.AccessPoint)
if modem.decryptError != nil {
a.log.Errorf("Failed to decrypt username/password for modem %s (%s): %v",
modem.config.LogicalLabel, modem.Path, modem.decryptError)
}
forceReconnect = true
}
a.reconcileModem(modem, forceReconnect)
}
// Resume monitoring of modems and record all state changes that happened during
// the execution of this function (while monitoring was paused).
modems := resumeMonitoring()
existingModems := make(map[string]struct{})
for _, modem := range modems {
existingModems[modem.Path] = struct{}{}
if _, haveInfo := a.modemInfo[modem.Path]; !haveInfo {
// This is very unlikely scenario.
a.log.Warnf(
"New modem %s appeared during the execution of applyWwanConfig: %+v",
modem.Path, modem.Status.PhysAddrs)
modemInfo := &ModemInfo{Modem: modem}
a.modemInfo[modem.Path] = modemInfo
a.findConfigForNewModem(modemInfo)
// Modem will be reconciled from retryTicker.
} else {
var providers []types.WwanProvider
if a.scanProviders && a.modemInfo[modem.Path].IsManaged() {
// Preserve output from the last scan of visible providers.
providers = a.modemInfo[modem.Path].Status.VisibleProviders
}
modem.Status.VisibleProviders = providers
a.modemInfo[modem.Path].Modem = modem
}
}
for _, modem := range a.modemInfo {
if _, exists := existingModems[modem.Path]; !exists {
// This is very unlikely scenario.
a.log.Warnf("Modem %s disappeared during the execution of applyWwanConfig",
modem.Path)
a.handleRemovedModem(modem)
}
}
a.publishWwanStatus()
if len(rescanProviders) > 0 && a.scanProviders && !a.radioSilence {
a.log.Noticef("Re-scanning visible providers for modems: %v", rescanProviders)
for _, modemPath := range rescanProviders {
modem := a.modemInfo[modemPath]
if modem == nil || !modem.IsManaged() {
continue
}
a.scanVisibleProviders(modem)
}
a.publishWwanStatus()
}
a.metricsUpdated = true
}
func (a *MMAgent) processModemNotif(notif mmdbus.Notification) {
switch notif.Event {
case mmdbus.EventUndefined:
a.log.Warnf("Undefined notification received from MM Client")
case mmdbus.EventAddedModem:
a.log.Noticef("New modem was added at path %s, physical addresses: %+v",
notif.Modem.Path, notif.Modem.Status.PhysAddrs)
_, haveInfo := a.modemInfo[notif.Modem.Path]
if haveInfo {
// Should be unreachable
a.log.Warnf("Received notification about new modem %s which is already known",
notif.Modem.Path)
return
}
modem := &ModemInfo{Modem: notif.Modem}
a.modemInfo[notif.Modem.Path] = modem
a.findConfigForNewModem(modem)
a.reconcileModem(modem, false)
if a.scanProviders && modem.IsManaged() && !a.radioSilence {
a.scanVisibleProviders(modem)
}
a.publishWwanStatus()
case mmdbus.EventUpdatedModemStatus:
modem, haveInfo := a.modemInfo[notif.Modem.Path]
if !haveInfo {
// Should be unreachable
a.log.Warnf("Received status change for an unknown modem %s",
notif.Modem.Path)
return
}
var providers []types.WwanProvider
if a.scanProviders && modem.IsManaged() {
// Preserve output from the last scan of visible providers.
providers = modem.Status.VisibleProviders
}
a.log.Functionf("Modem status update: %+v", notif.Modem)
modem.Status = notif.Modem.Status
modem.Status.VisibleProviders = providers
// Immediately publish status change, do not delay it with reconciliation.
a.publishWwanStatus()
statusChanged := a.reconcileModem(modem, false)
if statusChanged {
a.publishWwanStatus()
}
case mmdbus.EventRemovedModem:
a.log.Noticef("Modem at path %s was removed", notif.Modem.Path)
modem, haveInfo := a.modemInfo[notif.Modem.Path]
if !haveInfo {
// Should be unreachable
a.log.Warnf("Received notification about removal of an unknown modem %s",
notif.Modem.Path)
return
}
a.handleRemovedModem(modem)
a.publishWwanStatus()
case mmdbus.EventUpdatedModemMetrics:
modem, haveInfo := a.modemInfo[notif.Modem.Path]
if !haveInfo {
// Should be unreachable
a.log.Warnf("Received metrics for unknown modem %s", notif.Modem.Path)
return
}
modem.Metrics = notif.Modem.Metrics
a.metricsUpdated = true
case mmdbus.EventUpdatedModemLocation:
modem, haveInfo := a.modemInfo[notif.Modem.Path]
if !haveInfo {
// Should be unreachable
a.log.Warnf("Received location info for unknown modem %s", notif.Modem.Path)
return
}
location := notif.Modem.Location
if location.Latitude == mmdbus.UnavailLocAttribute ||
location.Longitude == mmdbus.UnavailLocAttribute {
// Do not publish incomplete location information.
return
}
modem.Location = location
location.LogicalLabel = modem.config.LogicalLabel
err := a.pubWwanLocationInfo.Publish("global", location)
if err != nil {
a.log.Errorf("Failed to publish location info: %v", err)
}
}
}
// Check if we already have config for this modem inside the missingModems slice.
func (a *MMAgent) findConfigForNewModem(modem *ModemInfo) {
for i, config := range a.missingModems {
if !a.configMatchesModem(config, modem) {
continue
}
modem.config = config
a.log.Noticef("Associated modem at path %s with logical label %s",
modem.Path, modem.config.LogicalLabel)
modem.decryptedUsername, modem.decryptedPassword, modem.decryptError =
a.decryptAPCredentials(&config.AccessPoint)
if modem.decryptError != nil {
a.log.Errorf("Failed to decrypt username/password for modem %s (%s): %v",
modem.config.LogicalLabel, modem.Path, modem.decryptError)
}
// Remove entry from missingModems.
a.missingModems[i] = a.missingModems[len(a.missingModems)-1]
a.missingModems = a.missingModems[:len(a.missingModems)-1]
// Check if we should start location tracking on this modem.
if a.locTrackingModem == "" && modem.config.LocationTracking {
a.locTrackingModem = modem.Path
}
break
}
}
func (a *MMAgent) handleRemovedModem(modem *ModemInfo) {
delete(a.modemInfo, modem.Path)
if modem.IsManaged() {
a.missingModems = append(a.missingModems, modem.config)
}
if a.locTrackingModem == modem.Path {
// This removed modem was used for location tracking.
// Check if there is another modem with location tracking enabled.
a.locTrackingModem = ""
for _, modem2 := range a.modemInfo {
if modem2.config.LocationTracking {
a.locTrackingModem = modem2.Path
a.reconcileModem(modem2, false)
break
}
}
}
}
// Reconcile the modem current state with the intended state (i.e. config).
// Possible actions that may be performed are:
// - (dis)connect modem
// - start/stop location tracking
// - enable/disable radio
func (a *MMAgent) reconcileModem(
modem *ModemInfo, forceReconnect bool) (statusChanged bool) {
if !forceReconnect && modem.suspendedReconcileUntil.After(time.Now()) {
if modem.IsManaged() {
a.log.Noticef("Skipping reconcileModem for modem %s (%s) - suspended",
modem.config.LogicalLabel, modem.Path)
} else {
a.log.Noticef("Skipping reconcileModem for unmanaged modem %+v (%s) - suspended",
modem.Status.PhysAddrs, modem.Path)
}
return false
}
// Sync connection state.
var connErr error
var connErrChanged bool
if !modem.IsManaged() || a.radioSilence {
opReason := "modem is not managed"
if a.radioSilence {
opReason = "radio silence"
}
// Modem should be switched off.
if modem.Status.Module.OpMode == types.WwanOpModeConnected {
connErr = a.disconnectModem(modem)
connErrChanged = true
a.logReconcileOp(modem, "close connection", opReason, connErr)
}
if connErr == nil && modem.Status.Module.OpMode != types.WwanOpModeRadioOff {
// Note that we disable radio function of all unmanaged modems.
connErr = a.mmClient.DisableRadio(modem.Path)
connErrChanged = true
a.logReconcileOp(modem, "disable radio", opReason, connErr)
}
} else {
// Modem should be connected.
isConnected := modem.Status.Module.OpMode == types.WwanOpModeConnected
if !isConnected || forceReconnect {
opReason := "modem not connected"
if forceReconnect {
opReason = "forcing reconnection"
}
if modem.Status.Module.OpMode == types.WwanOpModeRadioOff {
connErr = a.mmClient.EnableRadio(modem.Path)
a.logReconcileOp(modem, "enable radio", opReason, connErr)
}
if connErr == nil {
if isConnected {
connErr = a.disconnectModem(modem)
a.logReconcileOp(modem, "close (obsolete) connection",
opReason, connErr)
} else {
// Make sure that the wwan interface is in the clean state
// before connecting.
connErr = a.removeIPSettings(modem)
a.logReconcileOp(modem, "remove (obsolete) IP settings",
opReason, connErr)
}
}
if connErr == nil &&
// Do not try to connect if we failed to decrypt credentials.
modem.decryptError == nil {
connErr = a.connectModem(modem)
a.logReconcileOp(modem, "establish connection", opReason, connErr)
}
if connErr == nil {
// Clear probe error after successfully reconnecting.
modem.probeError = nil
}
connErrChanged = true
} else {
// Connection is already working. Clear previous error if there is any.
connErrChanged = modem.connectError != nil
}
}
if connErr == nil &&
!modem.appliedIPSettings.Equal(modem.Status.IPSettings) ||
modem.appliedUserMTU != modem.config.MTU {
// IP settings between modem (+ user intent) and Linux network stack are out-of-sync.
// This could happen if:
// * modem re-connects behind the scenes, or
// * if network changes IP settings in run-time, or
// * if user changes MTU config
opReason := "IP settings are out-of-sync"
connErr = a.removeIPSettings(modem)
a.logReconcileOp(modem, "remove (obsolete) IP settings", opReason, connErr)
if connErr == nil && !modem.Status.IPSettings.Equal(emptyIPSettings) {
connErr = a.applyIPSettings(modem, modem.Status.IPSettings)
a.logReconcileOp(modem, "apply IP settings", opReason, connErr)
}
connErrChanged = true
}
if connErrChanged {
modem.connectError = connErr
if connErr != nil {
a.log.Warnf(connErr.Error())
}
}
// Sync location tracking state.
var locErr error
var locErrChanged bool
if modem.Status.LocationTracking {
if a.locTrackingModem != modem.Path {
// This modem should have location tracking disabled.
locErr = a.mmClient.StopLocationTracking(modem.Path)
locErrChanged = true
a.logReconcileOp(modem, "stop location tracking", "", locErr)
}
} else {
if a.locTrackingModem == modem.Path && !a.radioSilence {
// This modem should have location tracking enabled.
locErr = a.mmClient.StartLocationTracking(
modem.Path, a.locPublishPeriod)
locErrChanged = true
a.logReconcileOp(modem, "start location tracking", "", locErr)
}
}
if locErrChanged {
modem.locTrackingError = locErr
if locErr != nil {
a.log.Warnf(locErr.Error())
}
}
statusChanged = connErrChanged || locErrChanged
if statusChanged {
a.suspendReconcile(modem)
}
return statusChanged
}
// After modifying modem settings, give changes some time to apply before trying
// to reconcile again.
func (a *MMAgent) suspendReconcile(modem *ModemInfo) {
modem.suspendedReconcileUntil = time.Now().Add(suspendReconcilePeriod)
if modem.IsManaged() {
a.log.Noticef("Suspended reconciliation for modem %s (%s) until %v",
modem.config.LogicalLabel, modem.Path, modem.suspendedReconcileUntil)
} else {
a.log.Noticef("Suspended reconciliation for unmanaged modem %+v (%s) until %v",
modem.Status.PhysAddrs, modem.Path, modem.suspendedReconcileUntil)
}
}
func (a *MMAgent) logReconcileOp(modem *ModemInfo, operation, reason string, retval error) {
var modemDescr string
if modem.IsManaged() {
modemDescr = fmt.Sprintf("modem %s (%s)", modem.config.LogicalLabel, modem.Path)
} else {
modemDescr = fmt.Sprintf("unmanaged modem %+v", modem.Status.PhysAddrs)
}
var reasonDescr string
if reason != "" {
reasonDescr = fmt.Sprintf(" (run due to: %s)", reason)
}
if retval == nil {
a.log.Noticef("Succeeded to %s for %s%s", operation, modemDescr, reasonDescr)
} else {
a.log.Errorf("Failed to %s for %s%s: %v", operation, modemDescr,
reasonDescr, retval)
}
}
func (a *MMAgent) scanVisibleProviders(modem *ModemInfo) {
var resumeRecAfter time.Duration
suspRecUntil := modem.suspendedReconcileUntil
if suspRecUntil.After(time.Now()) {
// Pause the countdown of suspended reconciliation while we wait
// for visible providers.
// Otherwise, scan will eat up all the duration for suspension, and therefore
// it will lose its meaning (to wait for the last reconciliation changes to take
// effect and to receive the corresponding status update)
resumeRecAfter = time.Until(suspRecUntil)
}
providers, err := a.mmClient.ScanVisibleProviders(modem.Path)
if err == nil {
modem.Status.VisibleProviders = providers
} else {
modem.Status.VisibleProviders = nil
a.log.Errorf("Failed to scan visible providers for modem %s (%s): %v",
modem.config.LogicalLabel, modem.Path, err)
}
if resumeRecAfter > 0 {
modem.suspendedReconcileUntil = time.Now().Add(resumeRecAfter)
}
}
// Check if connected modems are actually working and traffic is getting through.
func (a *MMAgent) probeConnectivity() {
if a.radioSilence {
return
}
var statusChanged bool
for _, modem := range a.modemInfo {
if !modem.IsManaged() {
continue
}
prevError := modem.probeError
if modem.Status.Module.OpMode != types.WwanOpModeConnected {
modem.probeError = fmt.Errorf("modem is not connected")