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

mendersoftware / mender / 2434577541

07 Apr 2026 01:24PM UTC coverage: 75.855% (+0.02%) from 75.834%
2434577541

push

gitlab-ci

web-flow
Merge pull request #1932 from vpodzime/5.0.x-renovate_mender-artifact

[5.0.x] ci: Add renovate CI job for updating mender-artifact version

7559 of 9965 relevant lines covered (75.86%)

14327.65 hits per line

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

79.6
/src/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 http = mender::common::http;
48
namespace io = mender::common::io;
49
namespace json = mender::common::json;
50
namespace log = mender::common::log;
51
namespace path = mender::common::path;
52

53
using ExpectedOffset = expected::expected<ifstream::off_type, error::Error>;
54

55
const DeploymentsErrorCategoryClass DeploymentsErrorCategory;
56

57
const char *DeploymentsErrorCategoryClass::name() const noexcept {
×
58
        return "DeploymentsErrorCategory";
×
59
}
60

61
string DeploymentsErrorCategoryClass::message(int code) const {
3✔
62
        switch (code) {
3✔
63
        case NoError:
64
                return "Success";
×
65
        case InvalidDataError:
66
                return "Invalid data error";
×
67
        case BadResponseError:
68
                return "Bad response error";
×
69
        case DeploymentAbortedError:
70
                return "Deployment was aborted on the server";
3✔
71
        case TooManyRequestsError:
72
                return "Too many requests";
×
73
        case RequestBodyTooLargeError:
74
                return "Request body too large";
×
75
        }
76
        assert(false);
77
        return "Unknown";
×
78
}
79

80
error::Error MakeError(DeploymentsErrorCode code, const string &msg) {
53✔
81
        return error::Error(error_condition(code, DeploymentsErrorCategory), msg);
59✔
82
}
83

84
static const string check_updates_v1_uri = "/api/devices/v1/deployments/device/deployments/next";
85
static const string check_updates_v2_uri = "/api/devices/v2/deployments/device/deployments/next";
86

87
error::Error DeploymentClient::CheckNewDeployments(
7✔
88
        context::MenderContext &ctx, api::Client &client, CheckUpdatesAPIResponseHandler api_handler) {
89
        auto ex_dev_type = ctx.GetDeviceType();
7✔
90
        if (!ex_dev_type) {
7✔
91
                return ex_dev_type.error();
1✔
92
        }
93
        string device_type = ex_dev_type.value();
6✔
94

95
        auto ex_provides = ctx.LoadProvides();
6✔
96
        if (!ex_provides) {
6✔
97
                return ex_provides.error();
×
98
        }
99
        auto provides = ex_provides.value();
6✔
100
        if (provides.find("artifact_name") == provides.end()) {
12✔
101
                return MakeError(InvalidDataError, "Missing artifact name data");
×
102
        }
103

104
        stringstream ss;
12✔
105
        ss << R"({"device_provides":{)";
6✔
106
        ss << R"("device_type":")";
6✔
107
        ss << json::EscapeString(device_type);
12✔
108

109
        for (const auto &kv : provides) {
14✔
110
                ss << "\",\"" + json::EscapeString(kv.first) + "\":\"";
16✔
111
                ss << json::EscapeString(kv.second);
16✔
112
        }
113

114
        ss << R"("}})";
6✔
115

116
        string v2_payload = ss.str();
117
        log::Debug("deployments/next v2 payload " + v2_payload);
6✔
118
        http::BodyGenerator payload_gen = [v2_payload]() {
48✔
119
                return make_shared<io::StringReader>(v2_payload);
6✔
120
        };
6✔
121

122
        auto v2_req = make_shared<api::APIRequest>();
6✔
123
        v2_req->SetPath(check_updates_v2_uri);
124
        v2_req->SetMethod(http::Method::POST);
6✔
125
        v2_req->SetHeader("Content-Type", "application/json");
12✔
126
        v2_req->SetHeader("Content-Length", to_string(v2_payload.size()));
12✔
127
        v2_req->SetHeader("Accept", "application/json");
12✔
128
        v2_req->SetBodyGenerator(payload_gen);
6✔
129

130
        string v1_args = "artifact_name=" + http::URLEncode(provides["artifact_name"])
18✔
131
                                         + "&device_type=" + http::URLEncode(device_type);
18✔
132
        auto v1_req = make_shared<api::APIRequest>();
6✔
133
        v1_req->SetPath(check_updates_v1_uri + "?" + v1_args);
12✔
134
        v1_req->SetMethod(http::Method::GET);
6✔
135
        v1_req->SetHeader("Accept", "application/json");
12✔
136

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

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

167
                        auto resp = exp_resp.value();
9✔
168
                        received_body->clear();
9✔
169
                        auto body_writer = make_shared<io::ByteWriter>(received_body);
9✔
170
                        body_writer->SetUnlimited(true);
9✔
171
                        resp->SetBodyWriter(body_writer);
18✔
172
                };
12✔
173

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

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

238
        return client.AsyncCall(v2_req, header_handler, v2_body_handler);
18✔
239
}
240

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

252
static const string deployments_uri_prefix = "/api/devices/v1/deployments/device/deployments";
253
static const string status_uri_suffix = "/status";
254

255
string DeploymentStatusString(DeploymentStatus status) {
501✔
256
        return deployment_status_strings[static_cast<int>(status)];
505✔
257
}
258

259
error::Error DeploymentClient::PushStatus(
4✔
260
        const string &deployment_id,
261
        DeploymentStatus status,
262
        const string &substate,
263
        api::Client &client,
264
        StatusAPIResponseHandler api_handler) {
265
        // Cannot push a status update without a deployment ID
266
        AssertOrReturnError(deployment_id != "");
4✔
267
        string payload = R"({"status":")" + DeploymentStatusString(status) + "\"";
8✔
268
        if (substate != "") {
4✔
269
                payload += R"(,"substate":")" + json::EscapeString(substate) + "\"}";
6✔
270
        } else {
271
                payload += "}";
1✔
272
        }
273
        http::BodyGenerator payload_gen = [payload]() {
32✔
274
                return make_shared<io::StringReader>(payload);
4✔
275
        };
4✔
276

277
        auto req = make_shared<api::APIRequest>();
4✔
278
        req->SetPath(http::JoinUrl(deployments_uri_prefix, deployment_id, status_uri_suffix));
8✔
279
        req->SetMethod(http::Method::PUT);
4✔
280
        req->SetHeader("Content-Type", "application/json");
8✔
281
        req->SetHeader("Content-Length", to_string(payload.size()));
8✔
282
        req->SetHeader("Accept", "application/json");
8✔
283
        req->SetBodyGenerator(payload_gen);
4✔
284

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

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

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

346
using mender::common::expected::ExpectedSize;
347

348
static ExpectedSize GetLogFileDataSize(const string &path) {
23✔
349
        auto ex_istr = io::OpenIfstream(path);
23✔
350
        if (!ex_istr) {
23✔
351
                return expected::unexpected(ex_istr.error());
×
352
        }
353
        auto istr = std::move(ex_istr.value());
46✔
354

355
        // We want the size of the actual data without a potential trailing
356
        // comma. So let's seek one byte before the end of file, check if the last
357
        // byte is a comma and return the appropriate number.
358
        istr.seekg(-1, ios_base::end);
23✔
359
        int c = istr.get();
23✔
360
        if (c == ',') {
23✔
361
                return istr.tellg() - static_cast<ifstream::off_type>(1);
23✔
362
        } else {
363
                return istr.tellg();
×
364
        }
365
}
366

367
// Find the beginning of the next log message JSON after offset
368
static ExpectedOffset FindNextMsgAfter(const string &path, ifstream::off_type offset) {
1✔
369
        auto ex_is = io::OpenIfstream(path);
1✔
370
        if (!ex_is) {
1✔
371
                return expected::unexpected(ex_is.error());
×
372
        }
373
        auto is = std::move(ex_is.value());
2✔
374
        is.seekg(offset);
1✔
375
        int io_errno = errno;
1✔
376
        if (!is) {
1✔
377
                return expected::unexpected(error::Error(
×
378
                        generic_category().default_error_condition(io_errno),
×
379
                        "Failed to seek to truncated logs offset in '" + path + "'"));
×
380
        }
381

382
        // Now that we have seeked to the starting offset, we need to find the next
383
        // boundary between JSON log entries.
384
        const string pattern = R"(},{"timestamp")";
1✔
385
        string buf(1024, '\0');
386
        while (is.read(buf.data(), 1024)) {
1✔
387
                // make sure we don't work with some stale data from the previous read()
388
                buf.resize(is.gcount());
1✔
389

390
                // XXX: This is not perfect as it can fail to find the next boundary if
391
                //      it's split between the end of the current buffer contents and
392
                //      the start of the next chunk read from the file. However, with a
393
                //      1K buffer, this is very unlikely to happen and even if it does
394
                //      happen, the logs will just be trimmed a bit more than
395
                //      necessary. For the sake of incomparably simpler code that is
396
                //      easy to test.
397
                auto pos = buf.find(pattern);
1✔
398
                if (pos != string::npos) {
1✔
399
                        offset += pos + 2; // skip "},"
1✔
400
                        break;
1✔
401
                }
402
                offset += buf.size();
×
403
        }
404
        io_errno = errno;
1✔
405
        if (!is && !is.eof()) {
1✔
406
                return expected::unexpected(error::Error(
×
407
                        generic_category().default_error_condition(io_errno),
×
408
                        "Failed to read logs from '" + path + "'"));
×
409
        }
410

411
        // In case we read the whole rest of the file not finding the next JSON log
412
        // entry, there must be something really wrong with the log and it should be
413
        // fully skipped. The user will still get the information that the log was
414
        // truncated and they will still have the full log on the device.
415
        return offset;
416
}
417

418
const vector<uint8_t> JsonLogMessagesReader::header_ = {
419
        '{', '"', 'm', 'e', 's', 's', 'a', 'g', 'e', 's', '"', ':', '['};
420
const vector<uint8_t> JsonLogMessagesReader::closing_ = {']', '}'};
421
const string JsonLogMessagesReader::default_tstamp_ = "1970-01-01T00:00:00.000000000Z";
422
const string JsonLogMessagesReader::bad_data_msg_tmpl_ =
423
        R"d({"timestamp": "1970-01-01T00:00:00.000000000Z", "level": "ERROR", "message": "(THE ORIGINAL LOGS CONTAINED INVALID ENTRIES)"},)d";
424
const string JsonLogMessagesReader::too_much_data_msg_tmpl_ =
425
        R"d({"timestamp": "1970-01-01T00:00:00.000000000Z", "level": "WARNING", "message": "(THE ORIGINAL LOGS WERE TOO BIG, THIS LOG IS TRUNCATED. The full log can be found on the device)"},)d";
426

427
JsonLogMessagesReader::~JsonLogMessagesReader() {
54✔
428
        reader_.reset();
429
        if (!sanitized_fpath_.empty() && path::FileExists(sanitized_fpath_)) {
18✔
430
                auto del_err = path::FileDelete(sanitized_fpath_);
18✔
431
                if (del_err != error::NoError) {
18✔
432
                        log::Error("Failed to delete auxiliary logs file: " + del_err.String());
×
433
                }
434
        }
435
        sanitized_fpath_.erase();
18✔
436
}
18✔
437

438
static error::Error DoSanitizeLogs(
23✔
439
        const string &orig_path, const string &new_path, bool &all_valid, string &first_tstamp) {
440
        auto ex_ifs = io::OpenIfstream(orig_path);
23✔
441
        if (!ex_ifs) {
23✔
442
                return ex_ifs.error();
×
443
        }
444
        auto ex_ofs = io::OpenOfstream(new_path);
23✔
445
        if (!ex_ofs) {
23✔
446
                return ex_ofs.error();
×
447
        }
448
        auto &ifs = ex_ifs.value();
23✔
449
        auto &ofs = ex_ofs.value();
23✔
450

451
        string last_known_tstamp = first_tstamp;
23✔
452
        const string tstamp_prefix_data = R"d({"timestamp": ")d";
23✔
453
        const string corrupt_msg_suffix_data =
454
                R"d(", "level": "ERROR", "message": "(CORRUPTED LOG DATA)"},)d";
23✔
455

456
        string line;
457
        first_tstamp.erase();
23✔
458
        all_valid = true;
23✔
459
        error::Error err;
23✔
460
        while (!ifs.eof()) {
20,109✔
461
                getline(ifs, line);
20,086✔
462
                if (!ifs.eof() && !ifs) {
20,086✔
463
                        int io_errno = errno;
×
464
                        return error::Error(
465
                                generic_category().default_error_condition(io_errno),
×
466
                                "Failed to get line from deployment logs file '" + orig_path
×
467
                                        + "': " + strerror(io_errno));
×
468
                }
469
                if (line.empty()) {
20,086✔
470
                        // skip empty lines
471
                        continue;
23✔
472
                }
473
                auto ex_json = json::Load(line);
40,126✔
474
                if (ex_json) {
20,063✔
475
                        // valid JSON log line, just replace the newline after it with a comma and save the
476
                        // timestamp for later
477
                        auto ex_tstamp = ex_json.value().Get("timestamp").and_then(json::ToString);
40,100✔
478
                        if (ex_tstamp) {
20,050✔
479
                                if (first_tstamp.empty()) {
20,050✔
480
                                        first_tstamp = ex_tstamp.value();
22✔
481
                                }
482
                                last_known_tstamp = std::move(ex_tstamp.value());
20,050✔
483
                        }
484
                        line.append(1, ',');
20,050✔
485
                        err = io::WriteStringIntoOfstream(ofs, line);
20,050✔
486
                        if (err != error::NoError) {
20,050✔
487
                                return err.WithContext("Failed to write pre-processed deployment logs data");
×
488
                        }
489
                } else {
490
                        all_valid = false;
13✔
491
                        if (first_tstamp.empty()) {
13✔
492
                                // If we still don't have the first valid tstamp, we need to
493
                                // save the last known one (potentially pre-set) as the first
494
                                // one.
495
                                first_tstamp = last_known_tstamp;
496
                        }
497
                        err = io::WriteStringIntoOfstream(
13✔
498
                                ofs, tstamp_prefix_data + last_known_tstamp + corrupt_msg_suffix_data);
26✔
499
                        if (err != error::NoError) {
13✔
500
                                return err.WithContext("Failed to write pre-processed deployment logs data");
×
501
                        }
502
                }
503
        }
504
        return error::NoError;
23✔
505
}
506

507
static void ReplaceTimestampInMsgData(
10✔
508
        vector<uint8_t> &msg_data, string &timestamp, size_t default_tstamp_size) {
509
        auto msg_data_tstamp_start = msg_data.begin() + 15; // len(R"({"timestamp": ")")
510

511
        // The actual timestamp from logs can potentially have a different
512
        // (likely lower) time resolution and thus length than our default.
513
        const auto timestamp_size = timestamp.size();
514
        if (timestamp_size > default_tstamp_size) {
10✔
515
                // In case the time resolution is higher and the timestamp
516
                // longer (unlikely to happen)
517
                if (timestamp[timestamp_size - 1] == 'Z') {
1✔
518
                        timestamp[default_tstamp_size - 1] = 'Z';
1✔
519
                }
520
                timestamp.resize(default_tstamp_size);
1✔
521
        }
522
        copy_n(timestamp.cbegin(), timestamp.size(), msg_data_tstamp_start);
10✔
523
        if (timestamp.size() < default_tstamp_size) {
10✔
524
                // Add a closing '"' right after the timestamp and fill in the
525
                // rest of the space in the template with spaces that have no
526
                // effect in JSON.
527
                msg_data_tstamp_start[timestamp.size()] = '"';
1✔
528
                for (auto it = msg_data_tstamp_start + timestamp.size() + 1;
529
                         it < msg_data_tstamp_start + default_tstamp_size + 1;
4✔
530
                         it++) {
531
                        *it = ' ';
3✔
532
                }
533
        }
534
}
10✔
535

536
error::Error JsonLogMessagesReader::SanitizeLogs() {
23✔
537
        if (!sanitized_fpath_.empty()) {
23✔
538
                return error::NoError;
×
539
        }
540

541
        string prep_fpath = log_fpath_ + ".sanitized";
23✔
542
        string first_tstamp = default_tstamp_;
23✔
543
        auto err = DoSanitizeLogs(log_fpath_, prep_fpath, clean_logs_, first_tstamp);
23✔
544
        if (err != error::NoError) {
23✔
545
                if (path::FileExists(prep_fpath)) {
×
546
                        auto del_err = path::FileDelete(prep_fpath);
×
547
                        if (del_err != error::NoError) {
×
548
                                log::Error("Failed to delete auxiliary logs file: " + del_err.String());
×
549
                        }
550
                }
551
        } else {
552
                sanitized_fpath_ = std::move(prep_fpath);
23✔
553
                reader_ = make_unique<io::FileReader>(sanitized_fpath_);
46✔
554
                auto ex_sz = GetLogFileDataSize(sanitized_fpath_);
23✔
555
                if (!ex_sz) {
23✔
556
                        return ex_sz.error().WithContext("Failed to determine deployment logs size");
×
557
                }
558

559
                raw_data_size_ = ex_sz.value();
23✔
560
                if (raw_data_size_ > maximum_log_size_) {
23✔
561
                        large_logs_ = true;
1✔
562
                        // Make sure we end up with less data than the limit with all the
563
                        // potential extra messages added in JsonLogMessagesReader::Read()
564
                        // below.
565
                        auto ex_off = FindNextMsgAfter(
566
                                sanitized_fpath_,
567
                                (raw_data_size_ + too_much_data_msg_tmpl_.size() + bad_data_msg_tmpl_.size()
1✔
568
                                 - maximum_log_size_));
1✔
569
                        if (!ex_off) {
1✔
570
                                return ex_off.error().WithContext(
571
                                        "Failed to determine start offset in too large deployment logs");
×
572
                        }
573
                        reader_ = make_unique<io::FileReader>(sanitized_fpath_, ex_off.value());
2✔
574
                        raw_data_size_ -= ex_off.value();
1✔
575
                }
576
                rem_raw_data_size_ = raw_data_size_;
23✔
577
                if (!clean_logs_) {
23✔
578
                        ReplaceTimestampInMsgData(bad_data_msg_, first_tstamp, default_tstamp_.size());
9✔
579
                }
580
                if (large_logs_) {
23✔
581
                        ReplaceTimestampInMsgData(too_much_data_msg_, first_tstamp, default_tstamp_.size());
1✔
582
                }
583
        }
584
        return err;
23✔
585
}
586

587
error::Error JsonLogMessagesReader::Rewind() {
5✔
588
        AssertOrReturnError(!sanitized_fpath_.empty());
5✔
589
        header_rem_ = header_.size();
5✔
590
        closing_rem_ = closing_.size();
5✔
591
        bad_data_msg_rem_ = bad_data_msg_.size();
5✔
592
        too_much_data_msg_rem_ = too_much_data_msg_.size();
5✔
593

594
        // release/close the file first so that the FileDelete() below can actually
595
        // delete it and free space up
596
        reader_.reset();
597
        auto del_err = path::FileDelete(sanitized_fpath_);
5✔
598
        if (del_err != error::NoError) {
5✔
599
                log::Error("Failed to delete auxiliary logs file: " + del_err.String());
2✔
600
        }
601
        sanitized_fpath_.erase();
5✔
602
        return SanitizeLogs();
5✔
603
}
604

605
int64_t JsonLogMessagesReader::TotalDataSize() {
18✔
606
        assert(!sanitized_fpath_.empty());
607

608
        auto ret = raw_data_size_ + header_.size() + closing_.size();
18✔
609
        if (!clean_logs_) {
18✔
610
                ret += bad_data_msg_.size();
9✔
611
        }
612
        if (large_logs_) {
18✔
613
                ret += too_much_data_msg_.size();
1✔
614
        }
615
        return ret;
18✔
616
}
617

618
ExpectedSize JsonLogMessagesReader::Read(
1,141✔
619
        vector<uint8_t>::iterator start, vector<uint8_t>::iterator end) {
620
        AssertOrReturnUnexpected(!sanitized_fpath_.empty());
1,141✔
621

622
        if (header_rem_ > 0) {
1,141✔
623
                io::Vsize target_size = end - start;
20✔
624
                auto copy_end = copy_n(
625
                        header_.begin() + (header_.size() - header_rem_), min(header_rem_, target_size), start);
21✔
626
                auto n_copied = copy_end - start;
627
                header_rem_ -= n_copied;
20✔
628
                return static_cast<size_t>(n_copied);
629
        } else if (large_logs_ && (too_much_data_msg_rem_ > 0)) {
1,121✔
630
                io::Vsize target_size = end - start;
1✔
631
                auto copy_end = copy_n(
632
                        too_much_data_msg_.begin() + (too_much_data_msg_.size() - too_much_data_msg_rem_),
1✔
633
                        min(too_much_data_msg_rem_, target_size),
1✔
634
                        start);
1✔
635
                auto n_copied = copy_end - start;
636
                too_much_data_msg_rem_ -= n_copied;
1✔
637
                return static_cast<size_t>(n_copied);
638
        } else if (!clean_logs_ && (bad_data_msg_rem_ > 0)) {
1,120✔
639
                io::Vsize target_size = end - start;
16✔
640
                auto copy_end = copy_n(
641
                        bad_data_msg_.begin() + (bad_data_msg_.size() - bad_data_msg_rem_),
16✔
642
                        min(bad_data_msg_rem_, target_size),
16✔
643
                        start);
16✔
644
                auto n_copied = copy_end - start;
645
                bad_data_msg_rem_ -= n_copied;
16✔
646
                return static_cast<size_t>(n_copied);
647
        } else if (rem_raw_data_size_ > 0) {
1,104✔
648
                if (end - start > rem_raw_data_size_) {
1,066✔
649
                        end = start + static_cast<size_t>(rem_raw_data_size_);
650
                }
651
                auto ex_sz = reader_->Read(start, end);
1,066✔
652
                if (!ex_sz) {
1,066✔
653
                        return ex_sz;
654
                }
655
                auto n_read = ex_sz.value();
1,066✔
656
                rem_raw_data_size_ -= n_read;
1,066✔
657

658
                // We control how much we read from the file so we should never read
659
                // 0 bytes (meaning EOF reached). If we do, it means the file is
660
                // smaller than what we were told.
661
                assert(n_read > 0);
662
                if (n_read == 0) {
1,066✔
663
                        return expected::unexpected(
×
664
                                MakeError(InvalidDataError, "Unexpected EOF when reading logs file"));
×
665
                }
666
                return n_read;
667
        } else if (closing_rem_ > 0) {
38✔
668
                io::Vsize target_size = end - start;
19✔
669
                auto copy_end = copy_n(
670
                        closing_.begin() + (closing_.size() - closing_rem_),
19✔
671
                        min(closing_rem_, target_size),
19✔
672
                        start);
19✔
673
                auto n_copied = copy_end - start;
674
                closing_rem_ -= n_copied;
19✔
675
                return static_cast<size_t>(copy_end - start);
676
        } else {
677
                return 0;
678
        }
679
};
680

681
static const string logs_uri_suffix = "/log";
682

683
error::Error DeploymentClient::PushLogs(
4✔
684
        const string &deployment_id,
685
        const string &log_file_path,
686
        api::Client &client,
687
        LogsAPIResponseHandler api_handler) {
688
        auto logs_reader = make_shared<JsonLogMessagesReader>(log_file_path);
4✔
689
        auto err = logs_reader->SanitizeLogs();
4✔
690
        if (err != error::NoError) {
4✔
691
                return err;
×
692
        }
693

694
        auto req = make_shared<api::APIRequest>();
4✔
695
        req->SetPath(http::JoinUrl(deployments_uri_prefix, deployment_id, logs_uri_suffix));
8✔
696
        req->SetMethod(http::Method::PUT);
4✔
697
        req->SetHeader("Content-Type", "application/json");
8✔
698
        req->SetHeader("Content-Length", to_string(logs_reader->TotalDataSize()));
8✔
699
        req->SetHeader("Accept", "application/json");
8✔
700
        req->SetBodyGenerator([logs_reader]() {
24✔
701
                logs_reader->Rewind();
8✔
702
                return logs_reader;
4✔
703
        });
8✔
704

705
        auto received_body = make_shared<vector<uint8_t>>();
4✔
706
        return client.AsyncCall(
707
                req,
708
                [received_body, api_handler](http::ExpectedIncomingResponsePtr exp_resp) {
4✔
709
                        if (!exp_resp) {
4✔
710
                                log::Error("Request to push logs data failed: " + exp_resp.error().message);
×
711
                                api_handler(exp_resp.error());
×
712
                                return;
×
713
                        }
714

715
                        auto body_writer = make_shared<io::ByteWriter>(received_body);
4✔
716
                        auto resp = exp_resp.value();
4✔
717
                        auto content_length = resp->GetHeader("Content-Length");
8✔
718
                        if (!content_length) {
4✔
719
                                log::Debug(
×
720
                                        "Failed to get content length from the deployment log API response headers: "
721
                                        + content_length.error().String());
×
722
                                body_writer->SetUnlimited(true);
×
723
                        } else {
724
                                auto ex_len = common::StringTo<size_t>(content_length.value());
4✔
725
                                if (!ex_len) {
4✔
726
                                        log::Error(
×
727
                                                "Failed to convert the content length from the deployment log API response headers to an integer: "
728
                                                + ex_len.error().String());
×
729
                                        body_writer->SetUnlimited(true);
×
730
                                } else {
731
                                        received_body->resize(ex_len.value());
4✔
732
                                }
733
                        }
734
                        resp->SetBodyWriter(body_writer);
8✔
735
                },
736
                [received_body, api_handler](http::ExpectedIncomingResponsePtr exp_resp) {
4✔
737
                        if (!exp_resp) {
4✔
738
                                log::Error("Request to push logs data failed: " + exp_resp.error().message);
×
739
                                api_handler(exp_resp.error());
×
740
                                return;
×
741
                        }
742

743
                        auto resp = exp_resp.value();
4✔
744
                        auto status = resp->GetStatusCode();
4✔
745

746
                        if (status == http::StatusNoContent) {
4✔
747
                                api_handler(error::NoError);
4✔
748
                        } else if (status == http::StatusRequestBodyTooLarge) {
2✔
749
                                // Don't retry if the request body is too large
750
                                api_handler(MakeError(
2✔
751
                                        RequestBodyTooLargeError,
752
                                        "Could not send logs to server: request body too large"));
2✔
753
                        } else {
754
                                auto ex_err_msg = api::ErrorMsgFromErrorResponse(*received_body);
1✔
755
                                string err_str;
756
                                if (ex_err_msg) {
1✔
757
                                        err_str = ex_err_msg.value();
1✔
758
                                } else {
759
                                        err_str = resp->GetStatusMessage();
×
760
                                }
761
                                api_handler(MakeError(
2✔
762
                                        BadResponseError,
763
                                        "Got unexpected response " + to_string(status) + " from logs API: " + err_str));
2✔
764
                        }
765
                });
16✔
766
}
767
} // namespace deployments
768
} // namespace update
769
} // 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

© 2026 Coveralls, Inc