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