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

mendersoftware / mender / 1014406969

23 Sep 2023 12:41PM UTC coverage: 77.735% (+0.2%) from 77.579%
1014406969

push

gitlab-ci

lluiscampos
feat: Implement `mender::update::http_resumer`

Implement class to download the Artifact, which will react to server
disconnections or other sorts of short read by scheduling new HTTP
requests with `Range` header.

See https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests for
an introduction to the feature, and read the specification for more
details.

The user calls _once_ `AsyncCall` with the header and body handlers, and
`DownloadResumerClient` will call back these handlers _once_ (each). At
the user's header handler, the Reader returned by `MakeBodyAsyncReader`
is a wrapper of the actual Body reader that is taking care of the resume
of the download, calling the `AsyncRead` finalized handler only after
the download is fully completed (with potential resumes) and or/the
resuming times out.

The validation of the `Content-Range` header and the cases for the unit
tests are heavily inspired by the legacy client. See:
* https://github.com/mendersoftware/mender/blob/<a class=hub.com/mendersoftware/mender/commit/d9010526d35d3ac861ea1e4210d36c2fef748ef8">d9010526d/client/update_resumer.go#L113
* https://github.com/mendersoftware/mender/blob/d9010526d35d3ac861ea1e4210d36c2fef748ef8/client/update_resumer_test.go#L197

Ticket: MEN-6498
Changelog: None

Signed-off-by: Lluis Campos <lluis.campos@northern.tech>

267 of 267 new or added lines in 5 files covered. (100.0%)

6686 of 8601 relevant lines covered (77.74%)

10755.08 hits per line

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

88.37
/mender-update/daemon/context.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/context.hpp>
16

17
#include <common/common.hpp>
18
#include <common/conf.hpp>
19
#include <common/log.hpp>
20
#include <mender-update/http_resumer.hpp>
21

22
namespace mender {
23
namespace update {
24
namespace daemon {
25

26
namespace common = mender::common;
27
namespace conf = mender::common::conf;
28
namespace log = mender::common::log;
29
namespace http_resumer = mender::update::http_resumer;
30

31
namespace main_context = mender::update::context;
32

33
const int kStateDataVersion = 2;
34

35
// The maximum times we are allowed to move through update states. If this is exceeded then the
36
// update will be forcefully aborted. This can happen if we are in a reboot loop, for example.
37
const int kMaxStateDataStoreCount = 28;
38

39
ExpectedStateData ApiResponseJsonToStateData(const json::Json &json) {
55✔
40
        StateData data;
110✔
41

42
        expected::ExpectedString str = json.Get("id").and_then(json::ToString);
110✔
43
        if (!str) {
55✔
44
                return expected::unexpected(str.error().WithContext("Could not get deployment ID"));
×
45
        }
46
        data.update_info.id = str.value();
55✔
47

48
        str = json.Get("artifact")
55✔
49
                          .and_then([](const json::Json &json) { return json.Get("source"); })
165✔
50
                          .and_then([](const json::Json &json) { return json.Get("uri"); })
165✔
51
                          .and_then(json::ToString);
55✔
52
        if (!str) {
55✔
53
                return expected::unexpected(
×
54
                        str.error().WithContext("Could not get artifact URI for deployment"));
×
55
        }
56
        data.update_info.artifact.source.uri = str.value();
55✔
57
        log::Debug("Artifact Download URL: " + data.update_info.artifact.source.uri);
55✔
58

59
        str = json.Get("artifact")
55✔
60
                          .and_then([](const json::Json &json) { return json.Get("source"); })
165✔
61
                          .and_then([](const json::Json &json) { return json.Get("expire"); })
165✔
62
                          .and_then(json::ToString);
55✔
63
        if (str) {
55✔
64
                data.update_info.artifact.source.expire = str.value();
55✔
65
                // If it's not available, we don't care.
66
        }
67

68
        // For later: Update Control Maps should be handled here.
69

70
        // Note: There is more information available in the response than we collect here, but we
71
        // prefer to get the information from the artifact instead, since it is the authoritative
72
        // source. And it's also signed, unlike the response.
73

74
        return data;
55✔
75
}
76

77
// Database keys
78
const string Context::kRollbackNotSupported = "rollback-not-supported";
79
const string Context::kRollbackSupported = "rollback-supported";
80

81
string SupportsRollbackToDbString(bool support) {
43✔
82
        return support ? Context::kRollbackSupported : Context::kRollbackNotSupported;
43✔
83
}
84

85
expected::ExpectedBool DbStringToSupportsRollback(const string &str) {
14✔
86
        if (str == Context::kRollbackSupported) {
14✔
87
                return true;
12✔
88
        } else if (str == Context::kRollbackNotSupported) {
2✔
89
                return false;
2✔
90
        } else {
91
                return expected::unexpected(main_context::MakeError(
×
92
                        main_context::DatabaseValueError,
93
                        "\"" + str + "\" is not a valid value for SupportsRollback"));
×
94
        }
95
}
96

97
// Database keys
98
const string Context::kRebootTypeNone = "";
99
const string Context::kRebootTypeCustom = "reboot-type-custom";
100
const string Context::kRebootTypeAutomatic = "reboot-type-automatic";
101

102
string NeedsRebootToDbString(update_module::RebootAction action) {
70✔
103
        switch (action) {
70✔
104
        case update_module::RebootAction::No:
8✔
105
                return Context::kRebootTypeNone;
8✔
106
        case update_module::RebootAction::Automatic:
×
107
                return Context::kRebootTypeAutomatic;
×
108
        case update_module::RebootAction::Yes:
62✔
109
                return Context::kRebootTypeCustom;
62✔
110
        default:
×
111
                // Should not happen.
112
                assert(false);
×
113
                return Context::kRebootTypeNone;
114
        }
115
}
116

117
update_module::ExpectedRebootAction DbStringToNeedsReboot(const string &str) {
48✔
118
        if (str == Context::kRebootTypeNone) {
48✔
119
                return update_module::RebootAction::No;
×
120
        } else if (str == Context::kRebootTypeAutomatic) {
48✔
121
                return update_module::RebootAction::Automatic;
×
122
        } else if (str == Context::kRebootTypeCustom) {
48✔
123
                return update_module::RebootAction::Yes;
48✔
124
        } else {
125
                return expected::unexpected(main_context::MakeError(
×
126
                        main_context::DatabaseValueError,
127
                        "\"" + str + "\" is not a valid value for RebootRequested"));
×
128
        }
129
}
130

131
void StateData::FillUpdateDataFromArtifact(artifact::PayloadHeaderView &view) {
49✔
132
        auto &artifact = update_info.artifact;
49✔
133
        auto &header = view.header;
49✔
134
        artifact.compatible_devices = header.header_info.depends.device_type;
49✔
135
        artifact.payload_types = {header.payload_type};
98✔
136
        artifact.artifact_name = header.artifact_name;
49✔
137
        artifact.artifact_group = header.artifact_group;
49✔
138
        if (header.type_info.artifact_provides) {
49✔
139
                artifact.type_info_provides = header.type_info.artifact_provides.value();
48✔
140
        } else {
141
                artifact.type_info_provides.clear();
1✔
142
        }
143
        if (header.type_info.clears_artifact_provides) {
49✔
144
                artifact.clears_artifact_provides = header.type_info.clears_artifact_provides.value();
48✔
145
        } else {
146
                artifact.clears_artifact_provides.clear();
1✔
147
        }
148
}
49✔
149

150
Context::Context(main_context::MenderContext &mender_context, events::EventLoop &event_loop) :
90✔
151
        mender_context(mender_context),
152
        event_loop(event_loop),
153
        authenticator(
154
                event_loop,
155
                http::ClientConfig(mender_context.GetConfig().server_certificate),
180✔
156
                mender_context.GetConfig().server_url,
90✔
157
                mender_context.GetConfig().paths.GetKeyFile(),
180✔
158
                mender_context.GetConfig().paths.GetIdentityScript()),
180✔
159
        http_client(
160
                http::ClientConfig(mender_context.GetConfig().server_certificate),
180✔
161
                event_loop,
162
                authenticator),
90✔
163
        download_client(make_shared<http_resumer::DownloadResumerClient>(
90✔
164
                http::ClientConfig(mender_context.GetConfig().server_certificate), event_loop)),
180✔
165
        deployment_client(make_shared<deployments::DeploymentClient>()),
90✔
166
        inventory_client(make_shared<inventory::InventoryClient>()) {
720✔
167
}
90✔
168

169
///////////////////////////////////////////////////////////////////////////////////////////////////
170
// Values for various states in the database.
171
///////////////////////////////////////////////////////////////////////////////////////////////////
172

173
// In use by current client. Some of the variable names have been updated from the Golang version,
174
// but the database strings are the same. Some naming is inconsistent, this is for historical
175
// reasons, and it's better to look at the names for the variables.
176
const string Context::kUpdateStateDownload = "update-store";
177
const string Context::kUpdateStateArtifactInstall = "update-install";
178
const string Context::kUpdateStateArtifactReboot = "reboot";
179
const string Context::kUpdateStateArtifactVerifyReboot = "after-reboot";
180
const string Context::kUpdateStateArtifactCommit = "update-commit";
181
const string Context::kUpdateStateAfterArtifactCommit = "update-after-commit";
182
const string Context::kUpdateStateArtifactRollback = "rollback";
183
const string Context::kUpdateStateArtifactRollbackReboot = "rollback-reboot";
184
const string Context::kUpdateStateArtifactVerifyRollbackReboot = "after-rollback-reboot";
185
const string Context::kUpdateStateArtifactFailure = "update-error";
186
const string Context::kUpdateStateCleanup = "cleanup";
187
const string Context::kUpdateStateStatusReportRetry = "update-retry-report";
188

189
///////////////////////////////////////////////////////////////////////////////////////////////////
190
// Not in use by current client, but were in use by Golang client, and still important to handle
191
// correctly in recovery scenarios.
192
///////////////////////////////////////////////////////////////////////////////////////////////////
193

194
// This client doesn't use it, but it's essentially equivalent to "update-after-commit".
195
const string Context::kUpdateStateUpdateAfterFirstCommit = "update-after-first-commit";
196
// This client doesn't use it, but it's essentially equivalent to "after-rollback-reboot".
197
const string Context::kUpdateStateVerifyRollbackReboot = "verify-rollback-reboot";
198
// No longer used. Since this used to be at the very end of an update, if we encounter it in the
199
// database during startup, we just go back to Idle.
200
const string UpdateStateReportStatusError = "status-report-error";
201

202
///////////////////////////////////////////////////////////////////////////////////////////////////
203
// Not in use. All of these, as well as unknown values, will cause a rollback.
204
///////////////////////////////////////////////////////////////////////////////////////////////////
205

206
// Disable, but distinguish from comments.
207
#if false
208
// These were never actually saved due to not being update states.
209
const string Context::kUpdateStateInit = "init";
210
const string Context::kUpdateStateIdle = "idle";
211
const string Context::kUpdateStateAuthorize = "authorize";
212
const string Context::kUpdateStateAuthorizeWait = "authorize-wait";
213
const string Context::kUpdateStateInventoryUpdate = "inventory-update";
214
const string Context::kUpdateStateInventoryUpdateRetryWait = "inventory-update-retry-wait";
215

216
const string Context::kUpdateStateCheckWait = "check-wait";
217
const string Context::kUpdateStateUpdateCheck = "update-check";
218
const string Context::kUpdateStateUpdateFetch = "update-fetch";
219
const string Context::kUpdateStateUpdateAfterStore = "update-after-store";
220
const string Context::kUpdateStateFetchStoreRetryWait = "fetch-install-retry-wait";
221
const string Context::kUpdateStateUpdateVerify = "update-verify";
222
const string Context::kUpdateStateUpdatePreCommitStatusReportRetry = "update-pre-commit-status-report-retry";
223
const string Context::kUpdateStateUpdateStatusReport = "update-status-report";
224
// Would have been used, but a copy/paste error in the Golang client means that it was never
225
// saved. "after-reboot" is stored twice instead.
226
const string Context::kUpdateStateVerifyReboot = "verify-reboot";
227
const string Context::kUpdateStateError = "error";
228
const string Context::kUpdateStateDone = "finished";
229
const string Context::kUpdateStateUpdateControl = "mender-update-control";
230
const string Context::kUpdateStateUpdateControlPause = "mender-update-control-pause";
231
const string Context::kUpdateStateFetchUpdateControl = "mender-update-control-refresh-maps";
232
const string Context::kUpdateStateFetchRetryUpdateControl = "mender-update-control-retry-refresh-maps";
233
#endif
234

235
///////////////////////////////////////////////////////////////////////////////////////////////////
236
// End of database values.
237
///////////////////////////////////////////////////////////////////////////////////////////////////
238

239
static string GenerateStateDataJson(const StateData &state_data) {
632✔
240
        stringstream content;
1,264✔
241

242
        auto append_vector = [&content](const vector<string> &data) {
4,653✔
243
                for (auto entry = data.begin(); entry != data.end(); entry++) {
4,653✔
244
                        if (entry != data.begin()) {
2,125✔
245
                                content << ",";
×
246
                        }
247
                        content << R"(")" << json::EscapeString(*entry) << R"(")";
2,125✔
248
                }
249
        };
2,528✔
250

251
        auto append_map = [&content](const unordered_map<string, string> &data) {
1,200✔
252
                for (auto entry = data.begin(); entry != data.end(); entry++) {
1,200✔
253
                        if (entry != data.begin()) {
568✔
254
                                content << ",";
×
255
                        }
256
                        content << R"(")" << json::EscapeString(entry->first) << R"(":")"
1,136✔
257
                                        << json::EscapeString(entry->second) << R"(")";
1,136✔
258
                }
259
        };
632✔
260

261
        content << "{";
632✔
262
        {
263
                content << R"("Version":)" << to_string(state_data.version) << ",";
632✔
264
                content << R"("Name":")" << json::EscapeString(state_data.state) << R"(",)";
632✔
265
                content << R"("UpdateInfo":{)";
632✔
266
                {
267
                        auto &update_info = state_data.update_info;
632✔
268
                        content << R"("Artifact":{)";
632✔
269
                        {
270
                                auto &artifact = update_info.artifact;
632✔
271
                                content << R"("Source":{)";
632✔
272
                                {
273
                                        content << R"("URI":")" << json::EscapeString(artifact.source.uri) << R"(",)";
632✔
274
                                        content << R"("Expire":")" << json::EscapeString(artifact.source.expire)
632✔
275
                                                        << R"(")";
632✔
276
                                }
277
                                content << "},";
632✔
278

279
                                content << R"("CompatibleDevices":[)";
632✔
280
                                append_vector(artifact.compatible_devices);
632✔
281
                                content << "],";
632✔
282

283
                                content << R"("PayloadTypes":[)";
632✔
284
                                append_vector(artifact.payload_types);
632✔
285
                                content << "],";
632✔
286

287
                                content << R"("ArtifactName":")" << json::EscapeString(artifact.artifact_name)
632✔
288
                                                << R"(",)";
632✔
289
                                content << R"("ArtifactGroup":")" << json::EscapeString(artifact.artifact_group)
632✔
290
                                                << R"(",)";
632✔
291

292
                                content << R"("TypeInfoProvides":{)";
632✔
293
                                append_map(artifact.type_info_provides);
632✔
294
                                content << "},";
632✔
295

296
                                content << R"("ClearsArtifactProvides":[)";
632✔
297
                                append_vector(artifact.clears_artifact_provides);
632✔
298
                                content << "]";
632✔
299
                        }
300
                        content << "},";
632✔
301

302
                        content << R"("ID":")" << json::EscapeString(update_info.id) << R"(",)";
632✔
303

304
                        content << R"("RebootRequested":[)";
632✔
305
                        append_vector(update_info.reboot_requested);
632✔
306
                        content << R"(],)";
632✔
307

308
                        content << R"("SupportsRollback":")"
309
                                        << json::EscapeString(update_info.supports_rollback) << R"(",)";
632✔
310
                        content << R"("StateDataStoreCount":)" << to_string(update_info.state_data_store_count)
632✔
311
                                        << R"(,)";
632✔
312
                        content << R"("HasDBSchemaUpdate":)"
313
                                        << string(update_info.has_db_schema_update ? "true," : "false,");
632✔
314
                        content << R"("AllRollbacksSuccessful":)"
315
                                        << string(update_info.all_rollbacks_successful ? "true" : "false");
632✔
316
                }
317
                content << "}";
632✔
318
        }
319
        content << "}";
632✔
320

321
        return std::move(*content.rdbuf()).str();
1,264✔
322
}
323

324
error::Error Context::SaveDeploymentStateData(kv_db::Transaction &txn, StateData &state_data) {
634✔
325
        if (state_data.update_info.state_data_store_count++ >= kMaxStateDataStoreCount) {
634✔
326
                return main_context::MakeError(
327
                        main_context::StateDataStoreCountExceededError,
328
                        "State looping detected, breaking out of loop");
2✔
329
        }
330

331
        string content = GenerateStateDataJson(state_data);
1,264✔
332

333
        string store_key;
1,264✔
334
        if (state_data.update_info.has_db_schema_update) {
632✔
335
                store_key = mender_context.state_data_key_uncommitted;
4✔
336

337
                // Leave state_data_key alone.
338
        } else {
339
                store_key = mender_context.state_data_key;
628✔
340

341
                auto err = txn.Remove(mender_context.state_data_key_uncommitted);
628✔
342
                if (err != error::NoError) {
628✔
343
                        return err.WithContext("Could not remove uncommitted state data");
×
344
                }
345
        }
346

347
        auto err = txn.Write(store_key, common::ByteVectorFromString(content));
1,264✔
348
        if (err != error::NoError) {
632✔
349
                return err.WithContext("Could not write state data");
×
350
        }
351

352
        return error::NoError;
632✔
353
}
354

355
error::Error Context::SaveDeploymentStateData(StateData &state_data) {
574✔
356
        auto &db = mender_context.GetMenderStoreDB();
574✔
357
        return db.WriteTransaction([this, &state_data](kv_db::Transaction &txn) {
565✔
358
                return SaveDeploymentStateData(txn, state_data);
565✔
359
        });
574✔
360
}
361

362
static error::Error UnmarshalJsonStateData(const json::Json &json, StateData &state_data) {
35✔
363
#define SetOrReturnIfError(dst, expr) \
364
        if (!expr) {                      \
365
                return expr.error();          \
366
        }                                 \
367
        dst = expr.value()
368

369
#define DefaultOrSetOrReturnIfError(dst, expr, def)                            \
370
        if (!expr) {                                                               \
371
                if (expr.error().code == kv_db::MakeError(kv_db::KeyError, "").code) { \
372
                        dst = def;                                                         \
373
                } else {                                                               \
374
                        return expr.error();                                               \
375
                }                                                                      \
376
        } else {                                                                   \
377
                dst = expr.value();                                                    \
378
        }
379

380
        auto exp_int = json.Get("Version").and_then(json::ToInt);
70✔
381
        SetOrReturnIfError(state_data.version, exp_int);
35✔
382

383
        if (state_data.version != kStateDataVersion) {
35✔
384
                return error::Error(
385
                        make_error_condition(errc::not_supported),
1✔
386
                        "State Data version not supported by this client");
3✔
387
        }
388

389
        auto exp_string = json.Get("Name").and_then(json::ToString);
68✔
390
        SetOrReturnIfError(state_data.state, exp_string);
34✔
391

392
        const auto &exp_json_update_info = json.Get("UpdateInfo");
68✔
393
        SetOrReturnIfError(const auto &json_update_info, exp_json_update_info);
34✔
394

395
        const auto &exp_json_artifact = json_update_info.Get("Artifact");
68✔
396
        SetOrReturnIfError(const auto &json_artifact, exp_json_artifact);
34✔
397

398
        const auto &exp_json_source = json_artifact.Get("Source");
68✔
399
        SetOrReturnIfError(const auto &json_source, exp_json_source);
34✔
400

401
        auto &update_info = state_data.update_info;
34✔
402
        auto &artifact = update_info.artifact;
34✔
403
        auto &source = artifact.source;
34✔
404

405
        exp_string = json_source.Get("URI").and_then(json::ToString);
34✔
406
        SetOrReturnIfError(source.uri, exp_string);
34✔
407

408
        exp_string = json_source.Get("Expire").and_then(json::ToString);
34✔
409
        SetOrReturnIfError(source.expire, exp_string);
34✔
410

411
        auto exp_string_vector = json_artifact.Get("CompatibleDevices").and_then(json::ToStringVector);
68✔
412
        SetOrReturnIfError(artifact.compatible_devices, exp_string_vector);
34✔
413

414
        exp_string = json_artifact.Get("ArtifactName").and_then(json::ToString);
34✔
415
        SetOrReturnIfError(artifact.artifact_name, exp_string);
34✔
416

417
        exp_string_vector = json_artifact.Get("PayloadTypes").and_then(json::ToStringVector);
34✔
418
        SetOrReturnIfError(artifact.payload_types, exp_string_vector);
34✔
419
        // It's possible for there not to be an initialized update,
420
        // if the deployment failed before we could successfully parse the artifact.
421
        if (artifact.payload_types.size() == 0 and artifact.artifact_name == "") {
34✔
422
                return error::NoError;
1✔
423
        }
424
        if (artifact.payload_types.size() != 1) {
33✔
425
                return error::Error(
426
                        make_error_condition(errc::not_supported),
×
427
                        "Only exactly one payload type is supported. Got: "
428
                                + to_string(artifact.payload_types.size()));
×
429
        }
430

431
        exp_string = json_artifact.Get("ArtifactGroup").and_then(json::ToString);
33✔
432
        SetOrReturnIfError(artifact.artifact_group, exp_string);
33✔
433

434
        auto exp_string_map = json_artifact.Get("TypeInfoProvides").and_then(json::ToKeyValuesMap);
66✔
435
        DefaultOrSetOrReturnIfError(artifact.type_info_provides, exp_string_map, {});
33✔
436

437
        exp_string_vector = json_artifact.Get("ClearsArtifactProvides").and_then(json::ToStringVector);
33✔
438
        DefaultOrSetOrReturnIfError(artifact.clears_artifact_provides, exp_string_vector, {});
33✔
439

440
        exp_string = json_update_info.Get("ID").and_then(json::ToString);
33✔
441
        SetOrReturnIfError(update_info.id, exp_string);
33✔
442

443
        exp_string_vector = json_update_info.Get("RebootRequested").and_then(json::ToStringVector);
33✔
444
        SetOrReturnIfError(update_info.reboot_requested, exp_string_vector);
33✔
445
        // Check that it's valid strings.
446
        for (const auto &reboot_requested : update_info.reboot_requested) {
57✔
447
                if (reboot_requested != "") {
24✔
448
                        auto exp_needs_reboot = DbStringToNeedsReboot(reboot_requested);
21✔
449
                        if (!exp_needs_reboot) {
21✔
450
                                return exp_needs_reboot.error();
×
451
                        }
452
                }
453
        }
454

455
        exp_string = json_update_info.Get("SupportsRollback").and_then(json::ToString);
33✔
456
        SetOrReturnIfError(update_info.supports_rollback, exp_string);
33✔
457
        // Check that it's a valid string.
458
        if (update_info.supports_rollback != "") {
33✔
459
                auto exp_supports_rollback = DbStringToSupportsRollback(update_info.supports_rollback);
14✔
460
                if (!exp_supports_rollback) {
14✔
461
                        return exp_supports_rollback.error();
×
462
                }
463
        }
464

465
        exp_int = json_update_info.Get("StateDataStoreCount").and_then(json::ToInt);
33✔
466
        SetOrReturnIfError(update_info.state_data_store_count, exp_int);
33✔
467

468
        auto exp_bool = json_update_info.Get("HasDBSchemaUpdate").and_then(json::ToBool);
66✔
469
        SetOrReturnIfError(update_info.has_db_schema_update, exp_bool);
33✔
470

471
        exp_bool = json_update_info.Get("AllRollbacksSuccessful").and_then(json::ToBool);
33✔
472
        DefaultOrSetOrReturnIfError(update_info.all_rollbacks_successful, exp_bool, false);
33✔
473

474
#undef SetOrReturnIfError
475
#undef EmptyOrSetOrReturnIfError
476

477
        return error::NoError;
33✔
478
}
479

480
expected::ExpectedBool Context::LoadDeploymentStateData(StateData &state_data) {
87✔
481
        auto &db = mender_context.GetMenderStoreDB();
87✔
482
        auto err = db.WriteTransaction([this, &state_data](kv_db::Transaction &txn) {
156✔
483
                auto exp_content = txn.Read(mender_context.state_data_key);
172✔
484
                if (!exp_content) {
86✔
485
                        return exp_content.error().WithContext("Could not load state data");
52✔
486
                }
487
                auto &content = exp_content.value();
34✔
488

489
                auto exp_json = json::Load(common::StringFromByteVector(content));
68✔
490
                if (!exp_json) {
34✔
491
                        return exp_json.error().WithContext("Could not load state data");
×
492
                }
493

494
                auto err = UnmarshalJsonStateData(exp_json.value(), state_data);
68✔
495
                if (err != error::NoError) {
34✔
496
                        if (err.code != make_error_condition(errc::not_supported)) {
1✔
497
                                return err.WithContext("Could not load state data");
×
498
                        }
499

500
                        // Try again with the state_data_key_uncommitted.
501
                        exp_content = txn.Read(mender_context.state_data_key_uncommitted);
1✔
502
                        if (!exp_content) {
1✔
503
                                return err.WithContext("Could not load state data").FollowedBy(exp_content.error());
×
504
                        }
505
                        auto &content = exp_content.value();
1✔
506

507
                        exp_json = json::Load(common::StringFromByteVector(content));
1✔
508
                        if (!exp_json) {
1✔
509
                                return err.WithContext("Could not load state data").FollowedBy(exp_json.error());
×
510
                        }
511

512
                        auto inner_err = UnmarshalJsonStateData(exp_json.value(), state_data);
1✔
513
                        if (inner_err != error::NoError) {
1✔
514
                                return err.WithContext("Could not load state data").FollowedBy(inner_err);
×
515
                        }
516

517
                        // Since we loaded from the uncommitted key, set this.
518
                        state_data.update_info.has_db_schema_update = true;
1✔
519
                }
520

521
                // Every load also saves, which increments the state_data_store_count.
522
                return SaveDeploymentStateData(txn, state_data);
34✔
523
        });
174✔
524

525
        if (err == error::NoError) {
87✔
526
                return true;
33✔
527
        } else if (err.code == kv_db::MakeError(kv_db::KeyError, "").code) {
54✔
528
                return false;
52✔
529
        } else {
530
                return expected::unexpected(err);
4✔
531
        }
532
}
533

534
void Context::BeginDeploymentLogging() {
89✔
535
        deployment.logger.reset(new deployments::DeploymentLog(
89✔
536
                mender_context.GetConfig().paths.GetDataStore(), deployment.state_data->update_info.id));
178✔
537
        auto err = deployment.logger->BeginLogging();
178✔
538
        if (err != error::NoError) {
89✔
539
                log::Error(
×
540
                        "Was not able to set up deployment log for deployment ID "
541
                        + deployment.state_data->update_info.id + ": " + err.String());
×
542
                // It's not a fatal error, so continue.
543
        }
544
}
89✔
545

546
void Context::FinishDeploymentLogging() {
89✔
547
        auto err = deployment.logger->FinishLogging();
178✔
548
        if (err != error::NoError) {
89✔
549
                log::Error(
×
550
                        "Was not able to stop deployment log for deployment ID "
551
                        + deployment.state_data->update_info.id + ": " + err.String());
×
552
                // We need to continue regardless
553
        }
554
}
89✔
555

556
} // namespace daemon
557
} // namespace update
558
} // 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