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