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 boost::urls::url uri = 148 boost::urls::format("/redfish/v1/TaskService/Tasks/{}", strIdx); 149 150 res.jsonValue["@odata.id"] = uri; 151 res.jsonValue["@odata.type"] = "#Task.v1_4_3.Task"; 152 res.jsonValue["Id"] = strIdx; 153 res.jsonValue["TaskState"] = state; 154 res.jsonValue["TaskStatus"] = status; 155 156 boost::urls::url taskMonitor = boost::urls::format( 157 "/redfish/v1/TaskService/TaskMonitors/{}", strIdx); 158 159 res.addHeader(boost::beast::http::field::location, 160 taskMonitor.buffer()); 161 res.addHeader(boost::beast::http::field::retry_after, 162 std::to_string(retryAfterSeconds)); 163 } 164 else if (!gave204) 165 { 166 res.result(boost::beast::http::status::no_content); 167 gave204 = true; 168 } 169 } 170 171 void finishTask() 172 { 173 endTime = std::chrono::system_clock::to_time_t( 174 std::chrono::system_clock::now()); 175 } 176 177 void extendTimer(const std::chrono::seconds& timeout) 178 { 179 timer.expires_after(timeout); 180 timer.async_wait( 181 [self = shared_from_this()](boost::system::error_code ec) { 182 if (ec == boost::asio::error::operation_aborted) 183 { 184 return; // completed successfully 185 } 186 if (!ec) 187 { 188 // change ec to error as timer expired 189 ec = boost::asio::error::operation_aborted; 190 } 191 self->match.reset(); 192 sdbusplus::message_t msg; 193 self->finishTask(); 194 self->state = "Cancelled"; 195 self->status = "Warning"; 196 self->messages.emplace_back( 197 messages::taskAborted(std::to_string(self->index))); 198 // Send event :TaskAborted 199 self->sendTaskEvent(self->state, self->index); 200 self->callback(ec, msg, self); 201 }); 202 } 203 204 static void sendTaskEvent(std::string_view state, size_t index) 205 { 206 // TaskState enums which should send out an event are: 207 // "Starting" = taskResumed 208 // "Running" = taskStarted 209 // "Suspended" = taskPaused 210 // "Interrupted" = taskPaused 211 // "Pending" = taskPaused 212 // "Stopping" = taskAborted 213 // "Completed" = taskCompletedOK 214 // "Killed" = taskRemoved 215 // "Exception" = taskCompletedWarning 216 // "Cancelled" = taskCancelled 217 nlohmann::json event; 218 std::string indexStr = std::to_string(index); 219 if (state == "Starting") 220 { 221 event = redfish::messages::taskResumed(indexStr); 222 } 223 else if (state == "Running") 224 { 225 event = redfish::messages::taskStarted(indexStr); 226 } 227 else if ((state == "Suspended") || (state == "Interrupted") || 228 (state == "Pending")) 229 { 230 event = redfish::messages::taskPaused(indexStr); 231 } 232 else if (state == "Stopping") 233 { 234 event = redfish::messages::taskAborted(indexStr); 235 } 236 else if (state == "Completed") 237 { 238 event = redfish::messages::taskCompletedOK(indexStr); 239 } 240 else if (state == "Killed") 241 { 242 event = redfish::messages::taskRemoved(indexStr); 243 } 244 else if (state == "Exception") 245 { 246 event = redfish::messages::taskCompletedWarning(indexStr); 247 } 248 else if (state == "Cancelled") 249 { 250 event = redfish::messages::taskCancelled(indexStr); 251 } 252 else 253 { 254 BMCWEB_LOG_INFO("sendTaskEvent: No events to send"); 255 return; 256 } 257 boost::urls::url origin = 258 boost::urls::format("/redfish/v1/TaskService/Tasks/{}", index); 259 EventServiceManager::getInstance().sendEvent(event, origin.buffer(), 260 "Task"); 261 } 262 263 void startTimer(const std::chrono::seconds& timeout) 264 { 265 if (match) 266 { 267 return; 268 } 269 match = std::make_unique<sdbusplus::bus::match_t>( 270 static_cast<sdbusplus::bus_t&>(*crow::connections::systemBus), 271 matchStr, 272 [self = shared_from_this()](sdbusplus::message_t& message) { 273 boost::system::error_code ec; 274 275 // callback to return True if callback is done, callback needs 276 // to update status itself if needed 277 if (self->callback(ec, message, self) == task::completed) 278 { 279 self->timer.cancel(); 280 self->finishTask(); 281 282 // Send event 283 self->sendTaskEvent(self->state, self->index); 284 285 // reset the match after the callback was successful 286 boost::asio::post( 287 crow::connections::systemBus->get_io_context(), 288 [self] { self->match.reset(); }); 289 return; 290 } 291 }); 292 293 extendTimer(timeout); 294 messages.emplace_back(messages::taskStarted(std::to_string(index))); 295 // Send event : TaskStarted 296 sendTaskEvent(state, index); 297 } 298 299 std::function<bool(boost::system::error_code, sdbusplus::message_t&, 300 const std::shared_ptr<TaskData>&)> 301 callback; 302 std::string matchStr; 303 size_t index; 304 time_t startTime; 305 std::string status; 306 std::string state; 307 nlohmann::json messages; 308 boost::asio::steady_timer timer; 309 std::unique_ptr<sdbusplus::bus::match_t> match; 310 std::optional<time_t> endTime; 311 std::optional<Payload> payload; 312 bool gave204 = false; 313 int percentComplete = 0; 314 }; 315 316 } // namespace task 317 318 inline void requestRoutesTaskMonitor(App& app) 319 { 320 BMCWEB_ROUTE(app, "/redfish/v1/TaskService/TaskMonitors/<str>/") 321 .privileges(redfish::privileges::getTask) 322 .methods(boost::beast::http::verb::get)( 323 [&app](const crow::Request& req, 324 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, 325 const std::string& strParam) { 326 if (!redfish::setUpRedfishRoute(app, req, asyncResp)) 327 { 328 return; 329 } 330 auto find = std::ranges::find_if( 331 task::tasks, 332 [&strParam](const std::shared_ptr<task::TaskData>& task) { 333 if (!task) 334 { 335 return false; 336 } 337 338 // we compare against the string version as on failure 339 // strtoul returns 0 340 return std::to_string(task->index) == strParam; 341 }); 342 343 if (find == task::tasks.end()) 344 { 345 messages::resourceNotFound(asyncResp->res, "Task", strParam); 346 return; 347 } 348 std::shared_ptr<task::TaskData>& ptr = *find; 349 // monitor expires after 204 350 if (ptr->gave204) 351 { 352 messages::resourceNotFound(asyncResp->res, "Task", strParam); 353 return; 354 } 355 ptr->populateResp(asyncResp->res); 356 }); 357 } 358 359 inline void requestRoutesTask(App& app) 360 { 361 BMCWEB_ROUTE(app, "/redfish/v1/TaskService/Tasks/<str>/") 362 .privileges(redfish::privileges::getTask) 363 .methods(boost::beast::http::verb::get)( 364 [&app](const crow::Request& req, 365 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp, 366 const std::string& strParam) { 367 if (!redfish::setUpRedfishRoute(app, req, asyncResp)) 368 { 369 return; 370 } 371 auto find = std::ranges::find_if( 372 task::tasks, 373 [&strParam](const std::shared_ptr<task::TaskData>& task) { 374 if (!task) 375 { 376 return false; 377 } 378 379 // we compare against the string version as on failure 380 // strtoul returns 0 381 return std::to_string(task->index) == strParam; 382 }); 383 384 if (find == task::tasks.end()) 385 { 386 messages::resourceNotFound(asyncResp->res, "Task", strParam); 387 return; 388 } 389 390 const std::shared_ptr<task::TaskData>& ptr = *find; 391 392 asyncResp->res.jsonValue["@odata.type"] = "#Task.v1_4_3.Task"; 393 asyncResp->res.jsonValue["Id"] = strParam; 394 asyncResp->res.jsonValue["Name"] = "Task " + strParam; 395 asyncResp->res.jsonValue["TaskState"] = ptr->state; 396 asyncResp->res.jsonValue["StartTime"] = 397 redfish::time_utils::getDateTimeStdtime(ptr->startTime); 398 if (ptr->endTime) 399 { 400 asyncResp->res.jsonValue["EndTime"] = 401 redfish::time_utils::getDateTimeStdtime(*(ptr->endTime)); 402 } 403 asyncResp->res.jsonValue["TaskStatus"] = ptr->status; 404 asyncResp->res.jsonValue["Messages"] = ptr->messages; 405 asyncResp->res.jsonValue["@odata.id"] = 406 boost::urls::format("/redfish/v1/TaskService/Tasks/{}", strParam); 407 if (!ptr->gave204) 408 { 409 asyncResp->res.jsonValue["TaskMonitor"] = boost::urls::format( 410 "/redfish/v1/TaskService/TaskMonitors/{}", strParam); 411 } 412 413 asyncResp->res.jsonValue["HidePayload"] = !ptr->payload; 414 415 if (ptr->payload) 416 { 417 const task::Payload& p = *(ptr->payload); 418 asyncResp->res.jsonValue["Payload"]["TargetUri"] = p.targetUri; 419 asyncResp->res.jsonValue["Payload"]["HttpOperation"] = 420 p.httpOperation; 421 asyncResp->res.jsonValue["Payload"]["HttpHeaders"] = p.httpHeaders; 422 asyncResp->res.jsonValue["Payload"]["JsonBody"] = p.jsonBody.dump( 423 -1, ' ', true, nlohmann::json::error_handler_t::replace); 424 } 425 asyncResp->res.jsonValue["PercentComplete"] = ptr->percentComplete; 426 }); 427 } 428 429 inline void requestRoutesTaskCollection(App& app) 430 { 431 BMCWEB_ROUTE(app, "/redfish/v1/TaskService/Tasks/") 432 .privileges(redfish::privileges::getTaskCollection) 433 .methods(boost::beast::http::verb::get)( 434 [&app](const crow::Request& req, 435 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) { 436 if (!redfish::setUpRedfishRoute(app, req, asyncResp)) 437 { 438 return; 439 } 440 asyncResp->res.jsonValue["@odata.type"] = 441 "#TaskCollection.TaskCollection"; 442 asyncResp->res.jsonValue["@odata.id"] = "/redfish/v1/TaskService/Tasks"; 443 asyncResp->res.jsonValue["Name"] = "Task Collection"; 444 asyncResp->res.jsonValue["Members@odata.count"] = task::tasks.size(); 445 nlohmann::json& members = asyncResp->res.jsonValue["Members"]; 446 members = nlohmann::json::array(); 447 448 for (const std::shared_ptr<task::TaskData>& task : task::tasks) 449 { 450 if (task == nullptr) 451 { 452 continue; // shouldn't be possible 453 } 454 nlohmann::json::object_t member; 455 member["@odata.id"] = 456 boost::urls::format("/redfish/v1/TaskService/Tasks/{}", 457 std::to_string(task->index)); 458 members.emplace_back(std::move(member)); 459 } 460 }); 461 } 462 463 inline void requestRoutesTaskService(App& app) 464 { 465 BMCWEB_ROUTE(app, "/redfish/v1/TaskService/") 466 .privileges(redfish::privileges::getTaskService) 467 .methods(boost::beast::http::verb::get)( 468 [&app](const crow::Request& req, 469 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) { 470 if (!redfish::setUpRedfishRoute(app, req, asyncResp)) 471 { 472 return; 473 } 474 asyncResp->res.jsonValue["@odata.type"] = 475 "#TaskService.v1_1_4.TaskService"; 476 asyncResp->res.jsonValue["@odata.id"] = "/redfish/v1/TaskService"; 477 asyncResp->res.jsonValue["Name"] = "Task Service"; 478 asyncResp->res.jsonValue["Id"] = "TaskService"; 479 asyncResp->res.jsonValue["DateTime"] = 480 redfish::time_utils::getDateTimeOffsetNow().first; 481 asyncResp->res.jsonValue["CompletedTaskOverWritePolicy"] = "Oldest"; 482 483 asyncResp->res.jsonValue["LifeCycleEventOnTaskStateChange"] = true; 484 485 asyncResp->res.jsonValue["Status"]["State"] = "Enabled"; 486 asyncResp->res.jsonValue["ServiceEnabled"] = true; 487 asyncResp->res.jsonValue["Tasks"]["@odata.id"] = 488 "/redfish/v1/TaskService/Tasks"; 489 }); 490 } 491 492 } // namespace redfish 493