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

mendersoftware / mender / 1019451413

28 Sep 2023 10:09AM UTC coverage: 78.477%. Remained the same
1019451413

push

gitlab-ci

kacf
chore: Make our `optional` use compatible with C++17.

If the standard is pre-C++17, we use the `optional-lite` library, else
we use the one in `std`.

Signed-off-by: Kristian Amlie <kristian.amlie@northern.tech>

17 of 17 new or added lines in 6 files covered. (100.0%)

5546 of 7067 relevant lines covered (78.48%)

11103.41 hits per line

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

78.99
/mender-update/deployments/deployments.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/deployments.hpp>
16

17
#include <algorithm>
18
#include <sstream>
19
#include <string>
20

21
#include <api/api.hpp>
22
#include <common/common.hpp>
23
#include <common/error.hpp>
24
#include <common/events.hpp>
25
#include <common/expected.hpp>
26
#include <common/http.hpp>
27
#include <common/io.hpp>
28
#include <common/json.hpp>
29
#include <common/log.hpp>
30
#include <common/optional.hpp>
31
#include <common/path.hpp>
32
#include <mender-update/context.hpp>
33

34
namespace mender {
35
namespace update {
36
namespace deployments {
37

38
using namespace std;
39

40
namespace api = mender::api;
41
namespace common = mender::common;
42
namespace context = mender::update::context;
43
namespace error = mender::common::error;
44
namespace events = mender::common::events;
45
namespace expected = mender::common::expected;
46
namespace io = mender::common::io;
47
namespace json = mender::common::json;
48
namespace log = mender::common::log;
49
namespace path = mender::common::path;
50

51
const DeploymentsErrorCategoryClass DeploymentsErrorCategory;
52

53
const char *DeploymentsErrorCategoryClass::name() const noexcept {
×
54
        return "DeploymentsErrorCategory";
×
55
}
56

57
string DeploymentsErrorCategoryClass::message(int code) const {
2✔
58
        switch (code) {
2✔
59
        case NoError:
60
                return "Success";
×
61
        case InvalidDataError:
62
                return "Invalid data error";
×
63
        case BadResponseError:
64
                return "Bad response error";
×
65
        case DeploymentAbortedError:
66
                return "Deployment was aborted on the server";
2✔
67
        }
68
        assert(false);
69
        return "Unknown";
×
70
}
71

72
error::Error MakeError(DeploymentsErrorCode code, const string &msg) {
25✔
73
        return error::Error(error_condition(code, DeploymentsErrorCategory), msg);
30✔
74
}
75

76
static const string check_updates_v1_uri = "/api/devices/v1/deployments/device/deployments/next";
77
static const string check_updates_v2_uri = "/api/devices/v2/deployments/device/deployments/next";
78

79
error::Error DeploymentClient::CheckNewDeployments(
8✔
80
        context::MenderContext &ctx,
81
        const string &server_url,
82
        http::Client &client,
83
        CheckUpdatesAPIResponseHandler api_handler) {
84
        auto ex_dev_type = ctx.GetDeviceType();
8✔
85
        if (!ex_dev_type) {
8✔
86
                return ex_dev_type.error();
87
        }
88
        string device_type = ex_dev_type.value();
6✔
89

90
        auto ex_provides = ctx.LoadProvides();
6✔
91
        if (!ex_provides) {
6✔
92
                return ex_provides.error();
93
        }
94
        auto provides = ex_provides.value();
6✔
95
        if (provides.find("artifact_name") == provides.end()) {
12✔
96
                return MakeError(InvalidDataError, "Missing artifact name data");
×
97
        }
98

99
        stringstream ss;
12✔
100
        ss << R"({"update_control_map":false,"device_provides":{)";
6✔
101
        ss << R"("device_type":")";
6✔
102
        ss << json::EscapeString(device_type);
12✔
103

104
        for (const auto &kv : provides) {
14✔
105
                ss << "\",\"" + json::EscapeString(kv.first) + "\":\"";
16✔
106
                ss << json::EscapeString(kv.second);
16✔
107
        }
108

109
        ss << R"("}})";
6✔
110

111
        string v2_payload = ss.str();
112
        http::BodyGenerator payload_gen = [v2_payload]() {
30✔
113
                return make_shared<io::StringReader>(v2_payload);
6✔
114
        };
12✔
115

116
        // TODO: APIRequest
117
        auto v2_req = make_shared<http::OutgoingRequest>();
118
        v2_req->SetAddress(http::JoinUrl(server_url, check_updates_v2_uri));
18✔
119
        v2_req->SetMethod(http::Method::POST);
6✔
120
        v2_req->SetHeader("Content-Type", "application/json");
18✔
121
        v2_req->SetHeader("Content-Length", to_string(v2_payload.size()));
12✔
122
        v2_req->SetHeader("Accept", "application/json");
18✔
123
        v2_req->SetBodyGenerator(payload_gen);
6✔
124

125
        string v1_args = "artifact_name=" + http::URLEncode(provides["artifact_name"])
18✔
126
                                         + "&device_type=" + http::URLEncode(device_type);
24✔
127
        auto v1_req = make_shared<http::OutgoingRequest>();
128
        v1_req->SetAddress(http::JoinUrl(server_url, check_updates_v1_uri) + "?" + v1_args);
18✔
129
        v1_req->SetMethod(http::Method::GET);
6✔
130
        v1_req->SetHeader("Accept", "application/json");
18✔
131

132
        auto received_body = make_shared<vector<uint8_t>>();
133
        auto handle_data = [received_body, api_handler](unsigned status) {
4✔
134
                if (status == http::StatusOK) {
4✔
135
                        auto ex_j = json::Load(common::StringFromByteVector(*received_body));
4✔
136
                        if (ex_j) {
2✔
137
                                CheckUpdatesAPIResponse response {optional<json::Json> {ex_j.value()}};
4✔
138
                                api_handler(response);
2✔
139
                        } else {
140
                                api_handler(expected::unexpected(ex_j.error()));
×
141
                        }
142
                } else if (status == http::StatusNoContent) {
2✔
143
                        api_handler(CheckUpdatesAPIResponse {nullopt});
2✔
144
                }
145
        };
16✔
146

147
        http::ResponseHandler header_handler =
148
                [received_body, api_handler](http::ExpectedIncomingResponsePtr exp_resp) {
9✔
149
                        if (!exp_resp) {
9✔
150
                                log::Error("Request to check new deployments failed: " + exp_resp.error().message);
×
151
                                CheckUpdatesAPIResponse response = expected::unexpected(exp_resp.error());
×
152
                                api_handler(response);
×
153
                                return;
154
                        }
155

156
                        auto resp = exp_resp.value();
9✔
157
                        received_body->clear();
158
                        auto body_writer = make_shared<io::ByteWriter>(received_body);
9✔
159
                        body_writer->SetUnlimited(true);
9✔
160
                        resp->SetBodyWriter(body_writer);
18✔
161
                };
12✔
162

163
        http::ResponseHandler v1_body_handler =
164
                [received_body, api_handler, handle_data](http::ExpectedIncomingResponsePtr exp_resp) {
3✔
165
                        if (!exp_resp) {
3✔
166
                                log::Error("Request to check new deployments failed: " + exp_resp.error().message);
×
167
                                CheckUpdatesAPIResponse response = expected::unexpected(exp_resp.error());
×
168
                                api_handler(response);
×
169
                                return;
170
                        }
171
                        auto resp = exp_resp.value();
3✔
172
                        auto status = resp->GetStatusCode();
3✔
173
                        if ((status == http::StatusOK) || (status == http::StatusNoContent)) {
3✔
174
                                handle_data(status);
2✔
175
                        } else {
176
                                auto ex_err_msg = api::ErrorMsgFromErrorResponse(*received_body);
1✔
177
                                string err_str;
178
                                if (ex_err_msg) {
1✔
179
                                        err_str = ex_err_msg.value();
×
180
                                } else {
181
                                        err_str = resp->GetStatusMessage();
2✔
182
                                }
183
                                api_handler(expected::unexpected(MakeError(
2✔
184
                                        BadResponseError,
185
                                        "Got unexpected response " + to_string(status) + ": " + err_str)));
3✔
186
                        }
187
                };
12✔
188

189
        http::ResponseHandler v2_body_handler = [received_body,
6✔
190
                                                                                         v1_req,
191
                                                                                         header_handler,
192
                                                                                         v1_body_handler,
193
                                                                                         api_handler,
194
                                                                                         handle_data,
195
                                                                                         &client](http::ExpectedIncomingResponsePtr exp_resp) {
3✔
196
                if (!exp_resp) {
6✔
197
                        log::Error("Request to check new deployments failed: " + exp_resp.error().message);
×
198
                        CheckUpdatesAPIResponse response = expected::unexpected(exp_resp.error());
×
199
                        api_handler(response);
×
200
                        return;
201
                }
202
                auto resp = exp_resp.value();
6✔
203
                auto status = resp->GetStatusCode();
6✔
204
                if ((status == http::StatusOK) || (status == http::StatusNoContent)) {
6✔
205
                        handle_data(status);
2✔
206
                } else if (status == http::StatusNotFound) {
4✔
207
                        log::Info(
3✔
208
                                "POST request to v2 version of the deployments API failed, falling back to v1 version and GET");
6✔
209
                        auto err = client.AsyncCall(v1_req, header_handler, v1_body_handler);
12✔
210
                        if (err != error::NoError) {
3✔
211
                                api_handler(expected::unexpected(err.WithContext("While calling v1 endpoint")));
×
212
                        }
213
                } else {
214
                        auto ex_err_msg = api::ErrorMsgFromErrorResponse(*received_body);
1✔
215
                        string err_str;
216
                        if (ex_err_msg) {
1✔
217
                                err_str = ex_err_msg.value();
1✔
218
                        } else {
219
                                err_str = resp->GetStatusMessage();
×
220
                        }
221
                        api_handler(expected::unexpected(MakeError(
2✔
222
                                BadResponseError,
223
                                "Got unexpected response " + to_string(status) + ": " + err_str)));
3✔
224
                }
225
        };
6✔
226

227
        return client.AsyncCall(v2_req, header_handler, v2_body_handler);
30✔
228
}
229

230
static const string deployment_status_strings[static_cast<int>(DeploymentStatus::End_) + 1] = {
231
        "installing",
232
        "pause_before_installing",
233
        "downloading",
234
        "pause_before_rebooting",
235
        "rebooting",
236
        "pause_before_committing",
237
        "success",
238
        "failure",
239
        "already-installed"};
240

241
static const string deployments_uri_prefix = "/api/devices/v1/deployments/device/deployments";
242
static const string status_uri_suffix = "/status";
243

244
string DeploymentStatusString(DeploymentStatus status) {
488✔
245
        return deployment_status_strings[static_cast<int>(status)];
488✔
246
}
247

248
error::Error DeploymentClient::PushStatus(
4✔
249
        const string &deployment_id,
250
        DeploymentStatus status,
251
        const string &substate,
252
        const string &server_url,
253
        http::Client &client,
254
        StatusAPIResponseHandler api_handler) {
255
        string payload = R"({"status":")" + DeploymentStatusString(status) + "\"";
8✔
256
        if (substate != "") {
4✔
257
                payload += R"(,"substate":")" + json::EscapeString(substate) + "\"}";
6✔
258
        } else {
259
                payload += "}";
260
        }
261
        http::BodyGenerator payload_gen = [payload]() {
20✔
262
                return make_shared<io::StringReader>(payload);
4✔
263
        };
8✔
264

265
        auto req = make_shared<http::OutgoingRequest>();
266
        req->SetAddress(
4✔
267
                http::JoinUrl(server_url, deployments_uri_prefix, deployment_id, status_uri_suffix));
8✔
268
        req->SetMethod(http::Method::PUT);
4✔
269
        req->SetHeader("Content-Type", "application/json");
12✔
270
        req->SetHeader("Content-Length", to_string(payload.size()));
8✔
271
        req->SetHeader("Accept", "application/json");
12✔
272
        req->SetBodyGenerator(payload_gen);
8✔
273

274
        auto received_body = make_shared<vector<uint8_t>>();
275
        return client.AsyncCall(
276
                req,
277
                [received_body, api_handler](http::ExpectedIncomingResponsePtr exp_resp) {
4✔
278
                        if (!exp_resp) {
4✔
279
                                log::Error("Request to push status data failed: " + exp_resp.error().message);
×
280
                                api_handler(exp_resp.error());
×
281
                                return;
×
282
                        }
283

284
                        auto body_writer = make_shared<io::ByteWriter>(received_body);
4✔
285
                        auto resp = exp_resp.value();
4✔
286
                        auto content_length = resp->GetHeader("Content-Length");
8✔
287
                        if (!content_length) {
4✔
288
                                log::Error(
×
289
                                        "Failed to get content length from the status API response headers: "
290
                                        + content_length.error().String());
×
291
                                body_writer->SetUnlimited(true);
×
292
                        } else {
293
                                auto ex_len = common::StringToLongLong(content_length.value());
4✔
294
                                if (!ex_len) {
4✔
295
                                        log::Error(
×
296
                                                "Failed to convert the content length from the status API response headers to an integer: "
297
                                                + ex_len.error().String());
×
298
                                        body_writer->SetUnlimited(true);
×
299
                                } else {
300
                                        received_body->resize(ex_len.value());
4✔
301
                                }
302
                        }
303
                        resp->SetBodyWriter(body_writer);
8✔
304
                },
305
                [received_body, api_handler](http::ExpectedIncomingResponsePtr exp_resp) {
4✔
306
                        if (!exp_resp) {
4✔
307
                                log::Error("Request to push status data failed: " + exp_resp.error().message);
×
308
                                api_handler(exp_resp.error());
×
309
                                return;
×
310
                        }
311

312
                        auto resp = exp_resp.value();
4✔
313
                        auto status = resp->GetStatusCode();
4✔
314
                        if (status == http::StatusNoContent) {
4✔
315
                                api_handler(error::NoError);
2✔
316
                        } else if (status == http::StatusConflict) {
2✔
317
                                api_handler(
318
                                        MakeError(DeploymentAbortedError, "Could not send status update to server"));
3✔
319
                        } else {
320
                                auto ex_err_msg = api::ErrorMsgFromErrorResponse(*received_body);
1✔
321
                                string err_str;
322
                                if (ex_err_msg) {
1✔
323
                                        err_str = ex_err_msg.value();
1✔
324
                                } else {
325
                                        err_str = resp->GetStatusMessage();
×
326
                                }
327
                                api_handler(MakeError(
1✔
328
                                        BadResponseError,
329
                                        "Got unexpected response " + to_string(status)
2✔
330
                                                + " from status API: " + err_str));
2✔
331
                        }
332
                });
28✔
333
}
334

335
using mender::common::expected::ExpectedSize;
336

337
static ExpectedSize GetLogFileDataSize(const string &path) {
3✔
338
        auto ex_istr = io::OpenIfstream(path);
3✔
339
        if (!ex_istr) {
3✔
340
                return expected::unexpected(ex_istr.error());
×
341
        }
342
        auto istr = std::move(ex_istr.value());
6✔
343

344
        // We want the size of the actual data without a potential trailing
345
        // newline. So let's seek one byte before the end of file, check if the last
346
        // byte is a newline and return the appropriate number.
347
        istr.seekg(-1, ios_base::end);
3✔
348
        char c = istr.get();
3✔
349
        if (c == '\n') {
3✔
350
                return istr.tellg() - static_cast<ifstream::off_type>(1);
3✔
351
        } else {
352
                return istr.tellg();
×
353
        }
354
}
355

356
const vector<uint8_t> JsonLogMessagesReader::header_ = {
357
        '{', '"', 'm', 'e', 's', 's', 'a', 'g', 'e', 's', '"', ':', '['};
358
const vector<uint8_t> JsonLogMessagesReader::closing_ = {']', '}'};
359

360
ExpectedSize JsonLogMessagesReader::Read(
89✔
361
        vector<uint8_t>::iterator start, vector<uint8_t>::iterator end) {
362
        if (header_rem_ > 0) {
89✔
363
                io::Vsize target_size = end - start;
9✔
364
                auto copy_end = copy_n(
365
                        header_.begin() + (header_.size() - header_rem_), min(header_rem_, target_size), start);
10✔
366
                auto n_copied = copy_end - start;
367
                header_rem_ -= n_copied;
9✔
368
                return static_cast<size_t>(n_copied);
369
        } else if (rem_raw_data_size_ > 0) {
80✔
370
                if (static_cast<size_t>(end - start) > rem_raw_data_size_) {
64✔
371
                        end = start + rem_raw_data_size_;
372
                }
373
                auto ex_sz = reader_->Read(start, end);
64✔
374
                if (!ex_sz) {
64✔
375
                        return ex_sz;
376
                }
377
                auto n_read = ex_sz.value();
64✔
378
                rem_raw_data_size_ -= n_read;
64✔
379

380
                // We control how much we read from the file so we should never read
381
                // 0 bytes (meaning EOF reached). If we do, it means the file is
382
                // smaller than what we were told.
383
                assert(n_read > 0);
384
                if (n_read == 0) {
64✔
385
                        return expected::unexpected(
×
386
                                MakeError(InvalidDataError, "Unexpected EOF when reading logs file"));
×
387
                }
388

389
                // Replace all newlines with commas
390
                const auto read_end = start + n_read;
391
                for (auto it = start; it < read_end; it++) {
1,916✔
392
                        if (it[0] == '\n') {
1,852✔
393
                                it[0] = ',';
12✔
394
                        }
395
                }
396
                return n_read;
397
        } else if (closing_rem_ > 0) {
16✔
398
                io::Vsize target_size = end - start;
8✔
399
                auto copy_end = copy_n(
400
                        closing_.begin() + (closing_.size() - closing_rem_),
8✔
401
                        min(closing_rem_, target_size),
8✔
402
                        start);
8✔
403
                auto n_copied = copy_end - start;
404
                closing_rem_ -= n_copied;
8✔
405
                return static_cast<size_t>(copy_end - start);
406
        } else {
407
                return 0;
408
        }
409
};
410

411
static const string logs_uri_suffix = "/log";
412

413
error::Error DeploymentClient::PushLogs(
3✔
414
        const string &deployment_id,
415
        const string &log_file_path,
416
        const string &server_url,
417
        http::Client &client,
418
        LogsAPIResponseHandler api_handler) {
419
        auto ex_size = GetLogFileDataSize(log_file_path);
3✔
420
        if (!ex_size) {
3✔
421
                // api_handler(ex_size.error()) ???
422
                return ex_size.error();
423
        }
424
        auto data_size = ex_size.value();
3✔
425

426
        auto file_reader = make_shared<io::FileReader>(log_file_path);
427
        auto logs_reader = make_shared<JsonLogMessagesReader>(file_reader, data_size);
428

429
        auto req = make_shared<http::OutgoingRequest>();
430
        req->SetAddress(
3✔
431
                http::JoinUrl(server_url, deployments_uri_prefix, deployment_id, logs_uri_suffix));
6✔
432
        req->SetMethod(http::Method::PUT);
3✔
433
        req->SetHeader("Content-Type", "application/json");
9✔
434
        req->SetHeader("Content-Length", to_string(JsonLogMessagesReader::TotalDataSize(data_size)));
6✔
435
        req->SetHeader("Accept", "application/json");
9✔
436
        req->SetBodyGenerator([logs_reader]() {
12✔
437
                logs_reader->Rewind();
6✔
438
                return logs_reader;
3✔
439
        });
6✔
440

441
        auto received_body = make_shared<vector<uint8_t>>();
442
        return client.AsyncCall(
443
                req,
444
                [received_body, api_handler](http::ExpectedIncomingResponsePtr exp_resp) {
3✔
445
                        if (!exp_resp) {
3✔
446
                                log::Error("Request to push logs data failed: " + exp_resp.error().message);
×
447
                                api_handler(exp_resp.error());
×
448
                                return;
×
449
                        }
450

451
                        auto body_writer = make_shared<io::ByteWriter>(received_body);
3✔
452
                        auto resp = exp_resp.value();
3✔
453
                        auto content_length = resp->GetHeader("Content-Length");
6✔
454
                        if (!content_length) {
3✔
455
                                log::Error(
×
456
                                        "Failed to get content length from the status API response headers: "
457
                                        + content_length.error().String());
×
458
                                body_writer->SetUnlimited(true);
×
459
                        } else {
460
                                auto ex_len = common::StringToLongLong(content_length.value());
3✔
461
                                if (!ex_len) {
3✔
462
                                        log::Error(
×
463
                                                "Failed to convert the content length from the status API response headers to an integer: "
464
                                                + ex_len.error().String());
×
465
                                        body_writer->SetUnlimited(true);
×
466
                                } else {
467
                                        received_body->resize(ex_len.value());
3✔
468
                                }
469
                        }
470
                        resp->SetBodyWriter(body_writer);
6✔
471
                },
472
                [received_body, api_handler](http::ExpectedIncomingResponsePtr exp_resp) {
3✔
473
                        if (!exp_resp) {
3✔
474
                                log::Error("Request to push logs data failed: " + exp_resp.error().message);
×
475
                                api_handler(exp_resp.error());
×
476
                                return;
×
477
                        }
478

479
                        auto resp = exp_resp.value();
3✔
480
                        auto status = resp->GetStatusCode();
3✔
481
                        if (status == http::StatusNoContent) {
3✔
482
                                api_handler(error::NoError);
2✔
483
                        } else {
484
                                auto ex_err_msg = api::ErrorMsgFromErrorResponse(*received_body);
1✔
485
                                string err_str;
486
                                if (ex_err_msg) {
1✔
487
                                        err_str = ex_err_msg.value();
1✔
488
                                } else {
489
                                        err_str = resp->GetStatusMessage();
×
490
                                }
491
                                api_handler(MakeError(
1✔
492
                                        BadResponseError,
493
                                        "Got unexpected response " + to_string(status) + " from logs API: " + err_str));
2✔
494
                        }
495
                });
18✔
496
}
497

498
} // namespace deployments
499
} // namespace update
500
} // 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