blob: 1f87c57f590a1d0d9a07117530190bfae1c196fe [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 }
Andrew Jeffery1ae4ed62022-04-05 16:55:43 +0930233
234 return std::to_string(hash);
Andrew Jeffery47af65a2021-12-01 14:16:31 +1030235}
236
237PerformScan::PerformScan(nlohmann::json& systemConfiguration,
238 nlohmann::json& missingConfigurations,
239 std::list<nlohmann::json>& configurations,
240 sdbusplus::asio::object_server& objServerIn,
241 std::function<void()>&& callback) :
242 _systemConfiguration(systemConfiguration),
243 _missingConfigurations(missingConfigurations),
244 _configurations(configurations), objServer(objServerIn),
245 _callback(std::move(callback))
246{}
247void PerformScan::run()
248{
249 boost::container::flat_set<std::string> dbusProbeInterfaces;
250 std::vector<std::shared_ptr<PerformProbe>> dbusProbePointers;
251
252 for (auto it = _configurations.begin(); it != _configurations.end();)
253 {
254 auto findProbe = it->find("Probe");
255 auto findName = it->find("Name");
256
257 nlohmann::json probeCommand;
258 // check for poorly formatted fields, probe must be an array
259 if (findProbe == it->end())
260 {
261 std::cerr << "configuration file missing probe:\n " << *it << "\n";
262 it = _configurations.erase(it);
263 continue;
264 }
265 if ((*findProbe).type() != nlohmann::json::value_t::array)
266 {
267 probeCommand = nlohmann::json::array();
268 probeCommand.push_back(*findProbe);
269 }
270 else
271 {
272 probeCommand = *findProbe;
273 }
274
275 if (findName == it->end())
276 {
277 std::cerr << "configuration file missing name:\n " << *it << "\n";
278 it = _configurations.erase(it);
279 continue;
280 }
281 std::string probeName = *findName;
282
283 if (std::find(passedProbes.begin(), passedProbes.end(), probeName) !=
284 passedProbes.end())
285 {
286 it = _configurations.erase(it);
287 continue;
288 }
289 nlohmann::json* recordPtr = &(*it);
290
291 // store reference to this to children to makes sure we don't get
292 // destroyed too early
293 auto thisRef = shared_from_this();
294 auto probePointer = std::make_shared<PerformProbe>(
295 probeCommand, thisRef,
Andrew Jefferyac20bd92022-04-05 11:11:40 +0930296 [&, recordPtr,
297 probeName](FoundDeviceT& foundDevices,
298 const MapperGetSubTreeResponse& allInterfaces) {
Andrew Jeffery47af65a2021-12-01 14:16:31 +1030299 _passed = true;
300 std::set<nlohmann::json> usedNames;
301 passedProbes.push_back(probeName);
302 std::list<size_t> indexes(foundDevices.size());
303 std::iota(indexes.begin(), indexes.end(), 1);
304
305 size_t indexIdx = probeName.find('$');
306 bool hasTemplateName = (indexIdx != std::string::npos);
307
308 // copy over persisted configurations and make sure we remove
309 // indexes that are already used
310 for (auto itr = foundDevices.begin();
311 itr != foundDevices.end();)
312 {
313 std::string recordName =
314 getRecordName(std::get<0>(*itr), probeName);
315
316 auto fromLastJson = lastJson.find(recordName);
317 if (fromLastJson != lastJson.end())
318 {
319 auto findExposes = fromLastJson->find("Exposes");
320 // delete nulls from any updates
321 if (findExposes != fromLastJson->end())
322 {
323 auto copy = nlohmann::json::array();
324 for (auto& expose : *findExposes)
325 {
326 if (expose.is_null())
327 {
328 continue;
329 }
330 copy.emplace_back(expose);
331 }
332 *findExposes = copy;
333 }
334
335 // keep user changes
336 _systemConfiguration[recordName] = *fromLastJson;
337 _missingConfigurations.erase(recordName);
338 itr = foundDevices.erase(itr);
339 if (hasTemplateName)
340 {
341 auto nameIt = fromLastJson->find("Name");
342 if (nameIt == fromLastJson->end())
343 {
344 std::cerr << "Last JSON Illegal\n";
345 continue;
346 }
347 int index = 0;
348 auto str =
349 nameIt->get<std::string>().substr(indexIdx);
350 auto [p, ec] = std::from_chars(
351 str.data(), str.data() + str.size(), index);
352 if (ec != std::errc())
353 {
354 continue; // non-numeric replacement
355 }
356 usedNames.insert(nameIt.value());
357 auto usedIt = std::find(indexes.begin(),
358 indexes.end(), index);
359
360 if (usedIt == indexes.end())
361 {
362 continue; // less items now
363 }
364 indexes.erase(usedIt);
365 }
366
367 continue;
368 }
369 itr++;
370 }
371
372 std::optional<std::string> replaceStr;
373
Andrew Jefferyac20bd92022-04-05 11:11:40 +0930374 MapperGetSubTreeResponse::mapped_type emptyInterfaces;
Andrew Jeffery1983d2f2022-04-05 14:55:13 +0930375 DBusInterface emptyInterface;
376 emptyInterfaces.emplace(std::string{}, emptyInterface);
Andrew Jeffery47af65a2021-12-01 14:16:31 +1030377
378 for (auto& foundDeviceAndPath : foundDevices)
379 {
Andrew Jeffery1983d2f2022-04-05 14:55:13 +0930380 const DBusInterface& foundDevice =
Andrew Jeffery47af65a2021-12-01 14:16:31 +1030381 std::get<0>(foundDeviceAndPath);
382 const std::string& path = std::get<1>(foundDeviceAndPath);
383
384 // Need all interfaces on this path so that template
385 // substitutions can be done with any of the contained
386 // properties. If the probe that passed didn't use an
387 // interface, such as if it was just TRUE, then
388 // templateCharReplace will just get passed in an empty
389 // map.
Andrew Jefferyc6558f62022-04-05 15:39:31 +0930390 const MapperGetSubTreeResponse::mapped_type* dbusObject =
391 &emptyInterfaces;
Andrew Jeffery47af65a2021-12-01 14:16:31 +1030392
393 auto ifacesIt = allInterfaces.find(path);
394 if (ifacesIt != allInterfaces.end())
395 {
Andrew Jefferyc6558f62022-04-05 15:39:31 +0930396 dbusObject = &ifacesIt->second;
Andrew Jeffery47af65a2021-12-01 14:16:31 +1030397 }
398
399 nlohmann::json record = *recordPtr;
400 std::string recordName =
401 getRecordName(foundDevice, probeName);
402 size_t foundDeviceIdx = indexes.front();
403 indexes.pop_front();
404
405 // check name first so we have no duplicate names
406 auto getName = record.find("Name");
407 if (getName == record.end())
408 {
409 std::cerr << "Record Missing Name! " << record.dump();
410 continue; // this should be impossible at this level
411 }
412
413 nlohmann::json copyForName = {{"Name", getName.value()}};
414 nlohmann::json::iterator copyIt = copyForName.begin();
Andrew Jefferyc6558f62022-04-05 15:39:31 +0930415 std::optional<std::string> replaceVal = templateCharReplace(
416 copyIt, *dbusObject, foundDeviceIdx, replaceStr);
Andrew Jeffery47af65a2021-12-01 14:16:31 +1030417
418 if (!replaceStr && replaceVal)
419 {
420 if (usedNames.find(copyIt.value()) != usedNames.end())
421 {
422 replaceStr = replaceVal;
423 copyForName = {{"Name", getName.value()}};
424 copyIt = copyForName.begin();
Andrew Jefferyc6558f62022-04-05 15:39:31 +0930425 templateCharReplace(copyIt, *dbusObject,
Andrew Jeffery47af65a2021-12-01 14:16:31 +1030426 foundDeviceIdx, replaceStr);
427 }
428 }
429
430 if (replaceStr)
431 {
432 std::cerr << "Duplicates found, replacing "
433 << *replaceStr
434 << " with found device index.\n Consider "
435 "fixing template to not have duplicates\n";
436 }
437
438 for (auto keyPair = record.begin(); keyPair != record.end();
439 keyPair++)
440 {
441 if (keyPair.key() == "Name")
442 {
443 keyPair.value() = copyIt.value();
444 usedNames.insert(copyIt.value());
445
446 continue; // already covered above
447 }
Andrew Jefferyc6558f62022-04-05 15:39:31 +0930448 templateCharReplace(keyPair, *dbusObject,
Andrew Jeffery47af65a2021-12-01 14:16:31 +1030449 foundDeviceIdx, replaceStr);
450 }
451
452 // insert into configuration temporarily to be able to
453 // reference ourselves
454
455 _systemConfiguration[recordName] = record;
456
457 auto findExpose = record.find("Exposes");
458 if (findExpose == record.end())
459 {
460 _systemConfiguration[recordName] = record;
461 continue;
462 }
463
464 for (auto& expose : *findExpose)
465 {
466 for (auto keyPair = expose.begin();
467 keyPair != expose.end(); keyPair++)
468 {
469
Andrew Jefferyc6558f62022-04-05 15:39:31 +0930470 templateCharReplace(keyPair, *dbusObject,
Andrew Jeffery47af65a2021-12-01 14:16:31 +1030471 foundDeviceIdx, replaceStr);
472
473 bool isBind =
474 boost::starts_with(keyPair.key(), "Bind");
475 bool isDisable = keyPair.key() == "DisableNode";
476
477 // special cases
478 if (!(isBind || isDisable))
479 {
480 continue;
481 }
482
483 if (keyPair.value().type() !=
484 nlohmann::json::value_t::string &&
485 keyPair.value().type() !=
486 nlohmann::json::value_t::array)
487 {
488 std::cerr << "Value is invalid type "
489 << keyPair.key() << "\n";
490 continue;
491 }
492
493 std::vector<std::string> matches;
494 if (keyPair.value().type() ==
495 nlohmann::json::value_t::string)
496 {
497 matches.emplace_back(keyPair.value());
498 }
499 else
500 {
501 for (const auto& value : keyPair.value())
502 {
503 if (value.type() !=
504 nlohmann::json::value_t::string)
505 {
506 std::cerr << "Value is invalid type "
507 << value << "\n";
508 break;
509 }
510 matches.emplace_back(value);
511 }
512 }
513
514 std::set<std::string> foundMatches;
Andrew Jefferyf5184712022-03-25 13:38:07 +1030515 for (auto& [configId, config] :
Andrew Jeffery47af65a2021-12-01 14:16:31 +1030516 _systemConfiguration.items())
517 {
518 if (isDisable)
519 {
520 // don't disable ourselves
Andrew Jefferyf5184712022-03-25 13:38:07 +1030521 if (configId == recordName)
Andrew Jeffery47af65a2021-12-01 14:16:31 +1030522 {
523 continue;
524 }
525 }
Andrew Jefferyf5184712022-03-25 13:38:07 +1030526 auto configListFind = config.find("Exposes");
Andrew Jeffery47af65a2021-12-01 14:16:31 +1030527
Andrew Jefferyf5184712022-03-25 13:38:07 +1030528 if (configListFind == config.end() ||
Andrew Jeffery47af65a2021-12-01 14:16:31 +1030529 configListFind->type() !=
530 nlohmann::json::value_t::array)
531 {
532 continue;
533 }
534 for (auto& exposedObject : *configListFind)
535 {
536 auto matchIt = std::find_if(
537 matches.begin(), matches.end(),
538 [name = (exposedObject)["Name"]
539 .get<std::string>()](
540 const std::string& s) {
541 return s == name;
542 });
543 if (matchIt == matches.end())
544 {
545 continue;
546 }
547 foundMatches.insert(*matchIt);
548
549 if (isBind)
550 {
551 std::string bind = keyPair.key().substr(
552 sizeof("Bind") - 1);
553
554 exposedObject["Status"] = "okay";
555 expose[bind] = exposedObject;
556 }
557 else if (isDisable)
558 {
559 exposedObject["Status"] = "disabled";
560 }
561 }
562 }
563 if (foundMatches.size() != matches.size())
564 {
565 std::cerr << "configuration file "
566 "dependency error, "
567 "could not find "
568 << keyPair.key() << " "
569 << keyPair.value() << "\n";
570 }
571 }
572 }
573 // overwrite ourselves with cleaned up version
574 _systemConfiguration[recordName] = record;
575 _missingConfigurations.erase(recordName);
576 }
577 });
578
579 // parse out dbus probes by discarding other probe types, store in a
580 // map
581 for (const nlohmann::json& probeJson : probeCommand)
582 {
583 const std::string* probe = probeJson.get_ptr<const std::string*>();
584 if (probe == nullptr)
585 {
586 std::cerr << "Probe statement wasn't a string, can't parse";
587 continue;
588 }
Andrew Jeffery666583b2021-12-01 15:50:12 +1030589 if (findProbeType(probe->c_str()))
Andrew Jeffery47af65a2021-12-01 14:16:31 +1030590 {
591 continue;
592 }
593 // syntax requires probe before first open brace
594 auto findStart = probe->find('(');
595 std::string interface = probe->substr(0, findStart);
596 dbusProbeInterfaces.emplace(interface);
597 dbusProbePointers.emplace_back(probePointer);
598 }
599 it++;
600 }
601
602 // probe vector stores a shared_ptr to each PerformProbe that cares
603 // about a dbus interface
604 findDbusObjects(std::move(dbusProbePointers),
605 std::move(dbusProbeInterfaces), shared_from_this());
606 if constexpr (debug)
607 {
608 std::cerr << __func__ << " " << __LINE__ << "\n";
609 }
610}
611
612PerformScan::~PerformScan()
613{
614 if (_passed)
615 {
616 auto nextScan = std::make_shared<PerformScan>(
617 _systemConfiguration, _missingConfigurations, _configurations,
618 objServer, std::move(_callback));
619 nextScan->passedProbes = std::move(passedProbes);
620 nextScan->dbusProbeObjects = std::move(dbusProbeObjects);
621 nextScan->run();
622
623 if constexpr (debug)
624 {
625 std::cerr << __func__ << " " << __LINE__ << "\n";
626 }
627 }
628 else
629 {
630 _callback();
631
632 if constexpr (debug)
633 {
634 std::cerr << __func__ << " " << __LINE__ << "\n";
635 }
636 }
637}