1 #pragma once
2 
3 #include "sensors.hpp"
4 #include "utils/telemetry_utils.hpp"
5 #include "utils/time_utils.hpp"
6 
7 #include <app.hpp>
8 #include <boost/container/flat_map.hpp>
9 #include <registries/privilege_registry.hpp>
10 
11 #include <tuple>
12 #include <variant>
13 
14 namespace redfish
15 {
16 
17 namespace telemetry
18 {
19 
20 using ReadingParameters =
21     std::vector<std::tuple<sdbusplus::message::object_path, std::string,
22                            std::string, std::string>>;
23 
24 inline void fillReportDefinition(
25     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, const std::string& id,
26     const std::vector<
27         std::pair<std::string, std::variant<std::string, bool, uint64_t,
28                                             ReadingParameters>>>& ret)
29 {
30     asyncResp->res.jsonValue["@odata.type"] =
31         "#MetricReportDefinition.v1_3_0.MetricReportDefinition";
32     asyncResp->res.jsonValue["@odata.id"] =
33         telemetry::metricReportDefinitionUri + id;
34     asyncResp->res.jsonValue["Id"] = id;
35     asyncResp->res.jsonValue["Name"] = id;
36     asyncResp->res.jsonValue["MetricReport"]["@odata.id"] =
37         telemetry::metricReportUri + id;
38     asyncResp->res.jsonValue["Status"]["State"] = "Enabled";
39     asyncResp->res.jsonValue["ReportUpdates"] = "Overwrite";
40 
41     const bool* emitsReadingsUpdate = nullptr;
42     const bool* logToMetricReportsCollection = nullptr;
43     const ReadingParameters* readingParams = nullptr;
44     const std::string* reportingType = nullptr;
45     const uint64_t* interval = nullptr;
46     for (const auto& [key, var] : ret)
47     {
48         if (key == "EmitsReadingsUpdate")
49         {
50             emitsReadingsUpdate = std::get_if<bool>(&var);
51         }
52         else if (key == "LogToMetricReportsCollection")
53         {
54             logToMetricReportsCollection = std::get_if<bool>(&var);
55         }
56         else if (key == "ReadingParameters")
57         {
58             readingParams = std::get_if<ReadingParameters>(&var);
59         }
60         else if (key == "ReportingType")
61         {
62             reportingType = std::get_if<std::string>(&var);
63         }
64         else if (key == "Interval")
65         {
66             interval = std::get_if<uint64_t>(&var);
67         }
68     }
69     if (!emitsReadingsUpdate || !logToMetricReportsCollection ||
70         !readingParams || !reportingType || !interval)
71     {
72         BMCWEB_LOG_ERROR << "Property type mismatch or property is missing";
73         messages::internalError(asyncResp->res);
74         return;
75     }
76 
77     std::vector<std::string> redfishReportActions;
78     redfishReportActions.reserve(2);
79     if (*emitsReadingsUpdate)
80     {
81         redfishReportActions.emplace_back("RedfishEvent");
82     }
83     if (*logToMetricReportsCollection)
84     {
85         redfishReportActions.emplace_back("LogToMetricReportsCollection");
86     }
87 
88     nlohmann::json metrics = nlohmann::json::array();
89     for (auto& [sensorPath, operationType, id, metadata] : *readingParams)
90     {
91         metrics.push_back({
92             {"MetricId", id},
93             {"MetricProperties", {metadata}},
94         });
95     }
96     asyncResp->res.jsonValue["Metrics"] = metrics;
97     asyncResp->res.jsonValue["MetricReportDefinitionType"] = *reportingType;
98     asyncResp->res.jsonValue["ReportActions"] = redfishReportActions;
99     asyncResp->res.jsonValue["Schedule"]["RecurrenceInterval"] =
100         time_utils::toDurationString(std::chrono::milliseconds(*interval));
101 }
102 
103 struct AddReportArgs
104 {
105     std::string name;
106     std::string reportingType;
107     bool emitsReadingsUpdate = false;
108     bool logToMetricReportsCollection = false;
109     uint64_t interval = 0;
110     std::vector<std::pair<std::string, std::vector<std::string>>> metrics;
111 };
112 
113 inline bool toDbusReportActions(crow::Response& res,
114                                 std::vector<std::string>& actions,
115                                 AddReportArgs& args)
116 {
117     size_t index = 0;
118     for (auto& action : actions)
119     {
120         if (action == "RedfishEvent")
121         {
122             args.emitsReadingsUpdate = true;
123         }
124         else if (action == "LogToMetricReportsCollection")
125         {
126             args.logToMetricReportsCollection = true;
127         }
128         else
129         {
130             messages::propertyValueNotInList(
131                 res, action, "ReportActions/" + std::to_string(index));
132             return false;
133         }
134         index++;
135     }
136     return true;
137 }
138 
139 inline bool getUserParameters(crow::Response& res, const crow::Request& req,
140                               AddReportArgs& args)
141 {
142     std::vector<nlohmann::json> metrics;
143     std::vector<std::string> reportActions;
144     std::optional<nlohmann::json> schedule;
145     if (!json_util::readJson(req, res, "Id", args.name, "Metrics", metrics,
146                              "MetricReportDefinitionType", args.reportingType,
147                              "ReportActions", reportActions, "Schedule",
148                              schedule))
149     {
150         return false;
151     }
152 
153     constexpr const char* allowedCharactersInName =
154         "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
155     if (args.name.empty() || args.name.find_first_not_of(
156                                  allowedCharactersInName) != std::string::npos)
157     {
158         BMCWEB_LOG_ERROR << "Failed to match " << args.name
159                          << " with allowed character "
160                          << allowedCharactersInName;
161         messages::propertyValueIncorrect(res, "Id", args.name);
162         return false;
163     }
164 
165     if (args.reportingType != "Periodic" && args.reportingType != "OnRequest")
166     {
167         messages::propertyValueNotInList(res, args.reportingType,
168                                          "MetricReportDefinitionType");
169         return false;
170     }
171 
172     if (!toDbusReportActions(res, reportActions, args))
173     {
174         return false;
175     }
176 
177     if (args.reportingType == "Periodic")
178     {
179         if (!schedule)
180         {
181             messages::createFailedMissingReqProperties(res, "Schedule");
182             return false;
183         }
184 
185         std::string durationStr;
186         if (!json_util::readJson(*schedule, res, "RecurrenceInterval",
187                                  durationStr))
188         {
189             return false;
190         }
191 
192         std::optional<std::chrono::milliseconds> durationNum =
193             time_utils::fromDurationString(durationStr);
194         if (!durationNum)
195         {
196             messages::propertyValueIncorrect(res, "RecurrenceInterval",
197                                              durationStr);
198             return false;
199         }
200         args.interval = static_cast<uint64_t>(durationNum->count());
201     }
202 
203     args.metrics.reserve(metrics.size());
204     for (auto& m : metrics)
205     {
206         std::string id;
207         std::vector<std::string> uris;
208         if (!json_util::readJson(m, res, "MetricId", id, "MetricProperties",
209                                  uris))
210         {
211             return false;
212         }
213 
214         args.metrics.emplace_back(std::move(id), std::move(uris));
215     }
216 
217     return true;
218 }
219 
220 inline bool getChassisSensorNode(
221     const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
222     const std::vector<std::pair<std::string, std::vector<std::string>>>&
223         metrics,
224     boost::container::flat_set<std::pair<std::string, std::string>>& matched)
225 {
226     for (const auto& [id, uris] : metrics)
227     {
228         for (size_t i = 0; i < uris.size(); i++)
229         {
230             const std::string& uri = uris[i];
231             std::string chassis;
232             std::string node;
233 
234             if (!boost::starts_with(uri, "/redfish/v1/Chassis/") ||
235                 !dbus::utility::getNthStringFromPath(uri, 3, chassis) ||
236                 !dbus::utility::getNthStringFromPath(uri, 4, node))
237             {
238                 BMCWEB_LOG_ERROR << "Failed to get chassis and sensor Node "
239                                     "from "
240                                  << uri;
241                 messages::propertyValueIncorrect(asyncResp->res, uri,
242                                                  "MetricProperties/" +
243                                                      std::to_string(i));
244                 return false;
245             }
246 
247             if (boost::ends_with(node, "#"))
248             {
249                 node.pop_back();
250             }
251 
252             matched.emplace(std::move(chassis), std::move(node));
253         }
254     }
255     return true;
256 }
257 
258 class AddReport
259 {
260   public:
261     AddReport(AddReportArgs argsIn,
262               const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) :
263         asyncResp(asyncResp),
264         args{std::move(argsIn)}
265     {}
266     ~AddReport()
267     {
268         if (asyncResp->res.result() != boost::beast::http::status::ok)
269         {
270             return;
271         }
272 
273         telemetry::ReadingParameters readingParams;
274         readingParams.reserve(args.metrics.size());
275 
276         for (const auto& [id, uris] : args.metrics)
277         {
278             for (size_t i = 0; i < uris.size(); i++)
279             {
280                 const std::string& uri = uris[i];
281                 auto el = uriToDbus.find(uri);
282                 if (el == uriToDbus.end())
283                 {
284                     BMCWEB_LOG_ERROR << "Failed to find DBus sensor "
285                                         "corresponding to URI "
286                                      << uri;
287                     messages::propertyValueNotInList(asyncResp->res, uri,
288                                                      "MetricProperties/" +
289                                                          std::to_string(i));
290                     return;
291                 }
292 
293                 const std::string& dbusPath = el->second;
294                 readingParams.emplace_back(dbusPath, "SINGLE", id, uri);
295             }
296         }
297         const std::shared_ptr<bmcweb::AsyncResp> aResp = asyncResp;
298         crow::connections::systemBus->async_method_call(
299             [aResp, name = args.name, uriToDbus = std::move(uriToDbus)](
300                 const boost::system::error_code ec, const std::string&) {
301                 if (ec == boost::system::errc::file_exists)
302                 {
303                     messages::resourceAlreadyExists(
304                         aResp->res, "MetricReportDefinition", "Id", name);
305                     return;
306                 }
307                 if (ec == boost::system::errc::too_many_files_open)
308                 {
309                     messages::createLimitReachedForResource(aResp->res);
310                     return;
311                 }
312                 if (ec == boost::system::errc::argument_list_too_long)
313                 {
314                     nlohmann::json metricProperties = nlohmann::json::array();
315                     for (const auto& [uri, _] : uriToDbus)
316                     {
317                         metricProperties.emplace_back(uri);
318                     }
319                     messages::propertyValueIncorrect(
320                         aResp->res, metricProperties, "MetricProperties");
321                     return;
322                 }
323                 if (ec)
324                 {
325                     messages::internalError(aResp->res);
326                     BMCWEB_LOG_ERROR << "respHandler DBus error " << ec;
327                     return;
328                 }
329 
330                 messages::created(aResp->res);
331             },
332             telemetry::service, "/xyz/openbmc_project/Telemetry/Reports",
333             "xyz.openbmc_project.Telemetry.ReportManager", "AddReport",
334             "TelemetryService/" + args.name, args.reportingType,
335             args.emitsReadingsUpdate, args.logToMetricReportsCollection,
336             args.interval, readingParams);
337     }
338 
339     void insert(const boost::container::flat_map<std::string, std::string>& el)
340     {
341         uriToDbus.insert(el.begin(), el.end());
342     }
343 
344   private:
345     const std::shared_ptr<bmcweb::AsyncResp> asyncResp;
346     AddReportArgs args;
347     boost::container::flat_map<std::string, std::string> uriToDbus{};
348 };
349 } // namespace telemetry
350 
351 inline void requestRoutesMetricReportDefinitionCollection(App& app)
352 {
353     BMCWEB_ROUTE(app, "/redfish/v1/TelemetryService/MetricReportDefinitions/")
354         .privileges(redfish::privileges::getMetricReportDefinitionCollection)
355         .methods(boost::beast::http::verb::get)(
356             [](const crow::Request&,
357                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
358                 asyncResp->res.jsonValue["@odata.type"] =
359                     "#MetricReportDefinitionCollection."
360                     "MetricReportDefinitionCollection";
361                 asyncResp->res.jsonValue["@odata.id"] =
362                     "/redfish/v1/TelemetryService/MetricReportDefinitions";
363                 asyncResp->res.jsonValue["Name"] =
364                     "Metric Definition Collection";
365 
366                 telemetry::getReportCollection(
367                     asyncResp, telemetry::metricReportDefinitionUri);
368             });
369 
370     BMCWEB_ROUTE(app, "/redfish/v1/TelemetryService/MetricReportDefinitions/")
371         .privileges(redfish::privileges::postMetricReportDefinitionCollection)
372         .methods(boost::beast::http::verb::post)(
373             [](const crow::Request& req,
374                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
375                 telemetry::AddReportArgs args;
376                 if (!telemetry::getUserParameters(asyncResp->res, req, args))
377                 {
378                     return;
379                 }
380 
381                 boost::container::flat_set<std::pair<std::string, std::string>>
382                     chassisSensors;
383                 if (!telemetry::getChassisSensorNode(asyncResp, args.metrics,
384                                                      chassisSensors))
385                 {
386                     return;
387                 }
388 
389                 auto addReportReq = std::make_shared<telemetry::AddReport>(
390                     std::move(args), asyncResp);
391                 for (const auto& [chassis, sensorType] : chassisSensors)
392                 {
393                     retrieveUriToDbusMap(
394                         chassis, sensorType,
395                         [asyncResp, addReportReq](
396                             const boost::beast::http::status status,
397                             const boost::container::flat_map<
398                                 std::string, std::string>& uriToDbus) {
399                             if (status != boost::beast::http::status::ok)
400                             {
401                                 BMCWEB_LOG_ERROR
402                                     << "Failed to retrieve URI to dbus "
403                                        "sensors map with err "
404                                     << static_cast<unsigned>(status);
405                                 return;
406                             }
407                             addReportReq->insert(uriToDbus);
408                         });
409                 }
410             });
411 }
412 
413 inline void requestRoutesMetricReportDefinition(App& app)
414 {
415     BMCWEB_ROUTE(app,
416                  "/redfish/v1/TelemetryService/MetricReportDefinitions/<str>/")
417         .privileges(redfish::privileges::getMetricReportDefinition)
418         .methods(boost::beast::http::verb::get)(
419             [](const crow::Request&,
420                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
421                const std::string& id) {
422                 crow::connections::systemBus->async_method_call(
423                     [asyncResp, id](
424                         const boost::system::error_code ec,
425                         const std::vector<std::pair<
426                             std::string,
427                             std::variant<std::string, bool, uint64_t,
428                                          telemetry::ReadingParameters>>>& ret) {
429                         if (ec.value() == EBADR ||
430                             ec == boost::system::errc::host_unreachable)
431                         {
432                             messages::resourceNotFound(
433                                 asyncResp->res, "MetricReportDefinition", id);
434                             return;
435                         }
436                         if (ec)
437                         {
438                             BMCWEB_LOG_ERROR << "respHandler DBus error " << ec;
439                             messages::internalError(asyncResp->res);
440                             return;
441                         }
442 
443                         telemetry::fillReportDefinition(asyncResp, id, ret);
444                     },
445                     telemetry::service, telemetry::getDbusReportPath(id),
446                     "org.freedesktop.DBus.Properties", "GetAll",
447                     telemetry::reportInterface);
448             });
449     BMCWEB_ROUTE(app,
450                  "/redfish/v1/TelemetryService/MetricReportDefinitions/<str>/")
451         .privileges(redfish::privileges::deleteMetricReportDefinitionCollection)
452         .methods(boost::beast::http::verb::delete_)(
453             [](const crow::Request&,
454                const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
455                const std::string& id)
456 
457             {
458                 const std::string reportPath = telemetry::getDbusReportPath(id);
459 
460                 crow::connections::systemBus->async_method_call(
461                     [asyncResp, id](const boost::system::error_code ec) {
462                         /*
463                          * boost::system::errc and std::errc are missing value
464                          * for EBADR error that is defined in Linux.
465                          */
466                         if (ec.value() == EBADR)
467                         {
468                             messages::resourceNotFound(
469                                 asyncResp->res, "MetricReportDefinition", id);
470                             return;
471                         }
472 
473                         if (ec)
474                         {
475                             BMCWEB_LOG_ERROR << "respHandler DBus error " << ec;
476                             messages::internalError(asyncResp->res);
477                             return;
478                         }
479 
480                         asyncResp->res.result(
481                             boost::beast::http::status::no_content);
482                     },
483                     telemetry::service, reportPath,
484                     "xyz.openbmc_project.Object.Delete", "Delete");
485             });
486 }
487 } // namespace redfish
488