blob: 78d1cad767ceb164ae5e4718d784153206c69d6d [file] [log] [blame]
Andrew Jeffery47af65a2021-12-01 14:16:31 +10301/*
2// Copyright (c) 2018 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/// \file PerformScan.cpp
17#include "EntityManager.hpp"
18
19#include <boost/algorithm/string/predicate.hpp>
20#include <boost/asio/steady_timer.hpp>
21#include <boost/container/flat_map.hpp>
22#include <boost/container/flat_set.hpp>
23
24#include <charconv>
25
26/* Hacks from splitting EntityManager.cpp */
27extern std::shared_ptr<sdbusplus::asio::connection> systemBus;
28extern nlohmann::json lastJson;
29extern void
30 propertiesChangedCallback(nlohmann::json& systemConfiguration,
31 sdbusplus::asio::object_server& objServer);
32
Andrew Jeffery47af65a2021-12-01 14:16:31 +103033using GetSubTreeType = std::vector<
34 std::pair<std::string,
35 std::vector<std::pair<std::string, std::vector<std::string>>>>>;
36
37constexpr const int32_t maxMapperDepth = 0;
38
39constexpr const bool debug = false;
40
41void getInterfaces(
42 const std::tuple<std::string, std::string, std::string>& call,
43 const std::vector<std::shared_ptr<PerformProbe>>& probeVector,
44 const std::shared_ptr<PerformScan>& scan, size_t retries = 5)
45{
46 if (!retries)
47 {
48 std::cerr << "retries exhausted on " << std::get<0>(call) << " "
49 << std::get<1>(call) << " " << std::get<2>(call) << "\n";
50 return;
51 }
52
53 systemBus->async_method_call(
54 [call, scan, probeVector, retries](
55 boost::system::error_code& errc,
56 const boost::container::flat_map<std::string, BasicVariantType>&
57 resp) {
58 if (errc)
59 {
60 std::cerr << "error calling getall on " << std::get<0>(call)
61 << " " << std::get<1>(call) << " "
62 << std::get<2>(call) << "\n";
63
64 std::shared_ptr<boost::asio::steady_timer> timer =
65 std::make_shared<boost::asio::steady_timer>(io);
66 timer->expires_after(std::chrono::seconds(2));
67
68 timer->async_wait([timer, call, scan, probeVector,
69 retries](const boost::system::error_code&) {
70 getInterfaces(call, probeVector, scan, retries - 1);
71 });
72 return;
73 }
74
75 scan->dbusProbeObjects[std::get<1>(call)][std::get<2>(call)] = resp;
76 },
77 std::get<0>(call), std::get<1>(call), "org.freedesktop.DBus.Properties",
78 "GetAll", std::get<2>(call));
79
80 if constexpr (debug)
81 {
82 std::cerr << __func__ << " " << __LINE__ << "\n";
83 }
84}
85
86void registerCallback(nlohmann::json& systemConfiguration,
87 sdbusplus::asio::object_server& objServer,
88 const std::string& path)
89{
90 static boost::container::flat_map<std::string, sdbusplus::bus::match::match>
91 dbusMatches;
92
93 auto find = dbusMatches.find(path);
94 if (find != dbusMatches.end())
95 {
96 return;
97 }
98 std::function<void(sdbusplus::message::message & message)> eventHandler =
99
100 [&](sdbusplus::message::message&) {
101 propertiesChangedCallback(systemConfiguration, objServer);
102 };
103
104 sdbusplus::bus::match::match match(
105 static_cast<sdbusplus::bus::bus&>(*systemBus),
106 "type='signal',member='PropertiesChanged',path='" + path + "'",
107 eventHandler);
108 dbusMatches.emplace(path, std::move(match));
109}
110
111// Populates scan->dbusProbeObjects with all interfaces and properties
112// for the paths that own the interfaces passed in.
113void findDbusObjects(std::vector<std::shared_ptr<PerformProbe>>&& probeVector,
114 boost::container::flat_set<std::string>&& interfaces,
115 const std::shared_ptr<PerformScan>& scan,
116 size_t retries = 5)
117{
118 // Filter out interfaces already obtained.
119 for (const auto& [path, probeInterfaces] : scan->dbusProbeObjects)
120 {
121 for (const auto& [interface, _] : probeInterfaces)
122 {
123 interfaces.erase(interface);
124 }
125 }
126 if (interfaces.empty())
127 {
128 return;
129 }
130
131 // find all connections in the mapper that expose a specific type
132 systemBus->async_method_call(
133 [interfaces, probeVector{std::move(probeVector)}, scan,
134 retries](boost::system::error_code& ec,
135 const GetSubTreeType& interfaceSubtree) mutable {
136 boost::container::flat_set<
137 std::tuple<std::string, std::string, std::string>>
138 interfaceConnections;
139 if (ec)
140 {
141 if (ec.value() == ENOENT)
142 {
143 return; // wasn't found by mapper
144 }
145 std::cerr << "Error communicating to mapper.\n";
146
147 if (!retries)
148 {
149 // if we can't communicate to the mapper something is very
150 // wrong
151 std::exit(EXIT_FAILURE);
152 }
153 std::shared_ptr<boost::asio::steady_timer> timer =
154 std::make_shared<boost::asio::steady_timer>(io);
155 timer->expires_after(std::chrono::seconds(10));
156
157 timer->async_wait(
158 [timer, interfaces{std::move(interfaces)}, scan,
159 probeVector{std::move(probeVector)},
160 retries](const boost::system::error_code&) mutable {
161 findDbusObjects(std::move(probeVector),
162 std::move(interfaces), scan,
163 retries - 1);
164 });
165 return;
166 }
167
168 for (const auto& [path, object] : interfaceSubtree)
169 {
170 for (const auto& [busname, ifaces] : object)
171 {
172 for (const std::string& iface : ifaces)
173 {
174 // The 3 default org.freedeskstop interfaces (Peer,
175 // Introspectable, and Properties) are returned by
176 // the mapper but don't have properties, so don't bother
177 // with the GetAll call to save some cycles.
178 if (!boost::algorithm::starts_with(iface,
179 "org.freedesktop"))
180 {
181 interfaceConnections.emplace(busname, path, iface);
182 }
183 }
184 }
185
186 // Get a PropertiesChanged callback for all
187 // interfaces on this path.
188 registerCallback(scan->_systemConfiguration, scan->objServer,
189 path);
190 }
191
192 if (interfaceConnections.empty())
193 {
194 return;
195 }
196
197 for (const auto& call : interfaceConnections)
198 {
199 getInterfaces(call, probeVector, scan);
200 }
201 },
202 "xyz.openbmc_project.ObjectMapper",
203 "/xyz/openbmc_project/object_mapper",
204 "xyz.openbmc_project.ObjectMapper", "GetSubTree", "/", maxMapperDepth,
205 interfaces);
206
207 if constexpr (debug)
208 {
209 std::cerr << __func__ << " " << __LINE__ << "\n";
210 }
211}
212
213std::string getRecordName(
214 const boost::container::flat_map<std::string, BasicVariantType>& probe,
215 const std::string& probeName)
216{
217 if (probe.empty())
218 {
219 return probeName;
220 }
221
222 // use an array so alphabetical order from the
223 // flat_map is maintained
224 auto device = nlohmann::json::array();
225 for (auto& devPair : probe)
226 {
227 device.push_back(devPair.first);
228 std::visit([&device](auto&& v) { device.push_back(v); },
229 devPair.second);
230 }
231 size_t hash = std::hash<std::string>{}(probeName + device.dump());
232 // hashes are hard to distinguish, use the
233 // non-hashed version if we want debug
234 if constexpr (debug)
235 {
236 return probeName + device.dump();
237 }
238 else
239 {
240 return std::to_string(hash);
241 }
242}
243
244PerformScan::PerformScan(nlohmann::json& systemConfiguration,
245 nlohmann::json& missingConfigurations,
246 std::list<nlohmann::json>& configurations,
247 sdbusplus::asio::object_server& objServerIn,
248 std::function<void()>&& callback) :
249 _systemConfiguration(systemConfiguration),
250 _missingConfigurations(missingConfigurations),
251 _configurations(configurations), objServer(objServerIn),
252 _callback(std::move(callback))
253{}
254void PerformScan::run()
255{
256 boost::container::flat_set<std::string> dbusProbeInterfaces;
257 std::vector<std::shared_ptr<PerformProbe>> dbusProbePointers;
258
259 for (auto it = _configurations.begin(); it != _configurations.end();)
260 {
261 auto findProbe = it->find("Probe");
262 auto findName = it->find("Name");
263
264 nlohmann::json probeCommand;
265 // check for poorly formatted fields, probe must be an array
266 if (findProbe == it->end())
267 {
268 std::cerr << "configuration file missing probe:\n " << *it << "\n";
269 it = _configurations.erase(it);
270 continue;
271 }
272 if ((*findProbe).type() != nlohmann::json::value_t::array)
273 {
274 probeCommand = nlohmann::json::array();
275 probeCommand.push_back(*findProbe);
276 }
277 else
278 {
279 probeCommand = *findProbe;
280 }
281
282 if (findName == it->end())
283 {
284 std::cerr << "configuration file missing name:\n " << *it << "\n";
285 it = _configurations.erase(it);
286 continue;
287 }
288 std::string probeName = *findName;
289
290 if (std::find(passedProbes.begin(), passedProbes.end(), probeName) !=
291 passedProbes.end())
292 {
293 it = _configurations.erase(it);
294 continue;
295 }
296 nlohmann::json* recordPtr = &(*it);
297
298 // store reference to this to children to makes sure we don't get
299 // destroyed too early
300 auto thisRef = shared_from_this();
301 auto probePointer = std::make_shared<PerformProbe>(
302 probeCommand, thisRef,
303 [&, recordPtr, probeName](FoundDeviceT& foundDevices,
304 const DBusProbeObjectT& allInterfaces) {
305 _passed = true;
306 std::set<nlohmann::json> usedNames;
307 passedProbes.push_back(probeName);
308 std::list<size_t> indexes(foundDevices.size());
309 std::iota(indexes.begin(), indexes.end(), 1);
310
311 size_t indexIdx = probeName.find('$');
312 bool hasTemplateName = (indexIdx != std::string::npos);
313
314 // copy over persisted configurations and make sure we remove
315 // indexes that are already used
316 for (auto itr = foundDevices.begin();
317 itr != foundDevices.end();)
318 {
319 std::string recordName =
320 getRecordName(std::get<0>(*itr), probeName);
321
322 auto fromLastJson = lastJson.find(recordName);
323 if (fromLastJson != lastJson.end())
324 {
325 auto findExposes = fromLastJson->find("Exposes");
326 // delete nulls from any updates
327 if (findExposes != fromLastJson->end())
328 {
329 auto copy = nlohmann::json::array();
330 for (auto& expose : *findExposes)
331 {
332 if (expose.is_null())
333 {
334 continue;
335 }
336 copy.emplace_back(expose);
337 }
338 *findExposes = copy;
339 }
340
341 // keep user changes
342 _systemConfiguration[recordName] = *fromLastJson;
343 _missingConfigurations.erase(recordName);
344 itr = foundDevices.erase(itr);
345 if (hasTemplateName)
346 {
347 auto nameIt = fromLastJson->find("Name");
348 if (nameIt == fromLastJson->end())
349 {
350 std::cerr << "Last JSON Illegal\n";
351 continue;
352 }
353 int index = 0;
354 auto str =
355 nameIt->get<std::string>().substr(indexIdx);
356 auto [p, ec] = std::from_chars(
357 str.data(), str.data() + str.size(), index);
358 if (ec != std::errc())
359 {
360 continue; // non-numeric replacement
361 }
362 usedNames.insert(nameIt.value());
363 auto usedIt = std::find(indexes.begin(),
364 indexes.end(), index);
365
366 if (usedIt == indexes.end())
367 {
368 continue; // less items now
369 }
370 indexes.erase(usedIt);
371 }
372
373 continue;
374 }
375 itr++;
376 }
377
378 std::optional<std::string> replaceStr;
379
380 DBusProbeObjectT::mapped_type emptyInterfaces;
381 boost::container::flat_map<std::string, BasicVariantType>
382 emptyProps;
383 emptyInterfaces.emplace(std::string{}, emptyProps);
384
385 for (auto& foundDeviceAndPath : foundDevices)
386 {
387 const boost::container::flat_map<
388 std::string, BasicVariantType>& foundDevice =
389 std::get<0>(foundDeviceAndPath);
390 const std::string& path = std::get<1>(foundDeviceAndPath);
391
392 // Need all interfaces on this path so that template
393 // substitutions can be done with any of the contained
394 // properties. If the probe that passed didn't use an
395 // interface, such as if it was just TRUE, then
396 // templateCharReplace will just get passed in an empty
397 // map.
398 const DBusProbeObjectT::mapped_type* allInterfacesOnPath =
399 &emptyInterfaces;
400
401 auto ifacesIt = allInterfaces.find(path);
402 if (ifacesIt != allInterfaces.end())
403 {
404 allInterfacesOnPath = &ifacesIt->second;
405 }
406
407 nlohmann::json record = *recordPtr;
408 std::string recordName =
409 getRecordName(foundDevice, probeName);
410 size_t foundDeviceIdx = indexes.front();
411 indexes.pop_front();
412
413 // check name first so we have no duplicate names
414 auto getName = record.find("Name");
415 if (getName == record.end())
416 {
417 std::cerr << "Record Missing Name! " << record.dump();
418 continue; // this should be impossible at this level
419 }
420
421 nlohmann::json copyForName = {{"Name", getName.value()}};
422 nlohmann::json::iterator copyIt = copyForName.begin();
423 std::optional<std::string> replaceVal =
424 templateCharReplace(copyIt, *allInterfacesOnPath,
425 foundDeviceIdx, replaceStr);
426
427 if (!replaceStr && replaceVal)
428 {
429 if (usedNames.find(copyIt.value()) != usedNames.end())
430 {
431 replaceStr = replaceVal;
432 copyForName = {{"Name", getName.value()}};
433 copyIt = copyForName.begin();
434 templateCharReplace(copyIt, *allInterfacesOnPath,
435 foundDeviceIdx, replaceStr);
436 }
437 }
438
439 if (replaceStr)
440 {
441 std::cerr << "Duplicates found, replacing "
442 << *replaceStr
443 << " with found device index.\n Consider "
444 "fixing template to not have duplicates\n";
445 }
446
447 for (auto keyPair = record.begin(); keyPair != record.end();
448 keyPair++)
449 {
450 if (keyPair.key() == "Name")
451 {
452 keyPair.value() = copyIt.value();
453 usedNames.insert(copyIt.value());
454
455 continue; // already covered above
456 }
457 templateCharReplace(keyPair, *allInterfacesOnPath,
458 foundDeviceIdx, replaceStr);
459 }
460
461 // insert into configuration temporarily to be able to
462 // reference ourselves
463
464 _systemConfiguration[recordName] = record;
465
466 auto findExpose = record.find("Exposes");
467 if (findExpose == record.end())
468 {
469 _systemConfiguration[recordName] = record;
470 continue;
471 }
472
473 for (auto& expose : *findExpose)
474 {
475 for (auto keyPair = expose.begin();
476 keyPair != expose.end(); keyPair++)
477 {
478
479 templateCharReplace(keyPair, *allInterfacesOnPath,
480 foundDeviceIdx, replaceStr);
481
482 bool isBind =
483 boost::starts_with(keyPair.key(), "Bind");
484 bool isDisable = keyPair.key() == "DisableNode";
485
486 // special cases
487 if (!(isBind || isDisable))
488 {
489 continue;
490 }
491
492 if (keyPair.value().type() !=
493 nlohmann::json::value_t::string &&
494 keyPair.value().type() !=
495 nlohmann::json::value_t::array)
496 {
497 std::cerr << "Value is invalid type "
498 << keyPair.key() << "\n";
499 continue;
500 }
501
502 std::vector<std::string> matches;
503 if (keyPair.value().type() ==
504 nlohmann::json::value_t::string)
505 {
506 matches.emplace_back(keyPair.value());
507 }
508 else
509 {
510 for (const auto& value : keyPair.value())
511 {
512 if (value.type() !=
513 nlohmann::json::value_t::string)
514 {
515 std::cerr << "Value is invalid type "
516 << value << "\n";
517 break;
518 }
519 matches.emplace_back(value);
520 }
521 }
522
523 std::set<std::string> foundMatches;
Andrew Jefferyf5184712022-03-25 13:38:07 +1030524 for (auto& [configId, config] :
Andrew Jeffery47af65a2021-12-01 14:16:31 +1030525 _systemConfiguration.items())
526 {
527 if (isDisable)
528 {
529 // don't disable ourselves
Andrew Jefferyf5184712022-03-25 13:38:07 +1030530 if (configId == recordName)
Andrew Jeffery47af65a2021-12-01 14:16:31 +1030531 {
532 continue;
533 }
534 }
Andrew Jefferyf5184712022-03-25 13:38:07 +1030535 auto configListFind = config.find("Exposes");
Andrew Jeffery47af65a2021-12-01 14:16:31 +1030536
Andrew Jefferyf5184712022-03-25 13:38:07 +1030537 if (configListFind == config.end() ||
Andrew Jeffery47af65a2021-12-01 14:16:31 +1030538 configListFind->type() !=
539 nlohmann::json::value_t::array)
540 {
541 continue;
542 }
543 for (auto& exposedObject : *configListFind)
544 {
545 auto matchIt = std::find_if(
546 matches.begin(), matches.end(),
547 [name = (exposedObject)["Name"]
548 .get<std::string>()](
549 const std::string& s) {
550 return s == name;
551 });
552 if (matchIt == matches.end())
553 {
554 continue;
555 }
556 foundMatches.insert(*matchIt);
557
558 if (isBind)
559 {
560 std::string bind = keyPair.key().substr(
561 sizeof("Bind") - 1);
562
563 exposedObject["Status"] = "okay";
564 expose[bind] = exposedObject;
565 }
566 else if (isDisable)
567 {
568 exposedObject["Status"] = "disabled";
569 }
570 }
571 }
572 if (foundMatches.size() != matches.size())
573 {
574 std::cerr << "configuration file "
575 "dependency error, "
576 "could not find "
577 << keyPair.key() << " "
578 << keyPair.value() << "\n";
579 }
580 }
581 }
582 // overwrite ourselves with cleaned up version
583 _systemConfiguration[recordName] = record;
584 _missingConfigurations.erase(recordName);
585 }
586 });
587
588 // parse out dbus probes by discarding other probe types, store in a
589 // map
590 for (const nlohmann::json& probeJson : probeCommand)
591 {
592 const std::string* probe = probeJson.get_ptr<const std::string*>();
593 if (probe == nullptr)
594 {
595 std::cerr << "Probe statement wasn't a string, can't parse";
596 continue;
597 }
Andrew Jeffery666583b2021-12-01 15:50:12 +1030598 if (findProbeType(probe->c_str()))
Andrew Jeffery47af65a2021-12-01 14:16:31 +1030599 {
600 continue;
601 }
602 // syntax requires probe before first open brace
603 auto findStart = probe->find('(');
604 std::string interface = probe->substr(0, findStart);
605 dbusProbeInterfaces.emplace(interface);
606 dbusProbePointers.emplace_back(probePointer);
607 }
608 it++;
609 }
610
611 // probe vector stores a shared_ptr to each PerformProbe that cares
612 // about a dbus interface
613 findDbusObjects(std::move(dbusProbePointers),
614 std::move(dbusProbeInterfaces), shared_from_this());
615 if constexpr (debug)
616 {
617 std::cerr << __func__ << " " << __LINE__ << "\n";
618 }
619}
620
621PerformScan::~PerformScan()
622{
623 if (_passed)
624 {
625 auto nextScan = std::make_shared<PerformScan>(
626 _systemConfiguration, _missingConfigurations, _configurations,
627 objServer, std::move(_callback));
628 nextScan->passedProbes = std::move(passedProbes);
629 nextScan->dbusProbeObjects = std::move(dbusProbeObjects);
630 nextScan->run();
631
632 if constexpr (debug)
633 {
634 std::cerr << __func__ << " " << __LINE__ << "\n";
635 }
636 }
637 else
638 {
639 _callback();
640
641 if constexpr (debug)
642 {
643 std::cerr << __func__ << " " << __LINE__ << "\n";
644 }
645 }
646}