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

mendersoftware / mender / 1019451413

28 Sep 2023 10:09AM UTC coverage: 78.477%. Remained the same
1019451413

push

gitlab-ci

kacf
chore: Make our `optional` use compatible with C++17.

If the standard is pre-C++17, we use the `optional-lite` library, else
we use the one in `std`.

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

17 of 17 new or added lines in 6 files covered. (100.0%)

5546 of 7067 relevant lines covered (78.48%)

11103.41 hits per line

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

83.02
/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) {
289✔
42
                if (err != error::NoError) {
289✔
43
                        log::Error(err.String());
23✔
44
                        poster.PostEvent(StateEvent::Failure);
23✔
45
                        return;
23✔
46
                }
47
                poster.PostEvent(StateEvent::Success);
266✔
48
        }
49

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

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

60
void EmptyState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
146✔
61
        // Keep this state truly empty.
62
}
146✔
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,026✔
70
        string state_name {script_executor::Name(this->state_, this->action_)};
1,026✔
71
        log::Debug("Executing the  " + state_name + " State Scripts...");
2,052✔
72
        auto err = this->script_.AsyncRunScripts(
73
                this->state_, this->action_, [state_name, &poster](error::Error err) {
12,340✔
74
                        if (err != error::NoError) {
1,026✔
75
                                log::Error(
21✔
76
                                        "Received error: (" + err.String() + ") when running the State Script scripts "
42✔
77
                                        + state_name);
63✔
78
                                poster.PostEvent(StateEvent::Failure);
21✔
79
                                return;
21✔
80
                        }
81
                        log::Debug("Successfully ran the " + state_name + " State Scripts...");
2,010✔
82
                        poster.PostEvent(StateEvent::Success);
1,005✔
83
                });
3,078✔
84

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

94

95
void SaveStateScriptState::OnEnterSaveState(Context &ctx, sm::EventPoster<StateEvent> &poster) {
274✔
96
        return state_script_state_.OnEnter(ctx, poster);
274✔
97
}
98

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

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

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

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

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

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

143
        DoSubmitInventory(ctx, poster);
57✔
144
}
57✔
145

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

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

164
        auto err = ctx.deployment_client->CheckNewDeployments(
165
                ctx.mender_context,
166
                ctx.mender_context.GetConfig().server_url,
57✔
167
                ctx.http_client,
168
                [&ctx, &poster](mender::update::deployments::CheckUpdatesAPIResponse response) {
55✔
169
                        if (!response) {
55✔
170
                                log::Error("Error while polling for deployment: " + response.error().String());
×
171
                                poster.PostEvent(StateEvent::Failure);
×
172
                                return;
×
173
                        } else if (!response.value()) {
55✔
174
                                log::Info("No update available");
×
175
                                poster.PostEvent(StateEvent::NothingToDo);
×
176
                                return;
×
177
                        }
178

179
                        auto exp_data = ApiResponseJsonToStateData(response.value().value());
110✔
180
                        if (!exp_data) {
55✔
181
                                log::Error("Error in API response: " + exp_data.error().String());
×
182
                                poster.PostEvent(StateEvent::Failure);
×
183
                                return;
184
                        }
185

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

189
                        ctx.BeginDeploymentLogging();
55✔
190

191
                        log::Info("Running Mender client " + conf::kMenderVersion);
110✔
192
                        log::Info(
55✔
193
                                "Deployment with ID " + ctx.deployment.state_data->update_info.id + " started.");
110✔
194

195
                        poster.PostEvent(StateEvent::DeploymentStarted);
55✔
196
                        poster.PostEvent(StateEvent::Success);
55✔
197
                });
57✔
198

199
        if (err != error::NoError) {
57✔
200
                log::Error("Error when trying to poll for deployment: " + err.String());
4✔
201
                poster.PostEvent(StateEvent::Failure);
2✔
202
        }
203
}
57✔
204

205
void SaveState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
524✔
206
        assert(ctx.deployment.state_data);
207

208
        ctx.deployment.state_data->state = DatabaseStateString();
524✔
209

210
        log::Trace("Storing deployment state in the DB (database-string):" + DatabaseStateString());
1,048✔
211

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

227
        OnEnterSaveState(ctx, poster);
521✔
228
}
229

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

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

242
        err = ctx.download_client.AsyncCall(
53✔
243
                req,
244
                [&ctx, &poster](http::ExpectedIncomingResponsePtr exp_resp) {
105✔
245
                        if (!exp_resp) {
53✔
246
                                log::Error(exp_resp.error().String());
×
247
                                poster.PostEvent(StateEvent::Failure);
×
248
                                return;
1✔
249
                        }
250

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

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

282
        if (err != error::NoError) {
53✔
283
                log::Error(err.String());
×
284
                poster.PostEvent(StateEvent::Failure);
×
285
                return;
286
        }
287
}
288

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

303
        auto exp_header = artifact::View(*ctx.deployment.artifact_parser, 0);
52✔
304
        if (!exp_header) {
52✔
305
                log::Error(exp_header.error().String());
×
306
                poster.PostEvent(StateEvent::Failure);
×
307
                return;
308
        }
309
        auto &header = exp_header.value();
52✔
310

311
        auto exp_matches = ctx.mender_context.MatchesArtifactDepends(header.header);
52✔
312
        if (!exp_matches) {
52✔
313
                log::Error(exp_matches.error().String());
2✔
314
                poster.PostEvent(StateEvent::Failure);
2✔
315
                return;
316
        } else if (!exp_matches.value()) {
50✔
317
                // reasons already logged
318
                poster.PostEvent(StateEvent::Failure);
1✔
319
                return;
320
        }
321

322
        log::Info("Installing artifact...");
98✔
323

324
        ctx.deployment.state_data->FillUpdateDataFromArtifact(header);
49✔
325

326
        ctx.deployment.state_data->state = Context::kUpdateStateDownload;
49✔
327

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

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

344
        if (header.header.payload_type == "") {
49✔
345
                // Empty-payload-artifact, aka "bootstrap artifact".
346
                poster.PostEvent(StateEvent::NothingToDo);
1✔
347
                return;
348
        }
349

350
        ctx.deployment.update_module.reset(
351
                new update_module::UpdateModule(ctx.mender_context, header.header.payload_type));
48✔
352

353
        err = ctx.deployment.update_module->CleanAndPrepareFileTree(
48✔
354
                ctx.deployment.update_module->GetUpdateModuleWorkDir(), header);
48✔
355
        if (err != error::NoError) {
48✔
356
                log::Error(err.String());
×
357
                poster.PostEvent(StateEvent::Failure);
×
358
                return;
359
        }
360

361
        err = ctx.deployment.update_module->AsyncProvidePayloadFileSizes(
48✔
362
                ctx.event_loop, [&ctx, &poster](expected::ExpectedBool download_with_sizes) {
48✔
363
                        if (!download_with_sizes.has_value()) {
48✔
364
                                log::Error(download_with_sizes.error().String());
×
365
                                poster.PostEvent(StateEvent::Failure);
×
366
                                return;
×
367
                        }
368
                        ctx.deployment.download_with_sizes = download_with_sizes.value();
48✔
369
                        DoDownload(ctx, poster);
48✔
370
                });
48✔
371

372
        if (err != error::NoError) {
48✔
373
                log::Error(err.String());
×
374
                poster.PostEvent(StateEvent::Failure);
×
375
                return;
376
        }
377
}
378

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

388
        auto handler = [&poster](error::Error err) {
96✔
389
                if (err != error::NoError) {
48✔
390
                        log::Error(err.String());
2✔
391
                        poster.PostEvent(StateEvent::Failure);
2✔
392
                        return;
2✔
393
                }
394

395
                poster.PostEvent(StateEvent::Success);
46✔
396
        };
397

398
        if (ctx.deployment.download_with_sizes) {
48✔
399
                ctx.deployment.update_module->AsyncDownloadWithFileSizes(
1✔
400
                        ctx.event_loop, *ctx.deployment.artifact_payload, handler);
1✔
401
        } else {
402
                ctx.deployment.update_module->AsyncDownload(
47✔
403
                        ctx.event_loop, *ctx.deployment.artifact_payload, handler);
47✔
404
        }
405
}
406

407
SendStatusUpdateState::SendStatusUpdateState(optional<deployments::DeploymentStatus> status) :
×
408
        status_(status),
409
        mode_(FailureMode::Ignore) {
×
410
}
×
411

412
SendStatusUpdateState::SendStatusUpdateState(
×
413
        optional<deployments::DeploymentStatus> status,
414
        events::EventLoop &event_loop,
415
        int retry_interval_seconds) :
182✔
416
        status_(status),
417
        mode_(FailureMode::RetryThenFail),
418
        // MEN-2676: Cap at 10 retries.
419
        retry_(
420
                Retry {http::ExponentialBackoff(chrono::seconds(retry_interval_seconds), 10), event_loop}) {
×
421
}
×
422

423
void SendStatusUpdateState::SetSmallestWaitInterval(chrono::milliseconds interval) {
174✔
424
        if (retry_) {
174✔
425
                retry_->backoff.SetSmallestInterval(interval);
426
        }
427
}
174✔
428

429
void SendStatusUpdateState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
239✔
430
        // Reset this every time we enter the state, which means a new round of retries.
431
        if (retry_) {
239✔
432
                retry_->backoff.Reset();
433
        }
434

435
        DoStatusUpdate(ctx, poster);
239✔
436
}
239✔
437

438
void SendStatusUpdateState::DoStatusUpdate(Context &ctx, sm::EventPoster<StateEvent> &poster) {
258✔
439
        assert(ctx.deployment_client);
440
        assert(ctx.deployment.state_data);
441

442
        log::Info("Sending status update to server");
516✔
443

444
        auto result_handler = [this, &ctx, &poster](const error::Error &err) {
560✔
445
                if (err != error::NoError) {
258✔
446
                        log::Error("Could not send deployment status: " + err.String());
48✔
447

448
                        switch (mode_) {
24✔
449
                        case FailureMode::Ignore:
450
                                break;
3✔
451
                        case FailureMode::RetryThenFail:
452
                                if (err.code
21✔
453
                                        == deployments::MakeError(deployments::DeploymentAbortedError, "").code) {
42✔
454
                                        // If the deployment was aborted upstream it is an immediate
455
                                        // failure, even if retry is enabled.
456
                                        poster.PostEvent(StateEvent::Failure);
1✔
457
                                        return;
21✔
458
                                }
459

460
                                auto exp_interval = retry_->backoff.NextInterval();
20✔
461
                                if (!exp_interval) {
20✔
462
                                        log::Error(
1✔
463
                                                "Giving up on sending status updates to server: "
464
                                                + exp_interval.error().String());
2✔
465
                                        poster.PostEvent(StateEvent::Failure);
1✔
466
                                        return;
467
                                }
468

469
                                log::Info(
19✔
470
                                        "Retrying status update after "
471
                                        + to_string(chrono::milliseconds(*exp_interval).count() / 1000) + " seconds");
38✔
472

473
                                retry_->wait_timer.AsyncWait(
19✔
474
                                        *exp_interval, [this, &ctx, &poster](error::Error err) {
38✔
475
                                                // Error here is quite unexpected (from a timer), so treat
476
                                                // this as an immediate error, despite Retry flag.
477
                                                if (err != error::NoError) {
19✔
478
                                                        log::Error(
×
479
                                                                "Unexpected error in SendStatusUpdateState wait timer: "
480
                                                                + err.String());
×
481
                                                        poster.PostEvent(StateEvent::Failure);
×
482
                                                        return;
×
483
                                                }
484

485
                                                // Try again. Since both status and logs are sent
486
                                                // from here, there's a chance this might resubmit
487
                                                // the status, but there's no harm in it, and it
488
                                                // won't happen often.
489
                                                DoStatusUpdate(ctx, poster);
19✔
490
                                        });
19✔
491
                                return;
19✔
492
                        }
493
                }
494

495
                poster.PostEvent(StateEvent::Success);
237✔
496
        };
258✔
497

498
        deployments::DeploymentStatus status;
499
        if (status_) {
258✔
500
                status = status_.value();
169✔
501
        } else {
502
                // If nothing is specified, grab success/failure status from the deployment status.
503
                if (ctx.deployment.failed) {
89✔
504
                        status = deployments::DeploymentStatus::Failure;
505
                } else {
506
                        status = deployments::DeploymentStatus::Success;
507
                }
508
        }
509

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

528
                        // Push logs.
529
                        err = ctx.deployment_client->PushLogs(
72✔
530
                                ctx.deployment.state_data->update_info.id,
72✔
531
                                ctx.deployment.logger->LogFilePath(),
144✔
532
                                ctx.mender_context.GetConfig().server_url,
72✔
533
                                ctx.http_client,
534
                                result_handler);
72✔
535

536
                        if (err != error::NoError) {
72✔
537
                                result_handler(err);
×
538
                        }
539
                });
516✔
540

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

545
        // No action, wait for reply from status endpoint.
546
}
258✔
547

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

551
        DefaultAsyncErrorHandler(
42✔
552
                poster,
553
                ctx.deployment.update_module->AsyncArtifactInstall(
42✔
554
                        ctx.event_loop, DefaultStateHandler {poster}));
42✔
555
}
42✔
556

557
void UpdateCheckRebootState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
72✔
558
        DefaultAsyncErrorHandler(
72✔
559
                poster,
560
                ctx.deployment.update_module->AsyncNeedsReboot(
72✔
561
                        ctx.event_loop, [&ctx, &poster](update_module::ExpectedRebootAction reboot_action) {
142✔
562
                                if (!reboot_action.has_value()) {
72✔
563
                                        log::Error(reboot_action.error().String());
2✔
564
                                        poster.PostEvent(StateEvent::Failure);
2✔
565
                                        return;
2✔
566
                                }
567

568
                                ctx.deployment.state_data->update_info.reboot_requested.resize(1);
70✔
569
                                ctx.deployment.state_data->update_info.reboot_requested[0] =
570
                                        NeedsRebootToDbString(*reboot_action);
70✔
571
                                switch (*reboot_action) {
70✔
572
                                case update_module::RebootAction::No:
8✔
573
                                        poster.PostEvent(StateEvent::NothingToDo);
8✔
574
                                        break;
8✔
575
                                case update_module::RebootAction::Yes:
62✔
576
                                case update_module::RebootAction::Automatic:
577
                                        poster.PostEvent(StateEvent::Success);
62✔
578
                                        break;
62✔
579
                                }
580
                        }));
72✔
581
}
72✔
582

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

586
        assert(ctx.deployment.state_data->update_info.reboot_requested.size() == 1);
587
        auto exp_reboot_mode =
588
                DbStringToNeedsReboot(ctx.deployment.state_data->update_info.reboot_requested[0]);
27✔
589
        // Should always be true because we check it at load time.
590
        assert(exp_reboot_mode);
591

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

613
void UpdateVerifyRebootState::OnEnterSaveState(Context &ctx, sm::EventPoster<StateEvent> &poster) {
29✔
614
        log::Debug("Entering ArtifactVerifyReboot state");
58✔
615

616
        DefaultAsyncErrorHandler(
29✔
617
                poster,
618
                ctx.deployment.update_module->AsyncArtifactVerifyReboot(
29✔
619
                        ctx.event_loop, DefaultStateHandler {poster}));
29✔
620
}
29✔
621

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

627
        poster.PostEvent(StateEvent::Success);
22✔
628
}
22✔
629

630
void UpdateCommitState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
18✔
631
        log::Debug("Entering ArtifactCommit state");
36✔
632

633
        DefaultAsyncErrorHandler(
18✔
634
                poster,
635
                ctx.deployment.update_module->AsyncArtifactCommit(
18✔
636
                        ctx.event_loop, DefaultStateHandler {poster}));
18✔
637
}
18✔
638

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

653
        poster.PostEvent(StateEvent::Success);
18✔
654
}
655

656
void UpdateCheckRollbackState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
44✔
657
        DefaultAsyncErrorHandler(
44✔
658
                poster,
659
                ctx.deployment.update_module->AsyncSupportsRollback(
44✔
660
                        ctx.event_loop, [&ctx, &poster](expected::ExpectedBool rollback_supported) {
87✔
661
                                if (!rollback_supported.has_value()) {
44✔
662
                                        log::Error(rollback_supported.error().String());
1✔
663
                                        poster.PostEvent(StateEvent::Failure);
1✔
664
                                        return;
1✔
665
                                }
666

667
                                ctx.deployment.state_data->update_info.supports_rollback =
668
                                        SupportsRollbackToDbString(*rollback_supported);
43✔
669
                                if (*rollback_supported) {
43✔
670
                                        poster.PostEvent(StateEvent::RollbackStarted);
37✔
671
                                        poster.PostEvent(StateEvent::Success);
37✔
672
                                } else {
673
                                        poster.PostEvent(StateEvent::NothingToDo);
6✔
674
                                }
675
                        }));
44✔
676
}
44✔
677

678
void UpdateRollbackState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
40✔
679
        log::Debug("Entering ArtifactRollback state");
80✔
680

681
        DefaultAsyncErrorHandler(
40✔
682
                poster,
683
                ctx.deployment.update_module->AsyncArtifactRollback(
40✔
684
                        ctx.event_loop, DefaultStateHandler {poster}));
40✔
685
}
40✔
686

687
void UpdateRollbackRebootState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
56✔
688
        log::Debug("Entering ArtifactRollbackReboot state");
112✔
689

690
        // We ignore errors in this state as long as the ArtifactVerifyRollbackReboot state
691
        // succeeds.
692
        auto err = ctx.deployment.update_module->AsyncArtifactRollbackReboot(
693
                ctx.event_loop, [&poster](error::Error err) {
112✔
694
                        if (err != error::NoError) {
56✔
695
                                log::Error(err.String());
2✔
696
                        }
697
                        poster.PostEvent(StateEvent::Success);
56✔
698
                });
112✔
699

700
        if (err != error::NoError) {
56✔
701
                log::Error(err.String());
×
702
                poster.PostEvent(StateEvent::Success);
×
703
        }
704
}
56✔
705

706
void UpdateVerifyRollbackRebootState::OnEnterSaveState(
59✔
707
        Context &ctx, sm::EventPoster<StateEvent> &poster) {
708
        log::Debug("Entering ArtifactVerifyRollbackReboot state");
118✔
709

710
        // In this state we only retry, we don't fail. If this keeps on going forever, then the
711
        // state loop detection will eventually kick in.
712
        auto err = ctx.deployment.update_module->AsyncArtifactVerifyRollbackReboot(
713
                ctx.event_loop, [&poster](error::Error err) {
118✔
714
                        if (err != error::NoError) {
59✔
715
                                log::Error(err.String());
22✔
716
                                poster.PostEvent(StateEvent::Retry);
22✔
717
                                return;
22✔
718
                        }
719
                        poster.PostEvent(StateEvent::Success);
37✔
720
                });
59✔
721
        if (err != error::NoError) {
59✔
722
                log::Error(err.String());
×
723
                poster.PostEvent(StateEvent::Retry);
×
724
        }
725
}
59✔
726

727
void UpdateRollbackSuccessfulState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
49✔
728
        ctx.deployment.state_data->update_info.all_rollbacks_successful = true;
49✔
729
        poster.PostEvent(StateEvent::Success);
49✔
730
}
49✔
731

732
void UpdateFailureState::OnEnterSaveState(Context &ctx, sm::EventPoster<StateEvent> &poster) {
54✔
733
        log::Debug("Entering ArtifactFailure state");
108✔
734

735
        DefaultAsyncErrorHandler(
54✔
736
                poster,
737
                ctx.deployment.update_module->AsyncArtifactFailure(
54✔
738
                        ctx.event_loop, DefaultStateHandler {poster}));
54✔
739
}
54✔
740

741
static string AddInconsistentSuffix(const string &str) {
20✔
742
        const auto &suffix = main_context::MenderContext::broken_artifact_name_suffix;
743
        // `string::ends_with` is C++20... grumble
744
        string ret {str};
745
        if (!common::EndsWith(ret, suffix)) {
20✔
746
                ret.append(suffix);
747
        }
748
        return ret;
20✔
749
}
750

751
void UpdateSaveProvidesState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
73✔
752
        if (ctx.deployment.failed && !ctx.deployment.rollback_failed) {
73✔
753
                // If the update failed, but we rolled back successfully, then we don't need to do
754
                // anything, just keep the old data.
755
                poster.PostEvent(StateEvent::Success);
38✔
756
                return;
38✔
757
        }
758

759
        assert(ctx.deployment.state_data);
760
        // This state should never happen: rollback failed, but update not failed??
761
        assert(!(!ctx.deployment.failed && ctx.deployment.rollback_failed));
762

763
        // We expect Cleanup to be the next state after this.
764
        ctx.deployment.state_data->state = ctx.kUpdateStateCleanup;
35✔
765

766
        auto &artifact = ctx.deployment.state_data->update_info.artifact;
767

768
        string artifact_name;
769
        if (ctx.deployment.rollback_failed) {
35✔
770
                artifact_name = AddInconsistentSuffix(artifact.artifact_name);
36✔
771
        } else {
772
                artifact_name = artifact.artifact_name;
17✔
773
        }
774

775
        auto err = ctx.mender_context.CommitArtifactData(
35✔
776
                artifact_name,
777
                artifact.artifact_group,
778
                artifact.type_info_provides,
779
                artifact.clears_artifact_provides,
35✔
780
                [&ctx](kv_db::Transaction &txn) {
35✔
781
                        // Save the Cleanup state together with the artifact data, atomically.
782
                        return ctx.SaveDeploymentStateData(txn, *ctx.deployment.state_data);
35✔
783
                });
140✔
784
        if (err != error::NoError) {
35✔
785
                log::Error("Error saving artifact data: " + err.String());
×
786
                if (err.code
×
787
                        == main_context::MakeError(main_context::StateDataStoreCountExceededError, "").code) {
×
788
                        poster.PostEvent(StateEvent::StateLoopDetected);
×
789
                        return;
790
                }
791
                poster.PostEvent(StateEvent::Failure);
×
792
                return;
793
        }
794

795
        poster.PostEvent(StateEvent::Success);
35✔
796
}
797

798
void UpdateCleanupState::OnEnterSaveState(Context &ctx, sm::EventPoster<StateEvent> &poster) {
87✔
799
        log::Debug("Entering ArtifactCleanup state");
174✔
800

801
        // It's possible for there not to be an initialized update_module structure, if the
802
        // deployment failed before we could successfully parse the artifact. If so, cleanup is a
803
        // no-op.
804
        if (!ctx.deployment.update_module) {
87✔
805
                poster.PostEvent(StateEvent::Success);
8✔
806
                return;
8✔
807
        }
808

809
        DefaultAsyncErrorHandler(
79✔
810
                poster,
811
                ctx.deployment.update_module->AsyncCleanup(ctx.event_loop, DefaultStateHandler {poster}));
237✔
812
}
813

814
void ClearArtifactDataState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
89✔
815
        auto err = ctx.mender_context.GetMenderStoreDB().WriteTransaction([](kv_db::Transaction &txn) {
89✔
816
                // Remove state data, since we're done now.
817
                auto err = txn.Remove(main_context::MenderContext::state_data_key);
87✔
818
                if (err != error::NoError) {
87✔
819
                        return err;
820
                }
821
                return txn.Remove(main_context::MenderContext::state_data_key_uncommitted);
87✔
822
        });
89✔
823
        if (err != error::NoError) {
89✔
824
                log::Error("Error removing artifact data: " + err.String());
4✔
825
                poster.PostEvent(StateEvent::Failure);
2✔
826
                return;
827
        }
828

829
        poster.PostEvent(StateEvent::Success);
87✔
830
}
831

832
void StateLoopState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
2✔
833
        assert(ctx.deployment.state_data);
834
        auto &artifact = ctx.deployment.state_data->update_info.artifact;
835

836
        // Mark update as inconsistent.
837
        string artifact_name = AddInconsistentSuffix(artifact.artifact_name);
2✔
838

839
        auto err = ctx.mender_context.CommitArtifactData(
2✔
840
                artifact_name,
841
                artifact.artifact_group,
842
                artifact.type_info_provides,
843
                artifact.clears_artifact_provides,
2✔
844
                [](kv_db::Transaction &txn) { return error::NoError; });
8✔
845
        if (err != error::NoError) {
2✔
846
                log::Error("Error saving inconsistent artifact data: " + err.String());
×
847
                poster.PostEvent(StateEvent::Failure);
×
848
                return;
849
        }
850

851
        poster.PostEvent(StateEvent::Success);
2✔
852
}
853

854
void EndOfDeploymentState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
89✔
855
        ctx.FinishDeploymentLogging();
89✔
856

857
        ctx.deployment = {};
89✔
858
        poster.PostEvent(StateEvent::DeploymentEnded);
89✔
859
        poster.PostEvent(StateEvent::Success);
89✔
860
}
89✔
861

862
ExitState::ExitState(events::EventLoop &event_loop) :
×
863
        event_loop_(event_loop) {
×
864
}
×
865

866
void ExitState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
89✔
867
        event_loop_.Stop();
89✔
868
}
89✔
869

870
namespace deployment_tracking {
871

872
void NoFailuresState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
60✔
873
        ctx.deployment.failed = false;
60✔
874
        ctx.deployment.rollback_failed = false;
60✔
875
}
60✔
876

877
void FailureState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
57✔
878
        ctx.deployment.failed = true;
57✔
879
        ctx.deployment.rollback_failed = true;
57✔
880
}
57✔
881

882
void RollbackAttemptedState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
51✔
883
        ctx.deployment.failed = true;
51✔
884
        ctx.deployment.rollback_failed = false;
51✔
885
}
51✔
886

887
void RollbackFailedState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
12✔
888
        ctx.deployment.failed = true;
12✔
889
        ctx.deployment.rollback_failed = true;
12✔
890
}
12✔
891

892
} // namespace deployment_tracking
893

894
} // namespace daemon
895
} // namespace update
896
} // 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