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