1 /* 2 // Copyright (c) 2020 Intel Corporation 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 */ 16 #pragma once 17 18 #include "app.hpp" 19 #include "dbus_utility.hpp" 20 #include "event_service_manager.hpp" 21 #include "http/parsing.hpp" 22 #include "query.hpp" 23 #include "registries/privilege_registry.hpp" 24 #include "task_messages.hpp" 25 26 #include <boost/asio/post.hpp> 27 #include <boost/asio/steady_timer.hpp> 28 #include <boost/url/format.hpp> 29 #include <sdbusplus/bus/match.hpp> 30 31 #include <chrono> 32 #include <memory> 33 #include <ranges> 34 #include <variant> 35 36 namespace redfish 37 { 38 39 namespace task 40 { 41 constexpr size_t maxTaskCount = 100; // arbitrary limit 42 43 // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) 44 static std::deque<std::shared_ptr<struct TaskData>> tasks; 45 46 constexpr bool completed = true; 47 48 struct Payload 49 { 50 explicit Payload(const crow::Request& req) : 51 targetUri(req.url().encoded_path()), httpOperation(req.methodString()), 52 httpHeaders(nlohmann::json::array()) 53 { 54 using field_ns = boost::beast::http::field; 55 constexpr const std::array<boost::beast::http::field, 7> 56 headerWhitelist = {field_ns::accept, field_ns::accept_encoding, 57 field_ns::user_agent, field_ns::host, 58 field_ns::connection, field_ns::content_length, 59 field_ns::upgrade}; 60 61 JsonParseResult ret = parseRequestAsJson(req, jsonBody); 62 if (ret != JsonParseResult::Success) 63 { 64 return; 65 } 66 67 for (const auto& field : req.fields()) 68 { 69 if (std::ranges::find(headerWhitelist, field.name()) == 70 headerWhitelist.end()) 71 { 72 continue; 73 } 74 std::string header; 75 header.reserve(field.name_string().size() + 2 + 76 field.value().size()); 77 header += field.name_string(); 78 header += ": "; 79 header += field.value(); 80 httpHeaders.emplace_back(std::move(header)); 81 } 82 } 83 Payload() = delete; 84 85 std::string targetUri; 86 std::string httpOperation; 87 nlohmann::json httpHeaders; 88 nlohmann::json jsonBody; 89 }; 90 91 struct TaskData : std::enable_shared_from_this<TaskData> 92 { 93 private: 94 TaskData( 95 std::function<bool(boost::system::error_code, sdbusplus::message_t&, 96 const std::shared_ptr<TaskData>&)>&& handler, 97 const std::string& matchIn, size_t idx) : 98 callback(std::move(handler)), 99 matchStr(matchIn), index(idx), 100 startTime(std::chrono::system_clock::to_time_t( 101 std::chrono::system_clock::now())), 102 status("OK"), state("Running"), messages(nlohmann::json::array()), 103 timer(crow::connections::systemBus->get_io_context()) 104 105 {} 106 107 public: 108 TaskData() = delete; 109 110 static std::shared_ptr<TaskData>& createTask( 111 std::function<bool(boost::system::error_code, sdbusplus::message_t&, 112 const std::shared_ptr<TaskData>&)>&& handler, 113 const std::string& match) 114 { 115 static size_t lastTask = 0; 116 struct MakeSharedHelper : public TaskData 117 { 118 MakeSharedHelper( 119 std::function<bool(boost::system::error_code, 120 sdbusplus::message_t&, 121 const std::shared_ptr<TaskData>&)>&& handler, 122 const std::string& match2, size_t idx) : 123 TaskData(std::move(handler), match2, idx) 124 {} 125 }; 126 127 if (tasks.size() >= maxTaskCount) 128 { 129 const auto& last = tasks.front(); 130 131 // destroy all references 132 last->timer.cancel(); 133 last->match.reset(); 134 tasks.pop_front(); 135 } 136 137 return tasks.emplace_back(std::make_shared<MakeSharedHelper>( 138 std::move(handler), match, lastTask++)); 139 } 140 141 void populateResp(crow::Response& res, size_t retryAfterSeconds = 30) 142 { 143 if (!endTime) 144 { 145 res.result(boost::beast::http::status::accepted); 146 std::string strIdx = std::to_string(index); 147 std::string uri = "/redfish/v1/TaskService/Tasks/" + strIdx; 148 149 res.jsonValue["@odata.id"] = uri; 150 res.jsonValue["@odata.type"] = "#Task.v1_4_3.Task"; 151 res.jsonValue["Id"] = strIdx; 152 res.jsonValue["TaskState"] = state; 153 res.jsonValue["TaskStatus"] = status; 154 155 res.addHeader(boost::beast::http::field::location, 156 uri + "/Monitor"); 157 res.addHeader(boost::beast::http::field::retry_after, 158 std::to_string(retryAfterSeconds)); 159 } 160 else if (!gave204) 161 { 162 res.result(boost::beast::http::status::no_content); 163 gave204 = true; 164 } 165 } 166 167 void finishTask() 168 { 169 endTime = std::chrono::system_clock::to_time_t( 170 std::chrono::system_clock::now()); 171 } 172 173 void extendTimer(const std::chrono::seconds& timeout) 174 { 175 timer.expires_after(timeout); 176 timer.async_wait( 177 [self = shared_from_this()](boost::system::error_code ec) { 178 if (ec == boost::asio::error::operation_aborted) 179 { 180 return; // completed successfully 181 } 182 if (!ec) 183 { 184 // change ec to error as timer expired 185 ec = boost::asio::error::operation_aborted; 186 } 187 self->match.reset(); 188 sdbusplus::message_t msg; 189 self->finishTask(); 190 self->state = "Cancelled"; 191 self->status = "Warning"; 192 self->messages.emplace_back( 193 messages::taskAborted(std::to_string(self->index))); 194 // Send event :TaskAborted 195 self->sendTaskEvent(self->state, self->index); 196 self->callback(ec, msg, self); 197 }); 198 } 199 200 static void sendTaskEvent(std::string_view state, size_t index) 201 { 202 // TaskState enums which should send out an event are: 203 // "Starting" = taskResumed 204 // "Running" = taskStarted 205 // "Suspended" = taskPaused 206 // "Interrupted" = taskPaused 207 // "Pending" = taskPaused 208 // "Stopping" = taskAborted 209 // "Completed" = taskCompletedOK 210 // "Killed" = taskRemoved 211 // "Exception" = taskCompletedWarning 212 // "Cancelled" = taskCancelled 213 nlohmann::json event; 214 std::string indexStr = std::to_string(index); 215 if (state == "Starting") 216 { 217 event = redfish::messages::taskResumed(indexStr); 218 } 219 else if (state == "Running") 220 { 221 event = redfish::messages::taskStarted(indexStr); 222 } 223 else if ((state == "Suspended") || (state == "Interrupted") || 224 (state == "Pending")) 225 { 226 event = redfish::messages::taskPaused(indexStr); 227 } 228 else if (state == "Stopping") 229 { 230 event = redfish::messages::taskAborted(indexStr); 231 } 232 else if (state == "Completed") 233 { 234 event = redfish::messages::taskCompletedOK(indexStr); 235 } 236 else if (state == "Killed") 237 { 238 event = redfish::messages::taskRemoved(indexStr); 239 } 240 else if (state == "Exception") 241 { 242 event = redfish::messages::taskCompletedWarning(indexStr); 243 } 244 else if (state == "Cancelled") 245 { 246 event = redfish::messages::taskCancelled(indexStr); 247 } 248 else 249 { 250 BMCWEB_LOG_INFO("sendTaskEvent: No events to send"); 251 return; 252 } 253 boost::urls::url origin = 254 boost::urls::format("/redfish/v1/TaskService/Tasks/{}", index); 255 EventServiceManager::getInstance().sendEvent(event, origin.buffer(), 256 "Task"); 257 } 258 259 void startTimer(const std::chrono::seconds& timeout) 260 { 261 if (match) 262 { 263 return; 264 } 265 match = std::make_unique<sdbusplus::bus::match_t>( 266 static_cast<sdbusplus::bus_t&>(*crow::connections::systemBus), 267 matchStr, 268 [self = shared_from_this()](sdbusplus::message_t& message) { 269 boost::system::error_code ec; 270 271 // callback to return True if callback is done, callback needs 272 // to update status itself if needed 273 if (self->callback(ec, message, self) == task::completed) 274 { 275 self->timer.cancel(); 276 self->finishTask(); 277 278 // Send event 279 self->sendTaskEvent(self->state, self->index); 280 281 // reset the match after the callback was successful 282 boost::asio::post( 283 crow::connections::systemBus->get_io_context(), 284 [self] { self->match.reset(); }); 285 return; 286 } 287 }); 288 289 extendTimer(timeout); 290 messages.emplace_back(messages::taskStarted(std::to_string(index))); 291 // Send event : TaskStarted 292 sendTaskEvent(state, index); 293 } 294 295 std::function<bool(boost::system::error_code, sdbusplus::message_t&, 296 const std::shared_ptr<TaskData>&)> 297 callback; 298 std::string matchStr; 299 size_t index; 300 time_t startTime; 301 std::string status; 302 std::string state; 303 nlohmann::json messages; 304 boost::asio::steady_timer timer; 305 std::unique_ptr<sdbusplus::bus::match_t> match; 306 std::optional<time_t> endTime; 307 std::optional<Payload> payload; 308 bool gave204 = false; 309 int percentComplete = 0; 310 }; 311 312 } // namespace task 313 314 inline void requestRoutesTaskMonitor(App& app) 315 { 316 BMCWEB_ROUTE(app, "/redfish/v1/TaskService/Tasks/<str>/Monitor/") 317 .privileges(redfish::privileges::getTask) 318 .methods(boost::beast::http::verb::get)( 319 [&app](const crow::Request& req, 320 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, 321 const std::string& strParam) { 322 if (!redfish::setUpRedfishRoute(app, req, asyncResp)) 323 { 324 return; 325 } 326 auto find = std::ranges::find_if( 327 task::tasks, 328 [&strParam](const std::shared_ptr<task::TaskData>& task) { 329 if (!task) 330 { 331 return false; 332 } 333 334 // we compare against the string version as on failure 335 // strtoul returns 0 336 return std::to_string(task->index) == strParam; 337 }); 338 339 if (find == task::tasks.end()) 340 { 341 messages::resourceNotFound(asyncResp->res, "Task", strParam); 342 return; 343 } 344 std::shared_ptr<task::TaskData>& ptr = *find; 345 // monitor expires after 204 346 if (ptr->gave204) 347 { 348 messages::resourceNotFound(asyncResp->res, "Task", strParam); 349 return; 350 } 351 ptr->populateResp(asyncResp->res); 352 }); 353 } 354 355 inline void requestRoutesTask(App& app) 356 { 357 BMCWEB_ROUTE(app, "/redfish/v1/TaskService/Tasks/<str>/") 358 .privileges(redfish::privileges::getTask) 359 .methods(boost::beast::http::verb::get)( 360 [&app](const crow::Request& req, 361 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, 362 const std::string& strParam) { 363 if (!redfish::setUpRedfishRoute(app, req, asyncResp)) 364 { 365 return; 366 } 367 auto find = std::ranges::find_if( 368 task::tasks, 369 [&strParam](const std::shared_ptr<task::TaskData>& task) { 370 if (!task) 371 { 372 return false; 373 } 374 375 // we compare against the string version as on failure 376 // strtoul returns 0 377 return std::to_string(task->index) == strParam; 378 }); 379 380 if (find == task::tasks.end()) 381 { 382 messages::resourceNotFound(asyncResp->res, "Task", strParam); 383 return; 384 } 385 386 const std::shared_ptr<task::TaskData>& ptr = *find; 387 388 asyncResp->res.jsonValue["@odata.type"] = "#Task.v1_4_3.Task"; 389 asyncResp->res.jsonValue["Id"] = strParam; 390 asyncResp->res.jsonValue["Name"] = "Task " + strParam; 391 asyncResp->res.jsonValue["TaskState"] = ptr->state; 392 asyncResp->res.jsonValue["StartTime"] = 393 redfish::time_utils::getDateTimeStdtime(ptr->startTime); 394 if (ptr->endTime) 395 { 396 asyncResp->res.jsonValue["EndTime"] = 397 redfish::time_utils::getDateTimeStdtime(*(ptr->endTime)); 398 } 399 asyncResp->res.jsonValue["TaskStatus"] = ptr->status; 400 asyncResp->res.jsonValue["Messages"] = ptr->messages; 401 asyncResp->res.jsonValue["@odata.id"] = 402 boost::urls::format("/redfish/v1/TaskService/Tasks/{}", strParam); 403 if (!ptr->gave204) 404 { 405 asyncResp->res.jsonValue["TaskMonitor"] = 406 "/redfish/v1/TaskService/Tasks/" + strParam + "/Monitor"; 407 } 408 409 asyncResp->res.jsonValue["HidePayload"] = !ptr->payload; 410 411 if (ptr->payload) 412 { 413 const task::Payload& p = *(ptr->payload); 414 asyncResp->res.jsonValue["Payload"]["TargetUri"] = p.targetUri; 415 asyncResp->res.jsonValue["Payload"]["HttpOperation"] = 416 p.httpOperation; 417 asyncResp->res.jsonValue["Payload"]["HttpHeaders"] = p.httpHeaders; 418 asyncResp->res.jsonValue["Payload"]["JsonBody"] = p.jsonBody.dump( 419 -1, ' ', true, nlohmann::json::error_handler_t::replace); 420 } 421 asyncResp->res.jsonValue["PercentComplete"] = ptr->percentComplete; 422 }); 423 } 424 425 inline void requestRoutesTaskCollection(App& app) 426 { 427 BMCWEB_ROUTE(app, "/redfish/v1/TaskService/Tasks/") 428 .privileges(redfish::privileges::getTaskCollection) 429 .methods(boost::beast::http::verb::get)( 430 [&app](const crow::Request& req, 431 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) { 432 if (!redfish::setUpRedfishRoute(app, req, asyncResp)) 433 { 434 return; 435 } 436 asyncResp->res.jsonValue["@odata.type"] = 437 "#TaskCollection.TaskCollection"; 438 asyncResp->res.jsonValue["@odata.id"] = "/redfish/v1/TaskService/Tasks"; 439 asyncResp->res.jsonValue["Name"] = "Task Collection"; 440 asyncResp->res.jsonValue["Members@odata.count"] = task::tasks.size(); 441 nlohmann::json& members = asyncResp->res.jsonValue["Members"]; 442 members = nlohmann::json::array(); 443 444 for (const std::shared_ptr<task::TaskData>& task : task::tasks) 445 { 446 if (task == nullptr) 447 { 448 continue; // shouldn't be possible 449 } 450 nlohmann::json::object_t member; 451 member["@odata.id"] = 452 boost::urls::format("/redfish/v1/TaskService/Tasks/{}", 453 std::to_string(task->index)); 454 members.emplace_back(std::move(member)); 455 } 456 }); 457 } 458 459 inline void requestRoutesTaskService(App& app) 460 { 461 BMCWEB_ROUTE(app, "/redfish/v1/TaskService/") 462 .privileges(redfish::privileges::getTaskService) 463 .methods(boost::beast::http::verb::get)( 464 [&app](const crow::Request& req, 465 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) { 466 if (!redfish::setUpRedfishRoute(app, req, asyncResp)) 467 { 468 return; 469 } 470 asyncResp->res.jsonValue["@odata.type"] = 471 "#TaskService.v1_1_4.TaskService"; 472 asyncResp->res.jsonValue["@odata.id"] = "/redfish/v1/TaskService"; 473 asyncResp->res.jsonValue["Name"] = "Task Service"; 474 asyncResp->res.jsonValue["Id"] = "TaskService"; 475 asyncResp->res.jsonValue["DateTime"] = 476 redfish::time_utils::getDateTimeOffsetNow().first; 477 asyncResp->res.jsonValue["CompletedTaskOverWritePolicy"] = "Oldest"; 478 479 asyncResp->res.jsonValue["LifeCycleEventOnTaskStateChange"] = true; 480 481 asyncResp->res.jsonValue["Status"]["State"] = "Enabled"; 482 asyncResp->res.jsonValue["ServiceEnabled"] = true; 483 asyncResp->res.jsonValue["Tasks"]["@odata.id"] = 484 "/redfish/v1/TaskService/Tasks"; 485 }); 486 } 487 488 } // namespace redfish 489