1 #include "config.h"
2
3 #include "item_updater.hpp"
4
5 #include "utils.hpp"
6
7 #include <phosphor-logging/elog-errors.hpp>
8 #include <phosphor-logging/log.hpp>
9 #include <xyz/openbmc_project/Common/error.hpp>
10
11 #include <cassert>
12 #include <filesystem>
13
14 namespace
15 {
16 constexpr auto MANIFEST_VERSION = "version";
17 constexpr auto MANIFEST_EXTENDED_VERSION = "extended_version";
18 constexpr auto TIMEOUT = 10;
19 } // namespace
20
21 namespace phosphor
22 {
23 namespace software
24 {
25 namespace updater
26 {
27 namespace server = sdbusplus::xyz::openbmc_project::Software::server;
28
29 using namespace sdbusplus::xyz::openbmc_project::Common::Error;
30 using namespace phosphor::logging;
31 using SVersion = server::Version;
32 using VersionPurpose = SVersion::VersionPurpose;
33
createActivation(sdbusplus::message_t & m)34 void ItemUpdater::createActivation(sdbusplus::message_t& m)
35 {
36 sdbusplus::message::object_path objPath;
37 std::map<std::string, std::map<std::string, std::variant<std::string>>>
38 interfaces;
39 m.read(objPath, interfaces);
40
41 std::string path(std::move(objPath));
42 std::string filePath;
43 auto purpose = VersionPurpose::Unknown;
44 std::string version;
45
46 for (const auto& [interfaceName, propertyMap] : interfaces)
47 {
48 if (interfaceName == VERSION_IFACE)
49 {
50 for (const auto& [propertyName, propertyValue] : propertyMap)
51 {
52 if (propertyName == "Purpose")
53 {
54 // Only process the PSU images
55 auto value = SVersion::convertVersionPurposeFromString(
56 std::get<std::string>(propertyValue));
57
58 if (value == VersionPurpose::PSU)
59 {
60 purpose = value;
61 }
62 }
63 else if (propertyName == VERSION)
64 {
65 version = std::get<std::string>(propertyValue);
66 }
67 }
68 }
69 else if (interfaceName == FILEPATH_IFACE)
70 {
71 const auto& it = propertyMap.find("Path");
72 if (it != propertyMap.end())
73 {
74 filePath = std::get<std::string>(it->second);
75 }
76 }
77 }
78 if ((filePath.empty()) || (purpose == VersionPurpose::Unknown))
79 {
80 return;
81 }
82
83 // If we are only installing PSU images from the built-in directory, ignore
84 // PSU images from other directories
85 if (ALWAYS_USE_BUILTIN_IMG_DIR && !filePath.starts_with(IMG_DIR_BUILTIN))
86 {
87 return;
88 }
89
90 // Version id is the last item in the path
91 auto pos = path.rfind('/');
92 if (pos == std::string::npos)
93 {
94 log<level::ERR>("No version id found in object path",
95 entry("OBJPATH=%s", path.c_str()));
96 return;
97 }
98
99 auto versionId = path.substr(pos + 1);
100
101 if (activations.find(versionId) == activations.end())
102 {
103 // Determine the Activation state by processing the given image dir.
104 AssociationList associations;
105 auto activationState = Activation::Status::Ready;
106
107 associations.emplace_back(std::make_tuple(
108 ACTIVATION_FWD_ASSOCIATION, ACTIVATION_REV_ASSOCIATION,
109 PSU_INVENTORY_PATH_BASE));
110
111 fs::path manifestPath(filePath);
112 manifestPath /= MANIFEST_FILE;
113 std::string extendedVersion =
114 Version::getValue(manifestPath, {MANIFEST_EXTENDED_VERSION});
115
116 auto activation =
117 createActivationObject(path, versionId, extendedVersion,
118 activationState, associations, filePath);
119 activations.emplace(versionId, std::move(activation));
120
121 auto versionPtr =
122 createVersionObject(path, versionId, version, purpose);
123 versions.emplace(versionId, std::move(versionPtr));
124 }
125 return;
126 }
127
erase(const std::string & versionId)128 void ItemUpdater::erase(const std::string& versionId)
129 {
130 auto it = versions.find(versionId);
131 if (it == versions.end())
132 {
133 log<level::ERR>(("Error: Failed to find version " + versionId +
134 " in item updater versions map."
135 " Unable to remove.")
136 .c_str());
137 }
138 else
139 {
140 versionStrings.erase(it->second->getVersionString());
141 versions.erase(it);
142 }
143
144 // Removing entry in activations map
145 auto ita = activations.find(versionId);
146 if (ita == activations.end())
147 {
148 log<level::ERR>(("Error: Failed to find version " + versionId +
149 " in item updater activations map."
150 " Unable to remove.")
151 .c_str());
152 }
153 else
154 {
155 activations.erase(versionId);
156 }
157 }
158
createActiveAssociation(const std::string & path)159 void ItemUpdater::createActiveAssociation(const std::string& path)
160 {
161 assocs.emplace_back(
162 std::make_tuple(ACTIVE_FWD_ASSOCIATION, ACTIVE_REV_ASSOCIATION, path));
163 associations(assocs);
164 }
165
addFunctionalAssociation(const std::string & path)166 void ItemUpdater::addFunctionalAssociation(const std::string& path)
167 {
168 assocs.emplace_back(std::make_tuple(FUNCTIONAL_FWD_ASSOCIATION,
169 FUNCTIONAL_REV_ASSOCIATION, path));
170 associations(assocs);
171 }
172
addUpdateableAssociation(const std::string & path)173 void ItemUpdater::addUpdateableAssociation(const std::string& path)
174 {
175 assocs.emplace_back(std::make_tuple(UPDATEABLE_FWD_ASSOCIATION,
176 UPDATEABLE_REV_ASSOCIATION, path));
177 associations(assocs);
178 }
179
removeAssociation(const std::string & path)180 void ItemUpdater::removeAssociation(const std::string& path)
181 {
182 for (auto iter = assocs.begin(); iter != assocs.end();)
183 {
184 if ((std::get<2>(*iter)) == path)
185 {
186 iter = assocs.erase(iter);
187 associations(assocs);
188 }
189 else
190 {
191 ++iter;
192 }
193 }
194 }
195
onUpdateDone(const std::string & versionId,const std::string & psuInventoryPath)196 void ItemUpdater::onUpdateDone(const std::string& versionId,
197 const std::string& psuInventoryPath)
198 {
199 // After update is done, remove old activation objects
200 for (auto it = activations.begin(); it != activations.end(); ++it)
201 {
202 if (it->second->getVersionId() != versionId &&
203 utils::isAssociated(psuInventoryPath, it->second->associations()))
204 {
205 removePsuObject(psuInventoryPath);
206 break;
207 }
208 }
209
210 auto it = activations.find(versionId);
211 assert(it != activations.end());
212 psuPathActivationMap.emplace(psuInventoryPath, it->second);
213 }
214
createActivationObject(const std::string & path,const std::string & versionId,const std::string & extVersion,Activation::Status activationStatus,const AssociationList & assocs,const std::string & filePath)215 std::unique_ptr<Activation> ItemUpdater::createActivationObject(
216 const std::string& path, const std::string& versionId,
217 const std::string& extVersion, Activation::Status activationStatus,
218 const AssociationList& assocs, const std::string& filePath)
219 {
220 return std::make_unique<Activation>(bus, path, versionId, extVersion,
221 activationStatus, assocs, filePath,
222 this, this);
223 }
224
createPsuObject(const std::string & psuInventoryPath,const std::string & psuVersion)225 void ItemUpdater::createPsuObject(const std::string& psuInventoryPath,
226 const std::string& psuVersion)
227 {
228 auto versionId = utils::getVersionId(psuVersion);
229 auto path = std::string(SOFTWARE_OBJPATH) + "/" + versionId;
230
231 auto it = activations.find(versionId);
232 if (it != activations.end())
233 {
234 // The versionId is already created, associate the path
235 auto associations = it->second->associations();
236 associations.emplace_back(
237 std::make_tuple(ACTIVATION_FWD_ASSOCIATION,
238 ACTIVATION_REV_ASSOCIATION, psuInventoryPath));
239 it->second->associations(associations);
240 psuPathActivationMap.emplace(psuInventoryPath, it->second);
241 }
242 else
243 {
244 // Create a new object for running PSU inventory
245 AssociationList associations;
246 auto activationState = Activation::Status::Active;
247
248 associations.emplace_back(
249 std::make_tuple(ACTIVATION_FWD_ASSOCIATION,
250 ACTIVATION_REV_ASSOCIATION, psuInventoryPath));
251
252 auto activation = createActivationObject(
253 path, versionId, "", activationState, associations, "");
254 activations.emplace(versionId, std::move(activation));
255 psuPathActivationMap.emplace(psuInventoryPath, activations[versionId]);
256
257 auto versionPtr = createVersionObject(path, versionId, psuVersion,
258 VersionPurpose::PSU);
259 versions.emplace(versionId, std::move(versionPtr));
260
261 createActiveAssociation(path);
262 addFunctionalAssociation(path);
263 addUpdateableAssociation(path);
264 }
265 }
266
removePsuObject(const std::string & psuInventoryPath)267 void ItemUpdater::removePsuObject(const std::string& psuInventoryPath)
268 {
269 auto it = psuPathActivationMap.find(psuInventoryPath);
270 if (it == psuPathActivationMap.end())
271 {
272 log<level::ERR>("No Activation found for PSU",
273 entry("PSUPATH=%s", psuInventoryPath.c_str()));
274 return;
275 }
276 const auto& activationPtr = it->second;
277 psuPathActivationMap.erase(psuInventoryPath);
278
279 auto associations = activationPtr->associations();
280 for (auto iter = associations.begin(); iter != associations.end();)
281 {
282 if ((std::get<2>(*iter)) == psuInventoryPath)
283 {
284 iter = associations.erase(iter);
285 }
286 else
287 {
288 ++iter;
289 }
290 }
291 if (associations.empty())
292 {
293 // Remove the activation
294 erase(activationPtr->getVersionId());
295 }
296 else
297 {
298 // Update association
299 activationPtr->associations(associations);
300 }
301 }
302
addPsuToStatusMap(const std::string & psuPath)303 void ItemUpdater::addPsuToStatusMap(const std::string& psuPath)
304 {
305 if (!psuStatusMap.contains(psuPath))
306 {
307 psuStatusMap[psuPath] = {false, ""};
308
309 // Add matches for PSU Inventory's property changes
310 psuMatches.emplace_back(
311 bus, MatchRules::propertiesChanged(psuPath, ITEM_IFACE),
312 std::bind(&ItemUpdater::onPsuInventoryChangedMsg, this,
313 std::placeholders::_1)); // For present
314 psuMatches.emplace_back(
315 bus, MatchRules::propertiesChanged(psuPath, ASSET_IFACE),
316 std::bind(&ItemUpdater::onPsuInventoryChangedMsg, this,
317 std::placeholders::_1)); // For model
318 }
319 }
320
createVersionObject(const std::string & objPath,const std::string & versionId,const std::string & versionString,sdbusplus::xyz::openbmc_project::Software::server::Version::VersionPurpose versionPurpose)321 std::unique_ptr<Version> ItemUpdater::createVersionObject(
322 const std::string& objPath, const std::string& versionId,
323 const std::string& versionString,
324 sdbusplus::xyz::openbmc_project::Software::server::Version::VersionPurpose
325 versionPurpose)
326 {
327 versionStrings.insert(versionString);
328 auto version = std::make_unique<Version>(
329 bus, objPath, versionId, versionString, versionPurpose,
330 std::bind(&ItemUpdater::erase, this, std::placeholders::_1));
331 return version;
332 }
333
onPsuInventoryChangedMsg(sdbusplus::message_t & msg)334 void ItemUpdater::onPsuInventoryChangedMsg(sdbusplus::message_t& msg)
335 {
336 using Interface = std::string;
337 Interface interface;
338 Properties properties;
339 std::string psuPath = msg.get_path();
340
341 msg.read(interface, properties);
342 onPsuInventoryChanged(psuPath, properties);
343 }
344
onPsuInventoryChanged(const std::string & psuPath,const Properties & properties)345 void ItemUpdater::onPsuInventoryChanged(const std::string& psuPath,
346 const Properties& properties)
347 {
348 std::optional<bool> present;
349 std::optional<std::string> model;
350
351 // The code was expecting to get callback on multiple properties changed.
352 // But in practice, the callback is received one-by-one for each property.
353 // So it has to handle Present and Version property separately.
354 auto p = properties.find(PRESENT);
355 if (p != properties.end())
356 {
357 present = std::get<bool>(p->second);
358 psuStatusMap[psuPath].present = *present;
359 }
360 p = properties.find(MODEL);
361 if (p != properties.end())
362 {
363 model = std::get<std::string>(p->second);
364 psuStatusMap[psuPath].model = *model;
365 }
366
367 // If present or model is not changed, ignore
368 if (!present.has_value() && !model.has_value())
369 {
370 return;
371 }
372
373 if (psuStatusMap[psuPath].present)
374 {
375 // If model is not updated, let's wait for it
376 if (psuStatusMap[psuPath].model.empty())
377 {
378 log<level::DEBUG>("Waiting for model to be updated");
379 return;
380 }
381
382 auto version = utils::getVersion(psuPath);
383 if (!version.empty())
384 {
385 if (psuPathActivationMap.find(psuPath) ==
386 psuPathActivationMap.end())
387 {
388 createPsuObject(psuPath, version);
389 }
390 }
391 else
392 {
393 // TODO: log an event
394 log<level::ERR>("Failed to get PSU version",
395 entry("PSU=%s", psuPath.c_str()));
396 }
397 // Check if there are new PSU images to update
398 processStoredImage();
399 syncToLatestImage();
400 }
401 else
402 {
403 if (!present.has_value())
404 {
405 // If a PSU is plugged out, model property is update to empty as
406 // well, and we get callback here, but ignore that because it is
407 // handled by "Present" callback.
408 return;
409 }
410 psuStatusMap[psuPath].model = "";
411
412 // Remove object or association
413 removePsuObject(psuPath);
414 }
415 }
416
processPSUImage()417 void ItemUpdater::processPSUImage()
418 {
419 auto paths = utils::getPSUInventoryPath(bus);
420 for (const auto& p : paths)
421 {
422 addPsuToStatusMap(p);
423
424 auto service = utils::getService(bus, p.c_str(), ITEM_IFACE);
425 psuStatusMap[p].present = utils::getProperty<bool>(
426 bus, service.c_str(), p.c_str(), ITEM_IFACE, PRESENT);
427 psuStatusMap[p].model = utils::getProperty<std::string>(
428 bus, service.c_str(), p.c_str(), ASSET_IFACE, MODEL);
429 auto version = utils::getVersion(p);
430 if ((psuPathActivationMap.find(p) == psuPathActivationMap.end()) &&
431 psuStatusMap[p].present && !version.empty())
432 {
433 createPsuObject(p, version);
434 }
435 }
436 }
437
processStoredImage()438 void ItemUpdater::processStoredImage()
439 {
440 scanDirectory(IMG_DIR_BUILTIN);
441
442 if (!ALWAYS_USE_BUILTIN_IMG_DIR)
443 {
444 scanDirectory(IMG_DIR_PERSIST);
445 }
446 }
447
scanDirectory(const fs::path & dir)448 void ItemUpdater::scanDirectory(const fs::path& dir)
449 {
450 auto manifest = dir;
451 auto path = dir;
452 // The directory shall put PSU images in directories named with model
453 if (!fs::exists(dir))
454 {
455 // Skip
456 return;
457 }
458 if (!fs::is_directory(dir))
459 {
460 log<level::ERR>("The path is not a directory",
461 entry("PATH=%s", dir.c_str()));
462 return;
463 }
464
465 for (const auto& [key, item] : psuStatusMap)
466 {
467 if (!item.model.empty())
468 {
469 path = path / item.model;
470 manifest = dir / item.model / MANIFEST_FILE;
471 break;
472 }
473 }
474 if (path == dir)
475 {
476 log<level::ERR>("Model directory not found");
477 return;
478 }
479
480 if (!fs::is_directory(path))
481 {
482 log<level::ERR>("The path is not a directory",
483 entry("PATH=%s", path.c_str()));
484 return;
485 }
486
487 if (!fs::exists(manifest))
488 {
489 log<level::ERR>("No MANIFEST found",
490 entry("PATH=%s", manifest.c_str()));
491 return;
492 }
493 // If the model in manifest does not match the dir name
494 // Log a warning
495 if (fs::is_regular_file(manifest))
496 {
497 auto ret = Version::getValues(
498 manifest.string(), {MANIFEST_VERSION, MANIFEST_EXTENDED_VERSION});
499 auto version = ret[MANIFEST_VERSION];
500 auto extVersion = ret[MANIFEST_EXTENDED_VERSION];
501 auto info = Version::getExtVersionInfo(extVersion);
502 auto model = info["model"];
503 if (path.stem() != model)
504 {
505 log<level::ERR>("Unmatched model", entry("PATH=%s", path.c_str()),
506 entry("MODEL=%s", model.c_str()));
507 }
508 else
509 {
510 auto versionId = utils::getVersionId(version);
511 auto it = activations.find(versionId);
512 if (it == activations.end())
513 {
514 // This is a version that is different than the running PSUs
515 auto activationState = Activation::Status::Ready;
516 auto purpose = VersionPurpose::PSU;
517 auto objPath = std::string(SOFTWARE_OBJPATH) + "/" + versionId;
518
519 auto activation = createActivationObject(
520 objPath, versionId, extVersion, activationState, {}, path);
521 activations.emplace(versionId, std::move(activation));
522
523 auto versionPtr =
524 createVersionObject(objPath, versionId, version, purpose);
525 versions.emplace(versionId, std::move(versionPtr));
526 }
527 else
528 {
529 // This is a version that a running PSU is using, set the path
530 // on the version object
531 it->second->path(path);
532 }
533 }
534 }
535 else
536 {
537 log<level::ERR>("MANIFEST is not a file",
538 entry("PATH=%s", manifest.c_str()));
539 }
540 }
541
getLatestVersionId()542 std::optional<std::string> ItemUpdater::getLatestVersionId()
543 {
544 std::string latestVersion;
545 if (ALWAYS_USE_BUILTIN_IMG_DIR)
546 {
547 latestVersion = getFWVersionFromBuiltinDir();
548 }
549 else
550 {
551 latestVersion = utils::getLatestVersion(versionStrings);
552 }
553 if (latestVersion.empty())
554 {
555 return {};
556 }
557
558 std::optional<std::string> versionId;
559 for (const auto& v : versions)
560 {
561 if (v.second->version() == latestVersion)
562 {
563 versionId = v.first;
564 break;
565 }
566 }
567 assert(versionId.has_value());
568 return versionId;
569 }
570
syncToLatestImage()571 void ItemUpdater::syncToLatestImage()
572 {
573 auto latestVersionId = getLatestVersionId();
574 if (!latestVersionId)
575 {
576 return;
577 }
578 const auto& it = activations.find(*latestVersionId);
579 assert(it != activations.end());
580 const auto& activation = it->second;
581 const auto& assocs = activation->associations();
582
583 auto paths = utils::getPSUInventoryPath(bus);
584 for (const auto& p : paths)
585 {
586 // As long as there is a PSU is not associated with the latest
587 // image, run the activation so that all PSUs are running the same
588 // latest image.
589 if (!utils::isAssociated(p, assocs))
590 {
591 log<level::INFO>("Automatically update PSU",
592 entry("VERSION_ID=%s", latestVersionId->c_str()));
593 invokeActivation(activation);
594 break;
595 }
596 }
597 }
598
invokeActivation(const std::unique_ptr<Activation> & activation)599 void ItemUpdater::invokeActivation(
600 const std::unique_ptr<Activation>& activation)
601 {
602 activation->requestedActivation(Activation::RequestedActivations::Active);
603 }
604
onPSUInterfaceAdded(sdbusplus::message_t & msg)605 void ItemUpdater::onPSUInterfaceAdded(sdbusplus::message_t& msg)
606 {
607 sdbusplus::message::object_path objPath;
608 std::map<std::string,
609 std::map<std::string, std::variant<bool, std::string>>>
610 interfaces;
611 msg.read(objPath, interfaces);
612 std::string path = objPath.str;
613
614 if (interfaces.find(PSU_INVENTORY_IFACE) == interfaces.end())
615 {
616 return;
617 }
618
619 addPsuToStatusMap(path);
620
621 if (psuStatusMap[path].present && !psuStatusMap[path].model.empty())
622 {
623 return;
624 }
625
626 auto timeout = std::chrono::steady_clock::now() +
627 std::chrono::seconds(TIMEOUT);
628
629 // Poll the inventory item until it gets the present property
630 // or the timeout is reached
631 while (std::chrono::steady_clock::now() < timeout)
632 {
633 try
634 {
635 psuStatusMap[path].present = utils::getProperty<bool>(
636 bus, msg.get_sender(), path.c_str(), ITEM_IFACE, PRESENT);
637 break;
638 }
639 catch (const std::exception& e)
640 {
641 auto err = errno;
642 log<level::INFO>(
643 std::format("Failed to get Inventory Item Present. errno={}",
644 err)
645 .c_str());
646 sleep(1);
647 }
648 }
649
650 // Poll the inventory item until it retrieves model or the timeout is
651 // reached. The model is the path trail of the firmware's and manifest
652 // subdirectory. If the model not found the firmware and manifest
653 // cannot be located.
654 timeout = std::chrono::steady_clock::now() + std::chrono::seconds(TIMEOUT);
655 while (std::chrono::steady_clock::now() < timeout &&
656 psuStatusMap[path].present)
657 {
658 try
659 {
660 psuStatusMap[path].model = utils::getProperty<std::string>(
661 bus, msg.get_sender(), path.c_str(), ASSET_IFACE, MODEL);
662 processPSUImageAndSyncToLatest();
663 break;
664 }
665 catch (const std::exception& e)
666 {
667 auto err = errno;
668 log<level::INFO>(
669 std::format(
670 "Failed to get Inventory Decorator Asset model. errno={}",
671 err)
672 .c_str());
673 sleep(1);
674 }
675 }
676 }
677
processPSUImageAndSyncToLatest()678 void ItemUpdater::processPSUImageAndSyncToLatest()
679 {
680 processPSUImage();
681 processStoredImage();
682 syncToLatestImage();
683 }
684
getFWVersionFromBuiltinDir()685 std::string ItemUpdater::getFWVersionFromBuiltinDir()
686 {
687 std::string version;
688 for (const auto& activation : activations)
689 {
690 if (activation.second->path().starts_with(IMG_DIR_BUILTIN))
691 {
692 std::string versionId = activation.second->getVersionId();
693 auto it = versions.find(versionId);
694 if (it != versions.end())
695 {
696 const auto& versionPtr = it->second;
697 version = versionPtr->version();
698 break;
699 }
700 }
701 }
702 return version;
703 }
704
705 } // namespace updater
706 } // namespace software
707 } // namespace phosphor
708