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

mendersoftware / mender / 1070743650

13 Nov 2023 06:51PM UTC coverage: 80.107% (-0.05%) from 80.157%
1070743650

push

gitlab-ci

oleorhagen
chore: Error when trying to update with empty deployment ID

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

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

65 existing lines in 3 files now uncovered.

7011 of 8752 relevant lines covered (80.11%)

9197.49 hits per line

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

84.72
/src/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")
110✔
49
                          .and_then([](const json::Json &json) { return json.Get("source"); })
110✔
50
                          .and_then([](const json::Json &json) { return json.Get("uri"); })
110✔
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")
110✔
60
                          .and_then([](const json::Json &json) { return json.Get("source"); })
110✔
61
                          .and_then([](const json::Json &json) { return json.Get("expire"); })
110✔
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) {
44✔
82
        return support ? Context::kRollbackSupported : Context::kRollbackNotSupported;
50✔
83
}
84

85
expected::ExpectedBool DbStringToSupportsRollback(const string &str) {
14✔
86
        if (str == Context::kRollbackSupported) {
14✔
87
                return true;
88
        } else if (str == Context::kRollbackNotSupported) {
2✔
89
                return false;
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) {
71✔
103
        switch (action) {
71✔
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:
63✔
109
                return Context::kRebootTypeCustom;
63✔
110
        default:
×
111
                // Should not happen.
112
                assert(false);
113
                return Context::kRebootTypeNone;
×
114
        }
115
}
116

117
update_module::ExpectedRebootAction DbStringToNeedsReboot(const string &str) {
107✔
118
        if (str == Context::kRebootTypeNone) {
107✔
119
                return update_module::RebootAction::No;
120
        } else if (str == Context::kRebootTypeAutomatic) {
107✔
121
                return update_module::RebootAction::Automatic;
122
        } else if (str == Context::kRebootTypeCustom) {
107✔
123
                return update_module::RebootAction::Yes;
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;
133
        auto &header = view.header;
134
        artifact.compatible_devices = header.header_info.depends.device_type;
49✔
135
        artifact.payload_types = {header.payload_type};
147✔
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();
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(
94✔
151
        mender::update::context::MenderContext &mender_context, events::EventLoop &event_loop) :
94✔
152
        mender_context(mender_context),
153
        event_loop(event_loop),
154
        authenticator(event_loop),
155
        http_client(mender_context.GetConfig().GetHttpClientConfig(), event_loop, authenticator),
156
        download_client(make_shared<http_resumer::DownloadResumerClient>(
94✔
157
                mender_context.GetConfig().GetHttpClientConfig(), event_loop)),
94✔
158
        deployment_client(make_shared<deployments::DeploymentClient>()),
94✔
159
        inventory_client(make_shared<inventory::InventoryClient>()) {
376✔
160
}
94✔
161

162
///////////////////////////////////////////////////////////////////////////////////////////////////
163
// Values for various states in the database.
164
///////////////////////////////////////////////////////////////////////////////////////////////////
165

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

182
///////////////////////////////////////////////////////////////////////////////////////////////////
183
// Not in use by current client, but were in use by Golang client, and still important to handle
184
// correctly in recovery scenarios.
185
///////////////////////////////////////////////////////////////////////////////////////////////////
186

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

195
///////////////////////////////////////////////////////////////////////////////////////////////////
196
// Not in use. All of these, as well as unknown values, will cause a rollback.
197
///////////////////////////////////////////////////////////////////////////////////////////////////
198

199
// Disable, but distinguish from comments.
200
#if false
201
// These were never actually saved due to not being update states.
202
const string Context::kUpdateStateInit = "init";
203
const string Context::kUpdateStateIdle = "idle";
204
const string Context::kUpdateStateAuthorize = "authorize";
205
const string Context::kUpdateStateAuthorizeWait = "authorize-wait";
206
const string Context::kUpdateStateInventoryUpdate = "inventory-update";
207
const string Context::kUpdateStateInventoryUpdateRetryWait = "inventory-update-retry-wait";
208

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

228
///////////////////////////////////////////////////////////////////////////////////////////////////
229
// End of database values.
230
///////////////////////////////////////////////////////////////////////////////////////////////////
231

232
static string GenerateStateDataJson(const StateData &state_data) {
645✔
233
        stringstream content;
1,290✔
234

235
        auto append_vector = [&content](const vector<string> &data) {
2,580✔
236
                for (auto entry = data.begin(); entry != data.end(); entry++) {
4,756✔
237
                        if (entry != data.begin()) {
2,176✔
238
                                content << ",";
×
239
                        }
240
                        content << R"(")" << json::EscapeString(*entry) << R"(")";
4,352✔
241
                }
242
        };
2,580✔
243

244
        auto append_map = [&content](const unordered_map<string, string> &data) {
645✔
245
                for (auto entry = data.begin(); entry != data.end(); entry++) {
1,225✔
246
                        if (entry != data.begin()) {
580✔
247
                                content << ",";
×
248
                        }
249
                        content << R"(")" << json::EscapeString(entry->first) << R"(":")"
1,160✔
250
                                        << json::EscapeString(entry->second) << R"(")";
1,740✔
251
                }
252
        };
645✔
253

254
        content << "{";
645✔
255
        {
256
                content << R"("Version":)" << to_string(state_data.version) << ",";
645✔
257
                content << R"("Name":")" << json::EscapeString(state_data.state) << R"(",)";
645✔
258
                content << R"("UpdateInfo":{)";
645✔
259
                {
260
                        auto &update_info = state_data.update_info;
261
                        content << R"("Artifact":{)";
645✔
262
                        {
263
                                auto &artifact = update_info.artifact;
264
                                content << R"("Source":{)";
645✔
265
                                {
266
                                        content << R"("URI":")" << json::EscapeString(artifact.source.uri) << R"(",)";
645✔
267
                                        content << R"("Expire":")" << json::EscapeString(artifact.source.expire)
645✔
268
                                                        << R"(")";
1,290✔
269
                                }
270
                                content << "},";
645✔
271

272
                                content << R"("device_types_compatible":[)";
645✔
273
                                append_vector(artifact.compatible_devices);
645✔
274
                                content << "],";
645✔
275

276
                                content << R"("PayloadTypes":[)";
645✔
277
                                append_vector(artifact.payload_types);
645✔
278
                                content << "],";
645✔
279

280
                                content << R"("artifact_name":")" << json::EscapeString(artifact.artifact_name)
645✔
281
                                                << R"(",)";
1,290✔
282
                                content << R"("artifact_group":")" << json::EscapeString(artifact.artifact_group)
645✔
283
                                                << R"(",)";
1,290✔
284

285
                                content << R"("artifact_provides":{)";
645✔
286
                                append_map(artifact.type_info_provides);
645✔
287
                                content << "},";
645✔
288

289
                                content << R"("clears_artifact_provides":[)";
645✔
290
                                append_vector(artifact.clears_artifact_provides);
645✔
291
                                content << "]";
645✔
292
                        }
293
                        content << "},";
645✔
294

295
                        content << R"("ID":")" << json::EscapeString(update_info.id) << R"(",)";
645✔
296

297
                        content << R"("RebootRequested":[)";
645✔
298
                        append_vector(update_info.reboot_requested);
645✔
299
                        content << R"(],)";
645✔
300

301
                        content << R"("SupportsRollback":")"
302
                                        << json::EscapeString(update_info.supports_rollback) << R"(",)";
645✔
303
                        content << R"("StateDataStoreCount":)" << to_string(update_info.state_data_store_count)
645✔
304
                                        << R"(,)";
1,290✔
305
                        content << R"("HasDBSchemaUpdate":)"
306
                                        << string(update_info.has_db_schema_update ? "true," : "false,");
1,934✔
307
                        content << R"("AllRollbacksSuccessful":)"
308
                                        << string(update_info.all_rollbacks_successful ? "true" : "false");
1,788✔
309
                }
310
                content << "}";
645✔
311
        }
312
        content << "}";
645✔
313

314
        return std::move(*content.rdbuf()).str();
1,290✔
315
}
316

317
error::Error Context::SaveDeploymentStateData(kv_db::Transaction &txn, StateData &state_data) {
647✔
318
        if (state_data.update_info.state_data_store_count++ >= kMaxStateDataStoreCount) {
647✔
319
                return main_context::MakeError(
320
                        main_context::StateDataStoreCountExceededError,
321
                        "State looping detected, breaking out of loop");
4✔
322
        }
323

324
        string content = GenerateStateDataJson(state_data);
645✔
325

326
        string store_key;
327
        if (state_data.update_info.has_db_schema_update) {
645✔
328
                store_key = mender_context.state_data_key_uncommitted;
329

330
                // Leave state_data_key alone.
331
        } else {
332
                store_key = mender_context.state_data_key;
333

334
                auto err = txn.Remove(mender_context.state_data_key_uncommitted);
644✔
335
                if (err != error::NoError) {
644✔
336
                        return err.WithContext("Could not remove uncommitted state data");
×
337
                }
338
        }
339

340
        auto err = txn.Write(store_key, common::ByteVectorFromString(content));
645✔
341
        if (err != error::NoError) {
645✔
342
                return err.WithContext("Could not write state data");
×
343
        }
344

345
        return error::NoError;
645✔
346
}
347

348
error::Error Context::SaveDeploymentStateData(StateData &state_data) {
583✔
349
        auto &db = mender_context.GetMenderStoreDB();
583✔
350
        return db.WriteTransaction([this, &state_data](kv_db::Transaction &txn) {
574✔
351
                return SaveDeploymentStateData(txn, state_data);
574✔
352
        });
1,166✔
353
}
354

355
#define SetOrReturnIfError(dst, expr) \
356
        if (!expr) {                      \
357
                return expr.error();          \
358
        }                                 \
359
        dst = expr.value()
360

361
#define DefaultOrSetOrReturnIfError(dst, expr, def)                            \
362
        if (!expr) {                                                               \
363
                if (expr.error().code == kv_db::MakeError(kv_db::KeyError, "").code) { \
364
                        dst = def;                                                         \
365
                } else {                                                               \
366
                        return expr.error();                                               \
367
                }                                                                      \
368
        } else {                                                                   \
369
                dst = expr.value();                                                    \
370
        }
371

372
static error::Error UnmarshalJsonStateDataVersion1(const json::Json &json, StateData &state_data) {
1✔
373
        auto exp_int = json.Get("Version").and_then(json::ToInt);
2✔
374
        SetOrReturnIfError(state_data.version, exp_int);
1✔
375

376
        if (state_data.version != 1) {
1✔
377
                return error::MakeError(
UNCOV
378
                        error::ProgrammingError, "Only able to unmarshal version 1 of the state data format");
×
379
        }
380

381
        auto exp_string = json.Get("Name").and_then(json::ToString);
2✔
382
        SetOrReturnIfError(state_data.state, exp_string);
1✔
383

384
        const auto &exp_json_update_info = json.Get("UpdateInfo");
1✔
385
        SetOrReturnIfError(const auto &json_update_info, exp_json_update_info);
1✔
386

387
        const auto &exp_json_artifact = json_update_info.Get("Artifact");
1✔
388
        SetOrReturnIfError(const auto &json_artifact, exp_json_artifact);
1✔
389

390
        const auto &exp_json_source = json_artifact.Get("Source");
1✔
391
        SetOrReturnIfError(const auto &json_source, exp_json_source);
1✔
392

393
        auto &update_info = state_data.update_info;
394
        auto &artifact = update_info.artifact;
395
        auto &source = artifact.source;
396

397
        exp_string = json_source.Get("URI").and_then(json::ToString);
2✔
398
        SetOrReturnIfError(source.uri, exp_string);
1✔
399

400
        exp_string = json_source.Get("Expire").and_then(json::ToString);
2✔
401
        SetOrReturnIfError(source.expire, exp_string);
1✔
402

403
        auto exp_string_vector =
404
                json_artifact.Get("device_types_compatible").and_then(json::ToStringVector);
2✔
405
        SetOrReturnIfError(artifact.compatible_devices, exp_string_vector);
1✔
406

407
        exp_string = json_artifact.Get("artifact_name").and_then(json::ToString);
2✔
408
        SetOrReturnIfError(artifact.artifact_name, exp_string);
1✔
409

410
        exp_string = json_update_info.Get("ID").and_then(json::ToString);
2✔
411
        SetOrReturnIfError(update_info.id, exp_string);
1✔
412

413
        return error::NoError;
1✔
414
}
415

416
static error::Error UnmarshalJsonStateData(const json::Json &json, StateData &state_data) {
38✔
417
        auto exp_int = json.Get("Version").and_then(json::ToInt);
76✔
418
        SetOrReturnIfError(state_data.version, exp_int);
38✔
419

420
        if (state_data.version != kStateDataVersion && state_data.version != 1) {
38✔
421
                return error::Error(
422
                        make_error_condition(errc::not_supported),
2✔
423
                        "State Data version not supported by this client (" + to_string(state_data.version)
2✔
424
                                + ")");
2✔
425
        }
426

427
        if (state_data.version == 1) {
37✔
428
                return UnmarshalJsonStateDataVersion1(json, state_data);
1✔
429
        }
430

431
        auto exp_string = json.Get("Name").and_then(json::ToString);
72✔
432
        SetOrReturnIfError(state_data.state, exp_string);
36✔
433

434
        const auto &exp_json_update_info = json.Get("UpdateInfo");
36✔
435
        SetOrReturnIfError(const auto &json_update_info, exp_json_update_info);
36✔
436

437
        const auto &exp_json_artifact = json_update_info.Get("Artifact");
36✔
438
        SetOrReturnIfError(const auto &json_artifact, exp_json_artifact);
36✔
439

440
        const auto &exp_json_source = json_artifact.Get("Source");
36✔
441
        SetOrReturnIfError(const auto &json_source, exp_json_source);
36✔
442

443
        auto &update_info = state_data.update_info;
444
        auto &artifact = update_info.artifact;
445
        auto &source = artifact.source;
446

447
        exp_string = json_source.Get("URI").and_then(json::ToString);
72✔
448
        SetOrReturnIfError(source.uri, exp_string);
36✔
449

450
        exp_string = json_source.Get("Expire").and_then(json::ToString);
72✔
451
        SetOrReturnIfError(source.expire, exp_string);
36✔
452

453
        auto exp_string_vector =
454
                json_artifact.Get("device_types_compatible").and_then(json::ToStringVector);
72✔
455
        SetOrReturnIfError(artifact.compatible_devices, exp_string_vector);
36✔
456

457
        exp_string = json_artifact.Get("artifact_name").and_then(json::ToString);
72✔
458
        SetOrReturnIfError(artifact.artifact_name, exp_string);
36✔
459

460
        exp_string_vector = json_artifact.Get("PayloadTypes").and_then(json::ToStringVector);
72✔
461
        SetOrReturnIfError(artifact.payload_types, exp_string_vector);
36✔
462
        // It's possible for there not to be an initialized update,
463
        // if the deployment failed before we could successfully parse the artifact.
464
        if (artifact.payload_types.size() == 0 and artifact.artifact_name == "") {
36✔
465
                return error::NoError;
1✔
466
        }
467
        if (artifact.payload_types.size() != 1) {
35✔
468
                return error::Error(
UNCOV
469
                        make_error_condition(errc::not_supported),
×
470
                        "Only exactly one payload type is supported. Got: "
UNCOV
471
                                + to_string(artifact.payload_types.size()));
×
472
        }
473

474
        exp_string = json_artifact.Get("artifact_group").and_then(json::ToString);
70✔
475
        SetOrReturnIfError(artifact.artifact_group, exp_string);
35✔
476

477
        auto exp_string_map = json_artifact.Get("artifact_provides").and_then(json::ToKeyValueMap);
70✔
478
        DefaultOrSetOrReturnIfError(artifact.type_info_provides, exp_string_map, {});
35✔
479

480
        exp_string_vector =
481
                json_artifact.Get("clears_artifact_provides").and_then(json::ToStringVector);
70✔
482
        DefaultOrSetOrReturnIfError(artifact.clears_artifact_provides, exp_string_vector, {});
35✔
483

484
        exp_string = json_update_info.Get("ID").and_then(json::ToString);
70✔
485
        SetOrReturnIfError(update_info.id, exp_string);
35✔
486

487
        exp_string_vector = json_update_info.Get("RebootRequested").and_then(json::ToStringVector);
70✔
488
        SetOrReturnIfError(update_info.reboot_requested, exp_string_vector);
35✔
489
        // Check that it's valid strings.
490
        for (const auto &reboot_requested : update_info.reboot_requested) {
61✔
491
                if (reboot_requested != "") {
26✔
492
                        auto exp_needs_reboot = DbStringToNeedsReboot(reboot_requested);
23✔
493
                        if (!exp_needs_reboot) {
23✔
UNCOV
494
                                return exp_needs_reboot.error();
×
495
                        }
496
                }
497
        }
498

499
        exp_string = json_update_info.Get("SupportsRollback").and_then(json::ToString);
70✔
500
        SetOrReturnIfError(update_info.supports_rollback, exp_string);
35✔
501
        // Check that it's a valid string.
502
        if (update_info.supports_rollback != "") {
35✔
503
                auto exp_supports_rollback = DbStringToSupportsRollback(update_info.supports_rollback);
14✔
504
                if (!exp_supports_rollback) {
14✔
UNCOV
505
                        return exp_supports_rollback.error();
×
506
                }
507
        }
508

509
        exp_int = json_update_info.Get("StateDataStoreCount").and_then(json::ToInt);
70✔
510
        SetOrReturnIfError(update_info.state_data_store_count, exp_int);
35✔
511

512
        auto exp_bool = json_update_info.Get("HasDBSchemaUpdate").and_then(json::ToBool);
70✔
513
        SetOrReturnIfError(update_info.has_db_schema_update, exp_bool);
35✔
514

515
        exp_bool = json_update_info.Get("AllRollbacksSuccessful").and_then(json::ToBool);
70✔
516
        DefaultOrSetOrReturnIfError(update_info.all_rollbacks_successful, exp_bool, false);
35✔
517

518
        return error::NoError;
35✔
519
}
520

521
#undef SetOrReturnIfError
522
#undef EmptyOrSetOrReturnIfError
523

524
expected::ExpectedBool Context::LoadDeploymentStateData(StateData &state_data) {
91✔
525
        log::Trace("Loading the deployment state data");
273✔
526

527
        auto &db = mender_context.GetMenderStoreDB();
91✔
528
        auto err = db.WriteTransaction([this, &state_data](kv_db::Transaction &txn) {
243✔
529
                auto exp_content = txn.Read(mender_context.state_data_key);
90✔
530
                if (!exp_content) {
90✔
531
                        return exp_content.error().WithContext("Could not load state data");
106✔
532
                }
533
                auto content = common::StringFromByteVector(exp_content.value());
37✔
534

535
                auto exp_json = json::Load(content);
74✔
536
                if (!exp_json) {
37✔
537
                        return exp_json.error().WithContext("Could not load state data");
×
538
                }
539

540
                log::Trace("Got database state data content: " + content);
37✔
541

542
                auto err = UnmarshalJsonStateData(exp_json.value(), state_data);
37✔
543
                if (err != error::NoError) {
37✔
544
                        if (err.code == make_error_condition(errc::not_supported)) {
1✔
545
                                //
546
                                // Try and Roll back
547
                                //
548
                                // Try and load the uncommitted data, in case we are rolling back from an
549
                                // unsupported version
550
                                exp_content = txn.Read(mender_context.state_data_key_uncommitted);
2✔
551
                                if (!exp_content) {
1✔
UNCOV
552
                                        if (exp_content.error().code != kv_db::MakeError(kv_db::KeyError, "").code) {
×
UNCOV
553
                                                return exp_content.error().WithContext("Could not load state data");
×
554
                                        }
555
                                        // TODO - Error handling here and above
UNCOV
556
                                        return exp_content.error().WithContext("Could not load state data");
×
557
                                }
558

559
                                auto content = common::StringFromByteVector(exp_content.value());
1✔
560
                                log::Trace("Got database state data content from the uncommitted key: " + content);
1✔
561
                                auto exp_json = json::Load(content);
2✔
562
                                if (!exp_json) {
1✔
UNCOV
563
                                        return exp_json.error().WithContext("Could not load state data");
×
564
                                }
565
                                StateData state_data_uncommitted {};
2✔
566

567
                                err = UnmarshalJsonStateData(exp_json.value(), state_data_uncommitted);
1✔
568
                                if (err != error::NoError) {
1✔
569
                                        return err.WithContext(
UNCOV
570
                                                "Could not unmarshal the uncommited state data. This means we failed to roll back the state data");
×
571
                                }
572
                                state_data = state_data_uncommitted;
1✔
573
                        } else {
UNCOV
574
                                return err.WithContext("Failed to unmarshal the state data");
×
575
                        }
576
                }
577

578
                switch (state_data.version) {
37✔
579
                case 1: {
580
                        //
581
                        // Roll forwards
582
                        //
583
                        log::Debug("Got old state data version 1. Migrating it to version 2");
2✔
584

585
                        // We need to upgrade the schema. Check if we have
586
                        // already written an updated one.
587
                        exp_content = txn.Read(mender_context.state_data_key_uncommitted);
2✔
588
                        if (!exp_content) {
1✔
589
                                if (exp_content.error().code != kv_db::MakeError(kv_db::KeyError, "").code) {
1✔
UNCOV
590
                                        return exp_content.error().WithContext("Could not load state data");
×
591
                                }
592
                                log::Debug(
1✔
593
                                        "Got read error reading the uncommitted state data: "
594
                                        + exp_content.error().String());
2✔
595
                        } else {
UNCOV
596
                                auto content = common::StringFromByteVector(exp_content.value());
×
UNCOV
597
                                log::Trace("Loaded the uncommitted state data: " + content);
×
598

UNCOV
599
                                exp_json = json::Load(content);
×
UNCOV
600
                                if (!exp_json) {
×
UNCOV
601
                                        return exp_json.error().WithContext("Could not load state data");
×
602
                                }
603

UNCOV
604
                                StateData state_data_uncommitted {};
×
605

UNCOV
606
                                auto inner_err = UnmarshalJsonStateData(exp_json.value(), state_data_uncommitted);
×
UNCOV
607
                                if (inner_err != error::NoError) {
×
UNCOV
608
                                        return inner_err.WithContext("Could not load the uncommited state data");
×
609
                                }
610

611
                                // Verify that the update IDs are equal
UNCOV
612
                                if (state_data.update_info.id == state_data_uncommitted.update_info.id) {
×
UNCOV
613
                                        state_data = state_data_uncommitted;
×
614
                                }
615
                        }
616

617
                        // If we are upgrading the schema, we know for a fact
618
                        // that we came from a rootfs-image update, because it
619
                        // was the only thing that was supported there. Store
620
                        // this, since this information will be missing in
621
                        // databases before version 2.
622
                        state_data.update_info.artifact.payload_types = {"rootfs-image"};
2✔
623
                        state_data.update_info.reboot_requested = {"reboot-type-custom"};
2✔
624
                        state_data.update_info.supports_rollback = "rollback-supported";
1✔
625

626
                        log::Info("Storing new version of the state data");
2✔
627

628
                        // Since we loaded from the uncommitted key, set this.
629
                        state_data.update_info.has_db_schema_update = true;
1✔
630

631
                        break;
1✔
632
                }
633
                case 2:
36✔
634
                        state_data.update_info.has_db_schema_update = false;
36✔
635
                        break;
36✔
UNCOV
636
                default:
×
UNCOV
637
                        log::Fatal(
×
638
                                "ProgrammingError. Unsupported state data versions should already be handled, got: "
UNCOV
639
                                + to_string(state_data.version));
×
640
                }
641

642
                state_data.version = 2;
37✔
643
                log::Trace("Finished loading the state data");
74✔
644

645
                // Every load also saves, which increments the state_data_store_count.
646
                return SaveDeploymentStateData(txn, state_data);
37✔
647
        });
91✔
648

649
        if (err == error::NoError) {
91✔
650
                return true;
651
        } else if (err.code == kv_db::MakeError(kv_db::KeyError, "").code) {
55✔
652
                return false;
653
        } else {
654
                return expected::unexpected(err);
4✔
655
        }
656
}
657

658
void Context::BeginDeploymentLogging() {
91✔
659
        deployment.logger.reset(new deployments::DeploymentLog(
660
                mender_context.GetConfig().paths.GetUpdateLogPath(),
182✔
661
                deployment.state_data->update_info.id));
91✔
662
        auto err = deployment.logger->BeginLogging();
91✔
663
        if (err != error::NoError) {
91✔
UNCOV
664
                log::Error(
×
665
                        "Was not able to set up deployment log for deployment ID "
UNCOV
666
                        + deployment.state_data->update_info.id + ": " + err.String());
×
667
                // It's not a fatal error, so continue.
668
        }
669
}
91✔
670

671
void Context::FinishDeploymentLogging() {
91✔
672
        auto err = deployment.logger->FinishLogging();
91✔
673
        if (err != error::NoError) {
91✔
UNCOV
674
                log::Error(
×
675
                        "Was not able to stop deployment log for deployment ID "
UNCOV
676
                        + deployment.state_data->update_info.id + ": " + err.String());
×
677
                // We need to continue regardless
678
        }
679
}
91✔
680

681
} // namespace daemon
682
} // namespace update
683
} // 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