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

mendersoftware / mender / 1585732742

12 Dec 2024 11:46AM UTC coverage: 76.259% (+0.02%) from 76.236%
1585732742

push

gitlab-ci

web-flow
Merge pull request #1712 from vpodzime/http_resumer_leftovers

Proper cleanup of HTTP leftovers

8 of 8 new or added lines in 3 files covered. (100.0%)

1 existing line in 1 file now uncovered.

7375 of 9671 relevant lines covered (76.26%)

11182.96 hits per line

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

82.06
/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 <client_shared/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::client_shared::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) {
114✔
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.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) {
56✔
177
                        if (!response) {
56✔
178
                                log::Error("Error while polling for deployment: " + response.error().String());
×
179

180
                                // When unauthenticated,
181
                                // invalidate the cached inventory data so that it can be sent again
182
                                // and set clear the context flag so that it is triggered on re-authorization
183
                                if ((response.error().code == auth::MakeError(auth::UnauthorizedError, "").code)
×
184
                                        && ctx.has_submitted_inventory) {
×
185
                                        ctx.inventory_client->ClearDataCache();
×
186
                                        ctx.has_submitted_inventory = false;
×
187
                                }
188
                                poster.PostEvent(StateEvent::Failure);
×
189
                                return;
1✔
190
                        } else if (!response.value()) {
56✔
191
                                log::Info("No update available");
2✔
192
                                poster.PostEvent(StateEvent::NothingToDo);
1✔
193

194
                                if (not ctx.has_submitted_inventory) {
1✔
195
                                        // If we have not submitted inventory successfully at least
196
                                        // once, schedule this after receiving a successful response
197
                                        // with no update. This enables inventory to be submitted
198
                                        // immediately after the device has been accepted. If there
199
                                        // is an update available, an inventory update will be
200
                                        // scheduled at the end of it unconditionally.
201
                                        poster.PostEvent(StateEvent::InventoryPollingTriggered);
×
202
                                }
203

204
                                return;
1✔
205
                        }
206

207
                        auto exp_data = ApiResponseJsonToStateData(response.value().value());
55✔
208
                        if (!exp_data) {
55✔
209
                                log::Error("Error in API response: " + exp_data.error().String());
×
210
                                poster.PostEvent(StateEvent::Failure);
×
211
                                return;
212
                        }
213

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

217
                        ctx.BeginDeploymentLogging();
55✔
218

219
                        log::Info("Running Mender client " + conf::kMenderVersion);
110✔
220
                        log::Info(
55✔
221
                                "Deployment with ID " + ctx.deployment.state_data->update_info.id + " started.");
110✔
222

223
                        poster.PostEvent(StateEvent::DeploymentStarted);
55✔
224
                        poster.PostEvent(StateEvent::Success);
55✔
225
                });
57✔
226

227
        if (err != error::NoError) {
57✔
228
                log::Error("Error when trying to poll for deployment: " + err.String());
2✔
229
                poster.PostEvent(StateEvent::Failure);
1✔
230
        }
231
}
57✔
232

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

236
        ctx.deployment.state_data->state = DatabaseStateString();
534✔
237

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

240
        auto err = ctx.SaveDeploymentStateData(*ctx.deployment.state_data);
534✔
241
        if (err != error::NoError) {
534✔
242
                log::Error(err.String());
10✔
243
                if (err.code
10✔
244
                        == main_context::MakeError(main_context::StateDataStoreCountExceededError, "").code) {
10✔
245
                        poster.PostEvent(StateEvent::StateLoopDetected);
1✔
246
                        return;
247
                } else if (!IsFailureState()) {
9✔
248
                        // Non-failure states should be interrupted, but failure states should be
249
                        // allowed to do their work, even if a database error was detected.
250
                        poster.PostEvent(StateEvent::Failure);
2✔
251
                        return;
252
                }
253
        }
254

255
        OnEnterSaveState(ctx, poster);
531✔
256
}
257

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

261
        auto req = make_shared<http::OutgoingRequest>();
53✔
262
        req->SetMethod(http::Method::GET);
53✔
263
        auto err = req->SetAddress(ctx.deployment.state_data->update_info.artifact.source.uri);
53✔
264
        if (err != error::NoError) {
53✔
265
                log::Error(err.String());
×
266
                poster.PostEvent(StateEvent::Failure);
×
267
                return;
268
        }
269

270
        err = ctx.download_client->AsyncCall(
53✔
271
                req,
272
                [&ctx, &poster](http::ExpectedIncomingResponsePtr exp_resp) {
105✔
273
                        if (!exp_resp) {
53✔
274
                                log::Error("Unexpected error during download: " + exp_resp.error().String());
×
275
                                poster.PostEvent(StateEvent::Failure);
×
276
                                return;
1✔
277
                        }
278

279
                        auto &resp = exp_resp.value();
53✔
280
                        if (resp->GetStatusCode() != http::StatusOK) {
53✔
281
                                log::Error(
1✔
282
                                        "Unexpected status code while fetching artifact: " + resp->GetStatusMessage());
2✔
283
                                poster.PostEvent(StateEvent::Failure);
1✔
284
                                return;
1✔
285
                        }
286

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

308
        if (err != error::NoError) {
53✔
309
                log::Error(err.String());
×
310
                poster.PostEvent(StateEvent::Failure);
×
311
                return;
312
        }
313
}
314

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

318
        // Clear the artifact scripts directory so we don't risk old scripts lingering.
319
        auto err = path::DeleteRecursively(art_scripts_path);
52✔
320
        if (err != error::NoError) {
52✔
321
                log::Error("When preparing to parse artifact: " + err.String());
×
322
                poster.PostEvent(StateEvent::Failure);
×
323
                return;
324
        }
325

326
        artifact::config::ParserConfig config {
52✔
327
                .artifact_scripts_filesystem_path = art_scripts_path,
328
                .artifact_scripts_version = 3,
329
                .artifact_verify_keys = ctx.mender_context.GetConfig().artifact_verify_keys,
52✔
330
        };
100✔
331
        auto exp_parser = artifact::Parse(*ctx.deployment.artifact_reader, config);
104✔
332
        if (!exp_parser) {
52✔
333
                log::Error(exp_parser.error().String());
×
334
                poster.PostEvent(StateEvent::Failure);
×
335
                return;
336
        }
337
        ctx.deployment.artifact_parser.reset(new artifact::Artifact(std::move(exp_parser.value())));
52✔
338

339
        auto exp_header = artifact::View(*ctx.deployment.artifact_parser, 0);
52✔
340
        if (!exp_header) {
52✔
341
                log::Error(exp_header.error().String());
×
342
                poster.PostEvent(StateEvent::Failure);
×
343
                return;
344
        }
345
        auto &header = exp_header.value();
52✔
346

347
        auto exp_matches = ctx.mender_context.MatchesArtifactDepends(header.header);
52✔
348
        if (!exp_matches) {
52✔
349
                log::Error(exp_matches.error().String());
2✔
350
                poster.PostEvent(StateEvent::Failure);
2✔
351
                return;
352
        } else if (!exp_matches.value()) {
50✔
353
                // reasons already logged
354
                poster.PostEvent(StateEvent::Failure);
1✔
355
                return;
356
        }
357

358
        log::Info("Installing artifact...");
98✔
359

360
        ctx.deployment.state_data->FillUpdateDataFromArtifact(header);
49✔
361

362
        ctx.deployment.state_data->state = Context::kUpdateStateDownload;
49✔
363

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

366
        // Initial state data save, now that we have enough information from the artifact.
367
        err = ctx.SaveDeploymentStateData(*ctx.deployment.state_data);
49✔
368
        if (err != error::NoError) {
49✔
369
                log::Error(err.String());
×
370
                if (err.code
×
371
                        == main_context::MakeError(main_context::StateDataStoreCountExceededError, "").code) {
×
372
                        poster.PostEvent(StateEvent::StateLoopDetected);
×
373
                        return;
374
                } else {
375
                        poster.PostEvent(StateEvent::Failure);
×
376
                        return;
377
                }
378
        }
379

380
        if (header.header.payload_type == "") {
49✔
381
                // Empty-payload-artifact, aka "bootstrap artifact".
382
                poster.PostEvent(StateEvent::NothingToDo);
1✔
383
                return;
384
        }
385

386
        ctx.deployment.update_module.reset(
387
                new update_module::UpdateModule(ctx.mender_context, header.header.payload_type));
48✔
388

389
        err = ctx.deployment.update_module->CleanAndPrepareFileTree(
48✔
390
                ctx.deployment.update_module->GetUpdateModuleWorkDir(), header);
48✔
391
        if (err != error::NoError) {
48✔
392
                log::Error(err.String());
×
393
                poster.PostEvent(StateEvent::Failure);
×
394
                return;
395
        }
396

397
        err = ctx.deployment.update_module->AsyncProvidePayloadFileSizes(
48✔
398
                ctx.event_loop, [&ctx, &poster](expected::ExpectedBool download_with_sizes) {
48✔
399
                        if (!download_with_sizes.has_value()) {
48✔
400
                                log::Error(download_with_sizes.error().String());
×
401
                                poster.PostEvent(StateEvent::Failure);
×
402
                                return;
×
403
                        }
404
                        ctx.deployment.download_with_sizes = download_with_sizes.value();
48✔
405
                        DoDownload(ctx, poster);
48✔
406
                });
48✔
407

408
        if (err != error::NoError) {
48✔
409
                log::Error(err.String());
×
410
                poster.PostEvent(StateEvent::Failure);
×
411
                return;
412
        }
413
}
414

415
void UpdateDownloadState::DoDownload(Context &ctx, sm::EventPoster<StateEvent> &poster) {
48✔
416
        auto exp_payload = ctx.deployment.artifact_parser->Next();
48✔
417
        if (!exp_payload) {
48✔
418
                log::Error(exp_payload.error().String());
×
419
                poster.PostEvent(StateEvent::Failure);
×
420
                return;
421
        }
422
        ctx.deployment.artifact_payload.reset(new artifact::Payload(std::move(exp_payload.value())));
48✔
423

424
        auto handler = [&poster, &ctx](error::Error err) {
46✔
425
                if (err != error::NoError) {
48✔
426
                        log::Error(err.String());
2✔
427
                        poster.PostEvent(StateEvent::Failure);
2✔
428
                        return;
2✔
429
                }
430

431
                auto exp_payload = ctx.deployment.artifact_parser->Next();
46✔
432
                if (exp_payload) {
46✔
433
                        log::Error("Multiple payloads are not yet supported in daemon mode.");
×
434
                        poster.PostEvent(StateEvent::Failure);
×
435
                        return;
436
                } else if (
46✔
437
                        exp_payload.error().code
438
                        != artifact::parser_error::MakeError(artifact::parser_error::EOFError, "").code) {
46✔
439
                        log::Error(exp_payload.error().String());
×
440
                        poster.PostEvent(StateEvent::Failure);
×
441
                        return;
442
                }
443

444
                poster.PostEvent(StateEvent::Success);
46✔
445
        };
446

447
        if (ctx.deployment.download_with_sizes) {
48✔
448
                ctx.deployment.update_module->AsyncDownloadWithFileSizes(
1✔
449
                        ctx.event_loop, *ctx.deployment.artifact_payload, handler);
1✔
450
        } else {
451
                ctx.deployment.update_module->AsyncDownload(
47✔
452
                        ctx.event_loop, *ctx.deployment.artifact_payload, handler);
47✔
453
        }
454
}
455

456
void UpdateDownloadCancelState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
6✔
457
        log::Debug("Entering DownloadCancel state");
12✔
458
        ctx.download_client->Cancel();
6✔
459
        poster.PostEvent(StateEvent::Success);
6✔
460
}
6✔
461

UNCOV
462
SendStatusUpdateState::SendStatusUpdateState(optional<deployments::DeploymentStatus> status) :
×
463
        status_(status),
464
        mode_(FailureMode::Ignore) {
×
465
}
×
466

467
SendStatusUpdateState::SendStatusUpdateState(
188✔
468
        optional<deployments::DeploymentStatus> status,
469
        events::EventLoop &event_loop,
470
        int retry_interval_seconds,
471
        int retry_count) :
472
        status_(status),
473
        mode_(FailureMode::RetryThenFail),
474
        retry_(Retry {
188✔
475
                http::ExponentialBackoff(chrono::seconds(retry_interval_seconds), retry_count),
476
                event_loop}) {
564✔
477
}
188✔
478

479
void SendStatusUpdateState::SetSmallestWaitInterval(chrono::milliseconds interval) {
178✔
480
        if (retry_) {
178✔
481
                retry_->backoff.SetSmallestInterval(interval);
178✔
482
        }
483
}
178✔
484

485
void SendStatusUpdateState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
242✔
486
        // Reset this every time we enter the state, which means a new round of retries.
487
        if (retry_) {
242✔
488
                retry_->backoff.Reset();
489
        }
490

491
        DoStatusUpdate(ctx, poster);
242✔
492
}
242✔
493

494
void SendStatusUpdateState::DoStatusUpdate(Context &ctx, sm::EventPoster<StateEvent> &poster) {
261✔
495
        assert(ctx.deployment_client);
496
        assert(ctx.deployment.state_data);
497

498
        log::Info("Sending status update to server");
522✔
499

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

504
                        switch (mode_) {
24✔
505
                        case FailureMode::Ignore:
506
                                break;
3✔
507
                        case FailureMode::RetryThenFail:
508
                                if (err.code
21✔
509
                                        == deployments::MakeError(deployments::DeploymentAbortedError, "").code) {
21✔
510
                                        // If the deployment was aborted upstream it is an immediate
511
                                        // failure, even if retry is enabled.
512
                                        poster.PostEvent(StateEvent::Failure);
1✔
513
                                        return;
21✔
514
                                }
515

516
                                auto exp_interval = retry_->backoff.NextInterval();
20✔
517
                                if (!exp_interval) {
20✔
518
                                        log::Error(
1✔
519
                                                "Giving up on sending status updates to server: "
520
                                                + exp_interval.error().String());
2✔
521
                                        poster.PostEvent(StateEvent::Failure);
1✔
522
                                        return;
523
                                }
524

525
                                log::Info(
19✔
526
                                        "Retrying status update after "
527
                                        + to_string(chrono::duration_cast<chrono::seconds>(*exp_interval).count())
38✔
528
                                        + " seconds");
38✔
529
                                retry_->wait_timer.AsyncWait(
19✔
530
                                        *exp_interval, [this, &ctx, &poster](error::Error err) {
38✔
531
                                                // Error here is quite unexpected (from a timer), so treat
532
                                                // this as an immediate error, despite Retry flag.
533
                                                if (err != error::NoError) {
19✔
534
                                                        log::Error(
×
535
                                                                "Unexpected error in SendStatusUpdateState wait timer: "
536
                                                                + err.String());
×
537
                                                        poster.PostEvent(StateEvent::Failure);
×
538
                                                        return;
×
539
                                                }
540

541
                                                // Try again. Since both status and logs are sent
542
                                                // from here, there's a chance this might resubmit
543
                                                // the status, but there's no harm in it, and it
544
                                                // won't happen often.
545
                                                DoStatusUpdate(ctx, poster);
19✔
546
                                        });
19✔
547
                                return;
19✔
548
                        }
549
                }
550

551
                poster.PostEvent(StateEvent::Success);
240✔
552
        };
261✔
553

554
        deployments::DeploymentStatus status;
555
        if (status_) {
261✔
556
                status = status_.value();
170✔
557
        } else {
558
                // If nothing is specified, grab success/failure status from the deployment status.
559
                if (ctx.deployment.failed) {
91✔
560
                        status = deployments::DeploymentStatus::Failure;
561
                } else {
562
                        status = deployments::DeploymentStatus::Success;
563
                }
564
        }
565

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

583
                        // Push logs.
584
                        err = ctx.deployment_client->PushLogs(
73✔
585
                                ctx.deployment.state_data->update_info.id,
73✔
586
                                ctx.deployment.logger->LogFilePath(),
146✔
587
                                ctx.http_client,
588
                                result_handler);
73✔
589

590
                        if (err != error::NoError) {
73✔
591
                                result_handler(err);
×
592
                        }
593
                });
522✔
594

595
        if (err != error::NoError) {
261✔
596
                result_handler(err);
×
597
        }
598

599
        // No action, wait for reply from status endpoint.
600
}
261✔
601

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

605
        DefaultAsyncErrorHandler(
42✔
606
                poster,
607
                ctx.deployment.update_module->AsyncArtifactInstall(
42✔
608
                        ctx.event_loop, DefaultStateHandler {poster}));
42✔
609
}
42✔
610

611
void UpdateCheckRebootState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
73✔
612
        DefaultAsyncErrorHandler(
73✔
613
                poster,
614
                ctx.deployment.update_module->AsyncNeedsReboot(
73✔
615
                        ctx.event_loop, [&ctx, &poster](update_module::ExpectedRebootAction reboot_action) {
144✔
616
                                if (!reboot_action.has_value()) {
73✔
617
                                        log::Error(reboot_action.error().String());
2✔
618
                                        poster.PostEvent(StateEvent::Failure);
2✔
619
                                        return;
2✔
620
                                }
621

622
                                ctx.deployment.state_data->update_info.reboot_requested.resize(1);
71✔
623
                                ctx.deployment.state_data->update_info.reboot_requested[0] =
624
                                        NeedsRebootToDbString(*reboot_action);
71✔
625
                                switch (*reboot_action) {
71✔
626
                                case update_module::RebootAction::No:
8✔
627
                                        poster.PostEvent(StateEvent::NothingToDo);
8✔
628
                                        break;
8✔
629
                                case update_module::RebootAction::Yes:
63✔
630
                                case update_module::RebootAction::Automatic:
631
                                        poster.PostEvent(StateEvent::Success);
63✔
632
                                        break;
63✔
633
                                }
634
                        }));
73✔
635
}
73✔
636

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

640
        assert(ctx.deployment.state_data->update_info.reboot_requested.size() == 1);
641
        auto exp_reboot_mode =
642
                DbStringToNeedsReboot(ctx.deployment.state_data->update_info.reboot_requested[0]);
27✔
643
        // Should always be true because we check it at load time.
644
        assert(exp_reboot_mode);
645

646
        switch (exp_reboot_mode.value()) {
27✔
647
        case update_module::RebootAction::No:
×
648
                // Should not happen because then we don't enter this state.
649
                assert(false);
650
                poster.PostEvent(StateEvent::Failure);
×
651
                break;
652
        case update_module::RebootAction::Yes:
27✔
653
                DefaultAsyncErrorHandler(
27✔
654
                        poster,
655
                        ctx.deployment.update_module->AsyncArtifactReboot(
27✔
656
                                ctx.event_loop, DefaultStateHandler {poster}));
27✔
657
                break;
27✔
658
        case update_module::RebootAction::Automatic:
×
659
                DefaultAsyncErrorHandler(
×
660
                        poster,
661
                        ctx.deployment.update_module->AsyncSystemReboot(
×
662
                                ctx.event_loop, DefaultStateHandler {poster}));
×
663
                break;
×
664
        }
665
}
27✔
666

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

670
        ctx.deployment.update_module->EnsureRootfsImageFileTree(
30✔
671
                ctx.deployment.update_module->GetUpdateModuleWorkDir());
60✔
672

673
        DefaultAsyncErrorHandler(
30✔
674
                poster,
675
                ctx.deployment.update_module->AsyncArtifactVerifyReboot(
30✔
676
                        ctx.event_loop, DefaultStateHandler {poster}));
30✔
677
}
30✔
678

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

684
        poster.PostEvent(StateEvent::Success);
23✔
685
}
23✔
686

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

690
        // Explicitly check if state scripts version is supported
691
        auto err = script_executor::CheckScriptsCompatibility(
692
                ctx.mender_context.GetConfig().paths.GetRootfsScriptsPath());
19✔
693
        if (err != error::NoError) {
19✔
694
                log::Error("Failed script compatibility check: " + err.String());
×
695
                poster.PostEvent(StateEvent::Failure);
×
696
                return;
697
        }
698

699
        DefaultAsyncErrorHandler(
19✔
700
                poster,
701
                ctx.deployment.update_module->AsyncArtifactCommit(
19✔
702
                        ctx.event_loop, DefaultStateHandler {poster}));
38✔
703
}
704

705
void UpdateAfterCommitState::OnEnterSaveState(Context &ctx, sm::EventPoster<StateEvent> &poster) {
19✔
706
        // Now we have committed. If we had a schema update, re-save state data with the new schema.
707
        assert(ctx.deployment.state_data);
708
        auto &state_data = *ctx.deployment.state_data;
709
        if (state_data.update_info.has_db_schema_update) {
19✔
710
                state_data.update_info.has_db_schema_update = false;
×
711
                auto err = ctx.SaveDeploymentStateData(state_data);
×
712
                if (err != error::NoError) {
×
713
                        log::Error("Not able to commit schema update: " + err.String());
×
714
                        poster.PostEvent(StateEvent::Failure);
×
715
                        return;
716
                }
717
        }
718

719
        poster.PostEvent(StateEvent::Success);
19✔
720
}
721

722
void UpdateCheckRollbackState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
45✔
723
        DefaultAsyncErrorHandler(
45✔
724
                poster,
725
                ctx.deployment.update_module->AsyncSupportsRollback(
45✔
726
                        ctx.event_loop, [&ctx, &poster](expected::ExpectedBool rollback_supported) {
89✔
727
                                if (!rollback_supported.has_value()) {
45✔
728
                                        log::Error(rollback_supported.error().String());
1✔
729
                                        poster.PostEvent(StateEvent::Failure);
1✔
730
                                        return;
1✔
731
                                }
732

733
                                ctx.deployment.state_data->update_info.supports_rollback =
734
                                        SupportsRollbackToDbString(*rollback_supported);
44✔
735
                                if (*rollback_supported) {
44✔
736
                                        poster.PostEvent(StateEvent::RollbackStarted);
38✔
737
                                        poster.PostEvent(StateEvent::Success);
38✔
738
                                } else {
739
                                        poster.PostEvent(StateEvent::NothingToDo);
6✔
740
                                }
741
                        }));
45✔
742
}
45✔
743

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

747
        DefaultAsyncErrorHandler(
41✔
748
                poster,
749
                ctx.deployment.update_module->AsyncArtifactRollback(
41✔
750
                        ctx.event_loop, DefaultStateHandler {poster}));
41✔
751
}
41✔
752

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

756
        auto exp_reboot_mode =
757
                DbStringToNeedsReboot(ctx.deployment.state_data->update_info.reboot_requested[0]);
57✔
758
        // Should always be true because we check it at load time.
759
        assert(exp_reboot_mode);
760

761
        // We ignore errors in this state as long as the ArtifactVerifyRollbackReboot state
762
        // succeeds.
763
        auto handler = [&poster](error::Error err) {
114✔
764
                if (err != error::NoError) {
57✔
765
                        log::Error(err.String());
2✔
766
                }
767
                poster.PostEvent(StateEvent::Success);
57✔
768
        };
57✔
769

770
        error::Error err;
57✔
771
        switch (exp_reboot_mode.value()) {
57✔
772
        case update_module::RebootAction::No:
773
                // Should not happen because then we don't enter this state.
774
                assert(false);
775

776
                err = error::MakeError(
×
777
                        error::ProgrammingError, "Entered UpdateRollbackRebootState with RebootAction = No");
×
778
                break;
×
779

780
        case update_module::RebootAction::Yes:
57✔
781
                err = ctx.deployment.update_module->AsyncArtifactRollbackReboot(ctx.event_loop, handler);
114✔
782
                break;
57✔
783

784
        case update_module::RebootAction::Automatic:
×
785
                err = ctx.deployment.update_module->AsyncSystemReboot(ctx.event_loop, handler);
×
786
                break;
×
787
        }
788

789
        if (err != error::NoError) {
57✔
790
                log::Error(err.String());
×
791
                poster.PostEvent(StateEvent::Success);
×
792
        }
793
}
57✔
794

795
void UpdateVerifyRollbackRebootState::OnEnterSaveState(
60✔
796
        Context &ctx, sm::EventPoster<StateEvent> &poster) {
797
        log::Debug("Entering ArtifactVerifyRollbackReboot state");
120✔
798

799
        // In this state we only retry, we don't fail. If this keeps on going forever, then the
800
        // state loop detection will eventually kick in.
801
        auto err = ctx.deployment.update_module->AsyncArtifactVerifyRollbackReboot(
802
                ctx.event_loop, [&poster](error::Error err) {
120✔
803
                        if (err != error::NoError) {
60✔
804
                                log::Error(err.String());
22✔
805
                                poster.PostEvent(StateEvent::Retry);
22✔
806
                                return;
22✔
807
                        }
808
                        poster.PostEvent(StateEvent::Success);
38✔
809
                });
60✔
810
        if (err != error::NoError) {
60✔
811
                log::Error(err.String());
×
812
                poster.PostEvent(StateEvent::Retry);
×
813
        }
814
}
60✔
815

816
void UpdateRollbackSuccessfulState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
50✔
817
        ctx.deployment.state_data->update_info.all_rollbacks_successful = true;
50✔
818
        poster.PostEvent(StateEvent::Success);
50✔
819
}
50✔
820

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

824
        DefaultAsyncErrorHandler(
55✔
825
                poster,
826
                ctx.deployment.update_module->AsyncArtifactFailure(
55✔
827
                        ctx.event_loop, DefaultStateHandler {poster}));
55✔
828
}
55✔
829

830
static string AddInconsistentSuffix(const string &str) {
21✔
831
        const auto &suffix = main_context::MenderContext::broken_artifact_name_suffix;
832
        // `string::ends_with` is C++20... grumble
833
        string ret {str};
21✔
834
        if (!common::EndsWith(ret, suffix)) {
21✔
835
                ret.append(suffix);
21✔
836
        }
837
        return ret;
21✔
838
}
839

840
void UpdateSaveProvidesState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
75✔
841
        if (ctx.deployment.failed && !ctx.deployment.rollback_failed) {
75✔
842
                // If the update failed, but we rolled back successfully, then we don't need to do
843
                // anything, just keep the old data.
844
                poster.PostEvent(StateEvent::Success);
38✔
845
                return;
38✔
846
        }
847

848
        assert(ctx.deployment.state_data);
849
        // This state should never happen: rollback failed, but update not failed??
850
        assert(!(!ctx.deployment.failed && ctx.deployment.rollback_failed));
851

852
        // We expect Cleanup to be the next state after this.
853
        ctx.deployment.state_data->state = ctx.kUpdateStateCleanup;
37✔
854

855
        auto &artifact = ctx.deployment.state_data->update_info.artifact;
856

857
        string artifact_name;
858
        if (ctx.deployment.rollback_failed) {
37✔
859
                artifact_name = AddInconsistentSuffix(artifact.artifact_name);
38✔
860
        } else {
861
                artifact_name = artifact.artifact_name;
18✔
862
        }
863

864
        bool deploy_failed = ctx.deployment.failed;
37✔
865

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

891
        poster.PostEvent(StateEvent::Success);
37✔
892
}
893

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

897
        // It's possible for there not to be an initialized update_module structure, if the
898
        // deployment failed before we could successfully parse the artifact. If so, cleanup is a
899
        // no-op.
900
        if (!ctx.deployment.update_module) {
89✔
901
                poster.PostEvent(StateEvent::Success);
8✔
902
                return;
8✔
903
        }
904

905
        DefaultAsyncErrorHandler(
81✔
906
                poster,
907
                ctx.deployment.update_module->AsyncCleanup(ctx.event_loop, DefaultStateHandler {poster}));
162✔
908
}
909

910
void ClearArtifactDataState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
91✔
911
        auto err = ctx.mender_context.GetMenderStoreDB().WriteTransaction([](kv_db::Transaction &txn) {
91✔
912
                // Remove state data, since we're done now.
913
                auto err = txn.Remove(main_context::MenderContext::state_data_key);
89✔
914
                if (err != error::NoError) {
89✔
915
                        return err;
×
916
                }
917
                return txn.Remove(main_context::MenderContext::state_data_key_uncommitted);
89✔
918
        });
91✔
919
        if (err != error::NoError) {
91✔
920
                log::Error("Error removing artifact data: " + err.String());
4✔
921
                poster.PostEvent(StateEvent::Failure);
2✔
922
                return;
923
        }
924

925
        poster.PostEvent(StateEvent::Success);
89✔
926
}
927

928
void StateLoopState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
2✔
929
        assert(ctx.deployment.state_data);
930
        auto &artifact = ctx.deployment.state_data->update_info.artifact;
931

932
        // Mark update as inconsistent.
933
        string artifact_name = AddInconsistentSuffix(artifact.artifact_name);
2✔
934

935
        auto err = ctx.mender_context.CommitArtifactData(
2✔
936
                artifact_name,
937
                artifact.artifact_group,
2✔
938
                artifact.type_info_provides,
2✔
939
                artifact.clears_artifact_provides,
2✔
940
                [](kv_db::Transaction &txn) { return error::NoError; });
6✔
941
        if (err != error::NoError) {
2✔
942
                log::Error("Error saving inconsistent artifact data: " + err.String());
×
943
                poster.PostEvent(StateEvent::Failure);
×
944
                return;
945
        }
946

947
        poster.PostEvent(StateEvent::Success);
2✔
948
}
949

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

955
        ctx.FinishDeploymentLogging();
91✔
956

957
        ctx.deployment = {};
91✔
958
        poster.PostEvent(
91✔
959
                StateEvent::InventoryPollingTriggered); // Submit the inventory right after an update
91✔
960
        poster.PostEvent(StateEvent::DeploymentEnded);
91✔
961
        poster.PostEvent(StateEvent::Success);
91✔
962
}
91✔
963

964
ExitState::ExitState(events::EventLoop &event_loop) :
94✔
965
        event_loop_(event_loop) {
188✔
966
}
94✔
967

968
void ExitState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
91✔
969
#ifndef NDEBUG
970
        if (--iterations_left_ <= 0) {
971
                event_loop_.Stop();
972
        } else {
973
                poster.PostEvent(StateEvent::Success);
974
        }
975
#else
976
        event_loop_.Stop();
91✔
977
#endif
978
}
91✔
979

980
namespace deployment_tracking {
981

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

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

992
void RollbackAttemptedState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
52✔
993
        ctx.deployment.failed = true;
52✔
994
        ctx.deployment.rollback_failed = false;
52✔
995
}
52✔
996

997
void RollbackFailedState::OnEnter(Context &ctx, sm::EventPoster<StateEvent> &poster) {
12✔
998
        ctx.deployment.failed = true;
12✔
999
        ctx.deployment.rollback_failed = true;
12✔
1000
}
12✔
1001

1002
} // namespace deployment_tracking
1003

1004
} // namespace daemon
1005
} // namespace update
1006
} // 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