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