blob: 31a10bcd2698357ec531bc937796ddca093b6c71 [file] [log] [blame]
James Feist3cb5fec2018-01-23 14:41:51 -08001/*
2// Copyright (c) 2017 Intel Corporation
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15*/
Brad Bishop1fb9f3f2020-08-28 08:15:13 -040016/// \file Utils.cpp
James Feist3cb5fec2018-01-23 14:41:51 -080017
James Feist481c5d52019-08-13 14:40:40 -070018#include "Utils.hpp"
19
20#include "VariantVisitors.hpp"
21
22#include <boost/algorithm/string/classification.hpp>
23#include <boost/algorithm/string/find.hpp>
24#include <boost/algorithm/string/predicate.hpp>
25#include <boost/algorithm/string/replace.hpp>
26#include <boost/algorithm/string/split.hpp>
27#include <boost/container/flat_map.hpp>
28#include <boost/lexical_cast.hpp>
James Feist1df06a42019-04-11 14:23:04 -070029#include <sdbusplus/bus/match.hpp>
James Feistb4383f42018-08-06 16:54:10 -070030#include <valijson/adapters/nlohmann_json_adapter.hpp>
31#include <valijson/schema.hpp>
32#include <valijson/schema_parser.hpp>
33#include <valijson/validator.hpp>
James Feist3cb5fec2018-01-23 14:41:51 -080034
James Feist8c505da2020-05-28 10:06:33 -070035#include <filesystem>
36#include <fstream>
Andrew Jefferya9c58922021-06-01 09:28:59 +093037#include <map>
James Feist8c505da2020-05-28 10:06:33 -070038#include <regex>
39
James Feist481c5d52019-08-13 14:40:40 -070040constexpr const char* templateChar = "$";
41
Ed Tanous072e25d2018-12-16 21:45:20 -080042namespace fs = std::filesystem;
James Feist1df06a42019-04-11 14:23:04 -070043static bool powerStatusOn = false;
44static std::unique_ptr<sdbusplus::bus::match::match> powerMatch = nullptr;
James Feist3cb5fec2018-01-23 14:41:51 -080045
James Feista465ccc2019-02-08 12:51:01 -080046bool findFiles(const fs::path& dirPath, const std::string& matchString,
47 std::vector<fs::path>& foundPaths)
James Feist3cb5fec2018-01-23 14:41:51 -080048{
James Feista3c180a2018-08-09 16:06:04 -070049 if (!fs::exists(dirPath))
Ed Tanous07d467b2021-02-23 14:48:37 -080050 {
James Feist3cb5fec2018-01-23 14:41:51 -080051 return false;
Ed Tanous07d467b2021-02-23 14:48:37 -080052 }
James Feist3cb5fec2018-01-23 14:41:51 -080053
James Feista3c180a2018-08-09 16:06:04 -070054 std::regex search(matchString);
James Feist3cb5fec2018-01-23 14:41:51 -080055 std::smatch match;
James Feista465ccc2019-02-08 12:51:01 -080056 for (const auto& p : fs::directory_iterator(dirPath))
James Feist3cb5fec2018-01-23 14:41:51 -080057 {
58 std::string path = p.path().string();
James Feistc95cb142018-02-26 10:41:42 -080059 if (std::regex_search(path, match, search))
James Feist3cb5fec2018-01-23 14:41:51 -080060 {
James Feista3c180a2018-08-09 16:06:04 -070061 foundPaths.emplace_back(p.path());
James Feist3cb5fec2018-01-23 14:41:51 -080062 }
63 }
64 return true;
James Feistb4383f42018-08-06 16:54:10 -070065}
66
Andrew Jefferya9c58922021-06-01 09:28:59 +093067bool findFiles(const std::vector<fs::path>&& dirPaths,
68 const std::string& matchString,
69 std::vector<fs::path>& foundPaths)
70{
71 std::map<fs::path, fs::path> paths;
72 std::regex search(matchString);
73 std::smatch match;
74 for (const auto& dirPath : dirPaths)
75 {
76 if (!fs::exists(dirPath))
Bruce Mitchella6d47332021-12-13 10:18:03 -060077 {
Andrew Jefferya9c58922021-06-01 09:28:59 +093078 continue;
Bruce Mitchella6d47332021-12-13 10:18:03 -060079 }
Andrew Jefferya9c58922021-06-01 09:28:59 +093080
81 for (const auto& p : fs::directory_iterator(dirPath))
82 {
83 std::string path = p.path().string();
84 if (std::regex_search(path, match, search))
85 {
86 paths[p.path().filename()] = p.path();
87 }
88 }
89 }
90
91 for (const auto& [key, value] : paths)
92 {
93 foundPaths.emplace_back(value);
94 }
95
96 return !foundPaths.empty();
97}
98
Nikhil Potaded8884f12019-03-27 13:27:13 -070099bool getI2cDevicePaths(const fs::path& dirPath,
100 boost::container::flat_map<size_t, fs::path>& busPaths)
101{
102 if (!fs::exists(dirPath))
103 {
104 return false;
105 }
106
107 // Regex for matching the path
108 std::regex searchPath(std::string(R"(i2c-\d+$)"));
109 // Regex for matching the bus numbers
110 std::regex searchBus(std::string(R"(\w[^-]*$)"));
111 std::smatch matchPath;
112 std::smatch matchBus;
113 for (const auto& p : fs::directory_iterator(dirPath))
114 {
115 std::string path = p.path().string();
116 if (std::regex_search(path, matchPath, searchPath))
117 {
118 if (std::regex_search(path, matchBus, searchBus))
119 {
120 size_t bus = stoul(*matchBus.begin());
121 busPaths.insert(std::pair<size_t, fs::path>(bus, p.path()));
122 }
123 }
124 }
125
126 return true;
127}
128
James Feista465ccc2019-02-08 12:51:01 -0800129bool validateJson(const nlohmann::json& schemaFile, const nlohmann::json& input)
James Feistb4383f42018-08-06 16:54:10 -0700130{
131 valijson::Schema schema;
132 valijson::SchemaParser parser;
133 valijson::adapters::NlohmannJsonAdapter schemaAdapter(schemaFile);
134 parser.populateSchema(schemaAdapter, schema);
135 valijson::Validator validator;
136 valijson::adapters::NlohmannJsonAdapter targetAdapter(input);
Ed Tanous07d467b2021-02-23 14:48:37 -0800137 if (!validator.validate(schema, targetAdapter, nullptr))
James Feistb4383f42018-08-06 16:54:10 -0700138 {
139 return false;
140 }
141 return true;
Ed Tanous072e25d2018-12-16 21:45:20 -0800142}
James Feist1df06a42019-04-11 14:23:04 -0700143
144bool isPowerOn(void)
145{
146 if (!powerMatch)
147 {
148 throw std::runtime_error("Power Match Not Created");
149 }
150 return powerStatusOn;
151}
152
153void setupPowerMatch(const std::shared_ptr<sdbusplus::asio::connection>& conn)
154{
James Feist1df06a42019-04-11 14:23:04 -0700155 powerMatch = std::make_unique<sdbusplus::bus::match::match>(
156 static_cast<sdbusplus::bus::bus&>(*conn),
James Feist61f5ac42020-03-11 14:37:25 -0700157 "type='signal',interface='" + std::string(properties::interface) +
158 "',path='" + std::string(power::path) + "',arg0='" +
159 std::string(power::interface) + "'",
160 [](sdbusplus::message::message& message) {
161 std::string objectName;
162 boost::container::flat_map<std::string, std::variant<std::string>>
163 values;
164 message.read(objectName, values);
165 auto findState = values.find(power::property);
166 if (findState != values.end())
167 {
168 powerStatusOn = boost::ends_with(
169 std::get<std::string>(findState->second), "Running");
170 }
171 });
172
173 conn->async_method_call(
174 [](boost::system::error_code ec,
175 const std::variant<std::string>& state) {
176 if (ec)
177 {
178 return;
179 }
180 powerStatusOn =
181 boost::ends_with(std::get<std::string>(state), "Running");
182 },
183 power::busname, power::path, properties::interface, properties::get,
184 power::interface, power::property);
James Feist481c5d52019-08-13 14:40:40 -0700185}
186
Matt Spinlere789bf12021-02-24 12:33:01 -0600187// Replaces the template character like the other version of this function,
188// but checks all properties on all interfaces provided to do the substitution
189// with.
190std::optional<std::string> templateCharReplace(
191 nlohmann::json::iterator& keyPair,
192 const boost::container::flat_map<
193 std::string, boost::container::flat_map<std::string, BasicVariantType>>&
194 allInterfaces,
195 const size_t foundDeviceIdx, const std::optional<std::string>& replaceStr)
196{
197 for (const auto& [interface, properties] : allInterfaces)
198 {
199 auto ret = templateCharReplace(keyPair, properties, foundDeviceIdx,
200 replaceStr);
201 if (ret)
202 {
203 return ret;
204 }
205 }
206 return std::nullopt;
207}
208
James Feist481c5d52019-08-13 14:40:40 -0700209// finds the template character (currently set to $) and replaces the value with
210// the field found in a dbus object i.e. $ADDRESS would get populated with the
211// ADDRESS field from a object on dbus
James Feist35f5e0e2020-03-16 14:02:27 -0700212std::optional<std::string> templateCharReplace(
James Feist481c5d52019-08-13 14:40:40 -0700213 nlohmann::json::iterator& keyPair,
214 const boost::container::flat_map<std::string, BasicVariantType>&
215 foundDevice,
James Feist35f5e0e2020-03-16 14:02:27 -0700216 const size_t foundDeviceIdx, const std::optional<std::string>& replaceStr)
James Feist481c5d52019-08-13 14:40:40 -0700217{
James Feist35f5e0e2020-03-16 14:02:27 -0700218 std::optional<std::string> ret = std::nullopt;
219
James Feist481c5d52019-08-13 14:40:40 -0700220 if (keyPair.value().type() == nlohmann::json::value_t::object ||
221 keyPair.value().type() == nlohmann::json::value_t::array)
222 {
223 for (auto nextLayer = keyPair.value().begin();
224 nextLayer != keyPair.value().end(); nextLayer++)
225 {
James Feist35f5e0e2020-03-16 14:02:27 -0700226 templateCharReplace(nextLayer, foundDevice, foundDeviceIdx,
227 replaceStr);
James Feist481c5d52019-08-13 14:40:40 -0700228 }
James Feist35f5e0e2020-03-16 14:02:27 -0700229 return ret;
James Feist481c5d52019-08-13 14:40:40 -0700230 }
231
232 std::string* strPtr = keyPair.value().get_ptr<std::string*>();
233 if (strPtr == nullptr)
234 {
James Feist35f5e0e2020-03-16 14:02:27 -0700235 return ret;
James Feist481c5d52019-08-13 14:40:40 -0700236 }
237
238 boost::replace_all(*strPtr, std::string(templateChar) + "index",
239 std::to_string(foundDeviceIdx));
James Feist35f5e0e2020-03-16 14:02:27 -0700240 if (replaceStr)
241 {
242 boost::replace_all(*strPtr, *replaceStr,
243 std::to_string(foundDeviceIdx));
244 }
James Feist481c5d52019-08-13 14:40:40 -0700245
246 for (auto& foundDevicePair : foundDevice)
247 {
248 std::string templateName = templateChar + foundDevicePair.first;
249 boost::iterator_range<std::string::const_iterator> find =
250 boost::ifind_first(*strPtr, templateName);
251 if (find)
252 {
James Feist8c20feb2019-08-14 15:10:11 -0700253 constexpr const std::array<char, 5> mathChars = {'+', '-', '%', '*',
254 '/'};
James Feist481c5d52019-08-13 14:40:40 -0700255 size_t start = find.begin() - strPtr->begin();
James Feist8c20feb2019-08-14 15:10:11 -0700256 size_t nextItemIdx = start + templateName.size() + 1;
257
James Feist481c5d52019-08-13 14:40:40 -0700258 // check for additional operations
259 if (!start && find.end() == strPtr->end())
260 {
261 std::visit([&](auto&& val) { keyPair.value() = val; },
262 foundDevicePair.second);
James Feist35f5e0e2020-03-16 14:02:27 -0700263 return ret;
James Feist481c5d52019-08-13 14:40:40 -0700264 }
Ed Tanous07d467b2021-02-23 14:48:37 -0800265 if (nextItemIdx > strPtr->size() ||
266 std::find(mathChars.begin(), mathChars.end(),
267 strPtr->at(nextItemIdx)) == mathChars.end())
James Feist481c5d52019-08-13 14:40:40 -0700268 {
269 std::string val = std::visit(VariantToStringVisitor(),
270 foundDevicePair.second);
James Feistb0097d42019-08-15 09:24:13 -0700271 boost::ireplace_all(*strPtr,
272 templateChar + foundDevicePair.first, val);
James Feist8c20feb2019-08-14 15:10:11 -0700273 continue;
James Feist481c5d52019-08-13 14:40:40 -0700274 }
275
276 // save the prefix
277 std::string prefix = strPtr->substr(0, start);
278
James Feist8c20feb2019-08-14 15:10:11 -0700279 // operate on the rest
280 std::string end = strPtr->substr(nextItemIdx);
James Feist481c5d52019-08-13 14:40:40 -0700281
282 std::vector<std::string> split;
283 boost::split(split, end, boost::is_any_of(" "));
284
285 // need at least 1 operation and number
286 if (split.size() < 2)
287 {
288 std::cerr << "Syntax error on template replacement of "
289 << *strPtr << "\n";
290 for (const std::string& data : split)
291 {
292 std::cerr << data << " ";
293 }
294 std::cerr << "\n";
295 continue;
296 }
297
298 // we assume that the replacement is a number, because we can
299 // only do math on numbers.. we might concatenate strings in the
300 // future, but thats later
301 int number =
302 std::visit(VariantToIntVisitor(), foundDevicePair.second);
303
304 bool isOperator = true;
305 TemplateOperation next = TemplateOperation::addition;
306
307 auto it = split.begin();
308
309 for (; it != split.end(); it++)
310 {
311 if (isOperator)
312 {
313 if (*it == "+")
314 {
315 next = TemplateOperation::addition;
316 }
317 else if (*it == "-")
318 {
319 next = TemplateOperation::subtraction;
320 }
321 else if (*it == "*")
322 {
323 next = TemplateOperation::multiplication;
324 }
325 else if (*it == R"(%)")
326 {
327 next = TemplateOperation::modulo;
328 }
329 else if (*it == R"(/)")
330 {
331 next = TemplateOperation::division;
332 }
333 else
334 {
335 break;
336 }
337 }
338 else
339 {
340 int constant = 0;
341 try
342 {
343 constant = std::stoi(*it);
344 }
Patrick Williams83b1e9b2021-10-06 12:47:24 -0500345 catch (const std::invalid_argument&)
James Feist481c5d52019-08-13 14:40:40 -0700346 {
347 std::cerr << "Parameter not supported for templates "
348 << *it << "\n";
349 continue;
350 }
351 switch (next)
352 {
353 case TemplateOperation::addition:
354 {
355 number += constant;
356 break;
357 }
358 case TemplateOperation::subtraction:
359 {
360 number -= constant;
361 break;
362 }
363 case TemplateOperation::multiplication:
364 {
365 number *= constant;
366 break;
367 }
368 case TemplateOperation::division:
369 {
370 number /= constant;
371 break;
372 }
373 case TemplateOperation::modulo:
374 {
375 number = number % constant;
376 break;
377 }
378
379 default:
380 break;
381 }
382 }
383 isOperator = !isOperator;
384 }
James Feist35f5e0e2020-03-16 14:02:27 -0700385
James Feist481c5d52019-08-13 14:40:40 -0700386 std::string result = prefix + std::to_string(number);
387
James Feist35f5e0e2020-03-16 14:02:27 -0700388 std::string replaced(find.begin(), find.end());
389 for (auto it2 = split.begin(); it2 != split.end(); it2++)
390 {
391 replaced += " ";
392 replaced += *it2;
393 if (it2 == it)
394 {
395 break;
396 }
397 }
398 ret = replaced;
399
James Feist481c5d52019-08-13 14:40:40 -0700400 if (it != split.end())
401 {
402 for (; it != split.end(); it++)
403 {
404 result += " " + *it;
405 }
406 }
407 keyPair.value() = result;
408
Zhikui Rena0d1b3f2021-10-05 16:21:56 -0700409 // We probably just invalidated the pointer abovei,
410 // reset and continue to handle multiple templates
411 strPtr = keyPair.value().get_ptr<std::string*>();
412 if (strPtr == nullptr)
413 {
414 break;
415 }
James Feist481c5d52019-08-13 14:40:40 -0700416 }
417 }
418
419 strPtr = keyPair.value().get_ptr<std::string*>();
420 if (strPtr == nullptr)
421 {
James Feist35f5e0e2020-03-16 14:02:27 -0700422 return ret;
James Feist481c5d52019-08-13 14:40:40 -0700423 }
424
425 // convert hex numbers to ints
426 if (boost::starts_with(*strPtr, "0x"))
427 {
428 try
429 {
430 size_t pos = 0;
431 int64_t temp = std::stoul(*strPtr, &pos, 0);
432 if (pos == strPtr->size())
433 {
434 keyPair.value() = static_cast<uint64_t>(temp);
435 }
436 }
Patrick Williams83b1e9b2021-10-06 12:47:24 -0500437 catch (const std::invalid_argument&)
James Feist8c505da2020-05-28 10:06:33 -0700438 {}
Patrick Williams83b1e9b2021-10-06 12:47:24 -0500439 catch (const std::out_of_range&)
James Feist8c505da2020-05-28 10:06:33 -0700440 {}
James Feist481c5d52019-08-13 14:40:40 -0700441 }
442 // non-hex numbers
443 else
444 {
445 try
446 {
447 uint64_t temp = boost::lexical_cast<uint64_t>(*strPtr);
448 keyPair.value() = temp;
449 }
Patrick Williams83b1e9b2021-10-06 12:47:24 -0500450 catch (const boost::bad_lexical_cast&)
James Feist8c505da2020-05-28 10:06:33 -0700451 {}
James Feist481c5d52019-08-13 14:40:40 -0700452 }
James Feist35f5e0e2020-03-16 14:02:27 -0700453 return ret;
Xiang Liu2801a702020-01-20 14:29:34 -0800454}
Brad Bishop3cb8a602020-08-25 17:40:54 -0400455
Brad Bishop5d525412020-08-26 08:50:50 -0400456/// \brief JSON/DBus matching Callable for std::variant (visitor)
457///
458/// Default match JSON/DBus match implementation
459/// \tparam T The concrete DBus value type from BasicVariantType
460template <typename T>
461struct MatchProbe
462{
463 /// \param probe the probe statement to match against
464 /// \param value the property value being matched to a probe
465 /// \return true if the dbusValue matched the probe otherwise false
466 static bool match(const nlohmann::json& probe, const T& value)
467 {
468 return probe == value;
469 }
470};
471
472/// \brief JSON/DBus matching Callable for std::variant (visitor)
473///
474/// std::string specialization of MatchProbe enabling regex matching
475template <>
476struct MatchProbe<std::string>
477{
478 /// \param probe the probe statement to match against
479 /// \param value the string value being matched to a probe
480 /// \return true if the dbusValue matched the probe otherwise false
481 static bool match(const nlohmann::json& probe, const std::string& value)
482 {
483 if (probe.is_string())
484 {
485 try
486 {
487 std::regex search(probe);
488 std::smatch regMatch;
489 return std::regex_search(value, regMatch, search);
490 }
491 catch (const std::regex_error&)
492 {
493 std::cerr << "Syntax error in regular expression: " << probe
494 << " will never match";
495 }
496 }
497
498 // Skip calling nlohmann here, since it will never match a non-string
499 // to a std::string
500 return false;
501 }
502};
503
504/// \brief Forwarding JSON/DBus matching Callable for std::variant (visitor)
505///
506/// Forward calls to the correct template instantiation of MatchProbe
507struct MatchProbeForwarder
508{
509 explicit MatchProbeForwarder(const nlohmann::json& probe) : probeRef(probe)
510 {}
511 const nlohmann::json& probeRef;
512
513 template <typename T>
514 bool operator()(const T& dbusValue) const
515 {
516 return MatchProbe<T>::match(probeRef, dbusValue);
517 }
518};
519
Brad Bishop3cb8a602020-08-25 17:40:54 -0400520bool matchProbe(const nlohmann::json& probe, const BasicVariantType& dbusValue)
521{
Brad Bishop5d525412020-08-26 08:50:50 -0400522 return std::visit(MatchProbeForwarder(probe), dbusValue);
523}