blob: 3ef663c1301621a7df6113bc46bf8637d3224656 [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{
118 // create a match for powergood changes, first time do a method call to
119 // cache the correct value
120 std::function<void(sdbusplus::message::message & message)> eventHandler =
121 [](sdbusplus::message::message& message) {
122 std::string objectName;
123 boost::container::flat_map<std::string, std::variant<int32_t, bool>>
124 values;
125 message.read(objectName, values);
126 auto findPgood = values.find("pgood");
127 if (findPgood != values.end())
128 {
129 powerStatusOn = std::get<int32_t>(findPgood->second);
130 }
131 };
132
133 powerMatch = std::make_unique<sdbusplus::bus::match::match>(
134 static_cast<sdbusplus::bus::bus&>(*conn),
135 "type='signal',interface='org.freedesktop.DBus.Properties',path_"
136 "namespace='/xyz/openbmc_project/Chassis/Control/"
137 "Power0',arg0='xyz.openbmc_project.Chassis.Control.Power'",
138 eventHandler);
James Feist481c5d52019-08-13 14:40:40 -0700139}
140
141// finds the template character (currently set to $) and replaces the value with
142// the field found in a dbus object i.e. $ADDRESS would get populated with the
143// ADDRESS field from a object on dbus
144void templateCharReplace(
145 nlohmann::json::iterator& keyPair,
146 const boost::container::flat_map<std::string, BasicVariantType>&
147 foundDevice,
148 const size_t foundDeviceIdx)
149{
150 if (keyPair.value().type() == nlohmann::json::value_t::object ||
151 keyPair.value().type() == nlohmann::json::value_t::array)
152 {
153 for (auto nextLayer = keyPair.value().begin();
154 nextLayer != keyPair.value().end(); nextLayer++)
155 {
156 templateCharReplace(nextLayer, foundDevice, foundDeviceIdx);
157 }
158 return;
159 }
160
161 std::string* strPtr = keyPair.value().get_ptr<std::string*>();
162 if (strPtr == nullptr)
163 {
164 return;
165 }
166
167 boost::replace_all(*strPtr, std::string(templateChar) + "index",
168 std::to_string(foundDeviceIdx));
169
170 for (auto& foundDevicePair : foundDevice)
171 {
172 std::string templateName = templateChar + foundDevicePair.first;
173 boost::iterator_range<std::string::const_iterator> find =
174 boost::ifind_first(*strPtr, templateName);
175 if (find)
176 {
James Feist8c20feb2019-08-14 15:10:11 -0700177 constexpr const std::array<char, 5> mathChars = {'+', '-', '%', '*',
178 '/'};
James Feist481c5d52019-08-13 14:40:40 -0700179 size_t start = find.begin() - strPtr->begin();
James Feist8c20feb2019-08-14 15:10:11 -0700180 size_t nextItemIdx = start + templateName.size() + 1;
181
James Feist481c5d52019-08-13 14:40:40 -0700182 // check for additional operations
183 if (!start && find.end() == strPtr->end())
184 {
185 std::visit([&](auto&& val) { keyPair.value() = val; },
186 foundDevicePair.second);
187 return;
188 }
James Feist8c20feb2019-08-14 15:10:11 -0700189 else if (nextItemIdx > strPtr->size() ||
190 std::find(mathChars.begin(), mathChars.end(),
191 strPtr->at(nextItemIdx)) == mathChars.end())
James Feist481c5d52019-08-13 14:40:40 -0700192 {
193 std::string val = std::visit(VariantToStringVisitor(),
194 foundDevicePair.second);
James Feistb0097d42019-08-15 09:24:13 -0700195 boost::ireplace_all(*strPtr,
196 templateChar + foundDevicePair.first, val);
James Feist8c20feb2019-08-14 15:10:11 -0700197 continue;
James Feist481c5d52019-08-13 14:40:40 -0700198 }
199
200 // save the prefix
201 std::string prefix = strPtr->substr(0, start);
202
James Feist8c20feb2019-08-14 15:10:11 -0700203 // operate on the rest
204 std::string end = strPtr->substr(nextItemIdx);
James Feist481c5d52019-08-13 14:40:40 -0700205
206 std::vector<std::string> split;
207 boost::split(split, end, boost::is_any_of(" "));
208
209 // need at least 1 operation and number
210 if (split.size() < 2)
211 {
212 std::cerr << "Syntax error on template replacement of "
213 << *strPtr << "\n";
214 for (const std::string& data : split)
215 {
216 std::cerr << data << " ";
217 }
218 std::cerr << "\n";
219 continue;
220 }
221
222 // we assume that the replacement is a number, because we can
223 // only do math on numbers.. we might concatenate strings in the
224 // future, but thats later
225 int number =
226 std::visit(VariantToIntVisitor(), foundDevicePair.second);
227
228 bool isOperator = true;
229 TemplateOperation next = TemplateOperation::addition;
230
231 auto it = split.begin();
232
233 for (; it != split.end(); it++)
234 {
235 if (isOperator)
236 {
237 if (*it == "+")
238 {
239 next = TemplateOperation::addition;
240 }
241 else if (*it == "-")
242 {
243 next = TemplateOperation::subtraction;
244 }
245 else if (*it == "*")
246 {
247 next = TemplateOperation::multiplication;
248 }
249 else if (*it == R"(%)")
250 {
251 next = TemplateOperation::modulo;
252 }
253 else if (*it == R"(/)")
254 {
255 next = TemplateOperation::division;
256 }
257 else
258 {
259 break;
260 }
261 }
262 else
263 {
264 int constant = 0;
265 try
266 {
267 constant = std::stoi(*it);
268 }
269 catch (std::invalid_argument&)
270 {
271 std::cerr << "Parameter not supported for templates "
272 << *it << "\n";
273 continue;
274 }
275 switch (next)
276 {
277 case TemplateOperation::addition:
278 {
279 number += constant;
280 break;
281 }
282 case TemplateOperation::subtraction:
283 {
284 number -= constant;
285 break;
286 }
287 case TemplateOperation::multiplication:
288 {
289 number *= constant;
290 break;
291 }
292 case TemplateOperation::division:
293 {
294 number /= constant;
295 break;
296 }
297 case TemplateOperation::modulo:
298 {
299 number = number % constant;
300 break;
301 }
302
303 default:
304 break;
305 }
306 }
307 isOperator = !isOperator;
308 }
309 std::string result = prefix + std::to_string(number);
310
311 if (it != split.end())
312 {
313 for (; it != split.end(); it++)
314 {
315 result += " " + *it;
316 }
317 }
318 keyPair.value() = result;
319
320 // We probably just invalidated the pointer above, so set it to null
321 strPtr = nullptr;
322 break;
323 }
324 }
325
326 strPtr = keyPair.value().get_ptr<std::string*>();
327 if (strPtr == nullptr)
328 {
329 return;
330 }
331
332 // convert hex numbers to ints
333 if (boost::starts_with(*strPtr, "0x"))
334 {
335 try
336 {
337 size_t pos = 0;
338 int64_t temp = std::stoul(*strPtr, &pos, 0);
339 if (pos == strPtr->size())
340 {
341 keyPair.value() = static_cast<uint64_t>(temp);
342 }
343 }
344 catch (std::invalid_argument&)
345 {
346 }
347 catch (std::out_of_range&)
348 {
349 }
350 }
351 // non-hex numbers
352 else
353 {
354 try
355 {
356 uint64_t temp = boost::lexical_cast<uint64_t>(*strPtr);
357 keyPair.value() = temp;
358 }
359 catch (boost::bad_lexical_cast&)
360 {
361 }
362 }
Xiang Liu2801a702020-01-20 14:29:34 -0800363}