xref: /openbmc/bmcweb/features/redfish/include/redfish_aggregator.hpp (revision 26ccae32112679c4653c1e3f8a1203c828bea05c)
17fb33566SCarson Labrado #pragma once
27fb33566SCarson Labrado 
33ccb3adbSEd Tanous #include "aggregation_utils.hpp"
43ccb3adbSEd Tanous #include "dbus_utility.hpp"
53ccb3adbSEd Tanous #include "error_messages.hpp"
63ccb3adbSEd Tanous #include "http_client.hpp"
73ccb3adbSEd Tanous #include "http_connection.hpp"
83ccb3adbSEd Tanous 
9411e6a11SCarson Labrado #include <boost/algorithm/string/predicate.hpp>
107fb33566SCarson Labrado 
117e8890c5SCarson Labrado #include <array>
127e8890c5SCarson Labrado 
137fb33566SCarson Labrado namespace redfish
147fb33566SCarson Labrado {
157fb33566SCarson Labrado 
1605916cefSCarson Labrado enum class Result
1705916cefSCarson Labrado {
1805916cefSCarson Labrado     LocalHandle,
1905916cefSCarson Labrado     NoLocalHandle
2005916cefSCarson Labrado };
2105916cefSCarson Labrado 
227e8890c5SCarson Labrado // clang-format off
237e8890c5SCarson Labrado // These are all of the properties as of version 2022.2 of the Redfish Resource
247e8890c5SCarson Labrado // and Schema Guide whose Type is "string (URI)" and the name does not end in a
257e8890c5SCarson Labrado // case-insensitive form of "uri".  That version of the schema is associated
267e8890c5SCarson Labrado // with version 1.16.0 of the Redfish Specification.  Going forward, new URI
277e8890c5SCarson Labrado // properties should end in URI so this list should not need to be maintained as
287e8890c5SCarson Labrado // the spec is updated.  NOTE: These have been pre-sorted in order to be
297e8890c5SCarson Labrado // compatible with binary search
307e8890c5SCarson Labrado constexpr std::array nonUriProperties{
317e8890c5SCarson Labrado     "@Redfish.ActionInfo",
327e8890c5SCarson Labrado     // "@odata.context", // We can't fix /redfish/v1/$metadata URIs
337e8890c5SCarson Labrado     "@odata.id",
347e8890c5SCarson Labrado     // "Destination", // Only used by EventService and won't be a Redfish URI
357e8890c5SCarson Labrado     // "HostName", // Isn't actually a Redfish URI
367e8890c5SCarson Labrado     "Image",
377e8890c5SCarson Labrado     "MetricProperty",
3832d7d8ebSCarson Labrado     // "OriginOfCondition", // Is URI when in request, but is object in response
397e8890c5SCarson Labrado     "TaskMonitor",
407e8890c5SCarson Labrado     "target", // normal string, but target URI for POST to invoke an action
417e8890c5SCarson Labrado };
427e8890c5SCarson Labrado // clang-format on
437e8890c5SCarson Labrado 
447e8890c5SCarson Labrado // Determines if the passed property contains a URI.  Those property names
457e8890c5SCarson Labrado // either end with a case-insensitive version of "uri" or are specifically
467e8890c5SCarson Labrado // defined in the above array.
47*26ccae32SEd Tanous inline bool isPropertyUri(std::string_view propertyName)
487e8890c5SCarson Labrado {
497e8890c5SCarson Labrado     return boost::iends_with(propertyName, "uri") ||
507e8890c5SCarson Labrado            std::binary_search(nonUriProperties.begin(), nonUriProperties.end(),
517e8890c5SCarson Labrado                               propertyName);
527e8890c5SCarson Labrado }
537e8890c5SCarson Labrado 
540af78d5aSKhang Kieu static inline void addPrefixToStringItem(std::string& strValue,
550af78d5aSKhang Kieu                                          std::string_view prefix)
561c0bb5c6SCarson Labrado {
571c0bb5c6SCarson Labrado     // Make sure the value is a properly formatted URI
580af78d5aSKhang Kieu     auto parsed = boost::urls::parse_relative_ref(strValue);
591c0bb5c6SCarson Labrado     if (!parsed)
601c0bb5c6SCarson Labrado     {
610af78d5aSKhang Kieu         BMCWEB_LOG_CRITICAL << "Couldn't parse URI from resource " << strValue;
621c0bb5c6SCarson Labrado         return;
631c0bb5c6SCarson Labrado     }
641c0bb5c6SCarson Labrado 
651c0bb5c6SCarson Labrado     boost::urls::url_view thisUrl = *parsed;
661c0bb5c6SCarson Labrado 
67411e6a11SCarson Labrado     // We don't need to aggregate JsonSchemas due to potential issues such as
68411e6a11SCarson Labrado     // version mismatches between aggregator and satellite BMCs.  For now
69411e6a11SCarson Labrado     // assume that the aggregator has all the schemas and versions that the
70411e6a11SCarson Labrado     // aggregated server has.
71411e6a11SCarson Labrado     if (crow::utility::readUrlSegments(thisUrl, "redfish", "v1", "JsonSchemas",
72411e6a11SCarson Labrado                                        crow::utility::OrMorePaths()))
73411e6a11SCarson Labrado     {
74411e6a11SCarson Labrado         BMCWEB_LOG_DEBUG << "Skipping JsonSchemas URI prefix fixing";
75411e6a11SCarson Labrado         return;
76411e6a11SCarson Labrado     }
77411e6a11SCarson Labrado 
7811987af6SCarson Labrado     // The first two segments should be "/redfish/v1".  We need to check that
7911987af6SCarson Labrado     // before we can search topCollections
8011987af6SCarson Labrado     if (!crow::utility::readUrlSegments(thisUrl, "redfish", "v1",
8111987af6SCarson Labrado                                         crow::utility::OrMorePaths()))
821c0bb5c6SCarson Labrado     {
831c0bb5c6SCarson Labrado         return;
841c0bb5c6SCarson Labrado     }
851c0bb5c6SCarson Labrado 
8611987af6SCarson Labrado     // Check array adding a segment each time until collection is identified
8711987af6SCarson Labrado     // Add prefix to segment after the collection
8811987af6SCarson Labrado     const boost::urls::segments_view urlSegments = thisUrl.segments();
8911987af6SCarson Labrado     bool addedPrefix = false;
9011987af6SCarson Labrado     boost::urls::url url("/");
9111987af6SCarson Labrado     boost::urls::segments_view::iterator it = urlSegments.begin();
9211987af6SCarson Labrado     const boost::urls::segments_view::const_iterator end = urlSegments.end();
9311987af6SCarson Labrado 
9411987af6SCarson Labrado     // Skip past the leading "/redfish/v1"
9511987af6SCarson Labrado     it++;
9611987af6SCarson Labrado     it++;
9711987af6SCarson Labrado     for (; it != end; it++)
981c0bb5c6SCarson Labrado     {
9911987af6SCarson Labrado         // Trailing "/" will result in an empty segment.  In that case we need
10011987af6SCarson Labrado         // to return so we don't apply a prefix to top level collections such
10111987af6SCarson Labrado         // as "/redfish/v1/Chassis/"
10211987af6SCarson Labrado         if ((*it).empty())
10311987af6SCarson Labrado         {
104411e6a11SCarson Labrado             return;
1051c0bb5c6SCarson Labrado         }
1061c0bb5c6SCarson Labrado 
10711987af6SCarson Labrado         if (std::binary_search(topCollections.begin(), topCollections.end(),
10811987af6SCarson Labrado                                url.buffer()))
1091c0bb5c6SCarson Labrado         {
11011987af6SCarson Labrado             std::string collectionItem(prefix);
11111987af6SCarson Labrado             collectionItem += "_" + (*it);
11211987af6SCarson Labrado             url.segments().push_back(collectionItem);
11311987af6SCarson Labrado             it++;
11411987af6SCarson Labrado             addedPrefix = true;
11511987af6SCarson Labrado             break;
11611987af6SCarson Labrado         }
11711987af6SCarson Labrado 
11811987af6SCarson Labrado         url.segments().push_back(*it);
11911987af6SCarson Labrado     }
12011987af6SCarson Labrado 
12111987af6SCarson Labrado     // Finish constructing the URL here (if needed) to avoid additional checks
12211987af6SCarson Labrado     for (; it != end; it++)
12311987af6SCarson Labrado     {
12411987af6SCarson Labrado         url.segments().push_back(*it);
12511987af6SCarson Labrado     }
12611987af6SCarson Labrado 
12711987af6SCarson Labrado     if (addedPrefix)
12811987af6SCarson Labrado     {
12911987af6SCarson Labrado         url.segments().insert(url.segments().begin(), {"redfish", "v1"});
1300af78d5aSKhang Kieu         strValue = url.buffer();
1311c0bb5c6SCarson Labrado     }
1321c0bb5c6SCarson Labrado }
1331c0bb5c6SCarson Labrado 
1340af78d5aSKhang Kieu static inline void addPrefixToItem(nlohmann::json& item,
1350af78d5aSKhang Kieu                                    std::string_view prefix)
1360af78d5aSKhang Kieu {
1370af78d5aSKhang Kieu     std::string* strValue = item.get_ptr<std::string*>();
1380af78d5aSKhang Kieu     if (strValue == nullptr)
1390af78d5aSKhang Kieu     {
1400af78d5aSKhang Kieu         BMCWEB_LOG_CRITICAL << "Field wasn't a string????";
1410af78d5aSKhang Kieu         return;
1420af78d5aSKhang Kieu     }
1430af78d5aSKhang Kieu     addPrefixToStringItem(*strValue, prefix);
1440af78d5aSKhang Kieu     item = *strValue;
1450af78d5aSKhang Kieu }
1460af78d5aSKhang Kieu 
1470af78d5aSKhang Kieu static inline void addAggregatedHeaders(crow::Response& asyncResp,
14824dadc88SCarson Labrado                                         const crow::Response& resp,
1490af78d5aSKhang Kieu                                         std::string_view prefix)
1500af78d5aSKhang Kieu {
1510af78d5aSKhang Kieu     if (!resp.getHeaderValue("Content-Type").empty())
1520af78d5aSKhang Kieu     {
1530af78d5aSKhang Kieu         asyncResp.addHeader(boost::beast::http::field::content_type,
1540af78d5aSKhang Kieu                             resp.getHeaderValue("Content-Type"));
1550af78d5aSKhang Kieu     }
1560af78d5aSKhang Kieu     if (!resp.getHeaderValue("Allow").empty())
1570af78d5aSKhang Kieu     {
1580af78d5aSKhang Kieu         asyncResp.addHeader(boost::beast::http::field::allow,
1590af78d5aSKhang Kieu                             resp.getHeaderValue("Allow"));
1600af78d5aSKhang Kieu     }
1610af78d5aSKhang Kieu     std::string_view header = resp.getHeaderValue("Location");
1620af78d5aSKhang Kieu     if (!header.empty())
1630af78d5aSKhang Kieu     {
1640af78d5aSKhang Kieu         std::string location(header);
1650af78d5aSKhang Kieu         addPrefixToStringItem(location, prefix);
1660af78d5aSKhang Kieu         asyncResp.addHeader(boost::beast::http::field::location, location);
1670af78d5aSKhang Kieu     }
1680af78d5aSKhang Kieu     if (!resp.getHeaderValue("Retry-After").empty())
1690af78d5aSKhang Kieu     {
1700af78d5aSKhang Kieu         asyncResp.addHeader(boost::beast::http::field::retry_after,
1710af78d5aSKhang Kieu                             resp.getHeaderValue("Retry-After"));
1720af78d5aSKhang Kieu     }
1730af78d5aSKhang Kieu     // TODO: we need special handling for Link Header Value
1740af78d5aSKhang Kieu }
1750af78d5aSKhang Kieu 
1761c0bb5c6SCarson Labrado // Search the json for all URIs and add the supplied prefix if the URI is for
1777e8890c5SCarson Labrado // an aggregated resource.
1780af78d5aSKhang Kieu static inline void addPrefixes(nlohmann::json& json, std::string_view prefix)
1791c0bb5c6SCarson Labrado {
1801c0bb5c6SCarson Labrado     nlohmann::json::object_t* object =
1811c0bb5c6SCarson Labrado         json.get_ptr<nlohmann::json::object_t*>();
1821c0bb5c6SCarson Labrado     if (object != nullptr)
1831c0bb5c6SCarson Labrado     {
1841c0bb5c6SCarson Labrado         for (std::pair<const std::string, nlohmann::json>& item : *object)
1851c0bb5c6SCarson Labrado         {
1867e8890c5SCarson Labrado             if (isPropertyUri(item.first))
1871c0bb5c6SCarson Labrado             {
1887e8890c5SCarson Labrado                 addPrefixToItem(item.second, prefix);
1891c0bb5c6SCarson Labrado                 continue;
1901c0bb5c6SCarson Labrado             }
1911c0bb5c6SCarson Labrado 
1921c0bb5c6SCarson Labrado             // Recusively parse the rest of the json
1931c0bb5c6SCarson Labrado             addPrefixes(item.second, prefix);
1941c0bb5c6SCarson Labrado         }
1951c0bb5c6SCarson Labrado         return;
1961c0bb5c6SCarson Labrado     }
1971c0bb5c6SCarson Labrado     nlohmann::json::array_t* array = json.get_ptr<nlohmann::json::array_t*>();
1981c0bb5c6SCarson Labrado     if (array != nullptr)
1991c0bb5c6SCarson Labrado     {
2001c0bb5c6SCarson Labrado         for (nlohmann::json& item : *array)
2011c0bb5c6SCarson Labrado         {
2021c0bb5c6SCarson Labrado             addPrefixes(item, prefix);
2031c0bb5c6SCarson Labrado         }
2041c0bb5c6SCarson Labrado     }
2051c0bb5c6SCarson Labrado }
2061c0bb5c6SCarson Labrado 
2077fb33566SCarson Labrado class RedfishAggregator
2087fb33566SCarson Labrado {
2097fb33566SCarson Labrado   private:
210a7a80296SCarson Labrado     const std::string retryPolicyName = "RedfishAggregation";
211ce969437SCarson Labrado     const std::string retryPolicyAction = "TerminateAfterRetries";
212ce969437SCarson Labrado     const uint32_t retryAttempts = 1;
213a7a80296SCarson Labrado     const uint32_t retryTimeoutInterval = 0;
21446a81465SCarson Labrado     const std::string id = "Aggregator";
215a7a80296SCarson Labrado 
2167fb33566SCarson Labrado     RedfishAggregator()
2177fb33566SCarson Labrado     {
2187fb33566SCarson Labrado         getSatelliteConfigs(constructorCallback);
219a7a80296SCarson Labrado 
220a7a80296SCarson Labrado         // Setup the retry policy to be used by Redfish Aggregation
221a7a80296SCarson Labrado         crow::HttpClient::getInstance().setRetryConfig(
222a7a80296SCarson Labrado             retryAttempts, retryTimeoutInterval, aggregationRetryHandler,
223a7a80296SCarson Labrado             retryPolicyName);
224ce969437SCarson Labrado         crow::HttpClient::getInstance().setRetryPolicy(retryPolicyAction,
225ce969437SCarson Labrado                                                        retryPolicyName);
2267fb33566SCarson Labrado     }
2277fb33566SCarson Labrado 
228a7a80296SCarson Labrado     static inline boost::system::error_code
229a7a80296SCarson Labrado         aggregationRetryHandler(unsigned int respCode)
230a7a80296SCarson Labrado     {
23132d7d8ebSCarson Labrado         // Allow all response codes because we want to surface any satellite
23232d7d8ebSCarson Labrado         // issue to the client
23332d7d8ebSCarson Labrado         BMCWEB_LOG_DEBUG << "Received " << respCode
23432d7d8ebSCarson Labrado                          << " response from satellite";
235a7a80296SCarson Labrado         return boost::system::errc::make_error_code(
236a7a80296SCarson Labrado             boost::system::errc::success);
2379fa6d147SNan Zhou     }
238a7a80296SCarson Labrado 
2397fb33566SCarson Labrado     // Dummy callback used by the Constructor so that it can report the number
2407fb33566SCarson Labrado     // of satellite configs when the class is first created
2417fb33566SCarson Labrado     static void constructorCallback(
2427fb33566SCarson Labrado         const std::unordered_map<std::string, boost::urls::url>& satelliteInfo)
2437fb33566SCarson Labrado     {
2447fb33566SCarson Labrado         BMCWEB_LOG_DEBUG << "There were "
2457fb33566SCarson Labrado                          << std::to_string(satelliteInfo.size())
2467fb33566SCarson Labrado                          << " satellite configs found at startup";
2477fb33566SCarson Labrado     }
2487fb33566SCarson Labrado 
2497fb33566SCarson Labrado     // Polls D-Bus to get all available satellite config information
2507fb33566SCarson Labrado     // Expects a handler which interacts with the returned configs
2517fb33566SCarson Labrado     static void getSatelliteConfigs(
2527fb33566SCarson Labrado         const std::function<void(
2537fb33566SCarson Labrado             const std::unordered_map<std::string, boost::urls::url>&)>& handler)
2547fb33566SCarson Labrado     {
2557fb33566SCarson Labrado         BMCWEB_LOG_DEBUG << "Gathering satellite configs";
2567fb33566SCarson Labrado         crow::connections::systemBus->async_method_call(
2577fb33566SCarson Labrado             [handler](const boost::system::error_code ec,
2587fb33566SCarson Labrado                       const dbus::utility::ManagedObjectType& objects) {
2597fb33566SCarson Labrado             if (ec)
2607fb33566SCarson Labrado             {
261002d39b4SEd Tanous                 BMCWEB_LOG_ERROR << "DBUS response error " << ec.value() << ", "
262002d39b4SEd Tanous                                  << ec.message();
2637fb33566SCarson Labrado                 return;
2647fb33566SCarson Labrado             }
2657fb33566SCarson Labrado 
2667fb33566SCarson Labrado             // Maps a chosen alias representing a satellite BMC to a url
2677fb33566SCarson Labrado             // containing the information required to create a http
2687fb33566SCarson Labrado             // connection to the satellite
2697fb33566SCarson Labrado             std::unordered_map<std::string, boost::urls::url> satelliteInfo;
2707fb33566SCarson Labrado 
2717fb33566SCarson Labrado             findSatelliteConfigs(objects, satelliteInfo);
2727fb33566SCarson Labrado 
2737fb33566SCarson Labrado             if (!satelliteInfo.empty())
2747fb33566SCarson Labrado             {
2757fb33566SCarson Labrado                 BMCWEB_LOG_DEBUG << "Redfish Aggregation enabled with "
2767fb33566SCarson Labrado                                  << std::to_string(satelliteInfo.size())
2777fb33566SCarson Labrado                                  << " satellite BMCs";
2787fb33566SCarson Labrado             }
2797fb33566SCarson Labrado             else
2807fb33566SCarson Labrado             {
2817fb33566SCarson Labrado                 BMCWEB_LOG_DEBUG
2827fb33566SCarson Labrado                     << "No satellite BMCs detected.  Redfish Aggregation not enabled";
2837fb33566SCarson Labrado             }
2847fb33566SCarson Labrado             handler(satelliteInfo);
2857fb33566SCarson Labrado             },
286c106b67aSNan Zhou             "xyz.openbmc_project.EntityManager",
287c106b67aSNan Zhou             "/xyz/openbmc_project/inventory",
2887fb33566SCarson Labrado             "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
2897fb33566SCarson Labrado     }
2907fb33566SCarson Labrado 
2917fb33566SCarson Labrado     // Search D-Bus objects for satellite config objects and add their
2927fb33566SCarson Labrado     // information if valid
2937fb33566SCarson Labrado     static void findSatelliteConfigs(
2947fb33566SCarson Labrado         const dbus::utility::ManagedObjectType& objects,
2957fb33566SCarson Labrado         std::unordered_map<std::string, boost::urls::url>& satelliteInfo)
2967fb33566SCarson Labrado     {
2977fb33566SCarson Labrado         for (const auto& objectPath : objects)
2987fb33566SCarson Labrado         {
2997fb33566SCarson Labrado             for (const auto& interface : objectPath.second)
3007fb33566SCarson Labrado             {
3017fb33566SCarson Labrado                 if (interface.first ==
3027fb33566SCarson Labrado                     "xyz.openbmc_project.Configuration.SatelliteController")
3037fb33566SCarson Labrado                 {
3047fb33566SCarson Labrado                     BMCWEB_LOG_DEBUG << "Found Satellite Controller at "
3057fb33566SCarson Labrado                                      << objectPath.first.str;
3067fb33566SCarson Labrado 
30705916cefSCarson Labrado                     if (!satelliteInfo.empty())
30805916cefSCarson Labrado                     {
30905916cefSCarson Labrado                         BMCWEB_LOG_ERROR
31005916cefSCarson Labrado                             << "Redfish Aggregation only supports one satellite!";
31105916cefSCarson Labrado                         BMCWEB_LOG_DEBUG << "Clearing all satellite data";
31205916cefSCarson Labrado                         satelliteInfo.clear();
31305916cefSCarson Labrado                         return;
31405916cefSCarson Labrado                     }
31505916cefSCarson Labrado 
31605916cefSCarson Labrado                     // For now assume there will only be one satellite config.
31705916cefSCarson Labrado                     // Assign it the name/prefix "5B247A"
31805916cefSCarson Labrado                     addSatelliteConfig("5B247A", interface.second,
31905916cefSCarson Labrado                                        satelliteInfo);
3207fb33566SCarson Labrado                 }
3217fb33566SCarson Labrado             }
3227fb33566SCarson Labrado         }
3237fb33566SCarson Labrado     }
3247fb33566SCarson Labrado 
3257fb33566SCarson Labrado     // Parse the properties of a satellite config object and add the
3267fb33566SCarson Labrado     // configuration if the properties are valid
3277fb33566SCarson Labrado     static void addSatelliteConfig(
32805916cefSCarson Labrado         const std::string& name,
3297fb33566SCarson Labrado         const dbus::utility::DBusPropertiesMap& properties,
3307fb33566SCarson Labrado         std::unordered_map<std::string, boost::urls::url>& satelliteInfo)
3317fb33566SCarson Labrado     {
3327fb33566SCarson Labrado         boost::urls::url url;
3337fb33566SCarson Labrado 
3347fb33566SCarson Labrado         for (const auto& prop : properties)
3357fb33566SCarson Labrado         {
33605916cefSCarson Labrado             if (prop.first == "Hostname")
3377fb33566SCarson Labrado             {
3387fb33566SCarson Labrado                 const std::string* propVal =
3397fb33566SCarson Labrado                     std::get_if<std::string>(&prop.second);
3407fb33566SCarson Labrado                 if (propVal == nullptr)
3417fb33566SCarson Labrado                 {
3427fb33566SCarson Labrado                     BMCWEB_LOG_ERROR << "Invalid Hostname value";
3437fb33566SCarson Labrado                     return;
3447fb33566SCarson Labrado                 }
3457fb33566SCarson Labrado                 url.set_host(*propVal);
3467fb33566SCarson Labrado             }
3477fb33566SCarson Labrado 
3487fb33566SCarson Labrado             else if (prop.first == "Port")
3497fb33566SCarson Labrado             {
3507fb33566SCarson Labrado                 const uint64_t* propVal = std::get_if<uint64_t>(&prop.second);
3517fb33566SCarson Labrado                 if (propVal == nullptr)
3527fb33566SCarson Labrado                 {
3537fb33566SCarson Labrado                     BMCWEB_LOG_ERROR << "Invalid Port value";
3547fb33566SCarson Labrado                     return;
3557fb33566SCarson Labrado                 }
3567fb33566SCarson Labrado 
3577fb33566SCarson Labrado                 if (*propVal > std::numeric_limits<uint16_t>::max())
3587fb33566SCarson Labrado                 {
3597fb33566SCarson Labrado                     BMCWEB_LOG_ERROR << "Port value out of range";
3607fb33566SCarson Labrado                     return;
3617fb33566SCarson Labrado                 }
362079360aeSEd Tanous                 url.set_port(std::to_string(static_cast<uint16_t>(*propVal)));
3637fb33566SCarson Labrado             }
3647fb33566SCarson Labrado 
3657fb33566SCarson Labrado             else if (prop.first == "AuthType")
3667fb33566SCarson Labrado             {
3677fb33566SCarson Labrado                 const std::string* propVal =
3687fb33566SCarson Labrado                     std::get_if<std::string>(&prop.second);
3697fb33566SCarson Labrado                 if (propVal == nullptr)
3707fb33566SCarson Labrado                 {
3717fb33566SCarson Labrado                     BMCWEB_LOG_ERROR << "Invalid AuthType value";
3727fb33566SCarson Labrado                     return;
3737fb33566SCarson Labrado                 }
3747fb33566SCarson Labrado 
3757fb33566SCarson Labrado                 // For now assume authentication not required to communicate
3767fb33566SCarson Labrado                 // with the satellite BMC
3777fb33566SCarson Labrado                 if (*propVal != "None")
3787fb33566SCarson Labrado                 {
3797fb33566SCarson Labrado                     BMCWEB_LOG_ERROR
3807fb33566SCarson Labrado                         << "Unsupported AuthType value: " << *propVal
3817fb33566SCarson Labrado                         << ", only \"none\" is supported";
3827fb33566SCarson Labrado                     return;
3837fb33566SCarson Labrado                 }
3847fb33566SCarson Labrado                 url.set_scheme("http");
3857fb33566SCarson Labrado             }
3867fb33566SCarson Labrado         } // Finished reading properties
3877fb33566SCarson Labrado 
3887fb33566SCarson Labrado         // Make sure all required config information was made available
3897fb33566SCarson Labrado         if (url.host().empty())
3907fb33566SCarson Labrado         {
3917fb33566SCarson Labrado             BMCWEB_LOG_ERROR << "Satellite config " << name << " missing Host";
3927fb33566SCarson Labrado             return;
3937fb33566SCarson Labrado         }
3947fb33566SCarson Labrado 
3957fb33566SCarson Labrado         if (!url.has_port())
3967fb33566SCarson Labrado         {
3977fb33566SCarson Labrado             BMCWEB_LOG_ERROR << "Satellite config " << name << " missing Port";
3987fb33566SCarson Labrado             return;
3997fb33566SCarson Labrado         }
4007fb33566SCarson Labrado 
4017fb33566SCarson Labrado         if (!url.has_scheme())
4027fb33566SCarson Labrado         {
4037fb33566SCarson Labrado             BMCWEB_LOG_ERROR << "Satellite config " << name
4047fb33566SCarson Labrado                              << " missing AuthType";
4057fb33566SCarson Labrado             return;
4067fb33566SCarson Labrado         }
4077fb33566SCarson Labrado 
4087fb33566SCarson Labrado         std::string resultString;
4097fb33566SCarson Labrado         auto result = satelliteInfo.insert_or_assign(name, std::move(url));
4107fb33566SCarson Labrado         if (result.second)
4117fb33566SCarson Labrado         {
4127fb33566SCarson Labrado             resultString = "Added new satellite config ";
4137fb33566SCarson Labrado         }
4147fb33566SCarson Labrado         else
4157fb33566SCarson Labrado         {
4167fb33566SCarson Labrado             resultString = "Updated existing satellite config ";
4177fb33566SCarson Labrado         }
4187fb33566SCarson Labrado 
4197fb33566SCarson Labrado         BMCWEB_LOG_DEBUG << resultString << name << " at "
4207fb33566SCarson Labrado                          << result.first->second.scheme() << "://"
4217fb33566SCarson Labrado                          << result.first->second.encoded_host_and_port();
4227fb33566SCarson Labrado     }
4237fb33566SCarson Labrado 
42446a81465SCarson Labrado     enum AggregationType
42546a81465SCarson Labrado     {
42646a81465SCarson Labrado         Collection,
42746a81465SCarson Labrado         Resource,
42846a81465SCarson Labrado     };
42946a81465SCarson Labrado 
43046a81465SCarson Labrado     static void
43146a81465SCarson Labrado         startAggregation(AggregationType isCollection,
43246a81465SCarson Labrado                          const crow::Request& thisReq,
43346a81465SCarson Labrado                          const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
43446a81465SCarson Labrado     {
435db18fc98SCarson Labrado         if ((isCollection == AggregationType::Collection) &&
436db18fc98SCarson Labrado             (thisReq.method() != boost::beast::http::verb::get))
437db18fc98SCarson Labrado         {
438db18fc98SCarson Labrado             BMCWEB_LOG_DEBUG
439db18fc98SCarson Labrado                 << "Only aggregate GET requests to top level collections";
440db18fc98SCarson Labrado             return;
441db18fc98SCarson Labrado         }
442db18fc98SCarson Labrado 
44346a81465SCarson Labrado         // Create a copy of thisReq so we we can still locally process the req
44446a81465SCarson Labrado         std::error_code ec;
44546a81465SCarson Labrado         auto localReq = std::make_shared<crow::Request>(thisReq.req, ec);
44646a81465SCarson Labrado         if (ec)
44746a81465SCarson Labrado         {
44846a81465SCarson Labrado             BMCWEB_LOG_ERROR << "Failed to create copy of request";
44946a81465SCarson Labrado             if (isCollection != AggregationType::Collection)
45046a81465SCarson Labrado             {
45146a81465SCarson Labrado                 messages::internalError(asyncResp->res);
45246a81465SCarson Labrado             }
45346a81465SCarson Labrado             return;
45446a81465SCarson Labrado         }
45546a81465SCarson Labrado 
45646a81465SCarson Labrado         getSatelliteConfigs(std::bind_front(aggregateAndHandle, isCollection,
45746a81465SCarson Labrado                                             localReq, asyncResp));
45846a81465SCarson Labrado     }
45946a81465SCarson Labrado 
460db18fc98SCarson Labrado     static void findSatellite(
46146a81465SCarson Labrado         const crow::Request& req,
46246a81465SCarson Labrado         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
46346a81465SCarson Labrado         const std::unordered_map<std::string, boost::urls::url>& satelliteInfo,
46446a81465SCarson Labrado         std::string_view memberName)
46546a81465SCarson Labrado     {
46646a81465SCarson Labrado         // Determine if the resource ID begins with a known prefix
46746a81465SCarson Labrado         for (const auto& satellite : satelliteInfo)
46846a81465SCarson Labrado         {
46946a81465SCarson Labrado             std::string targetPrefix = satellite.first;
47046a81465SCarson Labrado             targetPrefix += "_";
47146a81465SCarson Labrado             if (memberName.starts_with(targetPrefix))
47246a81465SCarson Labrado             {
47346a81465SCarson Labrado                 BMCWEB_LOG_DEBUG << "\"" << satellite.first
47446a81465SCarson Labrado                                  << "\" is a known prefix";
47546a81465SCarson Labrado 
47646a81465SCarson Labrado                 // Remove the known prefix from the request's URI and
47746a81465SCarson Labrado                 // then forward to the associated satellite BMC
47846a81465SCarson Labrado                 getInstance().forwardRequest(req, asyncResp, satellite.first,
47946a81465SCarson Labrado                                              satelliteInfo);
48046a81465SCarson Labrado                 return;
48146a81465SCarson Labrado             }
48246a81465SCarson Labrado         }
483db18fc98SCarson Labrado 
484db18fc98SCarson Labrado         // We didn't recognize the prefix and need to return a 404
48593f7a0d6SEd Tanous         std::string nameStr = req.urlView.segments().back();
486db18fc98SCarson Labrado         messages::resourceNotFound(asyncResp->res, "", nameStr);
48746a81465SCarson Labrado     }
48846a81465SCarson Labrado 
48946a81465SCarson Labrado     // Intended to handle an incoming request based on if Redfish Aggregation
49046a81465SCarson Labrado     // is enabled.  Forwards request to satellite BMC if it exists.
49146a81465SCarson Labrado     static void aggregateAndHandle(
49246a81465SCarson Labrado         AggregationType isCollection,
49346a81465SCarson Labrado         const std::shared_ptr<crow::Request>& sharedReq,
49446a81465SCarson Labrado         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
49546a81465SCarson Labrado         const std::unordered_map<std::string, boost::urls::url>& satelliteInfo)
49646a81465SCarson Labrado     {
49746a81465SCarson Labrado         if (sharedReq == nullptr)
49846a81465SCarson Labrado         {
49946a81465SCarson Labrado             return;
50046a81465SCarson Labrado         }
501db18fc98SCarson Labrado 
502db18fc98SCarson Labrado         // No satellite configs means we don't need to keep attempting to
503db18fc98SCarson Labrado         // aggregate
504db18fc98SCarson Labrado         if (satelliteInfo.empty())
505db18fc98SCarson Labrado         {
506db18fc98SCarson Labrado             // For collections we'll also handle the request locally so we
507db18fc98SCarson Labrado             // don't need to write an error code
508db18fc98SCarson Labrado             if (isCollection == AggregationType::Resource)
509db18fc98SCarson Labrado             {
51093f7a0d6SEd Tanous                 std::string nameStr = sharedReq->urlView.segments().back();
511db18fc98SCarson Labrado                 messages::resourceNotFound(asyncResp->res, "", nameStr);
512db18fc98SCarson Labrado             }
513db18fc98SCarson Labrado             return;
514db18fc98SCarson Labrado         }
515db18fc98SCarson Labrado 
51646a81465SCarson Labrado         const crow::Request& thisReq = *sharedReq;
51746a81465SCarson Labrado         BMCWEB_LOG_DEBUG << "Aggregation is enabled, begin processing of "
51846a81465SCarson Labrado                          << thisReq.target();
51946a81465SCarson Labrado 
52046a81465SCarson Labrado         // We previously determined the request is for a collection.  No need to
52146a81465SCarson Labrado         // check again
52246a81465SCarson Labrado         if (isCollection == AggregationType::Collection)
52346a81465SCarson Labrado         {
52446a81465SCarson Labrado             BMCWEB_LOG_DEBUG << "Aggregating a collection";
5254c30e226SCarson Labrado             // We need to use a specific response handler and send the
5264c30e226SCarson Labrado             // request to all known satellites
5274c30e226SCarson Labrado             getInstance().forwardCollectionRequests(thisReq, asyncResp,
5284c30e226SCarson Labrado                                                     satelliteInfo);
52946a81465SCarson Labrado             return;
53046a81465SCarson Labrado         }
53146a81465SCarson Labrado 
5327c4c52cbSCarson Labrado         const boost::urls::segments_view urlSegments =
5337c4c52cbSCarson Labrado             thisReq.urlView.segments();
5347c4c52cbSCarson Labrado         boost::urls::url currentUrl("/");
5357c4c52cbSCarson Labrado         boost::urls::segments_view::iterator it = urlSegments.begin();
5367c4c52cbSCarson Labrado         const boost::urls::segments_view::const_iterator end =
5377c4c52cbSCarson Labrado             urlSegments.end();
5387c4c52cbSCarson Labrado 
5397c4c52cbSCarson Labrado         // Skip past the leading "/redfish/v1"
5407c4c52cbSCarson Labrado         it++;
5417c4c52cbSCarson Labrado         it++;
5427c4c52cbSCarson Labrado         for (; it != end; it++)
54346a81465SCarson Labrado         {
5447c4c52cbSCarson Labrado             if (std::binary_search(topCollections.begin(), topCollections.end(),
5457c4c52cbSCarson Labrado                                    currentUrl.buffer()))
5467c4c52cbSCarson Labrado             {
5477c4c52cbSCarson Labrado                 // We've matched a resource collection so this current segment
5487c4c52cbSCarson Labrado                 // must contain an aggregation prefix
5497c4c52cbSCarson Labrado                 findSatellite(thisReq, asyncResp, satelliteInfo, *it);
55046a81465SCarson Labrado                 return;
55146a81465SCarson Labrado             }
55246a81465SCarson Labrado 
5537c4c52cbSCarson Labrado             currentUrl.segments().push_back(*it);
55446a81465SCarson Labrado         }
555db18fc98SCarson Labrado 
556db18fc98SCarson Labrado         // We shouldn't reach this point since we should've hit one of the
557db18fc98SCarson Labrado         // previous exits
558db18fc98SCarson Labrado         messages::internalError(asyncResp->res);
55946a81465SCarson Labrado     }
56046a81465SCarson Labrado 
56146a81465SCarson Labrado     // Attempt to forward a request to the satellite BMC associated with the
56246a81465SCarson Labrado     // prefix.
56346a81465SCarson Labrado     void forwardRequest(
56446a81465SCarson Labrado         const crow::Request& thisReq,
56546a81465SCarson Labrado         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
56646a81465SCarson Labrado         const std::string& prefix,
56746a81465SCarson Labrado         const std::unordered_map<std::string, boost::urls::url>& satelliteInfo)
56846a81465SCarson Labrado     {
56946a81465SCarson Labrado         const auto& sat = satelliteInfo.find(prefix);
57046a81465SCarson Labrado         if (sat == satelliteInfo.end())
57146a81465SCarson Labrado         {
57246a81465SCarson Labrado             // Realistically this shouldn't get called since we perform an
57346a81465SCarson Labrado             // earlier check to make sure the prefix exists
57446a81465SCarson Labrado             BMCWEB_LOG_ERROR << "Unrecognized satellite prefix \"" << prefix
57546a81465SCarson Labrado                              << "\"";
57646a81465SCarson Labrado             return;
57746a81465SCarson Labrado         }
57846a81465SCarson Labrado 
57946a81465SCarson Labrado         // We need to strip the prefix from the request's path
58046a81465SCarson Labrado         std::string targetURI(thisReq.target());
58146a81465SCarson Labrado         size_t pos = targetURI.find(prefix + "_");
58246a81465SCarson Labrado         if (pos == std::string::npos)
58346a81465SCarson Labrado         {
58446a81465SCarson Labrado             // If this fails then something went wrong
58546a81465SCarson Labrado             BMCWEB_LOG_ERROR << "Error removing prefix \"" << prefix
58646a81465SCarson Labrado                              << "_\" from request URI";
58746a81465SCarson Labrado             messages::internalError(asyncResp->res);
58846a81465SCarson Labrado             return;
58946a81465SCarson Labrado         }
59046a81465SCarson Labrado         targetURI.erase(pos, prefix.size() + 1);
59146a81465SCarson Labrado 
59246a81465SCarson Labrado         std::function<void(crow::Response&)> cb =
5931c0bb5c6SCarson Labrado             std::bind_front(processResponse, prefix, asyncResp);
59446a81465SCarson Labrado 
59546a81465SCarson Labrado         std::string data = thisReq.req.body();
59646a81465SCarson Labrado         crow::HttpClient::getInstance().sendDataWithCallback(
59746a81465SCarson Labrado             data, id, std::string(sat->second.host()),
598e38778a5SAppaRao Puli             sat->second.port_number(), targetURI, false /*useSSL*/,
599e38778a5SAppaRao Puli             thisReq.fields, thisReq.method(), retryPolicyName, cb);
60046a81465SCarson Labrado     }
60146a81465SCarson Labrado 
6024c30e226SCarson Labrado     // Forward a request for a collection URI to each known satellite BMC
6034c30e226SCarson Labrado     void forwardCollectionRequests(
6044c30e226SCarson Labrado         const crow::Request& thisReq,
6054c30e226SCarson Labrado         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
6064c30e226SCarson Labrado         const std::unordered_map<std::string, boost::urls::url>& satelliteInfo)
6074c30e226SCarson Labrado     {
6084c30e226SCarson Labrado         for (const auto& sat : satelliteInfo)
6094c30e226SCarson Labrado         {
6104c30e226SCarson Labrado             std::function<void(crow::Response&)> cb = std::bind_front(
6114c30e226SCarson Labrado                 processCollectionResponse, sat.first, asyncResp);
6124c30e226SCarson Labrado 
6134c30e226SCarson Labrado             std::string targetURI(thisReq.target());
6144c30e226SCarson Labrado             std::string data = thisReq.req.body();
6154c30e226SCarson Labrado             crow::HttpClient::getInstance().sendDataWithCallback(
6164c30e226SCarson Labrado                 data, id, std::string(sat.second.host()),
617e38778a5SAppaRao Puli                 sat.second.port_number(), targetURI, false /*useSSL*/,
618e38778a5SAppaRao Puli                 thisReq.fields, thisReq.method(), retryPolicyName, cb);
6194c30e226SCarson Labrado         }
6204c30e226SCarson Labrado     }
6214c30e226SCarson Labrado 
62232d7d8ebSCarson Labrado   public:
62332d7d8ebSCarson Labrado     RedfishAggregator(const RedfishAggregator&) = delete;
62432d7d8ebSCarson Labrado     RedfishAggregator& operator=(const RedfishAggregator&) = delete;
62532d7d8ebSCarson Labrado     RedfishAggregator(RedfishAggregator&&) = delete;
62632d7d8ebSCarson Labrado     RedfishAggregator& operator=(RedfishAggregator&&) = delete;
62732d7d8ebSCarson Labrado     ~RedfishAggregator() = default;
62832d7d8ebSCarson Labrado 
62932d7d8ebSCarson Labrado     static RedfishAggregator& getInstance()
63032d7d8ebSCarson Labrado     {
63132d7d8ebSCarson Labrado         static RedfishAggregator handler;
63232d7d8ebSCarson Labrado         return handler;
63332d7d8ebSCarson Labrado     }
63432d7d8ebSCarson Labrado 
63546a81465SCarson Labrado     // Processes the response returned by a satellite BMC and loads its
63646a81465SCarson Labrado     // contents into asyncResp
63746a81465SCarson Labrado     static void
6381c0bb5c6SCarson Labrado         processResponse(std::string_view prefix,
6391c0bb5c6SCarson Labrado                         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
64046a81465SCarson Labrado                         crow::Response& resp)
64146a81465SCarson Labrado     {
64243e14d38SCarson Labrado         // 429 and 502 mean we didn't actually send the request so don't
64343e14d38SCarson Labrado         // overwrite the response headers in that case
64443e14d38SCarson Labrado         if ((resp.resultInt() == 429) || (resp.resultInt() == 502))
64543e14d38SCarson Labrado         {
64643e14d38SCarson Labrado             asyncResp->res.result(resp.result());
64743e14d38SCarson Labrado             return;
64843e14d38SCarson Labrado         }
64943e14d38SCarson Labrado 
65032d7d8ebSCarson Labrado         // We want to attempt prefix fixing regardless of response code
65146a81465SCarson Labrado         // The resp will not have a json component
65246a81465SCarson Labrado         // We need to create a json from resp's stringResponse
65346a81465SCarson Labrado         if (resp.getHeaderValue("Content-Type") == "application/json")
65446a81465SCarson Labrado         {
65546a81465SCarson Labrado             nlohmann::json jsonVal =
65646a81465SCarson Labrado                 nlohmann::json::parse(resp.body(), nullptr, false);
65746a81465SCarson Labrado             if (jsonVal.is_discarded())
65846a81465SCarson Labrado             {
65946a81465SCarson Labrado                 BMCWEB_LOG_ERROR << "Error parsing satellite response as JSON";
66046a81465SCarson Labrado                 messages::operationFailed(asyncResp->res);
66146a81465SCarson Labrado                 return;
66246a81465SCarson Labrado             }
66346a81465SCarson Labrado 
66446a81465SCarson Labrado             BMCWEB_LOG_DEBUG << "Successfully parsed satellite response";
66546a81465SCarson Labrado 
6661c0bb5c6SCarson Labrado             addPrefixes(jsonVal, prefix);
6671c0bb5c6SCarson Labrado 
6681c0bb5c6SCarson Labrado             BMCWEB_LOG_DEBUG << "Added prefix to parsed satellite response";
6691c0bb5c6SCarson Labrado 
67046a81465SCarson Labrado             asyncResp->res.result(resp.result());
67146a81465SCarson Labrado             asyncResp->res.jsonValue = std::move(jsonVal);
67246a81465SCarson Labrado 
67346a81465SCarson Labrado             BMCWEB_LOG_DEBUG << "Finished writing asyncResp";
67446a81465SCarson Labrado         }
67546a81465SCarson Labrado         else
67646a81465SCarson Labrado         {
6770af78d5aSKhang Kieu             // We allow any Content-Type that is not "application/json" now
6780af78d5aSKhang Kieu             asyncResp->res.result(resp.result());
6790af78d5aSKhang Kieu             asyncResp->res.write(resp.body());
68046a81465SCarson Labrado         }
6810af78d5aSKhang Kieu         addAggregatedHeaders(asyncResp->res, resp, prefix);
68246a81465SCarson Labrado     }
68346a81465SCarson Labrado 
6844c30e226SCarson Labrado     // Processes the collection response returned by a satellite BMC and merges
6854c30e226SCarson Labrado     // its "@odata.id" values
6864c30e226SCarson Labrado     static void processCollectionResponse(
6874c30e226SCarson Labrado         const std::string& prefix,
6884c30e226SCarson Labrado         const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
6894c30e226SCarson Labrado         crow::Response& resp)
6904c30e226SCarson Labrado     {
69143e14d38SCarson Labrado         // 429 and 502 mean we didn't actually send the request so don't
69243e14d38SCarson Labrado         // overwrite the response headers in that case
69343e14d38SCarson Labrado         if ((resp.resultInt() == 429) || (resp.resultInt() == 502))
69443e14d38SCarson Labrado         {
69543e14d38SCarson Labrado             return;
69643e14d38SCarson Labrado         }
69743e14d38SCarson Labrado 
6984c30e226SCarson Labrado         if (resp.resultInt() != 200)
6994c30e226SCarson Labrado         {
7004c30e226SCarson Labrado             BMCWEB_LOG_DEBUG
7014c30e226SCarson Labrado                 << "Collection resource does not exist in satellite BMC \""
7024c30e226SCarson Labrado                 << prefix << "\"";
7034c30e226SCarson Labrado             // Return the error if we haven't had any successes
7044c30e226SCarson Labrado             if (asyncResp->res.resultInt() != 200)
7054c30e226SCarson Labrado             {
7064c30e226SCarson Labrado                 asyncResp->res.stringResponse = std::move(resp.stringResponse);
7074c30e226SCarson Labrado             }
7084c30e226SCarson Labrado             return;
7094c30e226SCarson Labrado         }
7104c30e226SCarson Labrado 
7114c30e226SCarson Labrado         // The resp will not have a json component
7124c30e226SCarson Labrado         // We need to create a json from resp's stringResponse
7134c30e226SCarson Labrado         if (resp.getHeaderValue("Content-Type") == "application/json")
7144c30e226SCarson Labrado         {
7154c30e226SCarson Labrado             nlohmann::json jsonVal =
7164c30e226SCarson Labrado                 nlohmann::json::parse(resp.body(), nullptr, false);
7174c30e226SCarson Labrado             if (jsonVal.is_discarded())
7184c30e226SCarson Labrado             {
7194c30e226SCarson Labrado                 BMCWEB_LOG_ERROR << "Error parsing satellite response as JSON";
7204c30e226SCarson Labrado 
7214c30e226SCarson Labrado                 // Notify the user if doing so won't overwrite a valid response
7224c30e226SCarson Labrado                 if ((asyncResp->res.resultInt() != 200) &&
72343e14d38SCarson Labrado                     (asyncResp->res.resultInt() != 429) &&
7244c30e226SCarson Labrado                     (asyncResp->res.resultInt() != 502))
7254c30e226SCarson Labrado                 {
7264c30e226SCarson Labrado                     messages::operationFailed(asyncResp->res);
7274c30e226SCarson Labrado                 }
7284c30e226SCarson Labrado                 return;
7294c30e226SCarson Labrado             }
7304c30e226SCarson Labrado 
7314c30e226SCarson Labrado             BMCWEB_LOG_DEBUG << "Successfully parsed satellite response";
7324c30e226SCarson Labrado 
7334c30e226SCarson Labrado             // Now we need to add the prefix to the URIs contained in the
7344c30e226SCarson Labrado             // response.
7354c30e226SCarson Labrado             addPrefixes(jsonVal, prefix);
7364c30e226SCarson Labrado 
7374c30e226SCarson Labrado             BMCWEB_LOG_DEBUG << "Added prefix to parsed satellite response";
7384c30e226SCarson Labrado 
7394c30e226SCarson Labrado             // If this resource collection does not exist on the aggregating bmc
7404c30e226SCarson Labrado             // and has not already been added from processing the response from
7414c30e226SCarson Labrado             // a different satellite then we need to completely overwrite
7424c30e226SCarson Labrado             // asyncResp
7434c30e226SCarson Labrado             if (asyncResp->res.resultInt() != 200)
7444c30e226SCarson Labrado             {
7454c30e226SCarson Labrado                 // We only want to aggregate collections that contain a
7464c30e226SCarson Labrado                 // "Members" array
7474c30e226SCarson Labrado                 if ((!jsonVal.contains("Members")) &&
7484c30e226SCarson Labrado                     (!jsonVal["Members"].is_array()))
7494c30e226SCarson Labrado                 {
7504c30e226SCarson Labrado                     BMCWEB_LOG_DEBUG
7514c30e226SCarson Labrado                         << "Skipping aggregating unsupported resource";
7524c30e226SCarson Labrado                     return;
7534c30e226SCarson Labrado                 }
7544c30e226SCarson Labrado 
7554c30e226SCarson Labrado                 BMCWEB_LOG_DEBUG
7564c30e226SCarson Labrado                     << "Collection does not exist, overwriting asyncResp";
7574c30e226SCarson Labrado                 asyncResp->res.result(resp.result());
7584c30e226SCarson Labrado                 asyncResp->res.jsonValue = std::move(jsonVal);
75943e14d38SCarson Labrado                 asyncResp->res.addHeader("Content-Type", "application/json");
7604c30e226SCarson Labrado 
7614c30e226SCarson Labrado                 BMCWEB_LOG_DEBUG << "Finished overwriting asyncResp";
7624c30e226SCarson Labrado             }
7634c30e226SCarson Labrado             else
7644c30e226SCarson Labrado             {
7654c30e226SCarson Labrado                 // We only want to aggregate collections that contain a
7664c30e226SCarson Labrado                 // "Members" array
7674c30e226SCarson Labrado                 if ((!asyncResp->res.jsonValue.contains("Members")) &&
7684c30e226SCarson Labrado                     (!asyncResp->res.jsonValue["Members"].is_array()))
7694c30e226SCarson Labrado 
7704c30e226SCarson Labrado                 {
7714c30e226SCarson Labrado                     BMCWEB_LOG_DEBUG
7724c30e226SCarson Labrado                         << "Skipping aggregating unsupported resource";
7734c30e226SCarson Labrado                     return;
7744c30e226SCarson Labrado                 }
7754c30e226SCarson Labrado 
7764c30e226SCarson Labrado                 BMCWEB_LOG_DEBUG << "Adding aggregated resources from \""
7774c30e226SCarson Labrado                                  << prefix << "\" to collection";
7784c30e226SCarson Labrado 
7794c30e226SCarson Labrado                 // TODO: This is a potential race condition with multiple
7804c30e226SCarson Labrado                 // satellites and the aggregating bmc attempting to write to
7814c30e226SCarson Labrado                 // update this array.  May need to cascade calls to the next
7824c30e226SCarson Labrado                 // satellite at the end of this function.
7834c30e226SCarson Labrado                 // This is presumably not a concern when there is only a single
7844c30e226SCarson Labrado                 // satellite since the aggregating bmc should have completed
7854c30e226SCarson Labrado                 // before the response is received from the satellite.
7864c30e226SCarson Labrado 
7874c30e226SCarson Labrado                 auto& members = asyncResp->res.jsonValue["Members"];
7884c30e226SCarson Labrado                 auto& satMembers = jsonVal["Members"];
7894c30e226SCarson Labrado                 for (auto& satMem : satMembers)
7904c30e226SCarson Labrado                 {
7914c30e226SCarson Labrado                     members.push_back(std::move(satMem));
7924c30e226SCarson Labrado                 }
7934c30e226SCarson Labrado                 asyncResp->res.jsonValue["Members@odata.count"] =
7944c30e226SCarson Labrado                     members.size();
7954c30e226SCarson Labrado 
7964c30e226SCarson Labrado                 // TODO: Do we need to sort() after updating the array?
7974c30e226SCarson Labrado             }
7984c30e226SCarson Labrado         }
7994c30e226SCarson Labrado         else
8004c30e226SCarson Labrado         {
8014c30e226SCarson Labrado             BMCWEB_LOG_ERROR << "Received unparsable response from \"" << prefix
8024c30e226SCarson Labrado                              << "\"";
80343e14d38SCarson Labrado             // We received a response that was not a json.
8044c30e226SCarson Labrado             // Notify the user only if we did not receive any valid responses,
8054c30e226SCarson Labrado             // if the resource collection does not already exist on the
8064c30e226SCarson Labrado             // aggregating BMC, and if we did not already set this warning due
8074c30e226SCarson Labrado             // to a failure from a different satellite
8084c30e226SCarson Labrado             if ((asyncResp->res.resultInt() != 200) &&
80943e14d38SCarson Labrado                 (asyncResp->res.resultInt() != 429) &&
8104c30e226SCarson Labrado                 (asyncResp->res.resultInt() != 502))
8114c30e226SCarson Labrado             {
8124c30e226SCarson Labrado                 messages::operationFailed(asyncResp->res);
8134c30e226SCarson Labrado             }
8144c30e226SCarson Labrado         }
8154c30e226SCarson Labrado     } // End processCollectionResponse()
8164c30e226SCarson Labrado 
81705916cefSCarson Labrado     // Entry point to Redfish Aggregation
81805916cefSCarson Labrado     // Returns Result stating whether or not we still need to locally handle the
81905916cefSCarson Labrado     // request
82005916cefSCarson Labrado     static Result
82105916cefSCarson Labrado         beginAggregation(const crow::Request& thisReq,
82205916cefSCarson Labrado                          const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
82305916cefSCarson Labrado     {
82405916cefSCarson Labrado         using crow::utility::OrMorePaths;
82505916cefSCarson Labrado         using crow::utility::readUrlSegments;
82611987af6SCarson Labrado         const boost::urls::url_view url = thisReq.urlView;
827411e6a11SCarson Labrado 
828411e6a11SCarson Labrado         // We don't need to aggregate JsonSchemas due to potential issues such
829411e6a11SCarson Labrado         // as version mismatches between aggregator and satellite BMCs.  For
830411e6a11SCarson Labrado         // now assume that the aggregator has all the schemas and versions that
831411e6a11SCarson Labrado         // the aggregated server has.
832411e6a11SCarson Labrado         if (crow::utility::readUrlSegments(url, "redfish", "v1", "JsonSchemas",
833411e6a11SCarson Labrado                                            crow::utility::OrMorePaths()))
834411e6a11SCarson Labrado         {
835411e6a11SCarson Labrado             return Result::LocalHandle;
836411e6a11SCarson Labrado         }
837411e6a11SCarson Labrado 
8387c4c52cbSCarson Labrado         // The first two segments should be "/redfish/v1".  We need to check
8397c4c52cbSCarson Labrado         // that before we can search topCollections
8407c4c52cbSCarson Labrado         if (!crow::utility::readUrlSegments(url, "redfish", "v1",
8417c4c52cbSCarson Labrado                                             crow::utility::OrMorePaths()))
84246a81465SCarson Labrado         {
84346a81465SCarson Labrado             return Result::LocalHandle;
84446a81465SCarson Labrado         }
84505916cefSCarson Labrado 
8467c4c52cbSCarson Labrado         // Parse the URI to see if it begins with a known top level collection
8477c4c52cbSCarson Labrado         // such as:
8487c4c52cbSCarson Labrado         // /redfish/v1/Chassis
8497c4c52cbSCarson Labrado         // /redfish/v1/UpdateService/FirmwareInventory
8507c4c52cbSCarson Labrado         const boost::urls::segments_view urlSegments = url.segments();
8517c4c52cbSCarson Labrado         boost::urls::url currentUrl("/");
8527c4c52cbSCarson Labrado         boost::urls::segments_view::iterator it = urlSegments.begin();
8537c4c52cbSCarson Labrado         const boost::urls::segments_view::const_iterator end =
8547c4c52cbSCarson Labrado             urlSegments.end();
85505916cefSCarson Labrado 
8567c4c52cbSCarson Labrado         // Skip past the leading "/redfish/v1"
8577c4c52cbSCarson Labrado         it++;
8587c4c52cbSCarson Labrado         it++;
8597c4c52cbSCarson Labrado         for (; it != end; it++)
86005916cefSCarson Labrado         {
861d4413c5bSGeorge Liu             const std::string& collectionItem = *it;
8627c4c52cbSCarson Labrado             if (std::binary_search(topCollections.begin(), topCollections.end(),
8637c4c52cbSCarson Labrado                                    currentUrl.buffer()))
8647c4c52cbSCarson Labrado             {
8657c4c52cbSCarson Labrado                 // We've matched a resource collection so this current segment
8667c4c52cbSCarson Labrado                 // might contain an aggregation prefix
8677c4c52cbSCarson Labrado                 if (collectionItem.starts_with("5B247A"))
86805916cefSCarson Labrado                 {
86905916cefSCarson Labrado                     BMCWEB_LOG_DEBUG << "Need to forward a request";
87005916cefSCarson Labrado 
87146a81465SCarson Labrado                     // Extract the prefix from the request's URI, retrieve the
8727c4c52cbSCarson Labrado                     // associated satellite config information, and then forward
8737c4c52cbSCarson Labrado                     // the request to that satellite.
8747c4c52cbSCarson Labrado                     startAggregation(AggregationType::Resource, thisReq,
8757c4c52cbSCarson Labrado                                      asyncResp);
87605916cefSCarson Labrado                     return Result::NoLocalHandle;
87705916cefSCarson Labrado                 }
8787c4c52cbSCarson Labrado 
8797c4c52cbSCarson Labrado                 // Handle collection URI with a trailing backslash
8807c4c52cbSCarson Labrado                 // e.g. /redfish/v1/Chassis/
8817c4c52cbSCarson Labrado                 it++;
8827c4c52cbSCarson Labrado                 if ((it == end) && collectionItem.empty())
8837c4c52cbSCarson Labrado                 {
8847c4c52cbSCarson Labrado                     startAggregation(AggregationType::Collection, thisReq,
8857c4c52cbSCarson Labrado                                      asyncResp);
8867c4c52cbSCarson Labrado                 }
8877c4c52cbSCarson Labrado 
8887c4c52cbSCarson Labrado                 // We didn't recognize the prefix or it's a collection with a
8897c4c52cbSCarson Labrado                 // trailing "/".  In both cases we still want to locally handle
8907c4c52cbSCarson Labrado                 // the request
8917c4c52cbSCarson Labrado                 return Result::LocalHandle;
8927c4c52cbSCarson Labrado             }
8937c4c52cbSCarson Labrado 
8947c4c52cbSCarson Labrado             currentUrl.segments().push_back(collectionItem);
8957c4c52cbSCarson Labrado         }
8967c4c52cbSCarson Labrado 
8977c4c52cbSCarson Labrado         // If we made it here then currentUrl could contain a top level
8987c4c52cbSCarson Labrado         // collection URI without a trailing "/", e.g. /redfish/v1/Chassis
8997c4c52cbSCarson Labrado         if (std::binary_search(topCollections.begin(), topCollections.end(),
9007c4c52cbSCarson Labrado                                currentUrl.buffer()))
9017c4c52cbSCarson Labrado         {
9027c4c52cbSCarson Labrado             startAggregation(AggregationType::Collection, thisReq, asyncResp);
90305916cefSCarson Labrado             return Result::LocalHandle;
90405916cefSCarson Labrado         }
90505916cefSCarson Labrado 
90605916cefSCarson Labrado         BMCWEB_LOG_DEBUG << "Aggregation not required";
90705916cefSCarson Labrado         return Result::LocalHandle;
90805916cefSCarson Labrado     }
9097fb33566SCarson Labrado };
9107fb33566SCarson Labrado 
9117fb33566SCarson Labrado } // namespace redfish
912