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

mendersoftware / mender / 1033375910

11 Oct 2023 01:55PM UTC coverage: 79.921% (-0.07%) from 79.99%
1033375910

push

gitlab-ci

oleorhagen
style: Run clang-format on the whole repository

Signed-off-by: Ole Petter <ole.orhagen@northern.tech>

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

6492 of 8123 relevant lines covered (79.92%)

9892.8 hits per line

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

97

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

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

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

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

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

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

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

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

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

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

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

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

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

192
                        ctx.BeginDeploymentLogging();
55✔
193

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

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

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

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

211
        ctx.deployment.state_data->state = DatabaseStateString();
534✔
212

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

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

230
        OnEnterSaveState(ctx, poster);
531✔
231
}
232

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

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

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

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

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

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

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

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

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

326
        log::Info("Installing artifact...");
98✔
327

328
        ctx.deployment.state_data->FillUpdateDataFromArtifact(header);
49✔
329

330
        ctx.deployment.state_data->state = Context::kUpdateStateDownload;
49✔
331

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

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

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

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

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

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

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

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

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

399
                poster.PostEvent(StateEvent::Success);
46✔
400
        };
401

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

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

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

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

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

440
        DoStatusUpdate(ctx, poster);
242✔
441
}
242✔
442

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

447
        log::Info("Sending status update to server");
522✔
448

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

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

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

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

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

500
                poster.PostEvent(StateEvent::Success);
240✔
501
        };
261✔
502

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

695
        // We ignore errors in this state as long as the ArtifactVerifyRollbackReboot state
696
        // succeeds.
697
        auto err = ctx.deployment.update_module->AsyncArtifactRollbackReboot(
698
                ctx.event_loop, [&poster](error::Error err) {
114✔
699
                        if (err != error::NoError) {
57✔
700
                                log::Error(err.String());
2✔
701
                        }
702
                        poster.PostEvent(StateEvent::Success);
57✔
703
                });
114✔
704

705
        if (err != error::NoError) {
57✔
706
                log::Error(err.String());
×
707
                poster.PostEvent(StateEvent::Success);
×
708
        }
709
}
57✔
710

711
void UpdateVerifyRollbackRebootState::OnEnterSaveState(
60✔
712
        Context &ctx, sm::EventPoster<StateEvent> &poster) {
713
        log::Debug("Entering ArtifactVerifyRollbackReboot state");
120✔
714

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

732
void UpdateRollbackSuccessfulState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
50✔
733
        ctx.deployment.state_data->update_info.all_rollbacks_successful = true;
50✔
734
        poster.PostEvent(StateEvent::Success);
50✔
735
}
50✔
736

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

740
        DefaultAsyncErrorHandler(
55✔
741
                poster,
742
                ctx.deployment.update_module->AsyncArtifactFailure(
55✔
743
                        ctx.event_loop, DefaultStateHandler {poster}));
55✔
744
}
55✔
745

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

756
void UpdateSaveProvidesState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
75✔
757
        if (ctx.deployment.failed && !ctx.deployment.rollback_failed) {
75✔
758
                // If the update failed, but we rolled back successfully, then we don't need to do
759
                // anything, just keep the old data.
760
                poster.PostEvent(StateEvent::Success);
39✔
761
                return;
39✔
762
        }
763

764
        assert(ctx.deployment.state_data);
765
        // This state should never happen: rollback failed, but update not failed??
766
        assert(!(!ctx.deployment.failed && ctx.deployment.rollback_failed));
767

768
        // We expect Cleanup to be the next state after this.
769
        ctx.deployment.state_data->state = ctx.kUpdateStateCleanup;
36✔
770

771
        auto &artifact = ctx.deployment.state_data->update_info.artifact;
772

773
        string artifact_name;
774
        if (ctx.deployment.rollback_failed) {
36✔
775
                artifact_name = AddInconsistentSuffix(artifact.artifact_name);
36✔
776
        } else {
777
                artifact_name = artifact.artifact_name;
18✔
778
        }
779

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

800
        poster.PostEvent(StateEvent::Success);
36✔
801
}
802

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

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

814
        DefaultAsyncErrorHandler(
81✔
815
                poster,
816
                ctx.deployment.update_module->AsyncCleanup(ctx.event_loop, DefaultStateHandler {poster}));
162✔
817
}
818

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

834
        poster.PostEvent(StateEvent::Success);
89✔
835
}
836

837
void StateLoopState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
2✔
838
        assert(ctx.deployment.state_data);
839
        auto &artifact = ctx.deployment.state_data->update_info.artifact;
840

841
        // Mark update as inconsistent.
842
        string artifact_name = AddInconsistentSuffix(artifact.artifact_name);
2✔
843

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

856
        poster.PostEvent(StateEvent::Success);
2✔
857
}
858

859
void EndOfDeploymentState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
91✔
860
        ctx.FinishDeploymentLogging();
91✔
861

862
        ctx.deployment = {};
91✔
863
        poster.PostEvent(
91✔
864
                StateEvent::InventoryPollingTriggered); // Submit the inventory right after an update
91✔
865
        poster.PostEvent(StateEvent::DeploymentEnded);
91✔
866
        poster.PostEvent(StateEvent::Success);
91✔
867
}
91✔
868

869
ExitState::ExitState(events::EventLoop &event_loop) :
94✔
870
        event_loop_(event_loop) {
188✔
871
}
94✔
872

873
void ExitState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
91✔
874
        event_loop_.Stop();
91✔
875
}
91✔
876

877
namespace deployment_tracking {
878

879
void NoFailuresState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
61✔
880
        ctx.deployment.failed = false;
61✔
881
        ctx.deployment.rollback_failed = false;
61✔
882
}
61✔
883

884
void FailureState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
58✔
885
        ctx.deployment.failed = true;
58✔
886
        ctx.deployment.rollback_failed = true;
58✔
887
}
58✔
888

889
void RollbackAttemptedState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
52✔
890
        ctx.deployment.failed = true;
52✔
891
        ctx.deployment.rollback_failed = false;
52✔
892
}
52✔
893

894
void RollbackFailedState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
12✔
895
        ctx.deployment.failed = true;
12✔
896
        ctx.deployment.rollback_failed = true;
12✔
897
}
12✔
898

899
} // namespace deployment_tracking
900

901
} // namespace daemon
902
} // namespace update
903
} // 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