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

mendersoftware / mender / 1644050704

28 Jan 2025 07:35AM UTC coverage: 79.704% (-0.002%) from 79.706%
1644050704

push

gitlab-ci

web-flow
Merge pull request #1727 from jo-lund/4.0.x

4.0.x: fix: Clear the inventory data hash on re-authentication

3 of 10 new or added lines in 3 files covered. (30.0%)

1 existing line in 1 file now uncovered.

7214 of 9051 relevant lines covered (79.7%)

12088.5 hits per line

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

82.67
/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 = [&ctx, &poster](error::Error err) {
57✔
110
                if (err != error::NoError) {
57✔
111
                        log::Error("Failed to submit inventory: " + err.String());
×
112
                        poster.PostEvent(StateEvent::Failure);
×
113
                        return;
×
114
                }
115
                ctx.inventory_client->has_submitted_inventory = true;
57✔
116
                poster.PostEvent(StateEvent::Success);
57✔
117
        };
57✔
118

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

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

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

150
        DoSubmitInventory(ctx, poster);
57✔
151
}
57✔
152

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

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

173
        auto err = ctx.deployment_client->CheckNewDeployments(
174
                ctx.mender_context,
175
                ctx.http_client,
176
                [&ctx, &poster](mender::update::deployments::CheckUpdatesAPIResponse response) {
57✔
177
                        if (!response) {
56✔
178
                                log::Error("Error while polling for deployment: " + response.error().String());
×
UNCOV
179
                                poster.PostEvent(StateEvent::Failure);
×
180
                                return;
1✔
181
                        } else if (!response.value()) {
56✔
182
                                log::Info("No update available");
2✔
183
                                poster.PostEvent(StateEvent::NothingToDo);
1✔
184
                                if (not ctx.inventory_client->has_submitted_inventory) {
1✔
185
                                        // If we have not submitted inventory successfully at least
186
                                        // once, schedule this after receiving a successful response
187
                                        // with no update. This enables inventory to be submitted
188
                                        // immediately after the device has been accepted. If there
189
                                        // is an update available, an inventory update will be
190
                                        // scheduled at the end of it unconditionally.
191
                                        poster.PostEvent(StateEvent::InventoryPollingTriggered);
×
192
                                }
193

194
                                return;
1✔
195
                        }
196

197
                        auto exp_data = ApiResponseJsonToStateData(response.value().value());
55✔
198
                        if (!exp_data) {
55✔
199
                                log::Error("Error in API response: " + exp_data.error().String());
×
200
                                poster.PostEvent(StateEvent::Failure);
×
201
                                return;
202
                        }
203

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

207
                        ctx.BeginDeploymentLogging();
55✔
208

209
                        log::Info("Running Mender client " + conf::kMenderVersion);
110✔
210
                        log::Info(
55✔
211
                                "Deployment with ID " + ctx.deployment.state_data->update_info.id + " started.");
110✔
212

213
                        poster.PostEvent(StateEvent::DeploymentStarted);
55✔
214
                        poster.PostEvent(StateEvent::Success);
55✔
215
                });
57✔
216

217
        if (err != error::NoError) {
57✔
218
                log::Error("Error when trying to poll for deployment: " + err.String());
2✔
219
                poster.PostEvent(StateEvent::Failure);
1✔
220
        }
221
}
57✔
222

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

226
        ctx.deployment.state_data->state = DatabaseStateString();
534✔
227

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

230
        auto err = ctx.SaveDeploymentStateData(*ctx.deployment.state_data);
534✔
231
        if (err != error::NoError) {
534✔
232
                log::Error(err.String());
10✔
233
                if (err.code
10✔
234
                        == main_context::MakeError(main_context::StateDataStoreCountExceededError, "").code) {
10✔
235
                        poster.PostEvent(StateEvent::StateLoopDetected);
1✔
236
                        return;
237
                } else if (!IsFailureState()) {
9✔
238
                        // Non-failure states should be interrupted, but failure states should be
239
                        // allowed to do their work, even if a database error was detected.
240
                        poster.PostEvent(StateEvent::Failure);
2✔
241
                        return;
242
                }
243
        }
244

245
        OnEnterSaveState(ctx, poster);
531✔
246
}
247

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

251
        auto req = make_shared<http::OutgoingRequest>();
53✔
252
        req->SetMethod(http::Method::GET);
53✔
253
        auto err = req->SetAddress(ctx.deployment.state_data->update_info.artifact.source.uri);
53✔
254
        if (err != error::NoError) {
53✔
255
                log::Error(err.String());
×
256
                poster.PostEvent(StateEvent::Failure);
×
257
                return;
258
        }
259

260
        err = ctx.download_client->AsyncCall(
53✔
261
                req,
262
                [&ctx, &poster](http::ExpectedIncomingResponsePtr exp_resp) {
105✔
263
                        if (!exp_resp) {
53✔
264
                                log::Error("Unexpected error during download: " + exp_resp.error().String());
×
265
                                poster.PostEvent(StateEvent::Failure);
×
266
                                return;
1✔
267
                        }
268

269
                        auto &resp = exp_resp.value();
53✔
270
                        if (resp->GetStatusCode() != http::StatusOK) {
53✔
271
                                log::Error(
1✔
272
                                        "Unexpected status code while fetching artifact: " + resp->GetStatusMessage());
2✔
273
                                poster.PostEvent(StateEvent::Failure);
1✔
274
                                return;
1✔
275
                        }
276

277
                        auto http_reader = resp->MakeBodyAsyncReader();
52✔
278
                        if (!http_reader) {
52✔
279
                                log::Error(http_reader.error().String());
×
280
                                poster.PostEvent(StateEvent::Failure);
×
281
                                return;
282
                        }
283
                        ctx.deployment.artifact_reader =
284
                                make_shared<events::io::ReaderFromAsyncReader>(ctx.event_loop, http_reader.value());
52✔
285
                        ParseArtifact(ctx, poster);
52✔
286
                },
287
                [](http::ExpectedIncomingResponsePtr exp_resp) {
53✔
288
                        if (!exp_resp) {
53✔
289
                                log::Error(exp_resp.error().String());
6✔
290
                                // Cannot handle error here, because this handler is called at the
291
                                // end of the download, when we have already left this state. So
292
                                // rely on this error being propagated through the BodyAsyncReader
293
                                // above instead.
294
                                return;
6✔
295
                        }
296
                });
106✔
297

298
        if (err != error::NoError) {
53✔
299
                log::Error(err.String());
×
300
                poster.PostEvent(StateEvent::Failure);
×
301
                return;
302
        }
303
}
304

305
void UpdateDownloadState::ParseArtifact(Context &ctx, sm::EventPoster<StateEvent> &poster) {
52✔
306
        string art_scripts_path = ctx.mender_context.GetConfig().paths.GetArtScriptsPath();
52✔
307

308
        // Clear the artifact scripts directory so we don't risk old scripts lingering.
309
        auto err = path::DeleteRecursively(art_scripts_path);
52✔
310
        if (err != error::NoError) {
52✔
311
                log::Error("When preparing to parse artifact: " + err.String());
×
312
                poster.PostEvent(StateEvent::Failure);
×
313
                return;
314
        }
315

316
        artifact::config::ParserConfig config {
52✔
317
                .artifact_scripts_filesystem_path = art_scripts_path,
318
                .artifact_scripts_version = 3,
319
                .artifact_verify_keys = ctx.mender_context.GetConfig().artifact_verify_keys,
52✔
320
        };
100✔
321
        auto exp_parser = artifact::Parse(*ctx.deployment.artifact_reader, config);
104✔
322
        if (!exp_parser) {
52✔
323
                log::Error(exp_parser.error().String());
×
324
                poster.PostEvent(StateEvent::Failure);
×
325
                return;
326
        }
327
        ctx.deployment.artifact_parser.reset(new artifact::Artifact(std::move(exp_parser.value())));
52✔
328

329
        auto exp_header = artifact::View(*ctx.deployment.artifact_parser, 0);
52✔
330
        if (!exp_header) {
52✔
331
                log::Error(exp_header.error().String());
×
332
                poster.PostEvent(StateEvent::Failure);
×
333
                return;
334
        }
335
        auto &header = exp_header.value();
52✔
336

337
        auto exp_matches = ctx.mender_context.MatchesArtifactDepends(header.header);
52✔
338
        if (!exp_matches) {
52✔
339
                log::Error(exp_matches.error().String());
2✔
340
                poster.PostEvent(StateEvent::Failure);
2✔
341
                return;
342
        } else if (!exp_matches.value()) {
50✔
343
                // reasons already logged
344
                poster.PostEvent(StateEvent::Failure);
1✔
345
                return;
346
        }
347

348
        log::Info("Installing artifact...");
98✔
349

350
        ctx.deployment.state_data->FillUpdateDataFromArtifact(header);
49✔
351

352
        ctx.deployment.state_data->state = Context::kUpdateStateDownload;
49✔
353

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

356
        // Initial state data save, now that we have enough information from the artifact.
357
        err = ctx.SaveDeploymentStateData(*ctx.deployment.state_data);
49✔
358
        if (err != error::NoError) {
49✔
359
                log::Error(err.String());
×
360
                if (err.code
×
361
                        == main_context::MakeError(main_context::StateDataStoreCountExceededError, "").code) {
×
362
                        poster.PostEvent(StateEvent::StateLoopDetected);
×
363
                        return;
364
                } else {
365
                        poster.PostEvent(StateEvent::Failure);
×
366
                        return;
367
                }
368
        }
369

370
        if (header.header.payload_type == "") {
49✔
371
                // Empty-payload-artifact, aka "bootstrap artifact".
372
                poster.PostEvent(StateEvent::NothingToDo);
1✔
373
                return;
374
        }
375

376
        ctx.deployment.update_module.reset(
377
                new update_module::UpdateModule(ctx.mender_context, header.header.payload_type));
48✔
378

379
        err = ctx.deployment.update_module->CleanAndPrepareFileTree(
48✔
380
                ctx.deployment.update_module->GetUpdateModuleWorkDir(), header);
48✔
381
        if (err != error::NoError) {
48✔
382
                log::Error(err.String());
×
383
                poster.PostEvent(StateEvent::Failure);
×
384
                return;
385
        }
386

387
        err = ctx.deployment.update_module->AsyncProvidePayloadFileSizes(
48✔
388
                ctx.event_loop, [&ctx, &poster](expected::ExpectedBool download_with_sizes) {
48✔
389
                        if (!download_with_sizes.has_value()) {
48✔
390
                                log::Error(download_with_sizes.error().String());
×
391
                                poster.PostEvent(StateEvent::Failure);
×
392
                                return;
×
393
                        }
394
                        ctx.deployment.download_with_sizes = download_with_sizes.value();
48✔
395
                        DoDownload(ctx, poster);
48✔
396
                });
48✔
397

398
        if (err != error::NoError) {
48✔
399
                log::Error(err.String());
×
400
                poster.PostEvent(StateEvent::Failure);
×
401
                return;
402
        }
403
}
404

405
void UpdateDownloadState::DoDownload(Context &ctx, sm::EventPoster<StateEvent> &poster) {
48✔
406
        auto exp_payload = ctx.deployment.artifact_parser->Next();
48✔
407
        if (!exp_payload) {
48✔
408
                log::Error(exp_payload.error().String());
×
409
                poster.PostEvent(StateEvent::Failure);
×
410
                return;
411
        }
412
        ctx.deployment.artifact_payload.reset(new artifact::Payload(std::move(exp_payload.value())));
48✔
413

414
        auto handler = [&poster, &ctx](error::Error err) {
46✔
415
                if (err != error::NoError) {
48✔
416
                        log::Error(err.String());
2✔
417
                        poster.PostEvent(StateEvent::Failure);
2✔
418
                        return;
2✔
419
                }
420

421
                auto exp_payload = ctx.deployment.artifact_parser->Next();
46✔
422
                if (exp_payload) {
46✔
423
                        log::Error("Multiple payloads are not yet supported in daemon mode.");
×
424
                        poster.PostEvent(StateEvent::Failure);
×
425
                        return;
426
                } else if (
46✔
427
                        exp_payload.error().code
428
                        != artifact::parser_error::MakeError(artifact::parser_error::EOFError, "").code) {
46✔
429
                        log::Error(exp_payload.error().String());
×
430
                        poster.PostEvent(StateEvent::Failure);
×
431
                        return;
432
                }
433

434
                poster.PostEvent(StateEvent::Success);
46✔
435
        };
436

437
        if (ctx.deployment.download_with_sizes) {
48✔
438
                ctx.deployment.update_module->AsyncDownloadWithFileSizes(
1✔
439
                        ctx.event_loop, *ctx.deployment.artifact_payload, handler);
1✔
440
        } else {
441
                ctx.deployment.update_module->AsyncDownload(
47✔
442
                        ctx.event_loop, *ctx.deployment.artifact_payload, handler);
47✔
443
        }
444
}
445

446
void UpdateDownloadCancelState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
6✔
447
        log::Debug("Entering DownloadCancel state");
12✔
448
        ctx.download_client->Cancel();
6✔
449
        poster.PostEvent(StateEvent::Success);
6✔
450
}
6✔
451

452
SendStatusUpdateState::SendStatusUpdateState(optional<deployments::DeploymentStatus> status) :
×
453
        status_(status),
454
        mode_(FailureMode::Ignore) {
×
455
}
×
456

457
SendStatusUpdateState::SendStatusUpdateState(
188✔
458
        optional<deployments::DeploymentStatus> status,
459
        events::EventLoop &event_loop,
460
        int retry_interval_seconds,
461
        int retry_count) :
462
        status_(status),
463
        mode_(FailureMode::RetryThenFail),
464
        retry_(Retry {
188✔
465
                http::ExponentialBackoff(chrono::seconds(retry_interval_seconds), retry_count),
466
                event_loop}) {
564✔
467
}
188✔
468

469
void SendStatusUpdateState::SetSmallestWaitInterval(chrono::milliseconds interval) {
178✔
470
        if (retry_) {
178✔
471
                retry_->backoff.SetSmallestInterval(interval);
178✔
472
        }
473
}
178✔
474

475
void SendStatusUpdateState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
242✔
476
        // Reset this every time we enter the state, which means a new round of retries.
477
        if (retry_) {
242✔
478
                retry_->backoff.Reset();
479
        }
480

481
        DoStatusUpdate(ctx, poster);
242✔
482
}
242✔
483

484
void SendStatusUpdateState::DoStatusUpdate(Context &ctx, sm::EventPoster<StateEvent> &poster) {
261✔
485
        assert(ctx.deployment_client);
486
        assert(ctx.deployment.state_data);
487

488
        log::Info("Sending status update to server");
522✔
489

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

494
                        switch (mode_) {
24✔
495
                        case FailureMode::Ignore:
496
                                break;
3✔
497
                        case FailureMode::RetryThenFail:
498
                                if (err.code
21✔
499
                                        == deployments::MakeError(deployments::DeploymentAbortedError, "").code) {
21✔
500
                                        // If the deployment was aborted upstream it is an immediate
501
                                        // failure, even if retry is enabled.
502
                                        poster.PostEvent(StateEvent::Failure);
1✔
503
                                        return;
21✔
504
                                }
505

506
                                auto exp_interval = retry_->backoff.NextInterval();
20✔
507
                                if (!exp_interval) {
20✔
508
                                        log::Error(
1✔
509
                                                "Giving up on sending status updates to server: "
510
                                                + exp_interval.error().String());
2✔
511
                                        poster.PostEvent(StateEvent::Failure);
1✔
512
                                        return;
513
                                }
514

515
                                log::Info(
19✔
516
                                        "Retrying status update after "
517
                                        + to_string(chrono::duration_cast<chrono::seconds>(*exp_interval).count())
38✔
518
                                        + " seconds");
38✔
519
                                retry_->wait_timer.AsyncWait(
19✔
520
                                        *exp_interval, [this, &ctx, &poster](error::Error err) {
38✔
521
                                                // Error here is quite unexpected (from a timer), so treat
522
                                                // this as an immediate error, despite Retry flag.
523
                                                if (err != error::NoError) {
19✔
524
                                                        log::Error(
×
525
                                                                "Unexpected error in SendStatusUpdateState wait timer: "
526
                                                                + err.String());
×
527
                                                        poster.PostEvent(StateEvent::Failure);
×
528
                                                        return;
×
529
                                                }
530

531
                                                // Try again. Since both status and logs are sent
532
                                                // from here, there's a chance this might resubmit
533
                                                // the status, but there's no harm in it, and it
534
                                                // won't happen often.
535
                                                DoStatusUpdate(ctx, poster);
19✔
536
                                        });
19✔
537
                                return;
19✔
538
                        }
539
                }
540

541
                poster.PostEvent(StateEvent::Success);
240✔
542
        };
261✔
543

544
        deployments::DeploymentStatus status;
545
        if (status_) {
261✔
546
                status = status_.value();
170✔
547
        } else {
548
                // If nothing is specified, grab success/failure status from the deployment status.
549
                if (ctx.deployment.failed) {
91✔
550
                        status = deployments::DeploymentStatus::Failure;
551
                } else {
552
                        status = deployments::DeploymentStatus::Success;
553
                }
554
        }
555

556
        // Push status.
557
        log::Debug("Pushing deployment status: " + DeploymentStatusString(status));
522✔
558
        auto err = ctx.deployment_client->PushStatus(
559
                ctx.deployment.state_data->update_info.id,
261✔
560
                status,
561
                "",
562
                ctx.http_client,
563
                [result_handler, &ctx](error::Error err) {
73✔
564
                        // If there is an error, we don't submit logs now, but call the handler,
565
                        // which may schedule a retry later. If there is no error, and the
566
                        // deployment as a whole was successful, then also call the handler here,
567
                        // since we don't need to submit logs at all then.
568
                        if (err != error::NoError || !ctx.deployment.failed) {
261✔
569
                                result_handler(err);
188✔
570
                                return;
188✔
571
                        }
572

573
                        // Push logs.
574
                        err = ctx.deployment_client->PushLogs(
73✔
575
                                ctx.deployment.state_data->update_info.id,
73✔
576
                                ctx.deployment.logger->LogFilePath(),
146✔
577
                                ctx.http_client,
578
                                result_handler);
73✔
579

580
                        if (err != error::NoError) {
73✔
581
                                result_handler(err);
×
582
                        }
583
                });
522✔
584

585
        if (err != error::NoError) {
261✔
586
                result_handler(err);
×
587
        }
588

589
        // No action, wait for reply from status endpoint.
590
}
261✔
591

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

595
        DefaultAsyncErrorHandler(
42✔
596
                poster,
597
                ctx.deployment.update_module->AsyncArtifactInstall(
42✔
598
                        ctx.event_loop, DefaultStateHandler {poster}));
42✔
599
}
42✔
600

601
void UpdateCheckRebootState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
73✔
602
        DefaultAsyncErrorHandler(
73✔
603
                poster,
604
                ctx.deployment.update_module->AsyncNeedsReboot(
73✔
605
                        ctx.event_loop, [&ctx, &poster](update_module::ExpectedRebootAction reboot_action) {
144✔
606
                                if (!reboot_action.has_value()) {
73✔
607
                                        log::Error(reboot_action.error().String());
2✔
608
                                        poster.PostEvent(StateEvent::Failure);
2✔
609
                                        return;
2✔
610
                                }
611

612
                                ctx.deployment.state_data->update_info.reboot_requested.resize(1);
71✔
613
                                ctx.deployment.state_data->update_info.reboot_requested[0] =
614
                                        NeedsRebootToDbString(*reboot_action);
71✔
615
                                switch (*reboot_action) {
71✔
616
                                case update_module::RebootAction::No:
8✔
617
                                        poster.PostEvent(StateEvent::NothingToDo);
8✔
618
                                        break;
8✔
619
                                case update_module::RebootAction::Yes:
63✔
620
                                case update_module::RebootAction::Automatic:
621
                                        poster.PostEvent(StateEvent::Success);
63✔
622
                                        break;
63✔
623
                                }
624
                        }));
73✔
625
}
73✔
626

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

630
        assert(ctx.deployment.state_data->update_info.reboot_requested.size() == 1);
631
        auto exp_reboot_mode =
632
                DbStringToNeedsReboot(ctx.deployment.state_data->update_info.reboot_requested[0]);
27✔
633
        // Should always be true because we check it at load time.
634
        assert(exp_reboot_mode);
635

636
        switch (exp_reboot_mode.value()) {
27✔
637
        case update_module::RebootAction::No:
×
638
                // Should not happen because then we don't enter this state.
639
                assert(false);
640
                poster.PostEvent(StateEvent::Failure);
×
641
                break;
642
        case update_module::RebootAction::Yes:
27✔
643
                DefaultAsyncErrorHandler(
27✔
644
                        poster,
645
                        ctx.deployment.update_module->AsyncArtifactReboot(
27✔
646
                                ctx.event_loop, DefaultStateHandler {poster}));
27✔
647
                break;
27✔
648
        case update_module::RebootAction::Automatic:
×
649
                DefaultAsyncErrorHandler(
×
650
                        poster,
651
                        ctx.deployment.update_module->AsyncSystemReboot(
×
652
                                ctx.event_loop, DefaultStateHandler {poster}));
×
653
                break;
×
654
        }
655
}
27✔
656

657
void UpdateVerifyRebootState::OnEnterSaveState(Context &ctx, sm::EventPoster<StateEvent> &poster) {
30✔
658
        log::Debug("Entering ArtifactVerifyReboot state");
30✔
659

660
        ctx.deployment.update_module->EnsureRootfsImageFileTree(
30✔
661
                ctx.deployment.update_module->GetUpdateModuleWorkDir());
60✔
662

663
        DefaultAsyncErrorHandler(
30✔
664
                poster,
665
                ctx.deployment.update_module->AsyncArtifactVerifyReboot(
30✔
666
                        ctx.event_loop, DefaultStateHandler {poster}));
30✔
667
}
30✔
668

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

674
        poster.PostEvent(StateEvent::Success);
23✔
675
}
23✔
676

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

680
        // Explicitly check if state scripts version is supported
681
        auto err = script_executor::CheckScriptsCompatibility(
682
                ctx.mender_context.GetConfig().paths.GetRootfsScriptsPath());
19✔
683
        if (err != error::NoError) {
19✔
684
                log::Error("Failed script compatibility check: " + err.String());
×
685
                poster.PostEvent(StateEvent::Failure);
×
686
                return;
687
        }
688

689
        DefaultAsyncErrorHandler(
19✔
690
                poster,
691
                ctx.deployment.update_module->AsyncArtifactCommit(
19✔
692
                        ctx.event_loop, DefaultStateHandler {poster}));
38✔
693
}
694

695
void UpdateAfterCommitState::OnEnterSaveState(Context &ctx, sm::EventPoster<StateEvent> &poster) {
19✔
696
        // Now we have committed. If we had a schema update, re-save state data with the new schema.
697
        assert(ctx.deployment.state_data);
698
        auto &state_data = *ctx.deployment.state_data;
699
        if (state_data.update_info.has_db_schema_update) {
19✔
700
                state_data.update_info.has_db_schema_update = false;
×
701
                auto err = ctx.SaveDeploymentStateData(state_data);
×
702
                if (err != error::NoError) {
×
703
                        log::Error("Not able to commit schema update: " + err.String());
×
704
                        poster.PostEvent(StateEvent::Failure);
×
705
                        return;
706
                }
707
        }
708

709
        poster.PostEvent(StateEvent::Success);
19✔
710
}
711

712
void UpdateCheckRollbackState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
45✔
713
        DefaultAsyncErrorHandler(
45✔
714
                poster,
715
                ctx.deployment.update_module->AsyncSupportsRollback(
45✔
716
                        ctx.event_loop, [&ctx, &poster](expected::ExpectedBool rollback_supported) {
89✔
717
                                if (!rollback_supported.has_value()) {
45✔
718
                                        log::Error(rollback_supported.error().String());
1✔
719
                                        poster.PostEvent(StateEvent::Failure);
1✔
720
                                        return;
1✔
721
                                }
722

723
                                ctx.deployment.state_data->update_info.supports_rollback =
724
                                        SupportsRollbackToDbString(*rollback_supported);
44✔
725
                                if (*rollback_supported) {
44✔
726
                                        poster.PostEvent(StateEvent::RollbackStarted);
38✔
727
                                        poster.PostEvent(StateEvent::Success);
38✔
728
                                } else {
729
                                        poster.PostEvent(StateEvent::NothingToDo);
6✔
730
                                }
731
                        }));
45✔
732
}
45✔
733

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

737
        DefaultAsyncErrorHandler(
41✔
738
                poster,
739
                ctx.deployment.update_module->AsyncArtifactRollback(
41✔
740
                        ctx.event_loop, DefaultStateHandler {poster}));
41✔
741
}
41✔
742

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

746
        auto exp_reboot_mode =
747
                DbStringToNeedsReboot(ctx.deployment.state_data->update_info.reboot_requested[0]);
57✔
748
        // Should always be true because we check it at load time.
749
        assert(exp_reboot_mode);
750

751
        // We ignore errors in this state as long as the ArtifactVerifyRollbackReboot state
752
        // succeeds.
753
        auto handler = [&poster](error::Error err) {
114✔
754
                if (err != error::NoError) {
57✔
755
                        log::Error(err.String());
2✔
756
                }
757
                poster.PostEvent(StateEvent::Success);
57✔
758
        };
57✔
759

760
        error::Error err;
57✔
761
        switch (exp_reboot_mode.value()) {
57✔
762
        case update_module::RebootAction::No:
763
                // Should not happen because then we don't enter this state.
764
                assert(false);
765

766
                err = error::MakeError(
×
767
                        error::ProgrammingError, "Entered UpdateRollbackRebootState with RebootAction = No");
×
768
                break;
×
769

770
        case update_module::RebootAction::Yes:
57✔
771
                err = ctx.deployment.update_module->AsyncArtifactRollbackReboot(ctx.event_loop, handler);
114✔
772
                break;
57✔
773

774
        case update_module::RebootAction::Automatic:
×
775
                err = ctx.deployment.update_module->AsyncSystemReboot(ctx.event_loop, handler);
×
776
                break;
×
777
        }
778

779
        if (err != error::NoError) {
57✔
780
                log::Error(err.String());
×
781
                poster.PostEvent(StateEvent::Success);
×
782
        }
783
}
57✔
784

785
void UpdateVerifyRollbackRebootState::OnEnterSaveState(
60✔
786
        Context &ctx, sm::EventPoster<StateEvent> &poster) {
787
        log::Debug("Entering ArtifactVerifyRollbackReboot state");
120✔
788

789
        // In this state we only retry, we don't fail. If this keeps on going forever, then the
790
        // state loop detection will eventually kick in.
791
        auto err = ctx.deployment.update_module->AsyncArtifactVerifyRollbackReboot(
792
                ctx.event_loop, [&poster](error::Error err) {
120✔
793
                        if (err != error::NoError) {
60✔
794
                                log::Error(err.String());
22✔
795
                                poster.PostEvent(StateEvent::Retry);
22✔
796
                                return;
22✔
797
                        }
798
                        poster.PostEvent(StateEvent::Success);
38✔
799
                });
60✔
800
        if (err != error::NoError) {
60✔
801
                log::Error(err.String());
×
802
                poster.PostEvent(StateEvent::Retry);
×
803
        }
804
}
60✔
805

806
void UpdateRollbackSuccessfulState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
50✔
807
        ctx.deployment.state_data->update_info.all_rollbacks_successful = true;
50✔
808
        poster.PostEvent(StateEvent::Success);
50✔
809
}
50✔
810

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

814
        DefaultAsyncErrorHandler(
55✔
815
                poster,
816
                ctx.deployment.update_module->AsyncArtifactFailure(
55✔
817
                        ctx.event_loop, DefaultStateHandler {poster}));
55✔
818
}
55✔
819

820
static string AddInconsistentSuffix(const string &str) {
21✔
821
        const auto &suffix = main_context::MenderContext::broken_artifact_name_suffix;
822
        // `string::ends_with` is C++20... grumble
823
        string ret {str};
21✔
824
        if (!common::EndsWith(ret, suffix)) {
21✔
825
                ret.append(suffix);
21✔
826
        }
827
        return ret;
21✔
828
}
829

830
void UpdateSaveProvidesState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
75✔
831
        if (ctx.deployment.failed && !ctx.deployment.rollback_failed) {
75✔
832
                // If the update failed, but we rolled back successfully, then we don't need to do
833
                // anything, just keep the old data.
834
                poster.PostEvent(StateEvent::Success);
38✔
835
                return;
38✔
836
        }
837

838
        assert(ctx.deployment.state_data);
839
        // This state should never happen: rollback failed, but update not failed??
840
        assert(!(!ctx.deployment.failed && ctx.deployment.rollback_failed));
841

842
        // We expect Cleanup to be the next state after this.
843
        ctx.deployment.state_data->state = ctx.kUpdateStateCleanup;
37✔
844

845
        auto &artifact = ctx.deployment.state_data->update_info.artifact;
846

847
        string artifact_name;
848
        if (ctx.deployment.rollback_failed) {
37✔
849
                artifact_name = AddInconsistentSuffix(artifact.artifact_name);
38✔
850
        } else {
851
                artifact_name = artifact.artifact_name;
18✔
852
        }
853

854
        bool deploy_failed = ctx.deployment.failed;
37✔
855

856
        // Only the artifact_name and group should be committed in the case of a
857
        // failing update in order to make this consistent with the old client
858
        // behaviour.
859
        auto err = ctx.mender_context.CommitArtifactData(
37✔
860
                artifact_name,
861
                artifact.artifact_group,
37✔
862
                deploy_failed ? nullopt : optional<context::ProvidesData>(artifact.type_info_provides),
74✔
863
                /* Special case: Keep existing provides */
864
                deploy_failed ? context::ClearsProvidesData {}
93✔
865
                                          : optional<context::ClearsProvidesData>(artifact.clears_artifact_provides),
18✔
866
                [&ctx](kv_db::Transaction &txn) {
37✔
867
                        // Save the Cleanup state together with the artifact data, atomically.
868
                        return ctx.SaveDeploymentStateData(txn, *ctx.deployment.state_data);
37✔
869
                });
74✔
870
        if (err != error::NoError) {
37✔
871
                log::Error("Error saving artifact data: " + err.String());
×
872
                if (err.code
×
873
                        == main_context::MakeError(main_context::StateDataStoreCountExceededError, "").code) {
×
874
                        poster.PostEvent(StateEvent::StateLoopDetected);
×
875
                        return;
876
                }
877
                poster.PostEvent(StateEvent::Failure);
×
878
                return;
879
        }
880

881
        poster.PostEvent(StateEvent::Success);
37✔
882
}
883

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

887
        // It's possible for there not to be an initialized update_module structure, if the
888
        // deployment failed before we could successfully parse the artifact. If so, cleanup is a
889
        // no-op.
890
        if (!ctx.deployment.update_module) {
89✔
891
                poster.PostEvent(StateEvent::Success);
8✔
892
                return;
8✔
893
        }
894

895
        DefaultAsyncErrorHandler(
81✔
896
                poster,
897
                ctx.deployment.update_module->AsyncCleanup(ctx.event_loop, DefaultStateHandler {poster}));
162✔
898
}
899

900
void ClearArtifactDataState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
91✔
901
        auto err = ctx.mender_context.GetMenderStoreDB().WriteTransaction([](kv_db::Transaction &txn) {
91✔
902
                // Remove state data, since we're done now.
903
                auto err = txn.Remove(main_context::MenderContext::state_data_key);
89✔
904
                if (err != error::NoError) {
89✔
905
                        return err;
×
906
                }
907
                return txn.Remove(main_context::MenderContext::state_data_key_uncommitted);
89✔
908
        });
91✔
909
        if (err != error::NoError) {
91✔
910
                log::Error("Error removing artifact data: " + err.String());
4✔
911
                poster.PostEvent(StateEvent::Failure);
2✔
912
                return;
913
        }
914

915
        poster.PostEvent(StateEvent::Success);
89✔
916
}
917

918
void StateLoopState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
2✔
919
        assert(ctx.deployment.state_data);
920
        auto &artifact = ctx.deployment.state_data->update_info.artifact;
921

922
        // Mark update as inconsistent.
923
        string artifact_name = AddInconsistentSuffix(artifact.artifact_name);
2✔
924

925
        auto err = ctx.mender_context.CommitArtifactData(
2✔
926
                artifact_name,
927
                artifact.artifact_group,
2✔
928
                artifact.type_info_provides,
2✔
929
                artifact.clears_artifact_provides,
2✔
930
                [](kv_db::Transaction &txn) { return error::NoError; });
6✔
931
        if (err != error::NoError) {
2✔
932
                log::Error("Error saving inconsistent artifact data: " + err.String());
×
933
                poster.PostEvent(StateEvent::Failure);
×
934
                return;
935
        }
936

937
        poster.PostEvent(StateEvent::Success);
2✔
938
}
939

940
void EndOfDeploymentState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
91✔
941
        log::Info(
91✔
942
                "Deployment with ID " + ctx.deployment.state_data->update_info.id
182✔
943
                + " finished with status: " + string(ctx.deployment.failed ? "Failure" : "Success"));
382✔
944

945
        ctx.FinishDeploymentLogging();
91✔
946

947
        ctx.deployment = {};
91✔
948
        poster.PostEvent(
91✔
949
                StateEvent::InventoryPollingTriggered); // Submit the inventory right after an update
91✔
950
        poster.PostEvent(StateEvent::DeploymentEnded);
91✔
951
        poster.PostEvent(StateEvent::Success);
91✔
952
}
91✔
953

954
ExitState::ExitState(events::EventLoop &event_loop) :
94✔
955
        event_loop_(event_loop) {
188✔
956
}
94✔
957

958
void ExitState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
91✔
959
#ifndef NDEBUG
960
        if (--iterations_left_ <= 0) {
961
                event_loop_.Stop();
962
        } else {
963
                poster.PostEvent(StateEvent::Success);
964
        }
965
#else
966
        event_loop_.Stop();
91✔
967
#endif
968
}
91✔
969

970
namespace deployment_tracking {
971

972
void NoFailuresState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
61✔
973
        ctx.deployment.failed = false;
61✔
974
        ctx.deployment.rollback_failed = false;
61✔
975
}
61✔
976

977
void FailureState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
58✔
978
        ctx.deployment.failed = true;
58✔
979
        ctx.deployment.rollback_failed = true;
58✔
980
}
58✔
981

982
void RollbackAttemptedState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
52✔
983
        ctx.deployment.failed = true;
52✔
984
        ctx.deployment.rollback_failed = false;
52✔
985
}
52✔
986

987
void RollbackFailedState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
12✔
988
        ctx.deployment.failed = true;
12✔
989
        ctx.deployment.rollback_failed = true;
12✔
990
}
12✔
991

992
} // namespace deployment_tracking
993

994
} // namespace daemon
995
} // namespace update
996
} // 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

© 2026 Coveralls, Inc