-
Notifications
You must be signed in to change notification settings - Fork 165
/
Copy pathradiosilence.go
277 lines (258 loc) · 8.73 KB
/
radiosilence.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
// Copyright (c) 2021 Zededa, Inc.
// SPDX-License-Identifier: Apache-2.0
package zedagent
import (
"fmt"
"net/http"
"path/filepath"
"strings"
"time"
"github.com/lf-edge/eve-api/go/profile"
"github.com/lf-edge/eve/pkg/pillar/flextimer"
"github.com/lf-edge/eve/pkg/pillar/types"
"github.com/lf-edge/eve/pkg/pillar/zedcloud"
"google.golang.org/protobuf/proto"
)
const (
radioURLPath = "/api/v1/radio"
savedRadioConfigFile = "lastradioconfig"
radioPOSTInterval = 5 * time.Second
)
func initializeRadioConfig(ctx *getconfigContext) {
ctx.triggerRadioPOST = make(chan Notify, 1)
if !loadSavedRadioConfig(ctx) {
// invalid or missing configuration - overwrite with the default
saveRadioConfig(&profile.RadioConfig{RadioSilence: false})
}
ctx.radioSilence.ChangeRequestedAt = time.Now()
ctx.radioSilence.ChangeInProgress = true
// apply requested RF status immediately
publishZedAgentStatus(ctx)
}
func triggerRadioPOST(ctx *getconfigContext) {
log.Functionf("Triggering POST for %s to local server", radioURLPath)
select {
case ctx.triggerRadioPOST <- struct{}{}:
// Do nothing more
default:
log.Warnln("Failed to trigger Radio fetch operation")
}
}
// Run a periodic POST request to fetch the intended state of radio devices from local server.
func radioPOSTTask(ctx *getconfigContext) {
max := float64(radioPOSTInterval)
min := max * 0.3
ticker := flextimer.NewRangeTicker(time.Duration(min), time.Duration(max))
log.Functionf("radioPOSTTask: waiting for triggerRadioPOST")
// wait for the first trigger
<-ctx.triggerRadioPOST
log.Functionln("radioPOSTTask: waiting for triggerRadioPOST done")
// trigger again to pass into the loop
triggerRadioPOST(ctx)
wdName := agentName + "-radio"
// Run a periodic timer so we always update StillRunning
stillRunning := time.NewTicker(25 * time.Second)
ctx.zedagentCtx.ps.StillRunning(wdName, warningTime, errorTime)
ctx.zedagentCtx.ps.RegisterFileWatchdog(wdName)
task := func() {
start := time.Now()
status := getRadioStatus(ctx)
if status == nil {
log.Noticeln("Radio status is not yet available")
return
}
config := getRadioConfig(ctx, status)
if config != nil {
var configErr string
if config.RadioSilence && ctx.updateInprogress {
configErr = "Imposing radio silence during EVE update testing is not allowed"
}
if ctx.radioSilence.Imposed != config.RadioSilence ||
ctx.radioSilence.ConfigError != configErr {
// Configuration for radio silence has changed.
ctx.radioSilence.ChangeRequestedAt = time.Now()
ctx.radioSilence.Imposed = config.RadioSilence
// Zedagent uses RadioSilence.ConfigError to mark invalid request,
// which is then ignored by NIM.
ctx.radioSilence.ConfigError = configErr
if configErr != "" {
log.Error(configErr)
} else {
ctx.radioSilence.ChangeInProgress = true
log.Noticef("Triggering radio-silence state change to: %s",
ctx.radioSilence)
}
publishZedAgentStatus(ctx)
}
}
ctx.zedagentCtx.ps.CheckMaxTimeTopic(wdName, "radioPOSTTask", start,
warningTime, errorTime)
}
for {
select {
case <-ctx.triggerRadioPOST:
task()
case <-ticker.C:
task()
case <-stillRunning.C:
}
ctx.zedagentCtx.ps.StillRunning(wdName, warningTime, errorTime)
}
}
func getRadioStatus(ctx *getconfigContext) *profile.RadioStatus {
dnsCtx := ctx.zedagentCtx.dnsCtx
obj, err := dnsCtx.subDeviceNetworkStatus.Get("global")
if err != nil {
log.Error(err)
return nil
}
dns := obj.(types.DeviceNetworkStatus)
if !dns.RadioSilence.ChangeRequestedAt.Equal(ctx.radioSilence.ChangeRequestedAt) {
log.Noticeln("Up-to-date radio-silence status is not available")
return nil
}
if dns.RadioSilence.ChangeInProgress {
log.Noticeln("Skipping radio POST request - radio state changing operation is still in progress")
return nil
}
if ctx.radioSilence.ChangeInProgress {
// radio-silence state changing operation has finalized
log.Noticeln("Radio-silence state changing operation has finalized (as seen by zedagent)")
ctx.radioSilence.ChangeInProgress = false
}
var cellularStatus []*profile.CellularStatus
for _, port := range dns.Ports {
if port.WirelessStatus.WType != types.WirelessTypeCellular {
continue
}
wwanStatus := port.WirelessStatus.Cellular
cellularStatus = append(cellularStatus,
&profile.CellularStatus{
Logicallabel: port.Logicallabel,
Module: encodeCellModuleInfo(wwanStatus.Module),
SimCards: encodeSimCards(wwanStatus.Module.Name, wwanStatus.SimCards),
Providers: encodeCellProviders(wwanStatus),
ConfigError: wwanStatus.ConfigError,
ProbeError: wwanStatus.ProbeError,
})
}
return &profile.RadioStatus{
RadioSilence: dns.RadioSilence.Imposed,
ConfigError: dns.RadioSilence.ConfigError,
CellularStatus: cellularStatus,
CellularMetrics: getCellularMetrics(ctx.zedagentCtx),
}
}
func getRadioConfig(ctx *getconfigContext, radioStatus *profile.RadioStatus) *profile.RadioConfig {
localProfileServer := ctx.sideController.localProfileServer
if localProfileServer == "" {
// default configuration
return &profile.RadioConfig{
RadioSilence: false, // disabled by default
}
}
localServerURL, err := makeLocalServerBaseURL(localProfileServer)
if err != nil {
log.Errorf("getRadioConfig: makeLocalServerBaseURL: %v", err)
return nil
}
if !ctx.sideController.localServerMap.upToDate {
err := updateLocalServerMap(ctx, localServerURL)
if err != nil {
log.Errorf("getRadioConfig: updateLocalServerMap: %v", err)
return nil
}
// Make sure HasLocalServer is set correctly for the AppInstanceConfig
updateHasLocalServer(ctx)
}
srvMap := ctx.sideController.localServerMap.servers
if len(srvMap) == 0 {
log.Functionf("getRadioConfig: cannot find any configured apps for localServerURL: %s",
localServerURL)
return nil
}
var errList []string
for bridgeName, servers := range srvMap {
for _, srv := range servers {
fullURL := srv.localServerAddr + radioURLPath
radioConfig := &profile.RadioConfig{}
resp, err := zedcloud.SendLocalProto(
zedcloudCtx, fullURL, bridgeName, srv.bridgeIP, radioStatus, radioConfig)
if err != nil {
errList = append(errList, fmt.Sprintf("SendLocalProto: %v", err))
continue
}
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent && resp.StatusCode != http.StatusCreated {
errList = append(errList, fmt.Sprintf("SendLocal: wrong response status code: %d",
resp.StatusCode))
continue
}
if resp.StatusCode == http.StatusNoContent {
log.Functionf("Local server %s does not require change in the radio state", localServerURL)
touchRadioConfig()
return nil
}
if radioConfig.GetServerToken() != ctx.sideController.profileServerToken {
errList = append(errList,
fmt.Sprintf("invalid token submitted by local server (%s)", radioConfig.GetServerToken()))
continue
}
if ctx.radioSilence.Imposed == radioConfig.RadioSilence {
// no actual configuration change to apply, just refresh the persisted config
touchRadioConfig()
} else {
saveRadioConfig(radioConfig)
}
return radioConfig
}
}
log.Errorf("getRadioConfig: all attempts failed: %s", strings.Join(errList, ";"))
return nil
}
// read saved radio config in case of a reboot
func readSavedRadioConfig(ctx *getconfigContext) (*profile.RadioConfig, error) {
radioConfigBytes, ts, err := readSavedConfig(
filepath.Join(checkpointDirname, savedRadioConfigFile))
if err != nil {
return nil, fmt.Errorf("readSavedRadioConfig: %v", err)
}
if radioConfigBytes != nil {
radioConfig := &profile.RadioConfig{}
err := proto.Unmarshal(radioConfigBytes, radioConfig)
if err != nil {
return nil, fmt.Errorf("radio config unmarshalling failed: %v", err)
}
log.Noticef("Using saved radio config dated %s",
ts.Format(time.RFC3339Nano))
return radioConfig, nil
}
return nil, nil
}
// loadSavedRadioConfig reads saved radio config and sets it.
func loadSavedRadioConfig(ctx *getconfigContext) bool {
radioConfig, err := readSavedRadioConfig(ctx)
if err != nil {
log.Errorf("readSavedRadioConfig failed: %v", err)
return false
}
if radioConfig == nil {
log.Warnf("Loaded empty radio config: %+v", radioConfig)
return false
}
log.Noticef("Starting with radio config: %+v", radioConfig)
ctx.radioSilence.Imposed = radioConfig.RadioSilence
return true
}
// saveRadioConfig saves received RadioConfig into the persisted partition.
func saveRadioConfig(radioConfig *profile.RadioConfig) {
contents, err := proto.Marshal(radioConfig)
if err != nil {
log.Fatalf("saveRadioConfig: Marshalling failed: %v", err)
}
saveConfig(savedRadioConfigFile, contents)
return
}
// touchRadioConfig is used to update the modification time of the persisted radio config.
func touchRadioConfig() {
touchSavedConfig(savedRadioConfigFile)
}