blob: 81fa3d0f46085bd8c7f392e3b762973cc86bf9ca [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*/
16
James Feist481c5d52019-08-13 14:40:40 -070017#include "Utils.hpp"
18
19#include "VariantVisitors.hpp"
20
21#include <boost/algorithm/string/classification.hpp>
22#include <boost/algorithm/string/find.hpp>
23#include <boost/algorithm/string/predicate.hpp>
24#include <boost/algorithm/string/replace.hpp>
25#include <boost/algorithm/string/split.hpp>
26#include <boost/container/flat_map.hpp>
27#include <boost/lexical_cast.hpp>
James Feist637b3ef2019-04-15 16:35:30 -070028#include <filesystem>
James Feist3cb5fec2018-01-23 14:41:51 -080029#include <fstream>
30#include <regex>
James Feist1df06a42019-04-11 14:23:04 -070031#include <sdbusplus/bus/match.hpp>
James Feistb4383f42018-08-06 16:54:10 -070032#include <valijson/adapters/nlohmann_json_adapter.hpp>
33#include <valijson/schema.hpp>
34#include <valijson/schema_parser.hpp>
35#include <valijson/validator.hpp>
James Feist3cb5fec2018-01-23 14:41:51 -080036
James Feist481c5d52019-08-13 14:40:40 -070037constexpr const char* templateChar = "$";
38
Ed Tanous072e25d2018-12-16 21:45:20 -080039namespace fs = std::filesystem;
James Feist1df06a42019-04-11 14:23:04 -070040static bool powerStatusOn = false;
41static std::unique_ptr<sdbusplus::bus::match::match> powerMatch = nullptr;
James Feist3cb5fec2018-01-23 14:41:51 -080042
James Feista465ccc2019-02-08 12:51:01 -080043bool findFiles(const fs::path& dirPath, const std::string& matchString,
44 std::vector<fs::path>& foundPaths)
James Feist3cb5fec2018-01-23 14:41:51 -080045{
James Feista3c180a2018-08-09 16:06:04 -070046 if (!fs::exists(dirPath))
James Feist3cb5fec2018-01-23 14:41:51 -080047 return false;
48
James Feista3c180a2018-08-09 16:06:04 -070049 std::regex search(matchString);
James Feist3cb5fec2018-01-23 14:41:51 -080050 std::smatch match;
James Feista465ccc2019-02-08 12:51:01 -080051 for (const auto& p : fs::directory_iterator(dirPath))
James Feist3cb5fec2018-01-23 14:41:51 -080052 {
53 std::string path = p.path().string();
James Feistc95cb142018-02-26 10:41:42 -080054 if (std::regex_search(path, match, search))
James Feist3cb5fec2018-01-23 14:41:51 -080055 {
James Feista3c180a2018-08-09 16:06:04 -070056 foundPaths.emplace_back(p.path());
James Feist3cb5fec2018-01-23 14:41:51 -080057 }
58 }
59 return true;
James Feistb4383f42018-08-06 16:54:10 -070060}
61
Nikhil Potaded8884f12019-03-27 13:27:13 -070062bool getI2cDevicePaths(const fs::path& dirPath,
63 boost::container::flat_map<size_t, fs::path>& busPaths)
64{
65 if (!fs::exists(dirPath))
66 {
67 return false;
68 }
69
70 // Regex for matching the path
71 std::regex searchPath(std::string(R"(i2c-\d+$)"));
72 // Regex for matching the bus numbers
73 std::regex searchBus(std::string(R"(\w[^-]*$)"));
74 std::smatch matchPath;
75 std::smatch matchBus;
76 for (const auto& p : fs::directory_iterator(dirPath))
77 {
78 std::string path = p.path().string();
79 if (std::regex_search(path, matchPath, searchPath))
80 {
81 if (std::regex_search(path, matchBus, searchBus))
82 {
83 size_t bus = stoul(*matchBus.begin());
84 busPaths.insert(std::pair<size_t, fs::path>(bus, p.path()));
85 }
86 }
87 }
88
89 return true;
90}
91
James Feista465ccc2019-02-08 12:51:01 -080092bool validateJson(const nlohmann::json& schemaFile, const nlohmann::json& input)
James Feistb4383f42018-08-06 16:54:10 -070093{
94 valijson::Schema schema;
95 valijson::SchemaParser parser;
96 valijson::adapters::NlohmannJsonAdapter schemaAdapter(schemaFile);
97 parser.populateSchema(schemaAdapter, schema);
98 valijson::Validator validator;
99 valijson::adapters::NlohmannJsonAdapter targetAdapter(input);
100 if (!validator.validate(schema, targetAdapter, NULL))
101 {
102 return false;
103 }
104 return true;
Ed Tanous072e25d2018-12-16 21:45:20 -0800105}
James Feist1df06a42019-04-11 14:23:04 -0700106
107bool isPowerOn(void)
108{
109 if (!powerMatch)
110 {
111 throw std::runtime_error("Power Match Not Created");
112 }
113 return powerStatusOn;
114}
115
116void setupPowerMatch(const std::shared_ptr<sdbusplus::asio::connection>& conn)
117{
James Feist1df06a42019-04-11 14:23:04 -0700118 powerMatch = std::make_unique<sdbusplus::bus::match::match>(
119 static_cast<sdbusplus::bus::bus&>(*conn),
James Feist61f5ac42020-03-11 14:37:25 -0700120 "type='signal',interface='" + std::string(properties::interface) +
121 "',path='" + std::string(power::path) + "',arg0='" +
122 std::string(power::interface) + "'",
123 [](sdbusplus::message::message& message) {
124 std::string objectName;
125 boost::container::flat_map<std::string, std::variant<std::string>>
126 values;
127 message.read(objectName, values);
128 auto findState = values.find(power::property);
129 if (findState != values.end())
130 {
131 powerStatusOn = boost::ends_with(
132 std::get<std::string>(findState->second), "Running");
133 }
134 });
135
136 conn->async_method_call(
137 [](boost::system::error_code ec,
138 const std::variant<std::string>& state) {
139 if (ec)
140 {
141 return;
142 }
143 powerStatusOn =
144 boost::ends_with(std::get<std::string>(state), "Running");
145 },
146 power::busname, power::path, properties::interface, properties::get,
147 power::interface, power::property);
James Feist481c5d52019-08-13 14:40:40 -0700148}
149
150// finds the template character (currently set to $) and replaces the value with
151// the field found in a dbus object i.e. $ADDRESS would get populated with the
152// ADDRESS field from a object on dbus
153void templateCharReplace(
154 nlohmann::json::iterator& keyPair,
155 const boost::container::flat_map<std::string, BasicVariantType>&
156 foundDevice,
157 const size_t foundDeviceIdx)
158{
159 if (keyPair.value().type() == nlohmann::json::value_t::object ||
160 keyPair.value().type() == nlohmann::json::value_t::array)
161 {
162 for (auto nextLayer = keyPair.value().begin();
163 nextLayer != keyPair.value().end(); nextLayer++)
164 {
165 templateCharReplace(nextLayer, foundDevice, foundDeviceIdx);
166 }
167 return;
168 }
169
170 std::string* strPtr = keyPair.value().get_ptr<std::string*>();
171 if (strPtr == nullptr)
172 {
173 return;
174 }
175
176 boost::replace_all(*strPtr, std::string(templateChar) + "index",
177 std::to_string(foundDeviceIdx));
178
179 for (auto& foundDevicePair : foundDevice)
180 {
181 std::string templateName = templateChar + foundDevicePair.first;
182 boost::iterator_range<std::string::const_iterator> find =
183 boost::ifind_first(*strPtr, templateName);
184 if (find)
185 {
James Feist8c20feb2019-08-14 15:10:11 -0700186 constexpr const std::array<char, 5> mathChars = {'+', '-', '%', '*',
187 '/'};
James Feist481c5d52019-08-13 14:40:40 -0700188 size_t start = find.begin() - strPtr->begin();
James Feist8c20feb2019-08-14 15:10:11 -0700189 size_t nextItemIdx = start + templateName.size() + 1;
190
James Feist481c5d52019-08-13 14:40:40 -0700191 // check for additional operations
192 if (!start && find.end() == strPtr->end())
193 {
194 std::visit([&](auto&& val) { keyPair.value() = val; },
195 foundDevicePair.second);
196 return;
197 }
James Feist8c20feb2019-08-14 15:10:11 -0700198 else if (nextItemIdx > strPtr->size() ||
199 std::find(mathChars.begin(), mathChars.end(),
200 strPtr->at(nextItemIdx)) == mathChars.end())
James Feist481c5d52019-08-13 14:40:40 -0700201 {
202 std::string val = std::visit(VariantToStringVisitor(),
203 foundDevicePair.second);
James Feistb0097d42019-08-15 09:24:13 -0700204 boost::ireplace_all(*strPtr,
205 templateChar + foundDevicePair.first, val);
James Feist8c20feb2019-08-14 15:10:11 -0700206 continue;
James Feist481c5d52019-08-13 14:40:40 -0700207 }
208
209 // save the prefix
210 std::string prefix = strPtr->substr(0, start);
211
James Feist8c20feb2019-08-14 15:10:11 -0700212 // operate on the rest
213 std::string end = strPtr->substr(nextItemIdx);
James Feist481c5d52019-08-13 14:40:40 -0700214
215 std::vector<std::string> split;
216 boost::split(split, end, boost::is_any_of(" "));
217
218 // need at least 1 operation and number
219 if (split.size() < 2)
220 {
221 std::cerr << "Syntax error on template replacement of "
222 << *strPtr << "\n";
223 for (const std::string& data : split)
224 {
225 std::cerr << data << " ";
226 }
227 std::cerr << "\n";
228 continue;
229 }
230
231 // we assume that the replacement is a number, because we can
232 // only do math on numbers.. we might concatenate strings in the
233 // future, but thats later
234 int number =
235 std::visit(VariantToIntVisitor(), foundDevicePair.second);
236
237 bool isOperator = true;
238 TemplateOperation next = TemplateOperation::addition;
239
240 auto it = split.begin();
241
242 for (; it != split.end(); it++)
243 {
244 if (isOperator)
245 {
246 if (*it == "+")
247 {
248 next = TemplateOperation::addition;
249 }
250 else if (*it == "-")
251 {
252 next = TemplateOperation::subtraction;
253 }
254 else if (*it == "*")
255 {
256 next = TemplateOperation::multiplication;
257 }
258 else if (*it == R"(%)")
259 {
260 next = TemplateOperation::modulo;
261 }
262 else if (*it == R"(/)")
263 {
264 next = TemplateOperation::division;
265 }
266 else
267 {
268 break;
269 }
270 }
271 else
272 {
273 int constant = 0;
274 try
275 {
276 constant = std::stoi(*it);
277 }
278 catch (std::invalid_argument&)
279 {
280 std::cerr << "Parameter not supported for templates "
281 << *it << "\n";
282 continue;
283 }
284 switch (next)
285 {
286 case TemplateOperation::addition:
287 {
288 number += constant;
289 break;
290 }
291 case TemplateOperation::subtraction:
292 {
293 number -= constant;
294 break;
295 }
296 case TemplateOperation::multiplication:
297 {
298 number *= constant;
299 break;
300 }
301 case TemplateOperation::division:
302 {
303 number /= constant;
304 break;
305 }
306 case TemplateOperation::modulo:
307 {
308 number = number % constant;
309 break;
310 }
311
312 default:
313 break;
314 }
315 }
316 isOperator = !isOperator;
317 }
318 std::string result = prefix + std::to_string(number);
319
320 if (it != split.end())
321 {
322 for (; it != split.end(); it++)
323 {
324 result += " " + *it;
325 }
326 }
327 keyPair.value() = result;
328
329 // We probably just invalidated the pointer above, so set it to null
330 strPtr = nullptr;
331 break;
332 }
333 }
334
335 strPtr = keyPair.value().get_ptr<std::string*>();
336 if (strPtr == nullptr)
337 {
338 return;
339 }
340
341 // convert hex numbers to ints
342 if (boost::starts_with(*strPtr, "0x"))
343 {
344 try
345 {
346 size_t pos = 0;
347 int64_t temp = std::stoul(*strPtr, &pos, 0);
348 if (pos == strPtr->size())
349 {
350 keyPair.value() = static_cast<uint64_t>(temp);
351 }
352 }
353 catch (std::invalid_argument&)
354 {
355 }
356 catch (std::out_of_range&)
357 {
358 }
359 }
360 // non-hex numbers
361 else
362 {
363 try
364 {
365 uint64_t temp = boost::lexical_cast<uint64_t>(*strPtr);
366 keyPair.value() = temp;
367 }
368 catch (boost::bad_lexical_cast&)
369 {
370 }
371 }
Xiang Liu2801a702020-01-20 14:29:34 -0800372}