• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mendersoftware / mender / 1058883419

02 Nov 2023 12:38PM UTC coverage: 80.182% (+0.2%) from 79.944%
1058883419

push

gitlab-ci

kacf
fix: Make sure RebootAction::Automatic is handled in RollbackReboot.

Changelog: None
Ticket: None

Signed-off-by: Kristian Amlie <kristian.amlie@northern.tech>

17 of 17 new or added lines in 1 file covered. (100.0%)

6947 of 8664 relevant lines covered (80.18%)

9289.26 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

83.63
/src/mender-update/daemon/states.cpp
1
// Copyright 2023 Northern.tech AS
2
//
3
//    Licensed under the Apache License, Version 2.0 (the "License");
4
//    you may not use this file except in compliance with the License.
5
//    You may obtain a copy of the License at
6
//
7
//        http://www.apache.org/licenses/LICENSE-2.0
8
//
9
//    Unless required by applicable law or agreed to in writing, software
10
//    distributed under the License is distributed on an "AS IS" BASIS,
11
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
//    See the License for the specific language governing permissions and
13
//    limitations under the License.
14

15
#include <mender-update/daemon/states.hpp>
16

17
#include <common/conf.hpp>
18
#include <common/events_io.hpp>
19
#include <common/log.hpp>
20
#include <common/path.hpp>
21

22
#include <mender-update/daemon/context.hpp>
23
#include <mender-update/inventory.hpp>
24

25
namespace mender {
26
namespace update {
27
namespace daemon {
28

29
namespace conf = mender::common::conf;
30
namespace error = mender::common::error;
31
namespace events = mender::common::events;
32
namespace kv_db = mender::common::key_value_database;
33
namespace path = mender::common::path;
34
namespace log = mender::common::log;
35

36
namespace main_context = mender::update::context;
37
namespace inventory = mender::update::inventory;
38

39
class DefaultStateHandler {
40
public:
41
        void operator()(const error::Error &err) {
295✔
42
                if (err != error::NoError) {
295✔
43
                        log::Error(err.String());
23✔
44
                        poster.PostEvent(StateEvent::Failure);
23✔
45
                        return;
23✔
46
                }
47
                poster.PostEvent(StateEvent::Success);
272✔
48
        }
49

50
        sm::EventPoster<StateEvent> &poster;
51
};
52

53
static void DefaultAsyncErrorHandler(sm::EventPoster<StateEvent> &poster, const error::Error &err) {
413✔
54
        if (err != error::NoError) {
413✔
55
                log::Error(err.String());
×
56
                poster.PostEvent(StateEvent::Failure);
×
57
        }
58
}
413✔
59

60
void EmptyState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
148✔
61
        // Keep this state truly empty.
62
}
148✔
63

64
void InitState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
57✔
65
        // I will never run - just a placeholder to start the state-machine at
66
        poster.PostEvent(StateEvent::Started); // Start the state machine
57✔
67
}
57✔
68

69
void StateScriptState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
1,036✔
70
        string state_name {script_executor::Name(this->state_, this->action_)};
1,036✔
71
        log::Debug("Executing the  " + state_name + " State Scripts...");
2,072✔
72
        auto err = this->script_.AsyncRunScripts(
73
                this->state_,
74
                this->action_,
75
                [state_name, &poster](error::Error err) {
7,821✔
76
                        if (err != error::NoError) {
1,036✔
77
                                log::Error(
21✔
78
                                        "Received error: (" + err.String() + ") when running the State Script scripts "
42✔
79
                                        + state_name);
63✔
80
                                poster.PostEvent(StateEvent::Failure);
21✔
81
                                return;
21✔
82
                        }
83
                        log::Debug("Successfully ran the " + state_name + " State Scripts...");
2,030✔
84
                        poster.PostEvent(StateEvent::Success);
1,015✔
85
                },
86
                this->on_error_);
2,072✔
87

88
        if (err != error::NoError) {
1,036✔
89
                log::Error(
×
90
                        "Failed to schedule the state script execution for: " + state_name
×
91
                        + " got error: " + err.String());
×
92
                poster.PostEvent(StateEvent::Failure);
×
93
                return;
94
        }
95
}
96

97

98
void SaveStateScriptState::OnEnterSaveState(Context &ctx, sm::EventPoster<StateEvent> &poster) {
278✔
99
        return state_script_state_.OnEnter(ctx, poster);
278✔
100
}
101

102
void IdleState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
116✔
103
        log::Debug("Entering Idle state");
232✔
104
}
116✔
105

106
void SubmitInventoryState::DoSubmitInventory(Context &ctx, sm::EventPoster<StateEvent> &poster) {
57✔
107
        log::Debug("Submitting inventory");
114✔
108

109
        auto handler = [&poster](error::Error err) {
114✔
110
                if (err != error::NoError) {
57✔
111
                        log::Error("Failed to submit inventory: " + err.String());
×
112
                }
113
                poster.PostEvent((err == error::NoError) ? StateEvent::Success : StateEvent::Failure);
57✔
114
        };
114✔
115

116
        auto err = ctx.inventory_client->PushData(
117
                ctx.mender_context.GetConfig().paths.GetInventoryScriptsDir(),
114✔
118
                ctx.event_loop,
119
                ctx.http_client,
120
                handler);
57✔
121

122
        if (err != error::NoError) {
57✔
123
                // This is the only case the handler won't be called for us by
124
                // PushData() (see inventory::PushInventoryData()).
125
                handler(err);
×
126
        }
127
}
57✔
128

129
void SubmitInventoryState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
57✔
130
        // Schedule timer for next update first, so that long running submissions do not postpone
131
        // the schedule.
132
        log::Debug(
57✔
133
                "Scheduling the next inventory submission in: "
134
                + to_string(ctx.mender_context.GetConfig().inventory_poll_interval_seconds) + " seconds");
114✔
135
        poll_timer_.AsyncWait(
57✔
136
                chrono::seconds(ctx.mender_context.GetConfig().inventory_poll_interval_seconds),
57✔
137
                [&poster](error::Error err) {
2✔
138
                        if (err != error::NoError) {
1✔
139
                                if (err.code != make_error_condition(errc::operation_canceled)) {
×
140
                                        log::Error("Inventory poll timer caused error: " + err.String());
×
141
                                }
142
                        } else {
143
                                poster.PostEvent(StateEvent::InventoryPollingTriggered);
1✔
144
                        }
145
                });
1✔
146

147
        DoSubmitInventory(ctx, poster);
57✔
148
}
57✔
149

150
void PollForDeploymentState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
57✔
151
        log::Debug("Polling for update");
114✔
152

153
        // Schedule timer for next update first, so that long running submissions do not postpone
154
        // the schedule.
155
        log::Debug(
57✔
156
                "Scheduling the next deployment check in: "
157
                + to_string(ctx.mender_context.GetConfig().update_poll_interval_seconds) + " seconds");
114✔
158
        poll_timer_.AsyncWait(
57✔
159
                chrono::seconds(ctx.mender_context.GetConfig().update_poll_interval_seconds),
57✔
160
                [&poster](error::Error err) {
×
161
                        if (err != error::NoError) {
×
162
                                if (err.code != make_error_condition(errc::operation_canceled)) {
×
163
                                        log::Error("Update poll timer caused error: " + err.String());
×
164
                                }
165
                        } else {
166
                                poster.PostEvent(StateEvent::DeploymentPollingTriggered);
×
167
                        }
168
                });
57✔
169

170
        auto err = ctx.deployment_client->CheckNewDeployments(
171
                ctx.mender_context,
172
                ctx.http_client,
173
                [&ctx, &poster](mender::update::deployments::CheckUpdatesAPIResponse response) {
56✔
174
                        if (!response) {
56✔
175
                                log::Error("Error while polling for deployment: " + response.error().String());
×
176
                                poster.PostEvent(StateEvent::Failure);
×
177
                                return;
1✔
178
                        } else if (!response.value()) {
56✔
179
                                log::Info("No update available");
2✔
180
                                poster.PostEvent(StateEvent::NothingToDo);
1✔
181
                                return;
1✔
182
                        }
183

184
                        auto exp_data = ApiResponseJsonToStateData(response.value().value());
55✔
185
                        if (!exp_data) {
55✔
186
                                log::Error("Error in API response: " + exp_data.error().String());
×
187
                                poster.PostEvent(StateEvent::Failure);
×
188
                                return;
189
                        }
190

191
                        // Make a new set of update data.
192
                        ctx.deployment.state_data.reset(new StateData(std::move(exp_data.value())));
55✔
193

194
                        ctx.BeginDeploymentLogging();
55✔
195

196
                        log::Info("Running Mender client " + conf::kMenderVersion);
165✔
197
                        log::Info(
55✔
198
                                "Deployment with ID " + ctx.deployment.state_data->update_info.id + " started.");
110✔
199

200
                        poster.PostEvent(StateEvent::DeploymentStarted);
55✔
201
                        poster.PostEvent(StateEvent::Success);
55✔
202
                });
57✔
203

204
        if (err != error::NoError) {
57✔
205
                log::Error("Error when trying to poll for deployment: " + err.String());
2✔
206
                poster.PostEvent(StateEvent::Failure);
1✔
207
        }
208
}
57✔
209

210
void SaveState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
534✔
211
        assert(ctx.deployment.state_data);
212

213
        ctx.deployment.state_data->state = DatabaseStateString();
534✔
214

215
        log::Trace("Storing deployment state in the DB (database-string):" + DatabaseStateString());
1,068✔
216

217
        auto err = ctx.SaveDeploymentStateData(*ctx.deployment.state_data);
534✔
218
        if (err != error::NoError) {
534✔
219
                log::Error(err.String());
10✔
220
                if (err.code
10✔
221
                        == main_context::MakeError(main_context::StateDataStoreCountExceededError, "").code) {
10✔
222
                        poster.PostEvent(StateEvent::StateLoopDetected);
1✔
223
                        return;
224
                } else if (!IsFailureState()) {
9✔
225
                        // Non-failure states should be interrupted, but failure states should be
226
                        // allowed to do their work, even if a database error was detected.
227
                        poster.PostEvent(StateEvent::Failure);
2✔
228
                        return;
229
                }
230
        }
231

232
        OnEnterSaveState(ctx, poster);
531✔
233
}
234

235
void UpdateDownloadState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
53✔
236
        log::Debug("Entering Download state");
106✔
237

238
        auto req = make_shared<http::OutgoingRequest>();
53✔
239
        req->SetMethod(http::Method::GET);
53✔
240
        auto err = req->SetAddress(ctx.deployment.state_data->update_info.artifact.source.uri);
53✔
241
        if (err != error::NoError) {
53✔
242
                log::Error(err.String());
×
243
                poster.PostEvent(StateEvent::Failure);
×
244
                return;
245
        }
246

247
        err = ctx.download_client->AsyncCall(
53✔
248
                req,
249
                [&ctx, &poster](http::ExpectedIncomingResponsePtr exp_resp) {
105✔
250
                        if (!exp_resp) {
53✔
251
                                log::Error("Unexpected error during download: " + exp_resp.error().String());
×
252
                                poster.PostEvent(StateEvent::Failure);
×
253
                                return;
1✔
254
                        }
255

256
                        auto &resp = exp_resp.value();
53✔
257
                        if (resp->GetStatusCode() != http::StatusOK) {
53✔
258
                                log::Error(
1✔
259
                                        "Unexpected status code while fetching artifact: " + resp->GetStatusMessage());
2✔
260
                                ctx.download_client->Cancel();
1✔
261
                                poster.PostEvent(StateEvent::Failure);
1✔
262
                                return;
1✔
263
                        }
264

265
                        auto http_reader = resp->MakeBodyAsyncReader();
52✔
266
                        if (!http_reader) {
52✔
267
                                log::Error(http_reader.error().String());
×
268
                                ctx.download_client->Cancel();
×
269
                                poster.PostEvent(StateEvent::Failure);
×
270
                                return;
271
                        }
272
                        ctx.deployment.artifact_reader =
273
                                make_shared<events::io::ReaderFromAsyncReader>(ctx.event_loop, http_reader.value());
52✔
274
                        ParseArtifact(ctx, poster);
52✔
275
                },
276
                [](http::ExpectedIncomingResponsePtr exp_resp) {
53✔
277
                        if (!exp_resp) {
53✔
278
                                log::Error(exp_resp.error().String());
53✔
279
                                // Cannot handle error here, because this handler is called at the
280
                                // end of the download, when we have already left this state. So
281
                                // rely on this error being propagated through the BodyAsyncReader
282
                                // above instead.
283
                                return;
53✔
284
                        }
285
                });
106✔
286

287
        if (err != error::NoError) {
53✔
288
                log::Error(err.String());
×
289
                poster.PostEvent(StateEvent::Failure);
×
290
                return;
291
        }
292
}
293

294
void UpdateDownloadState::ParseArtifact(Context &ctx, sm::EventPoster<StateEvent> &poster) {
52✔
295
        artifact::config::ParserConfig config {
52✔
296
                .artifact_scripts_filesystem_path =
297
                        ctx.mender_context.GetConfig().paths.GetArtScriptsPath(),
52✔
298
                .artifact_scripts_version = 3,
299
                .artifact_verify_keys = ctx.mender_context.GetConfig().artifact_verify_keys,
52✔
300
        };
100✔
301
        auto exp_parser = artifact::Parse(*ctx.deployment.artifact_reader, config);
104✔
302
        if (!exp_parser) {
52✔
303
                log::Error(exp_parser.error().String());
×
304
                poster.PostEvent(StateEvent::Failure);
×
305
                return;
306
        }
307
        ctx.deployment.artifact_parser.reset(new artifact::Artifact(std::move(exp_parser.value())));
52✔
308

309
        auto exp_header = artifact::View(*ctx.deployment.artifact_parser, 0);
52✔
310
        if (!exp_header) {
52✔
311
                log::Error(exp_header.error().String());
×
312
                poster.PostEvent(StateEvent::Failure);
×
313
                return;
314
        }
315
        auto &header = exp_header.value();
52✔
316

317
        auto exp_matches = ctx.mender_context.MatchesArtifactDepends(header.header);
52✔
318
        if (!exp_matches) {
52✔
319
                log::Error(exp_matches.error().String());
2✔
320
                poster.PostEvent(StateEvent::Failure);
2✔
321
                return;
322
        } else if (!exp_matches.value()) {
50✔
323
                // reasons already logged
324
                poster.PostEvent(StateEvent::Failure);
1✔
325
                return;
326
        }
327

328
        log::Info("Installing artifact...");
98✔
329

330
        ctx.deployment.state_data->FillUpdateDataFromArtifact(header);
49✔
331

332
        ctx.deployment.state_data->state = Context::kUpdateStateDownload;
49✔
333

334
        assert(ctx.deployment.state_data->update_info.artifact.payload_types.size() == 1);
335

336
        // Initial state data save, now that we have enough information from the artifact.
337
        auto err = ctx.SaveDeploymentStateData(*ctx.deployment.state_data);
49✔
338
        if (err != error::NoError) {
49✔
339
                log::Error(err.String());
×
340
                if (err.code
×
341
                        == main_context::MakeError(main_context::StateDataStoreCountExceededError, "").code) {
×
342
                        poster.PostEvent(StateEvent::StateLoopDetected);
×
343
                        return;
344
                } else {
345
                        poster.PostEvent(StateEvent::Failure);
×
346
                        return;
347
                }
348
        }
349

350
        if (header.header.payload_type == "") {
49✔
351
                // Empty-payload-artifact, aka "bootstrap artifact".
352
                poster.PostEvent(StateEvent::NothingToDo);
1✔
353
                return;
354
        }
355

356
        ctx.deployment.update_module.reset(
357
                new update_module::UpdateModule(ctx.mender_context, header.header.payload_type));
48✔
358

359
        err = ctx.deployment.update_module->CleanAndPrepareFileTree(
48✔
360
                ctx.deployment.update_module->GetUpdateModuleWorkDir(), header);
48✔
361
        if (err != error::NoError) {
48✔
362
                log::Error(err.String());
×
363
                poster.PostEvent(StateEvent::Failure);
×
364
                return;
365
        }
366

367
        err = ctx.deployment.update_module->AsyncProvidePayloadFileSizes(
48✔
368
                ctx.event_loop, [&ctx, &poster](expected::ExpectedBool download_with_sizes) {
48✔
369
                        if (!download_with_sizes.has_value()) {
48✔
370
                                log::Error(download_with_sizes.error().String());
×
371
                                poster.PostEvent(StateEvent::Failure);
×
372
                                return;
×
373
                        }
374
                        ctx.deployment.download_with_sizes = download_with_sizes.value();
48✔
375
                        DoDownload(ctx, poster);
48✔
376
                });
48✔
377

378
        if (err != error::NoError) {
48✔
379
                log::Error(err.String());
×
380
                poster.PostEvent(StateEvent::Failure);
×
381
                return;
382
        }
383
}
384

385
void UpdateDownloadState::DoDownload(Context &ctx, sm::EventPoster<StateEvent> &poster) {
48✔
386
        auto exp_payload = ctx.deployment.artifact_parser->Next();
48✔
387
        if (!exp_payload) {
48✔
388
                log::Error(exp_payload.error().String());
×
389
                poster.PostEvent(StateEvent::Failure);
×
390
                return;
391
        }
392
        ctx.deployment.artifact_payload.reset(new artifact::Payload(std::move(exp_payload.value())));
48✔
393

394
        auto handler = [&poster](error::Error err) {
96✔
395
                if (err != error::NoError) {
48✔
396
                        log::Error(err.String());
2✔
397
                        poster.PostEvent(StateEvent::Failure);
2✔
398
                        return;
2✔
399
                }
400

401
                poster.PostEvent(StateEvent::Success);
46✔
402
        };
403

404
        if (ctx.deployment.download_with_sizes) {
48✔
405
                ctx.deployment.update_module->AsyncDownloadWithFileSizes(
1✔
406
                        ctx.event_loop, *ctx.deployment.artifact_payload, handler);
1✔
407
        } else {
408
                ctx.deployment.update_module->AsyncDownload(
47✔
409
                        ctx.event_loop, *ctx.deployment.artifact_payload, handler);
47✔
410
        }
411
}
412

413
SendStatusUpdateState::SendStatusUpdateState(optional<deployments::DeploymentStatus> status) :
×
414
        status_(status),
415
        mode_(FailureMode::Ignore) {
×
416
}
×
417

418
SendStatusUpdateState::SendStatusUpdateState(
188✔
419
        optional<deployments::DeploymentStatus> status,
420
        events::EventLoop &event_loop,
421
        int retry_interval_seconds,
422
        int retry_count) :
423
        status_(status),
424
        mode_(FailureMode::RetryThenFail),
425
        retry_(Retry {
188✔
426
                http::ExponentialBackoff(chrono::seconds(retry_interval_seconds), retry_count),
427
                event_loop}) {
564✔
428
}
188✔
429

430
void SendStatusUpdateState::SetSmallestWaitInterval(chrono::milliseconds interval) {
178✔
431
        if (retry_) {
178✔
432
                retry_->backoff.SetSmallestInterval(interval);
178✔
433
        }
434
}
178✔
435

436
void SendStatusUpdateState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
242✔
437
        // Reset this every time we enter the state, which means a new round of retries.
438
        if (retry_) {
242✔
439
                retry_->backoff.Reset();
440
        }
441

442
        DoStatusUpdate(ctx, poster);
242✔
443
}
242✔
444

445
void SendStatusUpdateState::DoStatusUpdate(Context &ctx, sm::EventPoster<StateEvent> &poster) {
261✔
446
        assert(ctx.deployment_client);
447
        assert(ctx.deployment.state_data);
448

449
        log::Info("Sending status update to server");
522✔
450

451
        auto result_handler = [this, &ctx, &poster](const error::Error &err) {
566✔
452
                if (err != error::NoError) {
261✔
453
                        log::Error("Could not send deployment status: " + err.String());
48✔
454

455
                        switch (mode_) {
24✔
456
                        case FailureMode::Ignore:
457
                                break;
3✔
458
                        case FailureMode::RetryThenFail:
459
                                if (err.code
21✔
460
                                        == deployments::MakeError(deployments::DeploymentAbortedError, "").code) {
21✔
461
                                        // If the deployment was aborted upstream it is an immediate
462
                                        // failure, even if retry is enabled.
463
                                        poster.PostEvent(StateEvent::Failure);
1✔
464
                                        return;
21✔
465
                                }
466

467
                                auto exp_interval = retry_->backoff.NextInterval();
20✔
468
                                if (!exp_interval) {
20✔
469
                                        log::Error(
1✔
470
                                                "Giving up on sending status updates to server: "
471
                                                + exp_interval.error().String());
2✔
472
                                        poster.PostEvent(StateEvent::Failure);
1✔
473
                                        return;
474
                                }
475

476
                                log::Info(
19✔
477
                                        "Retrying status update after "
478
                                        + to_string(chrono::duration_cast<chrono::seconds>(*exp_interval).count())
38✔
479
                                        + " seconds");
38✔
480
                                retry_->wait_timer.AsyncWait(
19✔
481
                                        *exp_interval, [this, &ctx, &poster](error::Error err) {
38✔
482
                                                // Error here is quite unexpected (from a timer), so treat
483
                                                // this as an immediate error, despite Retry flag.
484
                                                if (err != error::NoError) {
19✔
485
                                                        log::Error(
×
486
                                                                "Unexpected error in SendStatusUpdateState wait timer: "
487
                                                                + err.String());
×
488
                                                        poster.PostEvent(StateEvent::Failure);
×
489
                                                        return;
×
490
                                                }
491

492
                                                // Try again. Since both status and logs are sent
493
                                                // from here, there's a chance this might resubmit
494
                                                // the status, but there's no harm in it, and it
495
                                                // won't happen often.
496
                                                DoStatusUpdate(ctx, poster);
19✔
497
                                        });
19✔
498
                                return;
19✔
499
                        }
500
                }
501

502
                poster.PostEvent(StateEvent::Success);
240✔
503
        };
261✔
504

505
        deployments::DeploymentStatus status;
506
        if (status_) {
261✔
507
                status = status_.value();
170✔
508
        } else {
509
                // If nothing is specified, grab success/failure status from the deployment status.
510
                if (ctx.deployment.failed) {
91✔
511
                        status = deployments::DeploymentStatus::Failure;
512
                } else {
513
                        status = deployments::DeploymentStatus::Success;
514
                }
515
        }
516

517
        // Push status.
518
        log::Debug("Pushing deployment status: " + DeploymentStatusString(status));
522✔
519
        auto err = ctx.deployment_client->PushStatus(
520
                ctx.deployment.state_data->update_info.id,
261✔
521
                status,
522
                "",
523
                ctx.http_client,
524
                [result_handler, &ctx](error::Error err) {
73✔
525
                        // If there is an error, we don't submit logs now, but call the handler,
526
                        // which may schedule a retry later. If there is no error, and the
527
                        // deployment as a whole was successful, then also call the handler here,
528
                        // since we don't need to submit logs at all then.
529
                        if (err != error::NoError || !ctx.deployment.failed) {
261✔
530
                                result_handler(err);
188✔
531
                                return;
188✔
532
                        }
533

534
                        // Push logs.
535
                        err = ctx.deployment_client->PushLogs(
73✔
536
                                ctx.deployment.state_data->update_info.id,
73✔
537
                                ctx.deployment.logger->LogFilePath(),
146✔
538
                                ctx.http_client,
539
                                result_handler);
73✔
540

541
                        if (err != error::NoError) {
73✔
542
                                result_handler(err);
×
543
                        }
544
                });
522✔
545

546
        if (err != error::NoError) {
261✔
547
                result_handler(err);
×
548
        }
549

550
        // No action, wait for reply from status endpoint.
551
}
261✔
552

553
void UpdateInstallState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
42✔
554
        log::Debug("Entering ArtifactInstall state");
84✔
555

556
        DefaultAsyncErrorHandler(
42✔
557
                poster,
558
                ctx.deployment.update_module->AsyncArtifactInstall(
42✔
559
                        ctx.event_loop, DefaultStateHandler {poster}));
42✔
560
}
42✔
561

562
void UpdateCheckRebootState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
73✔
563
        DefaultAsyncErrorHandler(
73✔
564
                poster,
565
                ctx.deployment.update_module->AsyncNeedsReboot(
73✔
566
                        ctx.event_loop, [&ctx, &poster](update_module::ExpectedRebootAction reboot_action) {
144✔
567
                                if (!reboot_action.has_value()) {
73✔
568
                                        log::Error(reboot_action.error().String());
2✔
569
                                        poster.PostEvent(StateEvent::Failure);
2✔
570
                                        return;
2✔
571
                                }
572

573
                                ctx.deployment.state_data->update_info.reboot_requested.resize(1);
71✔
574
                                ctx.deployment.state_data->update_info.reboot_requested[0] =
575
                                        NeedsRebootToDbString(*reboot_action);
71✔
576
                                switch (*reboot_action) {
71✔
577
                                case update_module::RebootAction::No:
8✔
578
                                        poster.PostEvent(StateEvent::NothingToDo);
8✔
579
                                        break;
8✔
580
                                case update_module::RebootAction::Yes:
63✔
581
                                case update_module::RebootAction::Automatic:
582
                                        poster.PostEvent(StateEvent::Success);
63✔
583
                                        break;
63✔
584
                                }
585
                        }));
73✔
586
}
73✔
587

588
void UpdateRebootState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
27✔
589
        log::Debug("Entering ArtifactReboot state");
54✔
590

591
        assert(ctx.deployment.state_data->update_info.reboot_requested.size() == 1);
592
        auto exp_reboot_mode =
593
                DbStringToNeedsReboot(ctx.deployment.state_data->update_info.reboot_requested[0]);
27✔
594
        // Should always be true because we check it at load time.
595
        assert(exp_reboot_mode);
596

597
        switch (exp_reboot_mode.value()) {
27✔
598
        case update_module::RebootAction::No:
×
599
                // Should not happen because then we don't enter this state.
600
                assert(false);
601
                poster.PostEvent(StateEvent::Failure);
×
602
                break;
603
        case update_module::RebootAction::Yes:
27✔
604
                DefaultAsyncErrorHandler(
27✔
605
                        poster,
606
                        ctx.deployment.update_module->AsyncArtifactReboot(
27✔
607
                                ctx.event_loop, DefaultStateHandler {poster}));
27✔
608
                break;
27✔
609
        case update_module::RebootAction::Automatic:
×
610
                DefaultAsyncErrorHandler(
×
611
                        poster,
612
                        ctx.deployment.update_module->AsyncSystemReboot(
×
613
                                ctx.event_loop, DefaultStateHandler {poster}));
×
614
                break;
×
615
        }
616
}
27✔
617

618
void UpdateVerifyRebootState::OnEnterSaveState(Context &ctx, sm::EventPoster<StateEvent> &poster) {
30✔
619
        log::Debug("Entering ArtifactVerifyReboot state");
60✔
620

621
        DefaultAsyncErrorHandler(
30✔
622
                poster,
623
                ctx.deployment.update_module->AsyncArtifactVerifyReboot(
30✔
624
                        ctx.event_loop, DefaultStateHandler {poster}));
30✔
625
}
30✔
626

627
void UpdateBeforeCommitState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
23✔
628
        // It's possible that the update we have done has changed our credentials. Therefore it's
629
        // important that we try to log in from scratch and do not use the token we already have.
630
        ctx.http_client.ExpireToken();
23✔
631

632
        poster.PostEvent(StateEvent::Success);
23✔
633
}
23✔
634

635
void UpdateCommitState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
19✔
636
        log::Debug("Entering ArtifactCommit state");
38✔
637

638
        DefaultAsyncErrorHandler(
19✔
639
                poster,
640
                ctx.deployment.update_module->AsyncArtifactCommit(
19✔
641
                        ctx.event_loop, DefaultStateHandler {poster}));
19✔
642
}
19✔
643

644
void UpdateAfterCommitState::OnEnterSaveState(Context &ctx, sm::EventPoster<StateEvent> &poster) {
19✔
645
        // Now we have committed. If we had a schema update, re-save state data with the new schema.
646
        assert(ctx.deployment.state_data);
647
        auto &state_data = *ctx.deployment.state_data;
648
        if (state_data.update_info.has_db_schema_update) {
19✔
649
                state_data.update_info.has_db_schema_update = false;
1✔
650
                auto err = ctx.SaveDeploymentStateData(state_data);
1✔
651
                if (err != error::NoError) {
1✔
652
                        log::Error("Not able to commit schema update: " + err.String());
×
653
                        poster.PostEvent(StateEvent::Failure);
×
654
                        return;
655
                }
656
        }
657

658
        poster.PostEvent(StateEvent::Success);
19✔
659
}
660

661
void UpdateCheckRollbackState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
45✔
662
        DefaultAsyncErrorHandler(
45✔
663
                poster,
664
                ctx.deployment.update_module->AsyncSupportsRollback(
45✔
665
                        ctx.event_loop, [&ctx, &poster](expected::ExpectedBool rollback_supported) {
89✔
666
                                if (!rollback_supported.has_value()) {
45✔
667
                                        log::Error(rollback_supported.error().String());
1✔
668
                                        poster.PostEvent(StateEvent::Failure);
1✔
669
                                        return;
1✔
670
                                }
671

672
                                ctx.deployment.state_data->update_info.supports_rollback =
673
                                        SupportsRollbackToDbString(*rollback_supported);
44✔
674
                                if (*rollback_supported) {
44✔
675
                                        poster.PostEvent(StateEvent::RollbackStarted);
38✔
676
                                        poster.PostEvent(StateEvent::Success);
38✔
677
                                } else {
678
                                        poster.PostEvent(StateEvent::NothingToDo);
6✔
679
                                }
680
                        }));
45✔
681
}
45✔
682

683
void UpdateRollbackState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
41✔
684
        log::Debug("Entering ArtifactRollback state");
82✔
685

686
        DefaultAsyncErrorHandler(
41✔
687
                poster,
688
                ctx.deployment.update_module->AsyncArtifactRollback(
41✔
689
                        ctx.event_loop, DefaultStateHandler {poster}));
41✔
690
}
41✔
691

692
void UpdateRollbackRebootState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
57✔
693
        log::Debug("Entering ArtifactRollbackReboot state");
114✔
694

695
        auto exp_reboot_mode =
696
                DbStringToNeedsReboot(ctx.deployment.state_data->update_info.reboot_requested[0]);
57✔
697
        // Should always be true because we check it at load time.
698
        assert(exp_reboot_mode);
699

700
        // We ignore errors in this state as long as the ArtifactVerifyRollbackReboot state
701
        // succeeds.
702
        auto handler = [&poster](error::Error err) {
114✔
703
                if (err != error::NoError) {
57✔
704
                        log::Error(err.String());
2✔
705
                }
706
                poster.PostEvent(StateEvent::Success);
57✔
707
        };
57✔
708

709
        error::Error err;
57✔
710
        switch (exp_reboot_mode.value()) {
57✔
711
        case update_module::RebootAction::No:
712
                // Should not happen because then we don't enter this state.
713
                assert(false);
714

715
                err = error::MakeError(
×
716
                        error::ProgrammingError, "Entered UpdateRollbackRebootState with RebootAction = No");
×
717
                break;
×
718

719
        case update_module::RebootAction::Yes:
57✔
720
                err = ctx.deployment.update_module->AsyncArtifactRollbackReboot(ctx.event_loop, handler);
114✔
721
                break;
57✔
722

723
        case update_module::RebootAction::Automatic:
×
724
                err = ctx.deployment.update_module->AsyncSystemReboot(ctx.event_loop, handler);
×
725
                break;
×
726
        }
727

728
        if (err != error::NoError) {
57✔
729
                log::Error(err.String());
×
730
                poster.PostEvent(StateEvent::Success);
×
731
        }
732
}
57✔
733

734
void UpdateVerifyRollbackRebootState::OnEnterSaveState(
60✔
735
        Context &ctx, sm::EventPoster<StateEvent> &poster) {
736
        log::Debug("Entering ArtifactVerifyRollbackReboot state");
120✔
737

738
        // In this state we only retry, we don't fail. If this keeps on going forever, then the
739
        // state loop detection will eventually kick in.
740
        auto err = ctx.deployment.update_module->AsyncArtifactVerifyRollbackReboot(
741
                ctx.event_loop, [&poster](error::Error err) {
120✔
742
                        if (err != error::NoError) {
60✔
743
                                log::Error(err.String());
22✔
744
                                poster.PostEvent(StateEvent::Retry);
22✔
745
                                return;
22✔
746
                        }
747
                        poster.PostEvent(StateEvent::Success);
38✔
748
                });
60✔
749
        if (err != error::NoError) {
60✔
750
                log::Error(err.String());
×
751
                poster.PostEvent(StateEvent::Retry);
×
752
        }
753
}
60✔
754

755
void UpdateRollbackSuccessfulState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
50✔
756
        ctx.deployment.state_data->update_info.all_rollbacks_successful = true;
50✔
757
        poster.PostEvent(StateEvent::Success);
50✔
758
}
50✔
759

760
void UpdateFailureState::OnEnterSaveState(Context &ctx, sm::EventPoster<StateEvent> &poster) {
55✔
761
        log::Debug("Entering ArtifactFailure state");
110✔
762

763
        DefaultAsyncErrorHandler(
55✔
764
                poster,
765
                ctx.deployment.update_module->AsyncArtifactFailure(
55✔
766
                        ctx.event_loop, DefaultStateHandler {poster}));
55✔
767
}
55✔
768

769
static string AddInconsistentSuffix(const string &str) {
20✔
770
        const auto &suffix = main_context::MenderContext::broken_artifact_name_suffix;
771
        // `string::ends_with` is C++20... grumble
772
        string ret {str};
20✔
773
        if (!common::EndsWith(ret, suffix)) {
20✔
774
                ret.append(suffix);
20✔
775
        }
776
        return ret;
20✔
777
}
778

779
void UpdateSaveProvidesState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
75✔
780
        if (ctx.deployment.failed && !ctx.deployment.rollback_failed) {
75✔
781
                // If the update failed, but we rolled back successfully, then we don't need to do
782
                // anything, just keep the old data.
783
                poster.PostEvent(StateEvent::Success);
39✔
784
                return;
39✔
785
        }
786

787
        assert(ctx.deployment.state_data);
788
        // This state should never happen: rollback failed, but update not failed??
789
        assert(!(!ctx.deployment.failed && ctx.deployment.rollback_failed));
790

791
        // We expect Cleanup to be the next state after this.
792
        ctx.deployment.state_data->state = ctx.kUpdateStateCleanup;
36✔
793

794
        auto &artifact = ctx.deployment.state_data->update_info.artifact;
795

796
        string artifact_name;
797
        if (ctx.deployment.rollback_failed) {
36✔
798
                artifact_name = AddInconsistentSuffix(artifact.artifact_name);
36✔
799
        } else {
800
                artifact_name = artifact.artifact_name;
18✔
801
        }
802

803
        auto err = ctx.mender_context.CommitArtifactData(
36✔
804
                artifact_name,
805
                artifact.artifact_group,
36✔
806
                artifact.type_info_provides,
36✔
807
                artifact.clears_artifact_provides,
36✔
808
                [&ctx](kv_db::Transaction &txn) {
36✔
809
                        // Save the Cleanup state together with the artifact data, atomically.
810
                        return ctx.SaveDeploymentStateData(txn, *ctx.deployment.state_data);
36✔
811
                });
72✔
812
        if (err != error::NoError) {
36✔
813
                log::Error("Error saving artifact data: " + err.String());
×
814
                if (err.code
×
815
                        == main_context::MakeError(main_context::StateDataStoreCountExceededError, "").code) {
×
816
                        poster.PostEvent(StateEvent::StateLoopDetected);
×
817
                        return;
818
                }
819
                poster.PostEvent(StateEvent::Failure);
×
820
                return;
821
        }
822

823
        poster.PostEvent(StateEvent::Success);
36✔
824
}
825

826
void UpdateCleanupState::OnEnterSaveState(Context &ctx, sm::EventPoster<StateEvent> &poster) {
89✔
827
        log::Debug("Entering ArtifactCleanup state");
178✔
828

829
        // It's possible for there not to be an initialized update_module structure, if the
830
        // deployment failed before we could successfully parse the artifact. If so, cleanup is a
831
        // no-op.
832
        if (!ctx.deployment.update_module) {
89✔
833
                poster.PostEvent(StateEvent::Success);
8✔
834
                return;
8✔
835
        }
836

837
        DefaultAsyncErrorHandler(
81✔
838
                poster,
839
                ctx.deployment.update_module->AsyncCleanup(ctx.event_loop, DefaultStateHandler {poster}));
162✔
840
}
841

842
void ClearArtifactDataState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
91✔
843
        auto err = ctx.mender_context.GetMenderStoreDB().WriteTransaction([](kv_db::Transaction &txn) {
91✔
844
                // Remove state data, since we're done now.
845
                auto err = txn.Remove(main_context::MenderContext::state_data_key);
89✔
846
                if (err != error::NoError) {
89✔
847
                        return err;
×
848
                }
849
                return txn.Remove(main_context::MenderContext::state_data_key_uncommitted);
89✔
850
        });
91✔
851
        if (err != error::NoError) {
91✔
852
                log::Error("Error removing artifact data: " + err.String());
4✔
853
                poster.PostEvent(StateEvent::Failure);
2✔
854
                return;
855
        }
856

857
        poster.PostEvent(StateEvent::Success);
89✔
858
}
859

860
void StateLoopState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
2✔
861
        assert(ctx.deployment.state_data);
862
        auto &artifact = ctx.deployment.state_data->update_info.artifact;
863

864
        // Mark update as inconsistent.
865
        string artifact_name = AddInconsistentSuffix(artifact.artifact_name);
2✔
866

867
        auto err = ctx.mender_context.CommitArtifactData(
2✔
868
                artifact_name,
869
                artifact.artifact_group,
2✔
870
                artifact.type_info_provides,
2✔
871
                artifact.clears_artifact_provides,
2✔
872
                [](kv_db::Transaction &txn) { return error::NoError; });
6✔
873
        if (err != error::NoError) {
2✔
874
                log::Error("Error saving inconsistent artifact data: " + err.String());
×
875
                poster.PostEvent(StateEvent::Failure);
×
876
                return;
877
        }
878

879
        poster.PostEvent(StateEvent::Success);
2✔
880
}
881

882
void EndOfDeploymentState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
91✔
883
        ctx.FinishDeploymentLogging();
91✔
884

885
        ctx.deployment = {};
91✔
886
        poster.PostEvent(
91✔
887
                StateEvent::InventoryPollingTriggered); // Submit the inventory right after an update
91✔
888
        poster.PostEvent(StateEvent::DeploymentEnded);
91✔
889
        poster.PostEvent(StateEvent::Success);
91✔
890
}
91✔
891

892
ExitState::ExitState(events::EventLoop &event_loop) :
94✔
893
        event_loop_(event_loop) {
188✔
894
}
94✔
895

896
void ExitState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
91✔
897
        event_loop_.Stop();
91✔
898
}
91✔
899

900
namespace deployment_tracking {
901

902
void NoFailuresState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
61✔
903
        ctx.deployment.failed = false;
61✔
904
        ctx.deployment.rollback_failed = false;
61✔
905
}
61✔
906

907
void FailureState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
58✔
908
        ctx.deployment.failed = true;
58✔
909
        ctx.deployment.rollback_failed = true;
58✔
910
}
58✔
911

912
void RollbackAttemptedState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
52✔
913
        ctx.deployment.failed = true;
52✔
914
        ctx.deployment.rollback_failed = false;
52✔
915
}
52✔
916

917
void RollbackFailedState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
12✔
918
        ctx.deployment.failed = true;
12✔
919
        ctx.deployment.rollback_failed = true;
12✔
920
}
12✔
921

922
} // namespace deployment_tracking
923

924
} // namespace daemon
925
} // namespace update
926
} // namespace mender
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc