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