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

mendersoftware / mender / 1039476627

17 Oct 2023 10:49AM UTC coverage: 79.701% (-0.6%) from 80.278%
1039476627

push

gitlab-ci

oleorhagen
fix(mender-auth): Remember to pass in the needed params

Just add the missing identity script, and private key params.

Ticket: MEN-6671
Changelog: None

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

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

6557 of 8227 relevant lines covered (79.7%)

9764.5 hits per line

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

78.57
/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 <api/client.hpp>
23
#include <common/common.hpp>
24
#include <common/error.hpp>
25
#include <common/events.hpp>
26
#include <common/expected.hpp>
27
#include <common/http.hpp>
28
#include <common/io.hpp>
29
#include <common/json.hpp>
30
#include <common/log.hpp>
31
#include <common/optional.hpp>
32
#include <common/path.hpp>
33
#include <mender-update/context.hpp>
34

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

39
using namespace std;
40

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

52
const DeploymentsErrorCategoryClass DeploymentsErrorCategory;
53

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

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

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

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

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

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

97
        stringstream ss;
12✔
98
        ss << R"({"device_provides":{)";
6✔
99
        ss << R"("device_type":")";
6✔
100
        ss << json::EscapeString(device_type);
12✔
101

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

107
        ss << R"("}})";
6✔
108

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

114
        auto v2_req = make_shared<api::APIRequest>();
6✔
115
        v2_req->SetPath(check_updates_v2_uri);
116
        v2_req->SetMethod(http::Method::POST);
6✔
117
        v2_req->SetHeader("Content-Type", "application/json");
12✔
118
        v2_req->SetHeader("Content-Length", to_string(v2_payload.size()));
12✔
119
        v2_req->SetHeader("Accept", "application/json");
12✔
120
        v2_req->SetBodyGenerator(payload_gen);
6✔
121

122
        string v1_args = "artifact_name=" + http::URLEncode(provides["artifact_name"])
18✔
123
                                         + "&device_type=" + http::URLEncode(device_type);
18✔
124
        auto v1_req = make_shared<api::APIRequest>();
6✔
125
        v1_req->SetPath(check_updates_v1_uri + "?" + v1_args);
12✔
126
        v1_req->SetMethod(http::Method::GET);
6✔
127
        v1_req->SetHeader("Accept", "application/json");
12✔
128

129
        auto received_body = make_shared<vector<uint8_t>>();
6✔
130
        auto handle_data = [received_body, api_handler](unsigned status) {
4✔
131
                if (status == http::StatusOK) {
4✔
132
                        auto ex_j = json::Load(common::StringFromByteVector(*received_body));
4✔
133
                        if (ex_j) {
2✔
134
                                CheckUpdatesAPIResponse response {optional<json::Json> {ex_j.value()}};
2✔
135
                                api_handler(response);
4✔
136
                        } else {
137
                                api_handler(expected::unexpected(ex_j.error()));
×
138
                        }
139
                } else if (status == http::StatusNoContent) {
2✔
140
                        api_handler(CheckUpdatesAPIResponse {nullopt});
4✔
141
                } else {
142
                        log::Warning(
×
143
                                "DeploymentClient::CheckNewDeployments - received unhandled http response: "
144
                                + to_string(status));
×
145
                        api_handler(expected::unexpected(MakeError(
×
146
                                DeploymentAbortedError, "received unhandled HTTP response: " + to_string(status))));
×
147
                }
148
        };
16✔
149

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

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

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

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

230
        return client.AsyncCall(v2_req, header_handler, v2_body_handler);
18✔
231
}
232

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

244
static const string deployments_uri_prefix = "/api/devices/v1/deployments/device/deployments";
245
static const string status_uri_suffix = "/status";
246

247
string DeploymentStatusString(DeploymentStatus status) {
494✔
248
        return deployment_status_strings[static_cast<int>(status)];
494✔
249
}
250

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

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

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

285
                        auto body_writer = make_shared<io::ByteWriter>(received_body);
4✔
286
                        auto resp = exp_resp.value();
4✔
287
                        auto content_length = resp->GetHeader("Content-Length");
8✔
288
                        if (!content_length) {
4✔
289
                                log::Debug(
×
290
                                        "Failed to get content length from the status API response headers: "
291
                                        + content_length.error().String());
×
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);
4✔
316
                        } else if (status == http::StatusConflict) {
2✔
317
                                api_handler(
1✔
318
                                        MakeError(DeploymentAbortedError, "Could not send status update to server"));
2✔
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(
2✔
328
                                        BadResponseError,
329
                                        "Got unexpected response " + to_string(status)
2✔
330
                                                + " from status API: " + err_str));
2✔
331
                        }
332
                });
20✔
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
        api::Client &client,
417
        LogsAPIResponseHandler api_handler) {
418
        auto ex_size = GetLogFileDataSize(log_file_path);
3✔
419
        if (!ex_size) {
3✔
420
                // api_handler(ex_size.error()) ???
421
                return ex_size.error();
×
422
        }
423
        auto data_size = ex_size.value();
3✔
424

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

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

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

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

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

495
} // namespace deployments
496
} // namespace update
497
} // 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