Add PowerWatts for EnvironmentMetrics

The EnvironmentMetrics schema[1] provides for efficient retrieval of
environmental metrics by separating them from performance metrics.
EnvironmentMetrics is a property of the Chassis schema since v1_15_0[2].
EnvironmentMetrics was added to Redfish release 2021.2 [3] to be used
instead of the deprecated Power schema.[4]

This commit adds PowerWatts property of the EnvironmentMetrics schema.
PowerWatts has been part of the EnvironmentMetrics schema since v1_1_0.
PowerWatts is a SensorPowerExcerpt[5].

Implementation notes: The new D-Bus interface
"xyz.openbmc_project.Sensor.Purpose" is used to find the sensor with the
"TotalPower" purpose.[6][7] The new utility function
sensor_utils::getSensorsByPurpose() returns a subset of an incoming list
of sensors which implement a specified purpose.

Multiple D-Bus calls are needed to find the sensor providing the
totalPower:
1. Retrieve list of power sensors associated with specified chassis
   which implement the Sensor.Purpose interface using existing
   getAllSensorObjects() function.
2. For each of those power sensors retrieve the actual purpose of the
   sensor to find the sensor implementing totalPower purpose. Expect no
   more than one sensor to implement this purpose. New utility function
   getSensorsByPurpose() is used.
3. If a totalPower sensor is found then retrieve its properties to fill
   in PowerWatts in the response using existing
   sensor_utils::objectExcerptToJson() utility function.

If no sensor has the "TotalPower" purpose then PowerWatts is
not added to EnvironmentMetrics and no error is returned.

[1] https://redfish.dmtf.org/schemas/v1/EnvironmentMetrics.v1_3_2.json
[2] https://redfish.dmtf.org/schemas/v1/Chassis.v1_25_2.json
[3] http://redfish.dmtf.org/schemas/Redfish_Release_History.pdf
[4] https://redfish.dmtf.org/schemas/v1/Power.v1_7_3.json
[5] http://redfish.dmtf.org/schemas/v1/Sensor.v1_9_1.json#/definitions/SensorPowerExcerpt
[6] https://gerrit.openbmc.org/c/openbmc/phosphor-dbus-interfaces/+/75943
[7] https://gerrit.openbmc.org/c/openbmc/openpower-occ-control/+/77408

Tested:
 - Updated unit tests for new environmentMetricsNode enum
 - Redfish Service Validator passes (confirmed PowerWatts tested)
```
VERBOSE1 - ServiceRoot -> Chassis -> Members#4 -> EnvironmentMetrics, EnvironmentMetrics.v1_3_0, EnvironmentMetrics
VERBOSE1 - @odata.id                                               PASS
VERBOSE1 - @odata.type                                             PASS
VERBOSE1 - Id                                                      PASS
VERBOSE1 - Name                                                    PASS
VERBOSE1 - PowerWatts                                              PASS
```
 - No "TotalPower" sensor exists (system never powered on).
   PowerWatts is not shown and no error is returned.
```
curl -k -H "X-Auth-Token: $token" https://${bmc}/redfish/v1/Chassis/chassis/EnvironmentMetrics
{
  "@odata.id": "/redfish/v1/Chassis/chassis/EnvironmentMetrics",
  "@odata.type": "#EnvironmentMetrics.v1_3_0.EnvironmentMetrics",
  "Id": "EnvironmentMetrics",
  "Name": "Chassis Environment Metrics"
}
```

 - "TotalPower" sensor exists (system powered on)
```
curl -k -H "X-Auth-Token: $token" https://${bmc}/redfish/v1/Systems/system | grep PowerState
  "PowerState": "On",

curl -k -H "X-Auth-Token: $token" https://${bmc}/redfish/v1/Chassis/chassis/EnvironmentMetrics
{
  "@odata.id": "/redfish/v1/Chassis/chassis/EnvironmentMetrics",
  "@odata.type": "#EnvironmentMetrics.v1_3_0.EnvironmentMetrics",
  "Id": "EnvironmentMetrics",
  "Name": "Chassis Environment Metrics",
  "PowerWatts": {
    "DataSourceUri": "/redfish/v1/Chassis/chassis/Sensors/power_total_power",
    "Reading": 191.0
  }
}
```
   DataSourceUri is a valid sensor:
```
curl -k -H "X-Auth-Token: $token" https://${bmc}/redfish/v1/Chassis/chassis/Sensors/power_total_power
{
  "@odata.id": "/redfish/v1/Chassis/chassis/Sensors/power_total_power",
  "@odata.type": "#Sensor.v1_2_0.Sensor",
  "Id": "power_total_power",
  "Name": "total power",
  "Reading": 191.0,
  "ReadingType": "Power",
  "ReadingUnits": "W",
  "Status": {
    "Health": "OK",
    "State": "Enabled"
  }
}
```

 - "TotalPower" sensor exists but null value (system powered off)
```
curl -k -H "X-Auth-Token: $token" https://${bmc}/redfish/v1/Systems/system | grep PowerState
  "PowerState": "Off",

curl -k -H "X-Auth-Token: $token" https://${bmc}/redfish/v1/Chassis/chassis/EnvironmentMetrics
{
  "@odata.id": "/redfish/v1/Chassis/chassis/EnvironmentMetrics",
  "@odata.type": "#EnvironmentMetrics.v1_3_0.EnvironmentMetrics",
  "Id": "EnvironmentMetrics",
  "Name": "Chassis Environment Metrics",
  "PowerWatts": {
    "DataSourceUri": "/redfish/v1/Chassis/chassis/Sensors/power_total_power",
    "Reading": null
  }
}
```

And again the DataSourceUri points to a valid sensor:
```
curl -k -H "X-Auth-Token: $token" https://${bmc}/redfish/v1/Chassis/chassis/Sensors/power_total_power
{
  "@odata.id": "/redfish/v1/Chassis/chassis/Sensors/power_total_power",
  "@odata.type": "#Sensor.v1_2_0.Sensor",
  "Id": "power_total_power",
  "Name": "total power",
  "Reading": null,
  "ReadingType": "Power",
  "ReadingUnits": "W",
  "Status": {
    "Health": "OK",
    "State": "Enabled"
  }
}
```

 - Invalid chassis id ("TotalPower" sensor exists)
```
curl -k -H "X-Auth-Token: $token" https://${bmc}/redfish/v1/Chassis/chassisBAD/EnvironmentMetrics
{
  "error": {
    "@Message.ExtendedInfo": [
      {
        "@odata.type": "#Message.v1_1_1.Message",
        "Message": "The requested resource of type Chassis named 'chassisBAD' was not found.",
        "MessageArgs": [
          "Chassis",
          "chassisBAD"
        ],
        "MessageId": "Base.1.19.ResourceNotFound",
        "MessageSeverity": "Critical",
        "Resolution": "Provide a valid resource identifier and resubmit the request."
      }
    ],
    "code": "Base.1.19.ResourceNotFound",
    "message": "The requested resource of type Chassis named 'chassisBAD' was not found."
  }
}
```

Signed-off-by: George Liu <liuxiwei@inspur.com>
Signed-off-by: Janet Adkins <janeta@us.ibm.com>
Change-Id: Ibe84a5e7fe0d2b232f925e457a094c021ca85d36
diff --git a/redfish-core/include/utils/sensor_utils.hpp b/redfish-core/include/utils/sensor_utils.hpp
index 41c14fc..f1adafe 100644
--- a/redfish-core/include/utils/sensor_utils.hpp
+++ b/redfish-core/include/utils/sensor_utils.hpp
@@ -2,6 +2,9 @@
 // SPDX-FileCopyrightText: Copyright OpenBMC Authors
 #pragma once
 
+#include "bmcweb_config.h"
+
+#include "async_resp.hpp"
 #include "dbus_utility.hpp"
 #include "error_messages.hpp"
 #include "generated/enums/resource.hpp"
@@ -11,6 +14,8 @@
 #include "str_utility.hpp"
 #include "utils/dbus_utils.hpp"
 
+#include <asm-generic/errno.h>
+
 #include <boost/url/format.hpp>
 #include <nlohmann/json.hpp>
 #include <sdbusplus/message/native_types.hpp>
@@ -23,6 +28,7 @@
 #include <format>
 #include <functional>
 #include <iterator>
+#include <memory>
 #include <optional>
 #include <ranges>
 #include <set>
@@ -41,6 +47,7 @@
 
 enum class ChassisSubNode
 {
+    environmentMetricsNode,
     powerNode,
     sensorsNode,
     thermalNode,
@@ -52,6 +59,8 @@
 {
     switch (subNode)
     {
+        case ChassisSubNode::environmentMetricsNode:
+            return "EnvironmentMetrics";
         case ChassisSubNode::powerNode:
             return "Power";
         case ChassisSubNode::sensorsNode:
@@ -71,7 +80,11 @@
     // If none match unknownNode is returned
     ChassisSubNode subNode = ChassisSubNode::unknownNode;
 
-    if (subNodeStr == "Power")
+    if (subNodeStr == "EnvironmentMetrics")
+    {
+        subNode = ChassisSubNode::environmentMetricsNode;
+    }
+    else if (subNodeStr == "Power")
     {
         subNode = ChassisSubNode::powerNode;
     }
@@ -93,7 +106,8 @@
 
 inline bool isExcerptNode(const ChassisSubNode subNode)
 {
-    return (subNode == ChassisSubNode::thermalMetricsNode);
+    return ((subNode == ChassisSubNode::thermalMetricsNode) ||
+            (subNode == ChassisSubNode::environmentMetricsNode));
 }
 
 /**
@@ -799,5 +813,142 @@
         });
 }
 
+enum class SensorPurpose
+{
+    totalPower,
+    unknownPurpose,
+};
+
+constexpr std::string_view sensorPurposeToString(SensorPurpose subNode)
+{
+    if (subNode == SensorPurpose::totalPower)
+    {
+        return "xyz.openbmc_project.Sensor.Purpose.SensorPurpose.TotalPower";
+    }
+
+    return "Unknown Purpose";
+}
+
+inline SensorPurpose sensorPurposeFromString(const std::string& subNodeStr)
+{
+    // If none match unknownNode is returned
+    SensorPurpose subNode = SensorPurpose::unknownPurpose;
+
+    if (subNodeStr ==
+        "xyz.openbmc_project.Sensor.Purpose.SensorPurpose.TotalPower")
+    {
+        subNode = SensorPurpose::totalPower;
+    }
+
+    return subNode;
+}
+
+inline void checkSensorPurpose(
+    const std::string& serviceName, const std::string& sensorPath,
+    const SensorPurpose sensorPurpose,
+    const std::shared_ptr<SensorServicePathList>& sensorMatches,
+    const std::shared_ptr<boost::system::error_code>& asyncErrors,
+    const boost::system::error_code& ec,
+    const std::vector<std::string>& purposeList)
+{
+    // If not found this sensor will be skipped but allow to
+    // continue processing remaining sensors
+    if (ec && (ec != boost::system::errc::io_error) && (ec.value() != EBADR))
+    {
+        BMCWEB_LOG_DEBUG("D-Bus response error : {}", ec);
+        *asyncErrors = ec;
+    }
+
+    if (!ec)
+    {
+        const std::string_view checkPurposeStr =
+            sensorPurposeToString(sensorPurpose);
+
+        BMCWEB_LOG_DEBUG("checkSensorPurpose: {}", checkPurposeStr);
+
+        for (const std::string& purposeStr : purposeList)
+        {
+            if (purposeStr == checkPurposeStr)
+            {
+                // Add to list
+                BMCWEB_LOG_DEBUG("checkSensorPurpose adding {} {}", serviceName,
+                                 sensorPath);
+                sensorMatches->emplace_back(serviceName, sensorPath);
+                return;
+            }
+        }
+    }
+}
+
+/**
+ * @brief Gets sensors from list with specified purpose
+ *
+ * Checks the <sensorListIn> sensors for any which implement the specified
+ * <sensorPurpose> in interface xyz.openbmc_project.Sensor.Purpose. Adds any
+ * matches to the <sensorMatches> list. After checking all sensors in
+ * <sensorListIn> the <callback> is called with just the list of matching
+ * sensors, which could be an empty list. Additionally the <callback> is called
+ * on error and error handling is left to the callback.
+ *
+ * @param asyncResp Response data
+ * @param[in] sensorListIn List of sensors to check
+ * @param[in] sensorPurpose Looks for sensors matching this purpose
+ * @param[out] sensorMatches Sensors from sensorListIn with sensorPurpose
+ * @param[in] callback Callback to handle list of matching sensors
+ */
+inline void getSensorsByPurpose(
+    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
+    const SensorServicePathList& sensorListIn,
+    const SensorPurpose sensorPurpose,
+    const std::shared_ptr<SensorServicePathList>& sensorMatches,
+    const std::function<void(
+        const boost::system::error_code& ec,
+        const std::shared_ptr<SensorServicePathList>& sensorMatches)>& callback)
+{
+    /* Keeps track of number of asynchronous calls made. Once all handlers have
+     * been called the callback function is called with the results.
+     */
+    std::shared_ptr<int> remainingSensorsToVist =
+        std::make_shared<int>(sensorListIn.size());
+
+    /* Holds last unrecoverable error returned by any of the asynchronous
+     * handlers. Once all handlers have been called the callback will be sent
+     * the error to handle.
+     */
+    std::shared_ptr<boost::system::error_code> asyncErrors =
+        std::make_shared<boost::system::error_code>();
+
+    BMCWEB_LOG_DEBUG("getSensorsByPurpose enter {}", *remainingSensorsToVist);
+
+    for (const auto& [serviceName, sensorPath] : sensorListIn)
+    {
+        dbus::utility::getProperty<std::vector<std::string>>(
+            serviceName, sensorPath, "xyz.openbmc_project.Sensor.Purpose",
+            "Purpose",
+            [asyncResp, serviceName, sensorPath, sensorPurpose, sensorMatches,
+             callback, remainingSensorsToVist,
+             asyncErrors](const boost::system::error_code& ec,
+                          const std::vector<std::string>& purposeList) {
+                // Keep track of sensor visited
+                (*remainingSensorsToVist)--;
+                BMCWEB_LOG_DEBUG("Visited {}. Remaining sensors {}", sensorPath,
+                                 *remainingSensorsToVist);
+
+                checkSensorPurpose(serviceName, sensorPath, sensorPurpose,
+                                   sensorMatches, asyncErrors, ec, purposeList);
+
+                // All sensors have been visited
+                if (*remainingSensorsToVist == 0)
+                {
+                    BMCWEB_LOG_DEBUG(
+                        "getSensorsByPurpose, exit found {} matches",
+                        sensorMatches->size());
+                    callback(*asyncErrors, sensorMatches);
+                    return;
+                }
+            });
+    }
+}
+
 } // namespace sensor_utils
 } // namespace redfish
diff --git a/redfish-core/lib/environment_metrics.hpp b/redfish-core/lib/environment_metrics.hpp
index 9d92fd4..ec5a3ef 100644
--- a/redfish-core/lib/environment_metrics.hpp
+++ b/redfish-core/lib/environment_metrics.hpp
@@ -4,25 +4,174 @@
 
 #include "app.hpp"
 #include "async_resp.hpp"
+#include "dbus_singleton.hpp"
+#include "dbus_utility.hpp"
 #include "error_messages.hpp"
 #include "http_request.hpp"
+#include "logging.hpp"
 #include "query.hpp"
 #include "registries/privilege_registry.hpp"
 #include "utils/chassis_utils.hpp"
+#include "utils/sensor_utils.hpp"
 
 #include <boost/beast/http/field.hpp>
 #include <boost/beast/http/verb.hpp>
 #include <boost/url/format.hpp>
+#include <nlohmann/json.hpp>
+#include <sdbusplus/asio/property.hpp>
 
+#include <array>
 #include <functional>
 #include <memory>
 #include <optional>
 #include <string>
+#include <string_view>
 #include <utility>
 
 namespace redfish
 {
 
+inline void afterGetPowerWatts(
+    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
+    const std::string& chassisId, const std::string& path,
+    const boost::system::error_code& ec,
+    const dbus::utility::DBusPropertiesMap& valuesDict)
+{
+    if (ec)
+    {
+        if (ec != boost::system::errc::io_error)
+        {
+            BMCWEB_LOG_ERROR("DBUS response error for PowerWatts {}", ec);
+            messages::internalError(asyncResp->res);
+        }
+        return;
+    }
+
+    nlohmann::json item = nlohmann::json::object();
+
+    /* Don't return an error for a failure to fill in properties from the
+     * single sensor. Just skip adding it.
+     */
+    if (sensor_utils::objectExcerptToJson(
+            path, chassisId,
+            sensor_utils::ChassisSubNode::environmentMetricsNode, "power",
+            valuesDict, item))
+    {
+        asyncResp->res.jsonValue["PowerWatts"] = std::move(item);
+    }
+}
+
+inline void handleTotalPowerList(
+    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
+    const std::string& chassisId, const boost::system::error_code& ec,
+    const std::shared_ptr<sensor_utils::SensorServicePathList>& sensorList)
+{
+    BMCWEB_LOG_DEBUG("handleTotalPowerList: {}", sensorList->size());
+
+    if (ec)
+    {
+        if (ec != boost::system::errc::io_error)
+        {
+            BMCWEB_LOG_ERROR("D-Bus response error {}", ec);
+            messages::internalError(asyncResp->res);
+        }
+        return;
+    }
+
+    // TotalPower cannot be supplied by multiple sensors
+    if (sensorList->size() != 1)
+    {
+        if (sensorList->empty())
+        {
+            // None found, not an error
+            return;
+        }
+        BMCWEB_LOG_ERROR("Too many total power sensors found {}. Expected 1.",
+                         sensorList->size());
+        messages::internalError(asyncResp->res);
+        return;
+    }
+
+    const std::string& serviceName = (*sensorList)[0].first;
+    const std::string& sensorPath = (*sensorList)[0].second;
+    sdbusplus::asio::getAllProperties(
+        *crow::connections::systemBus, serviceName, sensorPath,
+        "xyz.openbmc_project.Sensor.Value",
+        [asyncResp, chassisId,
+         sensorPath](const boost::system::error_code& ec1,
+                     const dbus::utility::DBusPropertiesMap& propertiesList) {
+            afterGetPowerWatts(asyncResp, chassisId, sensorPath, ec1,
+                               propertiesList);
+        });
+}
+
+inline void getTotalPowerSensor(
+    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
+    const std::string& chassisId, const boost::system::error_code& ec,
+    const sensor_utils::SensorServicePathList& sensorsServiceAndPath)
+{
+    BMCWEB_LOG_DEBUG("getTotalPowerSensor {}", sensorsServiceAndPath.size());
+
+    if (ec)
+    {
+        if (ec != boost::system::errc::io_error)
+        {
+            BMCWEB_LOG_ERROR("DBUS response error {}", ec);
+            messages::internalError(asyncResp->res);
+        }
+        // None found, not an error
+        return;
+    }
+
+    if (sensorsServiceAndPath.empty())
+    {
+        // No power sensors implement Sensor.Purpose, not an error
+        return;
+    }
+
+    // Create vector to hold list of sensors with totalPower purpose
+    std::shared_ptr<sensor_utils::SensorServicePathList> sensorList =
+        std::make_shared<sensor_utils::SensorServicePathList>();
+
+    sensor_utils::getSensorsByPurpose(
+        asyncResp, sensorsServiceAndPath,
+        sensor_utils::SensorPurpose::totalPower, sensorList,
+        std::bind_front(handleTotalPowerList, asyncResp, chassisId));
+}
+
+/**
+ * @brief Find sensor providing totalPower and fill in response
+ *
+ * Multiple D-Bus calls are needed to find the sensor providing the totalPower
+ * details:
+ *
+ * 1. Retrieve list of power sensors associated with specified chassis which
+ * implement the Sensor.Purpose interface.
+ *
+ * 2. For each of those power sensors retrieve the actual purpose of the sensor
+ * to find the sensor implementing totalPower purpose. Expect no more than
+ * one sensor to implement this purpose.
+ *
+ * 3. If a totalPower sensor is found then retrieve its properties to fill in
+ * PowerWatts in the response.
+ *
+ * @param asyncResp Response data
+ * @param validChassisPath Path to chassis, caller confirms path is valid
+ * @param chassisId Chassis id matching <validChassisPath>
+ */
+inline void getPowerWatts(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
+                          const std::string& validChassisPath,
+                          const std::string& chassisId)
+{
+    BMCWEB_LOG_DEBUG("getPowerWatts: {}", validChassisPath);
+
+    constexpr std::array<std::string_view, 1> interfaces = {
+        "xyz.openbmc_project.Sensor.Purpose"};
+    sensor_utils::getAllSensorObjects(
+        validChassisPath, "/xyz/openbmc_project/sensors/power", interfaces, 1,
+        std::bind_front(getTotalPowerSensor, asyncResp, chassisId));
+}
+
 inline void handleEnvironmentMetricsHead(
     App& app, const crow::Request& req,
     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
@@ -50,6 +199,30 @@
                                                 std::move(respHandler));
 }
 
+inline void doEnvironmentMetricsGet(
+    const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
+    const std::string& chassisId,
+    const std::optional<std::string>& validChassisPath)
+{
+    if (!validChassisPath)
+    {
+        messages::resourceNotFound(asyncResp->res, "Chassis", chassisId);
+        return;
+    }
+
+    asyncResp->res.addHeader(
+        boost::beast::http::field::link,
+        "</redfish/v1/JsonSchemas/EnvironmentMetrics/EnvironmentMetrics.json>; rel=describedby");
+    asyncResp->res.jsonValue["@odata.type"] =
+        "#EnvironmentMetrics.v1_3_0.EnvironmentMetrics";
+    asyncResp->res.jsonValue["Name"] = "Chassis Environment Metrics";
+    asyncResp->res.jsonValue["Id"] = "EnvironmentMetrics";
+    asyncResp->res.jsonValue["@odata.id"] = boost::urls::format(
+        "/redfish/v1/Chassis/{}/EnvironmentMetrics", chassisId);
+
+    getPowerWatts(asyncResp, *validChassisPath, chassisId);
+}
+
 inline void handleEnvironmentMetricsGet(
     App& app, const crow::Request& req,
     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
@@ -60,27 +233,9 @@
         return;
     }
 
-    auto respHandler = [asyncResp, chassisId](
-                           const std::optional<std::string>& validChassisPath) {
-        if (!validChassisPath)
-        {
-            messages::resourceNotFound(asyncResp->res, "Chassis", chassisId);
-            return;
-        }
-
-        asyncResp->res.addHeader(
-            boost::beast::http::field::link,
-            "</redfish/v1/JsonSchemas/EnvironmentMetrics/EnvironmentMetrics.json>; rel=describedby");
-        asyncResp->res.jsonValue["@odata.type"] =
-            "#EnvironmentMetrics.v1_3_0.EnvironmentMetrics";
-        asyncResp->res.jsonValue["Name"] = "Chassis Environment Metrics";
-        asyncResp->res.jsonValue["Id"] = "EnvironmentMetrics";
-        asyncResp->res.jsonValue["@odata.id"] = boost::urls::format(
-            "/redfish/v1/Chassis/{}/EnvironmentMetrics", chassisId);
-    };
-
-    redfish::chassis_utils::getValidChassisPath(asyncResp, chassisId,
-                                                std::move(respHandler));
+    redfish::chassis_utils::getValidChassisPath(
+        asyncResp, chassisId,
+        std::bind_front(doEnvironmentMetricsGet, asyncResp, chassisId));
 }
 
 inline void requestRoutesEnvironmentMetrics(App& app)