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

mendersoftware / mender / 1022753986

02 Oct 2023 10:37AM UTC coverage: 78.168% (-2.0%) from 80.127%
1022753986

push

gitlab-ci

oleorhagen
feat: Run the authentication loop once upon bootstrap

Ticket: MEN-6658
Changelog: None

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

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

6996 of 8950 relevant lines covered (78.17%)

10353.4 hits per line

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

65.25
/common/conf/conf.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 <common/conf.hpp>
16

17
#include <string>
18
#include <cstdlib>
19
#include <cerrno>
20

21
#include <mender-version.h>
22

23
#include <common/error.hpp>
24
#include <common/expected.hpp>
25
#include <common/log.hpp>
26
#include <common/json.hpp>
27

28
namespace mender {
29
namespace common {
30
namespace conf {
31

32
using namespace std;
33
namespace error = mender::common::error;
34
namespace expected = mender::common::expected;
35
namespace log = mender::common::log;
36
namespace json = mender::common::json;
37

38
const string kMenderVersion = MENDER_VERSION;
39

40
const ConfigErrorCategoryClass ConfigErrorCategory;
41

42
const char *ConfigErrorCategoryClass::name() const noexcept {
×
43
        return "ConfigErrorCategory";
×
44
}
45

46
string ConfigErrorCategoryClass::message(int code) const {
8✔
47
        switch (code) {
8✔
48
        case NoError:
×
49
                return "Success";
×
50
        case InvalidOptionsError:
8✔
51
                return "Invalid options given";
8✔
52
        }
53
        assert(false);
×
54
        return "Unknown";
55
}
56

57
error::Error MakeError(ConfigErrorCode code, const string &msg) {
15✔
58
        return error::Error(error_condition(code, ConfigErrorCategory), msg);
30✔
59
}
60

61

62
string GetEnv(const string &var_name, const string &default_value) {
1,024✔
63
        const char *value = getenv(var_name.c_str());
1,024✔
64
        if (value == nullptr) {
1,024✔
65
                return string(default_value);
1,023✔
66
        } else {
67
                return string(value);
1✔
68
        }
69
}
70

71
ExpectedOptionValue CmdlineOptionsIterator::Next() {
375✔
72
        string option = "";
750✔
73
        string value = "";
750✔
74

75
        if (start_ + pos_ >= end_) {
375✔
76
                return ExpectedOptionValue({"", ""});
100✔
77
        }
78

79
        if (past_double_dash_) {
275✔
80
                OptionValue opt_val {"", start_[pos_]};
9✔
81
                pos_++;
3✔
82
                return ExpectedOptionValue(opt_val);
3✔
83
        }
84

85
        if (start_[pos_] == "--") {
272✔
86
                past_double_dash_ = true;
1✔
87
                pos_++;
1✔
88
                return ExpectedOptionValue({"--", ""});
1✔
89
        }
90

91
        if (start_[pos_][0] == '-') {
271✔
92
                auto eq_idx = start_[pos_].find('=');
116✔
93
                if (eq_idx != string::npos) {
116✔
94
                        option = start_[pos_].substr(0, eq_idx);
3✔
95
                        value = start_[pos_].substr(eq_idx + 1, start_[pos_].size() - eq_idx - 1);
3✔
96
                        pos_++;
3✔
97
                } else {
98
                        option = start_[pos_];
113✔
99
                        pos_++;
113✔
100
                }
101

102
                if (opts_with_value_.count(option) != 0) {
116✔
103
                        // option with value
104
                        if ((value == "") && ((start_ + pos_ >= end_) || (start_[pos_][0] == '-'))) {
106✔
105
                                // the next item is not a value
106
                                error::Error err = MakeError(
107
                                        ConfigErrorCode::InvalidOptionsError, "Option " + option + " missing value");
4✔
108
                                return ExpectedOptionValue(expected::unexpected(err));
4✔
109
                        } else if (value == "") {
104✔
110
                                // only assign the next item as value if there was no value
111
                                // specified as '--opt=value' (parsed above)
112
                                value = start_[pos_];
102✔
113
                                pos_++;
102✔
114
                        }
115
                } else if (opts_wo_value_.count(option) == 0) {
10✔
116
                        // unknown option
117
                        error::Error err = MakeError(
118
                                ConfigErrorCode::InvalidOptionsError, "Unrecognized option '" + option + "'");
8✔
119
                        return ExpectedOptionValue(expected::unexpected(err));
8✔
120
                } else if (value != "") {
6✔
121
                        // option without a value, yet, there was a value specified as '--opt=value' (parsed
122
                        // above)
123
                        error::Error err = MakeError(
124
                                ConfigErrorCode::InvalidOptionsError,
125
                                "Option " + option + " doesn't expect a value");
2✔
126
                        return ExpectedOptionValue(expected::unexpected(err));
2✔
127
                }
128
        } else {
129
                switch (mode_) {
155✔
130
                case ArgumentsMode::AcceptBareArguments:
50✔
131
                        value = start_[pos_];
50✔
132
                        pos_++;
50✔
133
                        break;
50✔
134
                case ArgumentsMode::RejectBareArguments:
3✔
135
                        return expected::unexpected(MakeError(
3✔
136
                                ConfigErrorCode::InvalidOptionsError,
137
                                "Unexpected argument '" + start_[pos_] + "'"));
6✔
138
                case ArgumentsMode::StopAtBareArguments:
102✔
139
                        return ExpectedOptionValue({"", ""});
102✔
140
                }
141
        }
142

143
        return ExpectedOptionValue({std::move(option), std::move(value)});
159✔
144
}
145

146
expected::ExpectedSize MenderConfig::ProcessCmdlineArgs(
102✔
147
        vector<string>::const_iterator start, vector<string>::const_iterator end) {
148
        bool explicit_config_path = false;
102✔
149
        bool explicit_fallback_config_path = false;
102✔
150
        string log_file = "";
204✔
151
        string log_level = log::ToStringLogLevel(log::kDefaultLogLevel);
204✔
152

153
        CmdlineOptionsIterator opts_iter(
154
                start,
155
                end,
156
                {"--config",
157
                 "-c",
158
                 "--fallback-config",
159
                 "-b",
160
                 "--data",
161
                 "-d",
162
                 "--log-file",
163
                 "-L",
164
                 "--log-level",
165
                 "-l"},
166
                {"--version", "-v"});
1,836✔
167
        opts_iter.SetArgumentsMode(ArgumentsMode::StopAtBareArguments);
102✔
168
        auto ex_opt_val = opts_iter.Next();
204✔
169
        int arg_count = 0;
102✔
170
        bool version_arg = false;
102✔
171
        while (ex_opt_val && ((ex_opt_val.value().option != "") || (ex_opt_val.value().value != ""))) {
199✔
172
                arg_count++;
97✔
173
                auto opt_val = ex_opt_val.value();
97✔
174
                if ((opt_val.option == "--config") || (opt_val.option == "-c")) {
97✔
175
                        paths.SetConfFile(opt_val.value);
×
176
                        explicit_config_path = true;
×
177
                } else if ((opt_val.option == "--fallback-config") || (opt_val.option == "-b")) {
97✔
178
                        paths.SetFallbackConfFile(opt_val.value);
×
179
                        explicit_fallback_config_path = true;
×
180
                } else if ((opt_val.option == "--data") || (opt_val.option == "-d")) {
97✔
181
                        paths.SetDataStore(opt_val.value);
97✔
182
                } else if ((opt_val.option == "--log-file") || (opt_val.option == "-L")) {
×
183
                        log_file = opt_val.value;
×
184
                } else if ((opt_val.option == "--log-level") || (opt_val.option == "-l")) {
×
185
                        log_level = opt_val.value;
×
186
                } else if ((opt_val.option == "--version") || (opt_val.option == "-v")) {
×
187
                        version_arg = true;
×
188
                }
189
                ex_opt_val = opts_iter.Next();
97✔
190
        }
191
        if (!ex_opt_val) {
102✔
192
                return expected::unexpected(ex_opt_val.error());
×
193
        }
194

195
        if (version_arg) {
102✔
196
                if (arg_count > 1 || opts_iter.GetPos() < static_cast<size_t>(end - start)) {
×
197
                        return expected::unexpected(error::Error(
×
198
                                make_error_condition(errc::invalid_argument),
×
199
                                "--version can not be combined with other commands and arguments"));
×
200
                } else {
201
                        cout << kMenderVersion << endl;
×
202
                        return expected::unexpected(error::MakeError(error::ExitWithSuccessError, ""));
×
203
                }
204
        }
205

206
        if (log_file != "") {
102✔
207
                auto err = log::SetupFileLogging(log_file, true);
×
208
                if (error::NoError != err) {
×
209
                        return expected::unexpected(err);
×
210
                }
211
        }
212

213
        auto ex_log_level = log::StringToLogLevel(log_level);
204✔
214
        if (!ex_log_level) {
102✔
215
                return expected::unexpected(ex_log_level.error());
×
216
        }
217
        SetLevel(ex_log_level.value());
102✔
218

219
        auto err = LoadConfigFile_(paths.GetConfFile(), explicit_config_path);
204✔
220
        if (error::NoError != err) {
102✔
221
                this->Reset();
×
222
                return expected::unexpected(err);
×
223
        }
224

225
        err = LoadConfigFile_(paths.GetFallbackConfFile(), explicit_fallback_config_path);
102✔
226
        if (error::NoError != err) {
102✔
227
                this->Reset();
×
228
                return expected::unexpected(err);
×
229
        }
230

231
        return opts_iter.GetPos();
204✔
232
}
233

234
error::Error MenderConfig::LoadConfigFile_(const string &path, bool required) {
204✔
235
        auto ret = this->LoadFile(path);
408✔
236
        if (!ret) {
204✔
237
                if (required) {
204✔
238
                        // any failure when a file is required (e.g. path was given explicitly) means an error
239
                        log::Error("Failed to load config from '" + path + "': " + ret.error().message);
×
240
                        return ret.error();
×
241
                } else if (ret.error().IsErrno(ENOENT)) {
204✔
242
                        // File doesn't exist, OK for non-required
243
                        log::Debug("Failed to load config from '" + path + "': " + ret.error().message);
204✔
244
                        return error::NoError;
204✔
245
                } else {
246
                        // other errors (parsing errors,...) for default paths should produce warnings
247
                        log::Warning("Failed to load config from '" + path + "': " + ret.error().message);
×
248
                        return error::NoError;
×
249
                }
250
        }
251
        // else
252
        auto valid = this->ValidateConfig();
×
253
        if (!valid) {
×
254
                // validation error is always an error
255
                log::Error("Failed to validate config from '" + path + "': " + valid.error().message);
×
256
                return valid.error();
×
257
        }
258

259
        return error::NoError;
×
260
}
261

262
error::Error MenderConfig::LoadDefaults() {
×
263
        auto err = LoadConfigFile_(paths.GetFallbackConfFile(), false);
×
264
        if (error::NoError != err) {
×
265
                this->Reset();
×
266
                return err;
×
267
        }
268

269
        err = LoadConfigFile_(paths.GetConfFile(), false);
×
270
        if (error::NoError != err) {
×
271
                this->Reset();
×
272
                return err;
×
273
        }
274

275
        return error::NoError;
×
276
}
277

278
} // namespace conf
279
} // namespace common
280
} // 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