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

mendersoftware / mender / 1033353997

11 Oct 2023 01:43PM UTC coverage: 79.99% (-0.2%) from 80.166%
1033353997

push

gitlab-ci

oleorhagen
style: Run clang-format on the whole repository

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

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

6492 of 8116 relevant lines covered (79.99%)

9901.24 hits per line

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

78.82
/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();
2✔
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"({"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]() {
36✔
113
                return make_shared<io::StringReader>(v2_payload);
6✔
114
        };
6✔
115

116
        // TODO: APIRequest
117
        auto v2_req = make_shared<http::OutgoingRequest>();
6✔
118
        v2_req->SetAddress(http::JoinUrl(server_url, check_updates_v2_uri));
12✔
119
        v2_req->SetMethod(http::Method::POST);
6✔
120
        v2_req->SetHeader("Content-Type", "application/json");
12✔
121
        v2_req->SetHeader("Content-Length", to_string(v2_payload.size()));
12✔
122
        v2_req->SetHeader("Accept", "application/json");
12✔
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);
18✔
127
        auto v1_req = make_shared<http::OutgoingRequest>();
6✔
128
        v1_req->SetAddress(http::JoinUrl(server_url, check_updates_v1_uri) + "?" + v1_args);
12✔
129
        v1_req->SetMethod(http::Method::GET);
6✔
130
        v1_req->SetHeader("Accept", "application/json");
12✔
131

132
        auto received_body = make_shared<vector<uint8_t>>();
6✔
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()}};
2✔
138
                                api_handler(response);
4✔
139
                        } else {
140
                                api_handler(expected::unexpected(ex_j.error()));
×
141
                        }
142
                } else if (status == http::StatusNoContent) {
2✔
143
                        api_handler(CheckUpdatesAPIResponse {nullopt});
4✔
144
                } else {
145
                        log::Warning(
×
146
                                "DeploymentClient::CheckNewDeployments - received unhandled http response: "
147
                                + to_string(status));
×
148
                        api_handler(expected::unexpected(MakeError(
×
149
                                DeploymentAbortedError, "received unhandled HTTP response: " + to_string(status))));
×
150
                }
151
        };
16✔
152

153
        http::ResponseHandler header_handler =
154
                [received_body, api_handler](http::ExpectedIncomingResponsePtr exp_resp) {
9✔
155
                        if (!exp_resp) {
9✔
156
                                log::Error("Request to check new deployments failed: " + exp_resp.error().message);
×
157
                                CheckUpdatesAPIResponse response = expected::unexpected(exp_resp.error());
×
158
                                api_handler(response);
×
159
                                return;
160
                        }
161

162
                        auto resp = exp_resp.value();
9✔
163
                        received_body->clear();
9✔
164
                        auto body_writer = make_shared<io::ByteWriter>(received_body);
9✔
165
                        body_writer->SetUnlimited(true);
9✔
166
                        resp->SetBodyWriter(body_writer);
18✔
167
                };
12✔
168

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

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

233
        return client.AsyncCall(v2_req, header_handler, v2_body_handler);
18✔
234
}
235

236
static const string deployment_status_strings[static_cast<int>(DeploymentStatus::End_) + 1] = {
237
        "installing",
238
        "pause_before_installing",
239
        "downloading",
240
        "pause_before_rebooting",
241
        "rebooting",
242
        "pause_before_committing",
243
        "success",
244
        "failure",
245
        "already-installed"};
246

247
static const string deployments_uri_prefix = "/api/devices/v1/deployments/device/deployments";
248
static const string status_uri_suffix = "/status";
249

250
string DeploymentStatusString(DeploymentStatus status) {
494✔
251
        return deployment_status_strings[static_cast<int>(status)];
494✔
252
}
253

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

271
        auto req = make_shared<http::OutgoingRequest>();
4✔
272
        req->SetAddress(
4✔
273
                http::JoinUrl(server_url, deployments_uri_prefix, deployment_id, status_uri_suffix));
8✔
274
        req->SetMethod(http::Method::PUT);
4✔
275
        req->SetHeader("Content-Type", "application/json");
8✔
276
        req->SetHeader("Content-Length", to_string(payload.size()));
8✔
277
        req->SetHeader("Accept", "application/json");
8✔
278
        req->SetBodyGenerator(payload_gen);
4✔
279

280
        auto received_body = make_shared<vector<uint8_t>>();
4✔
281
        return client.AsyncCall(
282
                req,
283
                [received_body, api_handler](http::ExpectedIncomingResponsePtr exp_resp) {
4✔
284
                        if (!exp_resp) {
4✔
285
                                log::Error("Request to push status data failed: " + exp_resp.error().message);
×
286
                                api_handler(exp_resp.error());
×
287
                                return;
×
288
                        }
289

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

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

340
using mender::common::expected::ExpectedSize;
341

342
static ExpectedSize GetLogFileDataSize(const string &path) {
3✔
343
        auto ex_istr = io::OpenIfstream(path);
3✔
344
        if (!ex_istr) {
3✔
345
                return expected::unexpected(ex_istr.error());
×
346
        }
347
        auto istr = std::move(ex_istr.value());
6✔
348

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

361
const vector<uint8_t> JsonLogMessagesReader::header_ = {
362
        '{', '"', 'm', 'e', 's', 's', 'a', 'g', 'e', 's', '"', ':', '['};
363
const vector<uint8_t> JsonLogMessagesReader::closing_ = {']', '}'};
364

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

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

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

416
static const string logs_uri_suffix = "/log";
417

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

431
        auto file_reader = make_shared<io::FileReader>(log_file_path);
3✔
432
        auto logs_reader = make_shared<JsonLogMessagesReader>(file_reader, data_size);
3✔
433

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

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

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

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

502
} // namespace deployments
503
} // namespace update
504
} // 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