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