-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutil.cpp
More file actions
344 lines (282 loc) · 9.31 KB
/
util.cpp
File metadata and controls
344 lines (282 loc) · 9.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
/*
* Copyright (C) 2025 James C. Owens
* Portions Copyright (c) 2019 The Bitcoin Core developers
* Portions Copyright (c) 2025 The Gridcoin developers
*
* This code is licensed under the MIT license. See LICENSE.md in the repository.
*/
#include <util.h>
#include <chrono>
#include <cstddef>
#include <regex>
#include <fstream>
//!
//! \brief This to support early use of the log utility functions before the config is read to get the
//! debug flag.
//!
std::atomic<bool> g_debug = false;
//!
//! \brief The flag controls the logging of timestamps by the log functions. This is used to suppress
//! timestamp output when run under systemd, where the journal appends a high resolution timestamp.
//!
std::atomic<bool> g_log_timestamps = true;
[[nodiscard]] std::vector<std::string> StringSplit(const std::string& s, const std::string& delim)
{
size_t pos = 0;
size_t end = 0;
std::vector<std::string> elems;
while((end = s.find(delim, pos)) != std::string::npos)
{
elems.push_back(s.substr(pos, end - pos));
pos = end + delim.size();
}
// Append final value
elems.push_back(s.substr(pos, end - pos));
return elems;
}
[[nodiscard]] std::string TrimString(const std::string& str, const std::string& pattern)
{
std::string::size_type front = str.find_first_not_of(pattern);
if (front == std::string::npos) {
return std::string();
}
std::string::size_type end = str.find_last_not_of(pattern);
return str.substr(front, end - front + 1);
}
[[nodiscard]] std::string StripQuotes(const std::string& str)
{
if (str.empty()) {
return str; // No quotes to strip from an empty string.
}
std::string result = str; // Create a copy so we can modify it.
if (result.front() == '"' || result.front() == '\'') {
result.erase(0, 1); // Remove the leading quote.
}
if (!result.empty() && (result.back() == '"' || result.back() == '\'')) {
result.pop_back(); // Remove the trailing quote.
}
return result;
}
constexpr char ToLower(char c)
{
return (c >= 'A' && c <= 'Z' ? (c - 'A') + 'a' : c);
}
std::string ToLower(const std::string& str)
{
std::string r;
for (auto ch : str) r += ToLower((unsigned char)ch);
return r;
}
int64_t GetUnixEpochTime()
{
// Get the current time point
auto now = std::chrono::system_clock::now();
// Convert the time point to a duration since the epoch
auto duration = now.time_since_epoch();
// Convert the duration to seconds
int64_t seconds = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
return seconds;
}
std::string FormatISO8601DateTime(int64_t time)
{
struct tm ts;
time_t time_val = time;
if (gmtime_r(&time_val, &ts) == nullptr) {
return {};
}
return strprintf("%04i-%02i-%02iT%02i:%02i:%02iZ",
ts.tm_year + 1900, ts.tm_mon + 1, ts.tm_mday, ts.tm_hour, ts.tm_min, ts.tm_sec);
}
bool IsValidTimestamp(const int64_t& timestamp)
{
int64_t now = GetUnixEpochTime();
int64_t future_limit = now + 60; // No more than 60 seconds in the future.
int64_t past_limit = now - 10 * 86400 * 365; // No more than ten years in the past.
return timestamp >= past_limit && timestamp <= future_limit;
}
[[nodiscard]] int ParseStringToInt(const std::string& str)
{
try {
return std::stoi(str);
} catch (const std::invalid_argument& e){
error_log("%s: Invalid argument: %s",
__func__,
e.what());
throw;
} catch (const std::out_of_range& e){
error_log("%s: Out of range: %s",
__func__,
e.what());
throw;
}
}
[[nodiscard]] int64_t ParseStringtoInt64(const std::string& str)
{
try {
return static_cast<int64_t>(std::stoll(str));
} catch (const std::invalid_argument& e){
error_log("%s: Invalid argument: %s",
__func__,
e.what());
throw;
} catch (const std::out_of_range& e){
error_log("%s: Out of range: %s",
__func__,
e.what());
throw;
}
}
std::vector<fs::path> FindDirEntriesWithWildcard(const fs::path& directory, const std::string& wildcard)
{
std::vector<fs::path> matching_entries;
std::regex regex_wildcard(wildcard); //convert wildcard to regex.
if (!fs::exists(directory) || !fs::is_directory(directory)) {
debug_log("WARNING: %s, directory %s to search for regex expression \"%s\""
"does not exist or is not a directory.",
__func__,
directory,
wildcard);
return matching_entries;
}
for (const auto& entry : fs::directory_iterator(directory)) {
if (std::regex_match(entry.path().filename().string(), regex_wildcard)) {
matching_entries.push_back(entry.path());
}
}
return matching_entries;
}
//! \brief Function to safely get an environment variable as a std::string
std::optional<std::string> GetEnvVariable(const std::string& var_name)
{
// Get the environment variable
const char* env_var_cstr = std::getenv(var_name.c_str());
// Check if the variable exists
if (env_var_cstr == nullptr) {
// The environment variable is not set
return std::nullopt; // Indicate failure / not found
} else {
// The variable exists, return it as a std::string
return std::string(env_var_cstr);
}
}
// Class Config
Config::Config()
{}
void Config::ReadAndUpdateConfig(const fs::path& config_file) {
std::unique_lock<std::mutex> lock(mtx_config);
std::multimap<std::string, std::string> config;
try {
std::ifstream file(config_file);
if (!file.is_open()) {
error_log("%s: Could not open the config file: %s. Using internal defaults.",
__func__,
config_file);
} else {
std::string line;
while (std::getline(file, line)) {
// Skip empty lines and lines starting with '#'
if (line.empty() || line[0] == '#') {
continue;
}
std::vector line_elements = StringSplit(line, "=");
if (line_elements.size() != 2) {
continue;
}
config.insert(std::make_pair(StripQuotes(TrimString(line_elements[0])),
StripQuotes(TrimString(line_elements[1]))));
}
file.close();
// Do this all at once so the result of the config read is essentially "atomic".
m_config_in.swap(config);
normal_log("INFO: %s: Successfully read config file: %s",
__func__,
config_file.string());
}
} catch (FileSystemException& e) {
error_log("%s: Reading config file failed, so defaults will be used: %s",
__func__,
e.what());
}
// If the config file read failed, we will process args anyway, which will result in defaults being chosen.
ProcessArgs();
}
config_variant Config::GetArg(const std::string& arg)
{
std::unique_lock<std::mutex> lock(mtx_config);
auto iter = m_config.find(arg);
if (iter != m_config.end()) {
return iter->second;
} else {
return std::string {};
}
}
std::string Config::GetArgString(const std::string& arg, const std::string& default_value) const
{
auto iter = m_config_in.find(arg);
if (iter != m_config_in.end()) {
return iter->second;
} else {
return default_value;
}
}
EventMessage::EventMessage()
: m_timestamp(0)
, m_event_type(UNKNOWN)
{}
EventMessage::EventType EventMessage::EventTypeStringToEnum(const std::string& event_type_str)
{
if (event_type_str == std::string {"USER_ACTIVE"}) {
return USER_ACTIVE;
} else if (event_type_str == std::string {"USER_UNFORCE"}) {
return USER_UNFORCE;
} else if (event_type_str == std::string {"USER_FORCE_ACTIVE"}) {
return USER_FORCE_ACTIVE;
} else if (event_type_str == std::string {"USER_FORCE_IDLE"}) {
return USER_FORCE_IDLE;
}
return UNKNOWN;
}
EventMessage::EventMessage(int64_t timestamp, EventType event_type)
: m_timestamp(timestamp)
, m_event_type(event_type)
{}
EventMessage::EventMessage(std::string timestamp_str, std::string event_type_str)
{
m_timestamp = ParseStringtoInt64(timestamp_str);
m_event_type = EventTypeStringToEnum(event_type_str);
}
std::string EventMessage::EventTypeToString()
{
return EventTypeToString(m_event_type);
}
std::string EventMessage::EventTypeToString(const EventType& event_type)
{
std::string out;
switch (event_type) {
case UNKNOWN:
out = "UNKNOWN";
break;
case USER_ACTIVE:
out = "USER_ACTIVE";
break;
case USER_UNFORCE:
out = "USER_UNFORCE";
break;
case USER_FORCE_ACTIVE:
out = "USER_FORCE_ACTIVE";
break;
case USER_FORCE_IDLE:
out = "USER_FORCE_IDLE";
break;
}
return out;
}
bool EventMessage::IsValid()
{
return m_event_type != UNKNOWN && IsValidTimestamp(m_timestamp);
}
std::string EventMessage::ToString()
{
std::string out = ::ToString(m_timestamp) + ":" + EventTypeToString(m_event_type);
return out;
}