blob: a097d06dcd34a80a5455366bca3ea4cd7256ed7f [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>
37#include <regex>
38
James Feist481c5d52019-08-13 14:40:40 -070039constexpr const char* templateChar = "$";
40
Ed Tanous072e25d2018-12-16 21:45:20 -080041namespace fs = std::filesystem;
James Feist1df06a42019-04-11 14:23:04 -070042static bool powerStatusOn = false;
43static std::unique_ptr<sdbusplus::bus::match::match> powerMatch = nullptr;
James Feist3cb5fec2018-01-23 14:41:51 -080044
James Feista465ccc2019-02-08 12:51:01 -080045bool findFiles(const fs::path& dirPath, const std::string& matchString,
46 std::vector<fs::path>& foundPaths)
James Feist3cb5fec2018-01-23 14:41:51 -080047{
James Feista3c180a2018-08-09 16:06:04 -070048 if (!fs::exists(dirPath))
James Feist3cb5fec2018-01-23 14:41:51 -080049 return false;
50
James Feista3c180a2018-08-09 16:06:04 -070051 std::regex search(matchString);
James Feist3cb5fec2018-01-23 14:41:51 -080052 std::smatch match;
James Feista465ccc2019-02-08 12:51:01 -080053 for (const auto& p : fs::directory_iterator(dirPath))
James Feist3cb5fec2018-01-23 14:41:51 -080054 {
55 std::string path = p.path().string();
James Feistc95cb142018-02-26 10:41:42 -080056 if (std::regex_search(path, match, search))
James Feist3cb5fec2018-01-23 14:41:51 -080057 {
James Feista3c180a2018-08-09 16:06:04 -070058 foundPaths.emplace_back(p.path());
James Feist3cb5fec2018-01-23 14:41:51 -080059 }
60 }
61 return true;
James Feistb4383f42018-08-06 16:54:10 -070062}
63
Nikhil Potaded8884f12019-03-27 13:27:13 -070064bool getI2cDevicePaths(const fs::path& dirPath,
65 boost::container::flat_map<size_t, fs::path>& busPaths)
66{
67 if (!fs::exists(dirPath))
68 {
69 return false;
70 }
71
72 // Regex for matching the path
73 std::regex searchPath(std::string(R"(i2c-\d+$)"));
74 // Regex for matching the bus numbers
75 std::regex searchBus(std::string(R"(\w[^-]*$)"));
76 std::smatch matchPath;
77 std::smatch matchBus;
78 for (const auto& p : fs::directory_iterator(dirPath))
79 {
80 std::string path = p.path().string();
81 if (std::regex_search(path, matchPath, searchPath))
82 {
83 if (std::regex_search(path, matchBus, searchBus))
84 {
85 size_t bus = stoul(*matchBus.begin());
86 busPaths.insert(std::pair<size_t, fs::path>(bus, p.path()));
87 }
88 }
89 }
90
91 return true;
92}
93
James Feista465ccc2019-02-08 12:51:01 -080094bool validateJson(const nlohmann::json& schemaFile, const nlohmann::json& input)
James Feistb4383f42018-08-06 16:54:10 -070095{
96 valijson::Schema schema;
97 valijson::SchemaParser parser;
98 valijson::adapters::NlohmannJsonAdapter schemaAdapter(schemaFile);
99 parser.populateSchema(schemaAdapter, schema);
100 valijson::Validator validator;
101 valijson::adapters::NlohmannJsonAdapter targetAdapter(input);
102 if (!validator.validate(schema, targetAdapter, NULL))
103 {
104 return false;
105 }
106 return true;
Ed Tanous072e25d2018-12-16 21:45:20 -0800107}
James Feist1df06a42019-04-11 14:23:04 -0700108
109bool isPowerOn(void)
110{
111 if (!powerMatch)
112 {
113 throw std::runtime_error("Power Match Not Created");
114 }
115 return powerStatusOn;
116}
117
118void setupPowerMatch(const std::shared_ptr<sdbusplus::asio::connection>& conn)
119{
James Feist1df06a42019-04-11 14:23:04 -0700120 powerMatch = std::make_unique<sdbusplus::bus::match::match>(
121 static_cast<sdbusplus::bus::bus&>(*conn),
James Feist61f5ac42020-03-11 14:37:25 -0700122 "type='signal',interface='" + std::string(properties::interface) +
123 "',path='" + std::string(power::path) + "',arg0='" +
124 std::string(power::interface) + "'",
125 [](sdbusplus::message::message& message) {
126 std::string objectName;
127 boost::container::flat_map<std::string, std::variant<std::string>>
128 values;
129 message.read(objectName, values);
130 auto findState = values.find(power::property);
131 if (findState != values.end())
132 {
133 powerStatusOn = boost::ends_with(
134 std::get<std::string>(findState->second), "Running");
135 }
136 });
137
138 conn->async_method_call(
139 [](boost::system::error_code ec,
140 const std::variant<std::string>& state) {
141 if (ec)
142 {
143 return;
144 }
145 powerStatusOn =
146 boost::ends_with(std::get<std::string>(state), "Running");
147 },
148 power::busname, power::path, properties::interface, properties::get,
149 power::interface, power::property);
James Feist481c5d52019-08-13 14:40:40 -0700150}
151
Matt Spinlere789bf12021-02-24 12:33:01 -0600152// Replaces the template character like the other version of this function,
153// but checks all properties on all interfaces provided to do the substitution
154// with.
155std::optional<std::string> templateCharReplace(
156 nlohmann::json::iterator& keyPair,
157 const boost::container::flat_map<
158 std::string, boost::container::flat_map<std::string, BasicVariantType>>&
159 allInterfaces,
160 const size_t foundDeviceIdx, const std::optional<std::string>& replaceStr)
161{
162 for (const auto& [interface, properties] : allInterfaces)
163 {
164 auto ret = templateCharReplace(keyPair, properties, foundDeviceIdx,
165 replaceStr);
166 if (ret)
167 {
168 return ret;
169 }
170 }
171 return std::nullopt;
172}
173
James Feist481c5d52019-08-13 14:40:40 -0700174// finds the template character (currently set to $) and replaces the value with
175// the field found in a dbus object i.e. $ADDRESS would get populated with the
176// ADDRESS field from a object on dbus
James Feist35f5e0e2020-03-16 14:02:27 -0700177std::optional<std::string> templateCharReplace(
James Feist481c5d52019-08-13 14:40:40 -0700178 nlohmann::json::iterator& keyPair,
179 const boost::container::flat_map<std::string, BasicVariantType>&
180 foundDevice,
James Feist35f5e0e2020-03-16 14:02:27 -0700181 const size_t foundDeviceIdx, const std::optional<std::string>& replaceStr)
James Feist481c5d52019-08-13 14:40:40 -0700182{
James Feist35f5e0e2020-03-16 14:02:27 -0700183 std::optional<std::string> ret = std::nullopt;
184
James Feist481c5d52019-08-13 14:40:40 -0700185 if (keyPair.value().type() == nlohmann::json::value_t::object ||
186 keyPair.value().type() == nlohmann::json::value_t::array)
187 {
188 for (auto nextLayer = keyPair.value().begin();
189 nextLayer != keyPair.value().end(); nextLayer++)
190 {
James Feist35f5e0e2020-03-16 14:02:27 -0700191 templateCharReplace(nextLayer, foundDevice, foundDeviceIdx,
192 replaceStr);
James Feist481c5d52019-08-13 14:40:40 -0700193 }
James Feist35f5e0e2020-03-16 14:02:27 -0700194 return ret;
James Feist481c5d52019-08-13 14:40:40 -0700195 }
196
197 std::string* strPtr = keyPair.value().get_ptr<std::string*>();
198 if (strPtr == nullptr)
199 {
James Feist35f5e0e2020-03-16 14:02:27 -0700200 return ret;
James Feist481c5d52019-08-13 14:40:40 -0700201 }
202
203 boost::replace_all(*strPtr, std::string(templateChar) + "index",
204 std::to_string(foundDeviceIdx));
James Feist35f5e0e2020-03-16 14:02:27 -0700205 if (replaceStr)
206 {
207 boost::replace_all(*strPtr, *replaceStr,
208 std::to_string(foundDeviceIdx));
209 }
James Feist481c5d52019-08-13 14:40:40 -0700210
211 for (auto& foundDevicePair : foundDevice)
212 {
213 std::string templateName = templateChar + foundDevicePair.first;
214 boost::iterator_range<std::string::const_iterator> find =
215 boost::ifind_first(*strPtr, templateName);
216 if (find)
217 {
James Feist8c20feb2019-08-14 15:10:11 -0700218 constexpr const std::array<char, 5> mathChars = {'+', '-', '%', '*',
219 '/'};
James Feist481c5d52019-08-13 14:40:40 -0700220 size_t start = find.begin() - strPtr->begin();
James Feist8c20feb2019-08-14 15:10:11 -0700221 size_t nextItemIdx = start + templateName.size() + 1;
222
James Feist481c5d52019-08-13 14:40:40 -0700223 // check for additional operations
224 if (!start && find.end() == strPtr->end())
225 {
226 std::visit([&](auto&& val) { keyPair.value() = val; },
227 foundDevicePair.second);
James Feist35f5e0e2020-03-16 14:02:27 -0700228 return ret;
James Feist481c5d52019-08-13 14:40:40 -0700229 }
James Feist8c20feb2019-08-14 15:10:11 -0700230 else if (nextItemIdx > strPtr->size() ||
231 std::find(mathChars.begin(), mathChars.end(),
232 strPtr->at(nextItemIdx)) == mathChars.end())
James Feist481c5d52019-08-13 14:40:40 -0700233 {
234 std::string val = std::visit(VariantToStringVisitor(),
235 foundDevicePair.second);
James Feistb0097d42019-08-15 09:24:13 -0700236 boost::ireplace_all(*strPtr,
237 templateChar + foundDevicePair.first, val);
James Feist8c20feb2019-08-14 15:10:11 -0700238 continue;
James Feist481c5d52019-08-13 14:40:40 -0700239 }
240
241 // save the prefix
242 std::string prefix = strPtr->substr(0, start);
243
James Feist8c20feb2019-08-14 15:10:11 -0700244 // operate on the rest
245 std::string end = strPtr->substr(nextItemIdx);
James Feist481c5d52019-08-13 14:40:40 -0700246
247 std::vector<std::string> split;
248 boost::split(split, end, boost::is_any_of(" "));
249
250 // need at least 1 operation and number
251 if (split.size() < 2)
252 {
253 std::cerr << "Syntax error on template replacement of "
254 << *strPtr << "\n";
255 for (const std::string& data : split)
256 {
257 std::cerr << data << " ";
258 }
259 std::cerr << "\n";
260 continue;
261 }
262
263 // we assume that the replacement is a number, because we can
264 // only do math on numbers.. we might concatenate strings in the
265 // future, but thats later
266 int number =
267 std::visit(VariantToIntVisitor(), foundDevicePair.second);
268
269 bool isOperator = true;
270 TemplateOperation next = TemplateOperation::addition;
271
272 auto it = split.begin();
273
274 for (; it != split.end(); it++)
275 {
276 if (isOperator)
277 {
278 if (*it == "+")
279 {
280 next = TemplateOperation::addition;
281 }
282 else if (*it == "-")
283 {
284 next = TemplateOperation::subtraction;
285 }
286 else if (*it == "*")
287 {
288 next = TemplateOperation::multiplication;
289 }
290 else if (*it == R"(%)")
291 {
292 next = TemplateOperation::modulo;
293 }
294 else if (*it == R"(/)")
295 {
296 next = TemplateOperation::division;
297 }
298 else
299 {
300 break;
301 }
302 }
303 else
304 {
305 int constant = 0;
306 try
307 {
308 constant = std::stoi(*it);
309 }
310 catch (std::invalid_argument&)
311 {
312 std::cerr << "Parameter not supported for templates "
313 << *it << "\n";
314 continue;
315 }
316 switch (next)
317 {
318 case TemplateOperation::addition:
319 {
320 number += constant;
321 break;
322 }
323 case TemplateOperation::subtraction:
324 {
325 number -= constant;
326 break;
327 }
328 case TemplateOperation::multiplication:
329 {
330 number *= constant;
331 break;
332 }
333 case TemplateOperation::division:
334 {
335 number /= constant;
336 break;
337 }
338 case TemplateOperation::modulo:
339 {
340 number = number % constant;
341 break;
342 }
343
344 default:
345 break;
346 }
347 }
348 isOperator = !isOperator;
349 }
James Feist35f5e0e2020-03-16 14:02:27 -0700350
James Feist481c5d52019-08-13 14:40:40 -0700351 std::string result = prefix + std::to_string(number);
352
James Feist35f5e0e2020-03-16 14:02:27 -0700353 std::string replaced(find.begin(), find.end());
354 for (auto it2 = split.begin(); it2 != split.end(); it2++)
355 {
356 replaced += " ";
357 replaced += *it2;
358 if (it2 == it)
359 {
360 break;
361 }
362 }
363 ret = replaced;
364
James Feist481c5d52019-08-13 14:40:40 -0700365 if (it != split.end())
366 {
367 for (; it != split.end(); it++)
368 {
369 result += " " + *it;
370 }
371 }
372 keyPair.value() = result;
373
374 // We probably just invalidated the pointer above, so set it to null
375 strPtr = nullptr;
376 break;
377 }
378 }
379
380 strPtr = keyPair.value().get_ptr<std::string*>();
381 if (strPtr == nullptr)
382 {
James Feist35f5e0e2020-03-16 14:02:27 -0700383 return ret;
James Feist481c5d52019-08-13 14:40:40 -0700384 }
385
386 // convert hex numbers to ints
387 if (boost::starts_with(*strPtr, "0x"))
388 {
389 try
390 {
391 size_t pos = 0;
392 int64_t temp = std::stoul(*strPtr, &pos, 0);
393 if (pos == strPtr->size())
394 {
395 keyPair.value() = static_cast<uint64_t>(temp);
396 }
397 }
398 catch (std::invalid_argument&)
James Feist8c505da2020-05-28 10:06:33 -0700399 {}
James Feist481c5d52019-08-13 14:40:40 -0700400 catch (std::out_of_range&)
James Feist8c505da2020-05-28 10:06:33 -0700401 {}
James Feist481c5d52019-08-13 14:40:40 -0700402 }
403 // non-hex numbers
404 else
405 {
406 try
407 {
408 uint64_t temp = boost::lexical_cast<uint64_t>(*strPtr);
409 keyPair.value() = temp;
410 }
411 catch (boost::bad_lexical_cast&)
James Feist8c505da2020-05-28 10:06:33 -0700412 {}
James Feist481c5d52019-08-13 14:40:40 -0700413 }
James Feist35f5e0e2020-03-16 14:02:27 -0700414 return ret;
Xiang Liu2801a702020-01-20 14:29:34 -0800415}
Brad Bishop3cb8a602020-08-25 17:40:54 -0400416
Brad Bishop5d525412020-08-26 08:50:50 -0400417/// \brief JSON/DBus matching Callable for std::variant (visitor)
418///
419/// Default match JSON/DBus match implementation
420/// \tparam T The concrete DBus value type from BasicVariantType
421template <typename T>
422struct MatchProbe
423{
424 /// \param probe the probe statement to match against
425 /// \param value the property value being matched to a probe
426 /// \return true if the dbusValue matched the probe otherwise false
427 static bool match(const nlohmann::json& probe, const T& value)
428 {
429 return probe == value;
430 }
431};
432
433/// \brief JSON/DBus matching Callable for std::variant (visitor)
434///
435/// std::string specialization of MatchProbe enabling regex matching
436template <>
437struct MatchProbe<std::string>
438{
439 /// \param probe the probe statement to match against
440 /// \param value the string value being matched to a probe
441 /// \return true if the dbusValue matched the probe otherwise false
442 static bool match(const nlohmann::json& probe, const std::string& value)
443 {
444 if (probe.is_string())
445 {
446 try
447 {
448 std::regex search(probe);
449 std::smatch regMatch;
450 return std::regex_search(value, regMatch, search);
451 }
452 catch (const std::regex_error&)
453 {
454 std::cerr << "Syntax error in regular expression: " << probe
455 << " will never match";
456 }
457 }
458
459 // Skip calling nlohmann here, since it will never match a non-string
460 // to a std::string
461 return false;
462 }
463};
464
465/// \brief Forwarding JSON/DBus matching Callable for std::variant (visitor)
466///
467/// Forward calls to the correct template instantiation of MatchProbe
468struct MatchProbeForwarder
469{
470 explicit MatchProbeForwarder(const nlohmann::json& probe) : probeRef(probe)
471 {}
472 const nlohmann::json& probeRef;
473
474 template <typename T>
475 bool operator()(const T& dbusValue) const
476 {
477 return MatchProbe<T>::match(probeRef, dbusValue);
478 }
479};
480
Brad Bishop3cb8a602020-08-25 17:40:54 -0400481bool matchProbe(const nlohmann::json& probe, const BasicVariantType& dbusValue)
482{
Brad Bishop5d525412020-08-26 08:50:50 -0400483 return std::visit(MatchProbeForwarder(probe), dbusValue);
484}