forked from mendersoftware/mender
-
Notifications
You must be signed in to change notification settings - Fork 0
/
state.go
1896 lines (1578 loc) · 53.9 KB
/
state.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 2019 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 main
import (
"encoding/json"
"fmt"
"io"
"os"
"time"
"github.com/mendersoftware/log"
"github.com/mendersoftware/mender/client"
"github.com/mendersoftware/mender/datastore"
"github.com/mendersoftware/mender/installer"
"github.com/mendersoftware/mender/store"
"github.com/pkg/errors"
)
// StateContext carrying over data that may be used by all state handlers
type StateContext struct {
// data store access
store store.Store
rebooter installer.Rebooter
lastUpdateCheckAttempt time.Time
lastInventoryUpdateAttempt time.Time
lastAuthorizeAttempt time.Time
fetchInstallAttempts int
wakeupChan chan bool
}
type StateRunner interface {
// Set runner's state to 's'
SetNextState(s State)
// Obtain runner's state
GetCurrentState() State
// Run the currently set state with this context
TransitionState(next State, ctx *StateContext) (State, bool)
}
var (
initState = &InitState{
baseState{
id: datastore.MenderStateInit,
t: ToNone,
},
}
idleState = &IdleState{
baseState{
id: datastore.MenderStateIdle,
t: ToIdle,
},
}
authorizeWaitState = NewAuthorizeWaitState()
authorizeState = &AuthorizeState{
baseState{
id: datastore.MenderStateAuthorize,
t: ToSync,
},
}
inventoryUpdateState = &InventoryUpdateState{
baseState{
id: datastore.MenderStateInventoryUpdate,
t: ToSync,
},
}
checkWaitState = NewCheckWaitState()
updateCheckState = &UpdateCheckState{
baseState{
id: datastore.MenderStateUpdateCheck,
t: ToSync,
},
}
doneState = &FinalState{
baseState{
id: datastore.MenderStateDone,
t: ToNone,
},
}
)
type State interface {
// Perform state action, returns next state and boolean flag indicating if
// execution was cancelled or not
Handle(ctx *StateContext, c Controller) (State, bool)
HandleError(ctx *StateContext, c Controller, err menderError) (State, bool)
// Cancel state action, returns true if action was cancelled
Cancel() bool
// Return numeric state ID
Id() datastore.MenderState
// Return transition
Transition() Transition
SetTransition(t Transition)
}
type WaitState interface {
Cancel() bool
Wake() bool
Wait(next, same State, wait time.Duration, wakeup chan bool) (State, bool)
}
type UpdateState interface {
State
Update() *datastore.UpdateInfo
}
// baseState is a helper state with some convenience methods
type baseState struct {
id datastore.MenderState
t Transition
}
func (b *baseState) Id() datastore.MenderState {
return b.id
}
func (b *baseState) Cancel() bool {
return false
}
func (b *baseState) Transition() Transition {
return b.t
}
func (b *baseState) SetTransition(tran Transition) {
b.t = tran
}
func (b *baseState) String() string {
return b.id.String()
}
func (b *baseState) HandleError(ctx *StateContext, c Controller, err menderError) (State, bool) {
log.Error(err.Error())
return NewErrorState(err), false
}
type waitState struct {
baseState
cancel chan bool
wakeup chan bool
}
func NewWaitState(id datastore.MenderState, t Transition) *waitState {
return &waitState{
baseState: baseState{id: id, t: t},
cancel: make(chan bool),
// wakeup: is a global channel shared between all states through the `StateContext`.
}
}
// Wait performs wait for time `wait` and return state (`next`, false) after the wait
// has completed. If wait was interrupted returns (`same`, true)
func (ws *waitState) Wait(next, same State,
wait time.Duration, wakeup chan bool) (State, bool) {
ticker := time.NewTicker(wait)
ws.wakeup = wakeup
defer ticker.Stop()
select {
case <-ticker.C:
log.Debugf("wait complete")
return next, false
case <-ws.wakeup:
log.Info("forced wake-up from sleep")
return next, false
case <-ws.cancel:
log.Infof("wait canceled")
}
return same, true
}
func (ws *waitState) Wake() bool {
ws.wakeup <- true
return true
}
func (ws *waitState) Cancel() bool {
ws.cancel <- true
return true
}
type updateState struct {
baseState
update datastore.UpdateInfo
}
func NewUpdateState(id datastore.MenderState, t Transition, u *datastore.UpdateInfo) *updateState {
return &updateState{
baseState: baseState{id: id, t: t},
update: *u,
}
}
func (us *updateState) Update() *datastore.UpdateInfo {
return &us.update
}
func (us *updateState) HandleError(ctx *StateContext, c Controller, err menderError) (State, bool) {
log.Error(err.Error())
// Default for most update states. Some states will override this.
if us.Update().SupportsRollback == datastore.RollbackSupported {
return NewUpdateRollbackState(us.Update()), false
} else {
setBrokenArtifactFlag(ctx.store, us.Update().ArtifactName())
return NewUpdateErrorState(err, us.Update()), false
}
}
type IdleState struct {
baseState
}
func (i *IdleState) Handle(ctx *StateContext, c Controller) (State, bool) {
// stop deployment logging
DeploymentLogger.Disable()
// cleanup state-data if any data is still present after an update
RemoveStateData(ctx.store)
// check if client is authorized
if c.IsAuthorized() {
return checkWaitState, false
}
return authorizeWaitState, false
}
type InitState struct {
baseState
}
func (i *InitState) Handle(ctx *StateContext, c Controller) (State, bool) {
// restore previous state information
sd, sdErr := LoadStateData(ctx.store)
// handle easy case first: no previous state stored,
// means no update was in progress; we should continue from idle
if sdErr != nil && os.IsNotExist(sdErr) {
log.Debug("no state data stored")
return idleState, false
}
if sdErr != nil && sdErr != maximumStateDataStoreCountExceeded {
log.Errorf("failed to restore state data: %v", sdErr)
me := NewFatalError(errors.Wrapf(sdErr, "failed to restore state data"))
return NewUpdateErrorState(me, &datastore.UpdateInfo{
ID: "unknown",
}), false
}
log.Infof("handling loaded state: %s", sd.Name)
if err := DeploymentLogger.Enable(sd.UpdateInfo.ID); err != nil {
// just log error
log.Errorf("failed to enable deployment logger: %s", err)
}
if sdErr == maximumStateDataStoreCountExceeded {
// State argument not needed since we already know that maximum
// count was exceeded and a different state will be returned.
return handleStateDataError(ctx, nil, false, sd.Name, &sd.UpdateInfo, sdErr)
}
msg := fmt.Sprintf("Update was interrupted in state: %s", sd.Name)
switch sd.Name {
case datastore.MenderStateReboot:
case datastore.MenderStateRollbackReboot:
// Interruption is expected in these, don't produce error.
log.Info(msg)
default:
log.Error(msg)
}
// Used in some cases below. Doesn't mean that there must be an error.
me := NewFatalError(errors.New(msg))
// We need to restore our payload handlers.
err := c.RestoreInstallersFromTypeList(sd.UpdateInfo.Artifact.PayloadTypes)
if err != nil {
// Getting an error here is *really* bad. It means that we
// cannot recover *anything*. Report big bad failure.
return NewUpdateStatusReportState(&sd.UpdateInfo, client.StatusFailure), false
}
return i.getNextState(ctx, &sd, me)
}
func (i *InitState) getNextState(ctx *StateContext, sd *datastore.StateData,
maybeErr menderError) (State, bool) {
// check last known state
switch sd.Name {
// The update never got a chance to even start. Go straight to Idle
// state, and it will be picked up again at the next polling interval.
case datastore.MenderStateUpdateFetch:
err := RemoveStateData(ctx.store)
if err != nil {
return NewErrorState(NewFatalError(err)), false
}
return idleState, false
// Go straight to cleanup if we rebooted from Download state. This is
// important so that artifact scripts from that state do not get to run,
// since they have not yet been signature checked.
case datastore.MenderStateUpdateStore,
datastore.MenderStateUpdateAfterStore:
return NewUpdateCleanupState(&sd.UpdateInfo, client.StatusFailure), false
// After reboot into new update.
case datastore.MenderStateReboot:
return NewUpdateVerifyRebootState(&sd.UpdateInfo), false
// VerifyRollbackReboot must be retried if interrupted, in order to
// possibly go back and RollbackReboot again.
case datastore.MenderStateRollbackReboot,
datastore.MenderStateVerifyRollbackReboot,
datastore.MenderStateAfterRollbackReboot:
return NewUpdateVerifyRollbackRebootState(&sd.UpdateInfo), false
// Rerun commits in subsequent payloads
case datastore.MenderStateUpdateAfterFirstCommit:
return NewUpdateAfterFirstCommitState(&sd.UpdateInfo), false
// Rerun commit-leave
case datastore.MenderStateUpdateAfterCommit:
return NewUpdateAfterCommitState(&sd.UpdateInfo), false
// Error state (ArtifactFailure) should be retried.
case datastore.MenderStateUpdateError:
return NewUpdateErrorState(maybeErr, &sd.UpdateInfo), false
// Cleanup state should be retried.
case datastore.MenderStateUpdateCleanup:
return NewUpdateCleanupState(&sd.UpdateInfo, client.StatusFailure), false
// All other states go to either error or rollback state, depending on
// what's supported.
default:
if sd.UpdateInfo.SupportsRollback == datastore.RollbackSupported {
return NewUpdateRollbackState(&sd.UpdateInfo), false
} else {
setBrokenArtifactFlag(ctx.store, sd.UpdateInfo.ArtifactName())
return NewUpdateErrorState(maybeErr, &sd.UpdateInfo), false
}
}
}
type AuthorizeWaitState struct {
baseState
WaitState
}
func NewAuthorizeWaitState() State {
return &AuthorizeWaitState{
baseState: baseState{
id: datastore.MenderStateAuthorizeWait,
t: ToIdle,
},
WaitState: NewWaitState(datastore.MenderStateAuthorizeWait, ToIdle),
}
}
func (a *AuthorizeWaitState) Cancel() bool {
return a.WaitState.Cancel()
}
func (a *AuthorizeWaitState) Handle(ctx *StateContext, c Controller) (State, bool) {
log.Debugf("handle authorize wait state")
attempt := ctx.lastAuthorizeAttempt.Add(c.GetRetryPollInterval())
now := time.Now()
var wait time.Duration
if attempt.After(now) {
wait = attempt.Sub(now)
}
log.Debugf("wait %v before next authorization attempt", wait)
if wait == 0 {
ctx.lastAuthorizeAttempt = now
return authorizeState, false
}
ctx.lastAuthorizeAttempt = attempt
return a.Wait(authorizeState, a, wait, ctx.wakeupChan)
}
type AuthorizeState struct {
baseState
}
func (a *AuthorizeState) Handle(ctx *StateContext, c Controller) (State, bool) {
// stop deployment logging
DeploymentLogger.Disable()
log.Debugf("handle authorize state")
if err := c.Authorize(); err != nil {
log.Errorf("authorize failed: %v", err)
if !err.IsFatal() {
return authorizeWaitState, false
}
return NewErrorState(err), false
}
// if everything is OK we should let Mender figure out what to do
// in MenderStateCheckWait state
return checkWaitState, false
}
type UpdateCommitState struct {
*updateState
reportTries int
}
func NewUpdateCommitState(update *datastore.UpdateInfo) State {
return &UpdateCommitState{
updateState: NewUpdateState(datastore.MenderStateUpdateCommit,
ToArtifactCommit_Enter, update),
}
}
func (uc *UpdateCommitState) Handle(ctx *StateContext, c Controller) (State, bool) {
var err error
// start deployment logging
if err = DeploymentLogger.Enable(uc.Update().ID); err != nil {
log.Errorf("Can not enable deployment logger: %s", err)
}
log.Debug("handle update commit state")
// check if state scripts version is supported
if err = c.CheckScriptsCompatibility(); err != nil {
merr := NewTransientError(errors.Errorf("update commit failed: %s", err.Error()))
return uc.HandleError(ctx, c, merr)
}
// A last status report to the server before committing. This is most
// likely a repeat of the previous status, but the real motivation
// behind it is to find out whether the server cancelled the deployment
// while we were installing/rebooting, and whether network is working.
merr := sendDeploymentStatus(uc.Update(), client.StatusInstalling, &uc.reportTries, c)
if merr != nil {
log.Errorf("Failed to send status report to server: %s", merr.Error())
if merr.IsFatal() {
return uc.HandleError(ctx, c, merr)
} else {
return NewUpdatePreCommitStatusReportRetryState(uc, uc.reportTries), false
}
}
// Commit first payload only. After this commit it is no longer possible
// to roll back, so the rest (if any) will be committed in the next
// state.
installers := c.GetInstallers()
if len(installers) < 1 {
return uc.HandleError(ctx, c, NewTransientError(
errors.New("GetInstallers() returned empty list? Should not happen")))
}
err = installers[0].CommitUpdate()
if err != nil {
// we need to perform roll-back here; one scenario is when
// u-boot fw utils won't work after update; at this point
// without rolling-back it won't be possible to perform new
// update
merr := NewTransientError(errors.Errorf("update commit failed: %s", err.Error()))
return uc.HandleError(ctx, c, merr)
}
// If the client migrated the database, we still need the old database
// information if we are to roll back. However, after the commit above,
// it is too late to roll back, so indidate that DB schema migration is
// now permanent, if there was one.
uc.Update().HasDBSchemaUpdate = false
// And then store the data together with the new artifact name,
// indicating that we have now migrated to a new artifact!
err = StoreStateDataAndTransaction(ctx.store, datastore.StateData{
Name: uc.Id(),
UpdateInfo: *uc.Update(),
}, func(txn store.Transaction) error {
log.Debugf("Committing new artifact name: %s", uc.Update().ArtifactName())
return txn.WriteAll(datastore.ArtifactNameKey, []byte(uc.Update().ArtifactName()))
})
if err != nil {
log.Error("Could not write state data to persistent storage: ", err.Error())
return handleStateDataError(ctx, NewUpdateErrorState(NewTransientError(err), uc.Update()),
false, datastore.MenderStateUpdateInstall, uc.Update(), err)
}
// Do rest of update commits now; then post commit-tasks
return NewUpdateAfterFirstCommitState(uc.Update()), false
}
type UpdatePreCommitStatusReportRetryState struct {
waitState
returnToState State
reportTries int
}
func NewUpdatePreCommitStatusReportRetryState(returnToState State, reportTries int) State {
return &UpdatePreCommitStatusReportRetryState{
waitState: waitState{
baseState: baseState{
id: datastore.MenderStateUpdatePreCommitStatusReportRetry,
t: ToArtifactCommit_Enter,
},
},
returnToState: returnToState,
reportTries: reportTries,
}
}
func (usr *UpdatePreCommitStatusReportRetryState) Handle(ctx *StateContext, c Controller) (State, bool) {
maxTrySending :=
maxSendingAttempts(c.GetUpdatePollInterval(),
c.GetRetryPollInterval(), minReportSendRetries)
// we are always initializing with triesSending = 1
maxTrySending++
if usr.reportTries < maxTrySending {
return usr.Wait(usr.returnToState, usr, c.GetRetryPollInterval(), ctx.wakeupChan)
}
return usr.returnToState.HandleError(ctx, c,
NewTransientError(errors.New("Tried sending status report maximum number of times.")))
}
type UpdateAfterFirstCommitState struct {
*updateState
}
func NewUpdateAfterFirstCommitState(update *datastore.UpdateInfo) State {
return &UpdateAfterFirstCommitState{
updateState: NewUpdateState(datastore.MenderStateUpdateAfterFirstCommit,
ToNone, update),
}
}
func (uc *UpdateAfterFirstCommitState) Handle(ctx *StateContext, c Controller) (State, bool) {
// This state exists to run Commit for payloads after the first
// one. After the first commit it is too late to roll back, which means
// that this state has both different error handling and different
// spontaneous reboot handling than the first commit state.
var firstErr error
for _, i := range c.GetInstallers()[1:] {
err := i.CommitUpdate()
if err != nil {
log.Errorf("Error committing %s payload: %s", i.GetType(), err.Error())
if firstErr == nil {
firstErr = err
}
}
}
if firstErr != nil {
merr := NewTransientError(errors.Errorf("update commit failed: %s", firstErr.Error()))
return uc.HandleError(ctx, c, merr)
}
// Move on to post-commit tasks.
return NewUpdateAfterCommitState(uc.Update()), false
}
func (uc *UpdateAfterFirstCommitState) HandleError(ctx *StateContext, c Controller, merr menderError) (State, bool) {
log.Error(merr.Error())
// Too late to back out now. Just report the error, but do not try to roll back.
setBrokenArtifactFlag(ctx.store, uc.Update().ArtifactName())
return NewUpdateCleanupState(uc.Update(), client.StatusFailure), false
}
type UpdateAfterCommitState struct {
*updateState
}
func NewUpdateAfterCommitState(update *datastore.UpdateInfo) State {
return &UpdateAfterCommitState{
updateState: NewUpdateState(datastore.MenderStateUpdateAfterCommit,
ToArtifactCommit_Leave, update),
}
}
func (uc *UpdateAfterCommitState) Handle(ctx *StateContext, c Controller) (State, bool) {
// This state only exists to rerun Commit_Leave scripts in the event of
// spontaneous shutdowns, so there is nothing else to do in this state.
// update is committed; clean up
return NewUpdateCleanupState(uc.Update(), client.StatusSuccess), false
}
func (uc *UpdateAfterCommitState) HandleError(ctx *StateContext, c Controller, merr menderError) (State, bool) {
log.Error(merr.Error())
// Too late to back out now. Just report the error, but do not try to roll back.
setBrokenArtifactFlag(ctx.store, uc.Update().ArtifactName())
return NewUpdateCleanupState(uc.Update(), client.StatusFailure), false
}
type UpdateCheckState struct {
baseState
}
func (u *UpdateCheckState) Handle(ctx *StateContext, c Controller) (State, bool) {
log.Debugf("handle update check state")
update, err := c.CheckUpdate()
if err != nil {
if err.Cause() == os.ErrExist {
// We are already running image which we are supposed to install.
// Just report successful update and return to normal operations.
return NewUpdateStatusReportState(update, client.StatusAlreadyInstalled), false
}
log.Errorf("update check failed: %s", err)
return NewErrorState(err), false
}
if update != nil {
return NewUpdateFetchState(update), false
}
return checkWaitState, false
}
type UpdateFetchState struct {
baseState
update datastore.UpdateInfo
}
func NewUpdateFetchState(update *datastore.UpdateInfo) State {
return &UpdateFetchState{
baseState: baseState{
id: datastore.MenderStateUpdateFetch,
t: ToDownload_Enter,
},
update: *update,
}
}
func (u *UpdateFetchState) Handle(ctx *StateContext, c Controller) (State, bool) {
// start deployment logging
if err := DeploymentLogger.Enable(u.update.ID); err != nil {
return NewUpdateStatusReportState(&u.update, client.StatusFailure), false
}
log.Debugf("handle update fetch state")
merr := c.ReportUpdateStatus(&u.update, client.StatusDownloading)
if merr != nil && merr.IsFatal() {
return NewUpdateStatusReportState(&u.update, client.StatusFailure), false
}
in, _, err := c.FetchUpdate(u.update.URI())
if err != nil {
log.Errorf("update fetch failed: %s", err)
return NewFetchStoreRetryState(u, &u.update, err), false
}
return NewUpdateStoreState(in, &u.update), false
}
func (uf *UpdateFetchState) Update() *datastore.UpdateInfo {
return &uf.update
}
type UpdateStoreState struct {
*updateState
// reader for obtaining image data
imagein io.ReadCloser
}
func NewUpdateStoreState(in io.ReadCloser, update *datastore.UpdateInfo) State {
return &UpdateStoreState{
NewUpdateState(datastore.MenderStateUpdateStore,
ToDownload_Enter, update),
in,
}
}
func (u *UpdateStoreState) Handle(ctx *StateContext, c Controller) (State, bool) {
// make sure to close the stream with image data
defer u.imagein.Close()
// start deployment logging
if err := DeploymentLogger.Enable(u.update.ID); err != nil {
return NewUpdateStatusReportState(&u.update, client.StatusFailure), false
}
log.Debugf("handle update install state")
merr := c.ReportUpdateStatus(&u.update, client.StatusDownloading)
if merr != nil && merr.IsFatal() {
return NewUpdateStatusReportState(&u.update, client.StatusFailure), false
}
installer, err := c.ReadArtifactHeaders(u.imagein)
if err != nil {
log.Errorf("Fetching Artifact headers failed: %s", err)
return NewFetchStoreRetryState(u, &u.update, err), false
}
if installer.GetArtifactName() != u.Update().ArtifactName() {
log.Errorf("Artifact name in artifact is not what the server claims (%s != %s).",
installer.GetArtifactName(), u.Update().ArtifactName())
return NewUpdateStatusReportState(u.Update(), client.StatusFailure), false
}
installers := c.GetInstallers()
u.update.Artifact.PayloadTypes = make([]string, len(installers))
for n, i := range installers {
u.update.Artifact.PayloadTypes[n] = i.GetType()
}
// Store state so that all the payload handlers are recorded there. This
// is important since they need to call their Cleanup functions after we
// have started the download.
err = StoreStateData(ctx.store, datastore.StateData{
Name: u.Id(),
UpdateInfo: u.update,
})
if err != nil {
log.Error("Could not write state data to persistent storage: ", err.Error())
return handleStateDataError(ctx, NewUpdateCleanupState(&u.update, client.StatusFailure),
false, u.Id(), &u.update, err)
}
err = installer.StorePayloads()
if err != nil {
log.Errorf("Artifact install failed: %s", err)
return NewUpdateCleanupState(&u.update, client.StatusFailure), false
}
ok, state, cancelled := u.handleSupportsRollback(ctx, c)
if !ok {
return state, cancelled
}
// restart counter so that we are able to retry next time
ctx.fetchInstallAttempts = 0
// check if update is not aborted
// this step is needed as installing might take a while and we might end up with
// proceeding with already cancelled update
merr = c.ReportUpdateStatus(&u.update, client.StatusDownloading)
if merr != nil && merr.IsFatal() {
return NewUpdateErrorState(merr, &u.update), false
}
return NewUpdateAfterStoreState(&u.update), false
}
func (u *UpdateStoreState) handleSupportsRollback(ctx *StateContext, c Controller) (bool, State, bool) {
for _, i := range c.GetInstallers() {
supportsRollback, err := i.SupportsRollback()
if err != nil {
log.Errorf("Could not determine if module supports rollback: %s", err.Error())
state, cancelled := NewUpdateErrorState(NewTransientError(err), &u.update), false
return false, state, cancelled
}
if supportsRollback {
err = u.update.SupportsRollback.Set(datastore.RollbackSupported)
} else {
err = u.update.SupportsRollback.Set(datastore.RollbackNotSupported)
}
if err != nil {
log.Errorf("Could update module rollback support status: %s", err.Error())
state, cancelled := NewUpdateErrorState(NewTransientError(err), &u.update), false
return false, state, cancelled
}
}
// Make sure SupportsRollback status is stored
err := StoreStateData(ctx.store, datastore.StateData{
Name: u.Id(),
UpdateInfo: u.update,
})
if err != nil {
log.Error("Could not write state data to persistent storage: ", err.Error())
state, cancelled := handleStateDataError(ctx, NewUpdateErrorState(NewTransientError(err), &u.update),
false, u.Id(), &u.update, err)
return false, state, cancelled
}
return true, nil, false
}
func (is *UpdateStoreState) HandleError(ctx *StateContext, c Controller, merr menderError) (State, bool) {
log.Error(merr.Error())
return NewUpdateCleanupState(is.Update(), client.StatusFailure), false
}
type UpdateAfterStoreState struct {
*updateState
}
func NewUpdateAfterStoreState(update *datastore.UpdateInfo) State {
return &UpdateAfterStoreState{
updateState: NewUpdateState(datastore.MenderStateUpdateAfterStore,
ToDownload_Leave, update),
}
}
func (s *UpdateAfterStoreState) Handle(ctx *StateContext, c Controller) (State, bool) {
// This state only exists to run Download_Leave.
return NewUpdateInstallState(s.Update()), false
}
func (s *UpdateAfterStoreState) HandleError(ctx *StateContext, c Controller, merr menderError) (State, bool) {
log.Error(merr.Error())
return NewUpdateCleanupState(s.Update(), client.StatusFailure), false
}
type UpdateInstallState struct {
*updateState
}
func NewUpdateInstallState(update *datastore.UpdateInfo) State {
return &UpdateInstallState{
updateState: NewUpdateState(datastore.MenderStateUpdateInstall,
ToArtifactInstall, update),
}
}
func (is *UpdateInstallState) Handle(ctx *StateContext, c Controller) (State, bool) {
// start deployment logging
if err := DeploymentLogger.Enable(is.Update().ID); err != nil {
return NewUpdateErrorState(NewTransientError(err), is.Update()), false
}
merr := c.ReportUpdateStatus(is.Update(), client.StatusInstalling)
if merr != nil && merr.IsFatal() {
return is.HandleError(ctx, c, merr)
}
// If download was successful, install update, which for dual rootfs
// means marking inactive partition as the active one.
for _, i := range c.GetInstallers() {
if err := i.InstallUpdate(); err != nil {
return is.HandleError(ctx, c, NewTransientError(err))
}
}
ok, state, cancelled := is.handleRebootType(ctx, c)
if !ok {
return state, cancelled
}
for n := range c.GetInstallers() {
rebootRequested, err := is.Update().RebootRequested.Get(n)
if err != nil {
return is.HandleError(ctx, c, NewTransientError(errors.Wrap(
err, "Unable to get requested reboot type")))
}
switch rebootRequested {
case datastore.RebootTypeNone:
// Do nothing.
case datastore.RebootTypeCustom, datastore.RebootTypeAutomatic:
// Go to reboot state if at least one payload requested it.
return NewUpdateRebootState(is.Update()), false
default:
return is.HandleError(ctx, c, NewTransientError(errors.New(
"Unknown reboot type stored in database. Not continuing")))
}
}
// No reboot requests, go to commit state.
return NewUpdateCommitState(is.Update()), false
}
func (is *UpdateInstallState) handleRebootType(ctx *StateContext, c Controller) (bool, State, bool) {
for n, i := range c.GetInstallers() {
needsReboot, err := i.NeedsReboot()
if err != nil {
state, cancelled := is.HandleError(ctx, c, NewTransientError(err))
return false, state, cancelled
}
switch needsReboot {
case installer.NoReboot:
err = is.Update().RebootRequested.Set(n, datastore.RebootTypeNone)
case installer.RebootRequired:
err = is.Update().RebootRequested.Set(n, datastore.RebootTypeCustom)
case installer.AutomaticReboot:
err = is.Update().RebootRequested.Set(n, datastore.RebootTypeAutomatic)
default:
state, cancelled := is.HandleError(ctx, c, NewFatalError(errors.New(
"Unknown reply from NeedsReboot. Should not happen")))
return false, state, cancelled
}
if err != nil {
state, cancelled := is.HandleError(ctx, c, NewTransientError(errors.Wrap(
err, "Unable to store requested reboot type")))
return false, state, cancelled
}
}
// Make sure RebootRequested status is stored
err := StoreStateData(ctx.store, datastore.StateData{
Name: datastore.MenderStateUpdateInstall,
UpdateInfo: *is.Update(),
})
if err != nil {
log.Error("Could not write state data to persistent storage: ", err.Error())
state, cancelled := is.HandleError(ctx, c, NewTransientError(err))
state, cancelled = handleStateDataError(ctx, state, cancelled,
datastore.MenderStateUpdateInstall, is.Update(), err)
return false, state, cancelled
}
return true, nil, false
}
type FetchStoreRetryState struct {
baseState
WaitState
from State
update datastore.UpdateInfo
err error
}
func NewFetchStoreRetryState(from State, update *datastore.UpdateInfo,
err error) State {
return &FetchStoreRetryState{
baseState: baseState{
id: datastore.MenderStateFetchStoreRetryWait,
t: ToDownload_Enter,
},
WaitState: NewWaitState(datastore.MenderStateFetchStoreRetryWait, ToDownload_Enter),
from: from,
update: *update,
err: err,
}
}
func (fir *FetchStoreRetryState) Cancel() bool {
return fir.WaitState.Cancel()
}
func (fir *FetchStoreRetryState) Handle(ctx *StateContext, c Controller) (State, bool) {
log.Debugf("handle fetch install retry state")
intvl, err := client.GetExponentialBackoffTime(ctx.fetchInstallAttempts, c.GetUpdatePollInterval())
if err != nil {
if fir.err != nil {
return NewUpdateErrorState(
NewTransientError(errors.Wrap(fir.err, err.Error())),
&fir.update), false
}
return NewUpdateErrorState(
NewTransientError(err), &fir.update), false
}
ctx.fetchInstallAttempts++
log.Debugf("wait %v before next fetch/install attempt", intvl)
return fir.Wait(NewUpdateFetchState(&fir.update), fir, intvl, ctx.wakeupChan)
}
type CheckWaitState struct {
baseState
WaitState
}
func NewCheckWaitState() State {
return &CheckWaitState{
baseState: baseState{
id: datastore.MenderStateCheckWait,
t: ToIdle,
},
WaitState: NewWaitState(datastore.MenderStateCheckWait, ToIdle),
}
}
func (cw *CheckWaitState) Cancel() bool {
return cw.WaitState.Cancel()