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