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