blob: 4662c2a6b9c7d9e133f2127a766f9cfcd542714c [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 {
177 size_t start = find.begin() - strPtr->begin();
178 // check for additional operations
179 if (!start && find.end() == strPtr->end())
180 {
181 std::visit([&](auto&& val) { keyPair.value() = val; },
182 foundDevicePair.second);
183 return;
184 }
185 else if (find.end() == strPtr->end())
186 {
187 std::string val = std::visit(VariantToStringVisitor(),
188 foundDevicePair.second);
189 boost::replace_all(*strPtr,
190 templateChar + foundDevicePair.first, val);
191 return;
192 }
193
194 // save the prefix
195 std::string prefix = strPtr->substr(0, start);
196
197 // operate on the rest (+1 for trailing space)
198 std::string end = strPtr->substr(start + templateName.size() + 1);
199
200 std::vector<std::string> split;
201 boost::split(split, end, boost::is_any_of(" "));
202
203 // need at least 1 operation and number
204 if (split.size() < 2)
205 {
206 std::cerr << "Syntax error on template replacement of "
207 << *strPtr << "\n";
208 for (const std::string& data : split)
209 {
210 std::cerr << data << " ";
211 }
212 std::cerr << "\n";
213 continue;
214 }
215
216 // we assume that the replacement is a number, because we can
217 // only do math on numbers.. we might concatenate strings in the
218 // future, but thats later
219 int number =
220 std::visit(VariantToIntVisitor(), foundDevicePair.second);
221
222 bool isOperator = true;
223 TemplateOperation next = TemplateOperation::addition;
224
225 auto it = split.begin();
226
227 for (; it != split.end(); it++)
228 {
229 if (isOperator)
230 {
231 if (*it == "+")
232 {
233 next = TemplateOperation::addition;
234 }
235 else if (*it == "-")
236 {
237 next = TemplateOperation::subtraction;
238 }
239 else if (*it == "*")
240 {
241 next = TemplateOperation::multiplication;
242 }
243 else if (*it == R"(%)")
244 {
245 next = TemplateOperation::modulo;
246 }
247 else if (*it == R"(/)")
248 {
249 next = TemplateOperation::division;
250 }
251 else
252 {
253 break;
254 }
255 }
256 else
257 {
258 int constant = 0;
259 try
260 {
261 constant = std::stoi(*it);
262 }
263 catch (std::invalid_argument&)
264 {
265 std::cerr << "Parameter not supported for templates "
266 << *it << "\n";
267 continue;
268 }
269 switch (next)
270 {
271 case TemplateOperation::addition:
272 {
273 number += constant;
274 break;
275 }
276 case TemplateOperation::subtraction:
277 {
278 number -= constant;
279 break;
280 }
281 case TemplateOperation::multiplication:
282 {
283 number *= constant;
284 break;
285 }
286 case TemplateOperation::division:
287 {
288 number /= constant;
289 break;
290 }
291 case TemplateOperation::modulo:
292 {
293 number = number % constant;
294 break;
295 }
296
297 default:
298 break;
299 }
300 }
301 isOperator = !isOperator;
302 }
303 std::string result = prefix + std::to_string(number);
304
305 if (it != split.end())
306 {
307 for (; it != split.end(); it++)
308 {
309 result += " " + *it;
310 }
311 }
312 keyPair.value() = result;
313
314 // We probably just invalidated the pointer above, so set it to null
315 strPtr = nullptr;
316 break;
317 }
318 }
319
320 strPtr = keyPair.value().get_ptr<std::string*>();
321 if (strPtr == nullptr)
322 {
323 return;
324 }
325
326 // convert hex numbers to ints
327 if (boost::starts_with(*strPtr, "0x"))
328 {
329 try
330 {
331 size_t pos = 0;
332 int64_t temp = std::stoul(*strPtr, &pos, 0);
333 if (pos == strPtr->size())
334 {
335 keyPair.value() = static_cast<uint64_t>(temp);
336 }
337 }
338 catch (std::invalid_argument&)
339 {
340 }
341 catch (std::out_of_range&)
342 {
343 }
344 }
345 // non-hex numbers
346 else
347 {
348 try
349 {
350 uint64_t temp = boost::lexical_cast<uint64_t>(*strPtr);
351 keyPair.value() = temp;
352 }
353 catch (boost::bad_lexical_cast&)
354 {
355 }
356 }
James Feist1df06a42019-04-11 14:23:04 -0700357}