/
updatemanager.go
568 lines (513 loc) · 15.2 KB
/
updatemanager.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
// Copyright 2023 Northern.tech AS
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package app
import (
"context"
"encoding/json"
"os"
"sort"
"strings"
"sync"
"time"
log "github.com/sirupsen/logrus"
"github.com/pkg/errors"
"github.com/mendersoftware/mender/app/updatecontrolmap"
"github.com/mendersoftware/mender/datastore"
"github.com/mendersoftware/mender/dbus"
"github.com/mendersoftware/mender/store"
)
const (
updateManagerSetUpdateControlMap = "SetUpdateControlMap"
UpdateManagerDBusPath = "/io/mender/UpdateManager"
UpdateManagerDBusObjectName = "io.mender.UpdateManager"
UpdateManagerDBusInterfaceName = "io.mender.Update1"
UpdateManagerDBusInterface = `
<node>
<interface name="io.mender.Update1">
<method name="SetUpdateControlMap">
<arg type="s" name="update_control_map" direction="in"/>
<arg type="i" name="refresh_timeout" direction="out"/>
</method>
</interface>
</node>`
)
var NoUpdateMapsErr = errors.New("No update control maps exist")
type UpdateManager struct {
dbus dbus.DBusAPI
controlMapPool *ControlMapPool
updateControlTimeoutSeconds int
}
func NewUpdateManager(
controlMapPool *ControlMapPool,
updateControlTimeoutSeconds int,
) *UpdateManager {
return &UpdateManager{
controlMapPool: controlMapPool,
updateControlTimeoutSeconds: updateControlTimeoutSeconds,
}
}
func (u *UpdateManager) EnableDBus(api dbus.DBusAPI) {
u.dbus = api
}
func (u *UpdateManager) Start() (context.CancelFunc, error) {
log.Debug("Running the UpdateManager")
if u.dbus == nil {
return nil, errors.New("DBus not enabled")
}
ctx, cancel := context.WithCancel(context.Background())
go func() {
_ = u.run(ctx)
}()
return cancel, nil
}
func (u *UpdateManager) run(ctx context.Context) error {
log.Debug("Running the UpdateManager")
dbusConn, err := u.dbus.BusGet(dbus.GBusTypeSystem)
if err != nil {
return errors.Wrap(err, "Failed to start the Update manager")
}
nameGID, err := u.dbus.BusOwnNameOnConnection(
dbusConn,
UpdateManagerDBusObjectName,
dbus.DBusNameOwnerFlagsAllowReplacement|dbus.DBusNameOwnerFlagsReplace,
)
if err != nil {
return errors.Wrap(err, "Failed to start the update manager")
}
defer u.dbus.BusUnownName(nameGID)
intGID, err := u.dbus.BusRegisterInterface(
dbusConn,
UpdateManagerDBusPath,
UpdateManagerDBusInterface,
)
if err != nil {
log.Errorf("Failed to register the DBus interface name %q at path %q: %s",
UpdateManagerDBusInterface,
UpdateManagerDBusPath,
err,
)
return err
}
defer u.dbus.BusUnregisterInterface(dbusConn, intGID)
u.dbus.RegisterMethodCallCallback(
UpdateManagerDBusPath,
UpdateManagerDBusInterfaceName,
updateManagerSetUpdateControlMap,
func(_ string, _ string, _ string, updateControlMap string) (interface{}, error) {
log.Infof("Received an update control map via D-Bus: %s", updateControlMap)
// Unmarshal json disallowing unknown fields
controlMap := updatecontrolmap.UpdateControlMap{}
decoder := json.NewDecoder(strings.NewReader(updateControlMap))
if err := decoder.Decode(&controlMap); err != nil {
log.Errorf(
"Failed to unmarshal the JSON in the string received via SetUpdateControlMap"+
" on D-Bus: %s",
err,
)
return u.updateControlTimeoutSeconds / 2, err
}
if len(controlMap.States) == 0 {
log.Debugf("Deleting UpdateControlMap %s, priority %d with no non-default States",
controlMap.ID, controlMap.Priority)
u.controlMapPool.Delete(controlMap.ID, controlMap.Priority)
} else {
log.Debugf("Setting the control map parameter to: %s", controlMap.ID)
controlMap.ExpirationChannel = u.controlMapPool.Updates
u.controlMapPool.Insert(controlMap.Stamp(u.updateControlTimeoutSeconds))
}
return u.updateControlTimeoutSeconds / 2, nil
})
defer u.dbus.UnregisterMethodCallCallback(
UpdateManagerDBusPath,
UpdateManagerDBusInterfaceName,
updateManagerSetUpdateControlMap)
<-ctx.Done()
return nil
}
type ControlMapPool struct {
Pool []*updatecontrolmap.UpdateControlMap
mutex sync.Mutex
store store.Store
Updates chan bool // Announces all updates to the maps
updateControlMapExpirationTimeSeconds int
}
// loadTimeout is how far in the future to set the map expiry when loading from
// the store.
func NewControlMap(
store store.Store,
loadTimeout, updateControlMapExpirationTimeSeconds int,
) *ControlMapPool {
pool := &ControlMapPool{
Pool: []*updatecontrolmap.UpdateControlMap{},
store: store,
Updates: make(chan bool, 1),
updateControlMapExpirationTimeSeconds: updateControlMapExpirationTimeSeconds,
}
pool.loadFromStore(loadTimeout)
return pool
}
func (c *ControlMapPool) SetStore(store store.Store) {
c.store = store
}
func (c *ControlMapPool) insertMap(keepPredicate func(*updatecontrolmap.UpdateControlMap) bool,
cm *updatecontrolmap.UpdateControlMap) {
c.mutex.Lock()
defer c.mutex.Unlock()
nm := []*updatecontrolmap.UpdateControlMap{}
query(
c.Pool,
// Collector
func(u *updatecontrolmap.UpdateControlMap) {
nm = append(nm, u)
},
keepPredicate,
)
c.Pool = append(nm, cm)
c.saveToStore()
c.announceUpdate()
}
// HasControlMap - Returns true in the event that a control map matches
// the given deploymentID.
func (c *ControlMapPool) HasControlMap(deploymentID string) bool {
activeMaps, passiveMaps := c.Get(deploymentID)
return len(activeMaps) > 0 || len(passiveMaps) > 0
}
func (c *ControlMapPool) Insert(cm *updatecontrolmap.UpdateControlMap) {
log.Debugf("Inserting Update Control Map: %v", cm)
c.insertMap(func(u *updatecontrolmap.UpdateControlMap) bool {
return !cm.Equal(u)
}, cm)
}
func (c *ControlMapPool) InsertReplaceAllPriorities(cm *updatecontrolmap.UpdateControlMap) {
log.Debugf("Inserting Update Control Map: %v, replacing all priorities", cm)
c.insertMap(func(u *updatecontrolmap.UpdateControlMap) bool {
return cm.ID != u.ID
}, cm)
}
func (c *ControlMapPool) announceUpdate() {
select {
case c.Updates <- true:
log.Debug("ControlMapPool: Announcing update to the map")
default:
}
}
func (c *ControlMapPool) Get(
ID string,
) (active []*updatecontrolmap.UpdateControlMap, expired []*updatecontrolmap.UpdateControlMap) {
c.mutex.Lock()
defer c.mutex.Unlock()
query(
c.Pool,
// Collector
func(u *updatecontrolmap.UpdateControlMap) {
if u.Expired() {
expired = append(expired, u)
return
}
active = append(active, u)
},
// Predicates
func(u *updatecontrolmap.UpdateControlMap) bool {
return u.ID == ID
},
)
return active, expired
}
func (c *ControlMapPool) deleteMaps(keepPredicate func(*updatecontrolmap.UpdateControlMap) bool) {
c.mutex.Lock()
defer c.mutex.Unlock()
filteredPool := []*updatecontrolmap.UpdateControlMap{}
query(
c.Pool,
// Collector
func(u *updatecontrolmap.UpdateControlMap) {
filteredPool = append(filteredPool, u)
},
keepPredicate,
)
c.Pool = filteredPool
c.saveToStore()
c.announceUpdate()
}
func (c *ControlMapPool) Delete(ID string, priority int) {
log.Debugf("Deleting Update Control Map: %s, priority %d", ID, priority)
c.deleteMaps(func(u *updatecontrolmap.UpdateControlMap) bool {
return u.ID != ID || u.Priority != priority
})
}
func (c *ControlMapPool) DeleteAllPriorities(ID string) {
log.Debugf("Deleting all Update Control Maps with ID: %s", ID)
c.deleteMaps(func(u *updatecontrolmap.UpdateControlMap) bool {
return u.ID != ID
})
}
func (c *ControlMapPool) ClearExpired() {
log.Debug("Clearing expired Update Control Maps")
c.mutex.Lock()
defer c.mutex.Unlock()
filteredPool := []*updatecontrolmap.UpdateControlMap{}
query(
c.Pool,
// Collector
func(u *updatecontrolmap.UpdateControlMap) {
filteredPool = append(filteredPool, u)
},
// Predicates
func(u *updatecontrolmap.UpdateControlMap) bool {
return !u.Expired()
},
)
c.Pool = filteredPool
c.saveToStore()
}
type controlMapPoolDBFormat struct {
Active []*updatecontrolmap.UpdateControlMap `json:"active"`
Expired []*updatecontrolmap.UpdateControlMap `json:"expired"`
}
// Must only be called from functions that have already locked the mutex.
func (c *ControlMapPool) saveToStore() {
if c.store == nil {
// Saving not enabled. This should not happen outside tests.
return
}
var active, expired []*updatecontrolmap.UpdateControlMap
query(
c.Pool,
func(m *updatecontrolmap.UpdateControlMap) {
if m.Expired() {
expired = append(expired, m)
} else {
active = append(active, m)
}
},
)
if len(active) == 0 && len(expired) == 0 {
err := c.store.Remove(datastore.UpdateControlMaps)
if err != nil {
log.Errorf("Could not save Update Control Maps to database: %s", err.Error())
// There isn't much we can do if it fails.
}
return
}
toSave := controlMapPoolDBFormat{
// Intentionally not using label assignment here. We want to
// know if we're missing any fields.
active,
expired,
}
data, err := json.Marshal(&toSave)
if err != nil {
log.Errorf("Could not marshal Update Control Maps to JSON: %s", err.Error())
// There isn't much we can do if it fails.
return
}
log.Debugf("Saving Update Control Maps to disk: %q", string(data))
err = c.store.WriteAll(datastore.UpdateControlMaps, data)
if err != nil {
log.Errorf("Could not save Update Control Maps to database: %s", err.Error())
// There isn't much we can do if it fails.
return
}
}
// `timeout` is the timeout that should be given to expired maps that we load
// from disk.
func (c *ControlMapPool) loadFromStore(timeout int) {
c.mutex.Lock()
defer c.mutex.Unlock()
log.Debugf("Loading update control maps from the store")
data, err := c.store.ReadAll(datastore.UpdateControlMaps)
if errors.Is(err, os.ErrNotExist) {
log.Debug("No Update Control Maps found in database.")
return
} else if err != nil {
log.Errorf("Could not read Update Control Maps from database: %s", err.Error())
// There isn't much we can do if it fails.
return
}
var maps controlMapPoolDBFormat
err = json.Unmarshal(data, &maps)
if err != nil {
log.Errorf("Could not unmarshal Update Control Maps from JSON: %s", err.Error())
// There isn't much we can do if it fails.
return
}
for _, m := range maps.Active {
m.ExpirationChannel = c.Updates
m.Stamp(timeout)
}
c.Pool = maps.Active
for _, m := range maps.Expired {
m.ExpirationChannel = c.Updates
m.Stamp(timeout)
m.Expire()
}
c.Pool = append(c.Pool, maps.Expired...)
log.Debugf("Loading Update Control Maps: %v", c.Pool)
}
// query is a utility function to run a 'closure' on all values of
// the list 'm' matching the predicates in 'predicates...'
func query(
m []*updatecontrolmap.UpdateControlMap,
f func(*updatecontrolmap.UpdateControlMap),
predicates ...func(*updatecontrolmap.UpdateControlMap) bool,
) {
for _, e := range m {
// Sentinels
for _, predicate := range predicates {
if !predicate(e) {
goto nextElement
}
}
f(e)
nextElement:
}
}
// QueryAndUpdate queries the map pool for the correct action to return
func (c *ControlMapPool) QueryAndUpdate(state string) (action string) {
c.mutex.Lock()
defer c.mutex.Unlock()
defer c.saveToStore()
maps := c.Pool
log.Debugf("Querying Update Control maps. Currently active maps: '%v'", maps)
sort.Slice(maps, func(i, j int) bool {
return maps[i].Priority > maps[j].Priority
})
actions := []string{}
for _, priority := range uniquePriorities(maps) {
query(maps,
// Collector
func(u *updatecontrolmap.UpdateControlMap) {
actions = append(actions, u.Action(state))
// Upgrade with the value from `on_action_executed`
s := u.States[state]
s.Action = u.States[state].OnActionExecuted
u.States[state] = s
},
// Predicates
func(u *updatecontrolmap.UpdateControlMap) bool {
return u.Priority == priority
},
func(u *updatecontrolmap.UpdateControlMap) bool {
_, hasState := u.States[state]
return hasState
},
)
v := queryActionList(actions)
if v != "" {
log.Debugf("Returning action %q", v)
return v
}
}
// No valid values
log.Debug("Returning action \"continue\"")
return "continue"
}
// nextHalfTime returns the minimum HalfWayTime of maps
func (c *ControlMapPool) nextHalfTime(
maps []*updatecontrolmap.UpdateControlMap,
) (time.Time, error) {
if len(maps) == 0 {
return time.Time{}, NoUpdateMapsErr
}
minTime := maps[0].HalfWayTime
for _, u := range maps {
t := u.HalfwayTime()
if t.Before(minTime) {
minTime = t
}
}
return minTime, nil
}
// NextIDControlMapHalfTime returns the minimum HalfWayTime of the active
// maps matching the given ID (typically, server-side maps)
func (c *ControlMapPool) NextIDControlMapHalfTime(ID string) (time.Time, error) {
m := []*updatecontrolmap.UpdateControlMap{}
query(c.Pool,
// Collector
func(u *updatecontrolmap.UpdateControlMap) {
m = append(m, u)
},
// Predicates
func(u *updatecontrolmap.UpdateControlMap) bool {
return u.ID == ID
},
func(u *updatecontrolmap.UpdateControlMap) bool {
return !u.Expired()
},
)
return c.nextHalfTime(m)
}
// NextAnyControlMapHalfTime returns the minimum HalfWayTime of the active maps
func (c *ControlMapPool) NextAnyControlMapHalfTime(ID string) (time.Time, error) {
m := []*updatecontrolmap.UpdateControlMap{}
query(c.Pool,
// Collector
func(u *updatecontrolmap.UpdateControlMap) {
m = append(m, u)
},
// Predicate
func(u *updatecontrolmap.UpdateControlMap) bool {
return !u.Expired()
},
)
return c.nextHalfTime(m)
}
// uniquePriorities returns a list of the unique elements in the list 'm', and
// 'm' must be sorted.
func uniquePriorities(m []*updatecontrolmap.UpdateControlMap) []int {
ps := []int{}
if len(m) == 0 {
return ps
}
oldPri := m[0].Priority
ps = append(ps, m[0].Priority)
for _, e := range m {
if e.Priority != oldPri {
ps = append(ps, e.Priority)
oldPri = e.Priority
}
}
return ps
}
// queryActionList returns the next action from the given list,
// according to this algorithm:
//
// 1. If "fail" exists in the list, return "fail".
// 2. If "pause" exists in the list, return "pause".
// 2. If "force_continue" exists in the list, return "continue" (<-- note the difference here)
// 4. "continue" should be ignored, don't return it
func queryActionList(stateActions []string) string {
// 1. If fail exists in the list, return fail
pauseExists := false
forceContinueExists := false
for _, e := range stateActions {
if e == "fail" {
return "fail"
}
if e == "pause" {
pauseExists = true
}
if e == "force_continue" {
forceContinueExists = true
}
}
if pauseExists {
return "pause"
}
if forceContinueExists {
log.Info("Forced continue from a control map")
return "continue"
}
return ""
}