blob: 199bc84b7d4629b52b3a2ebeb2ea4ebb480011db [file] [log] [blame]
James Feist46229572020-02-19 15:11:58 -08001/*
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
John Edward Broadbent7e860f12021-04-08 15:57:16 -070018#include <app.hpp>
Ed Tanousd43cd0c2020-09-30 20:46:53 -070019#include <boost/asio/post.hpp>
20#include <boost/asio/steady_timer.hpp>
Ed Tanousb9d36b42022-02-26 21:42:46 -080021#include <dbus_utility.hpp>
Ed Tanous45ca1b82022-03-25 13:07:27 -070022#include <query.hpp>
Ed Tanoused398212021-06-09 17:05:54 -070023#include <registries/privilege_registry.hpp>
James Feiste5d50062020-05-11 17:29:00 -070024#include <task_messages.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050025
26#include <chrono>
James Feist46229572020-02-19 15:11:58 -080027#include <variant>
28
29namespace redfish
30{
31
32namespace task
33{
34constexpr size_t maxTaskCount = 100; // arbitrary limit
35
36static std::deque<std::shared_ptr<struct TaskData>> tasks;
37
James Feist32898ce2020-03-10 16:16:52 -070038constexpr bool completed = true;
39
James Feistfe306722020-03-12 16:32:08 -070040struct Payload
41{
Gunnar Mills1214b7e2020-06-04 10:11:30 -050042 Payload(const crow::Request& req) :
James Feistfe306722020-03-12 16:32:08 -070043 targetUri(req.url), httpOperation(req.methodString()),
44 httpHeaders(nlohmann::json::array())
45
46 {
47 using field_ns = boost::beast::http::field;
48 constexpr const std::array<boost::beast::http::field, 7>
49 headerWhitelist = {field_ns::accept, field_ns::accept_encoding,
50 field_ns::user_agent, field_ns::host,
51 field_ns::connection, field_ns::content_length,
52 field_ns::upgrade};
53
54 jsonBody = nlohmann::json::parse(req.body, nullptr, false);
55 if (jsonBody.is_discarded())
56 {
57 jsonBody = nullptr;
58 }
59
Gunnar Mills1214b7e2020-06-04 10:11:30 -050060 for (const auto& field : req.fields)
James Feistfe306722020-03-12 16:32:08 -070061 {
62 if (std::find(headerWhitelist.begin(), headerWhitelist.end(),
63 field.name()) == headerWhitelist.end())
64 {
65 continue;
66 }
67 std::string header;
68 header.reserve(field.name_string().size() + 2 +
69 field.value().size());
70 header += field.name_string();
71 header += ": ";
72 header += field.value();
73 httpHeaders.emplace_back(std::move(header));
74 }
75 }
76 Payload() = delete;
77
78 std::string targetUri;
79 std::string httpOperation;
80 nlohmann::json httpHeaders;
81 nlohmann::json jsonBody;
82};
83
James Feist46229572020-02-19 15:11:58 -080084struct TaskData : std::enable_shared_from_this<TaskData>
85{
86 private:
87 TaskData(std::function<bool(boost::system::error_code,
Gunnar Mills1214b7e2020-06-04 10:11:30 -050088 sdbusplus::message::message&,
89 const std::shared_ptr<TaskData>&)>&& handler,
Ed Tanous23a21a12020-07-25 04:45:05 +000090 const std::string& matchIn, size_t idx) :
James Feist46229572020-02-19 15:11:58 -080091 callback(std::move(handler)),
Ed Tanous23a21a12020-07-25 04:45:05 +000092 matchStr(matchIn), index(idx),
James Feist46229572020-02-19 15:11:58 -080093 startTime(std::chrono::system_clock::to_time_t(
94 std::chrono::system_clock::now())),
95 status("OK"), state("Running"), messages(nlohmann::json::array()),
96 timer(crow::connections::systemBus->get_io_context())
97
Gunnar Mills1214b7e2020-06-04 10:11:30 -050098 {}
James Feist46229572020-02-19 15:11:58 -080099
100 public:
Ed Tanousd609fd62020-09-28 19:08:03 -0700101 TaskData() = delete;
102
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500103 static std::shared_ptr<TaskData>& createTask(
James Feist46229572020-02-19 15:11:58 -0800104 std::function<bool(boost::system::error_code,
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500105 sdbusplus::message::message&,
106 const std::shared_ptr<TaskData>&)>&& handler,
107 const std::string& match)
James Feist46229572020-02-19 15:11:58 -0800108 {
109 static size_t lastTask = 0;
110 struct MakeSharedHelper : public TaskData
111 {
112 MakeSharedHelper(
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500113 std::function<bool(boost::system::error_code,
114 sdbusplus::message::message&,
115 const std::shared_ptr<TaskData>&)>&& handler,
Ed Tanous23a21a12020-07-25 04:45:05 +0000116 const std::string& match2, size_t idx) :
117 TaskData(std::move(handler), match2, idx)
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500118 {}
James Feist46229572020-02-19 15:11:58 -0800119 };
120
121 if (tasks.size() >= maxTaskCount)
122 {
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500123 auto& last = tasks.front();
James Feist46229572020-02-19 15:11:58 -0800124
125 // destroy all references
126 last->timer.cancel();
127 last->match.reset();
128 tasks.pop_front();
129 }
130
131 return tasks.emplace_back(std::make_shared<MakeSharedHelper>(
132 std::move(handler), match, lastTask++));
133 }
134
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500135 void populateResp(crow::Response& res, size_t retryAfterSeconds = 30)
James Feist46229572020-02-19 15:11:58 -0800136 {
137 if (!endTime)
138 {
139 res.result(boost::beast::http::status::accepted);
140 std::string strIdx = std::to_string(index);
141 std::string uri = "/redfish/v1/TaskService/Tasks/" + strIdx;
142 res.jsonValue = {{"@odata.id", uri},
143 {"@odata.type", "#Task.v1_4_3.Task"},
144 {"Id", strIdx},
145 {"TaskState", state},
146 {"TaskStatus", status}};
147 res.addHeader(boost::beast::http::field::location,
148 uri + "/Monitor");
149 res.addHeader(boost::beast::http::field::retry_after,
150 std::to_string(retryAfterSeconds));
151 }
152 else if (!gave204)
153 {
154 res.result(boost::beast::http::status::no_content);
155 gave204 = true;
156 }
157 }
158
Ed Tanousd609fd62020-09-28 19:08:03 -0700159 void finishTask()
James Feist46229572020-02-19 15:11:58 -0800160 {
161 endTime = std::chrono::system_clock::to_time_t(
162 std::chrono::system_clock::now());
163 }
164
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500165 void extendTimer(const std::chrono::seconds& timeout)
James Feist46229572020-02-19 15:11:58 -0800166 {
James Feist46229572020-02-19 15:11:58 -0800167 timer.expires_after(timeout);
168 timer.async_wait(
169 [self = shared_from_this()](boost::system::error_code ec) {
170 if (ec == boost::asio::error::operation_aborted)
171 {
Gunnar Mills4e0453b2020-07-08 14:00:30 -0500172 return; // completed successfully
James Feist46229572020-02-19 15:11:58 -0800173 }
174 if (!ec)
175 {
176 // change ec to error as timer expired
177 ec = boost::asio::error::operation_aborted;
178 }
179 self->match.reset();
180 sdbusplus::message::message msg;
181 self->finishTask();
182 self->state = "Cancelled";
183 self->status = "Warning";
James Feiste5d50062020-05-11 17:29:00 -0700184 self->messages.emplace_back(
185 messages::taskAborted(std::to_string(self->index)));
Sunitha Harishe7686572020-07-15 02:32:44 -0500186 // Send event :TaskAborted
187 self->sendTaskEvent(self->state, self->index);
James Feist46229572020-02-19 15:11:58 -0800188 self->callback(ec, msg, self);
189 });
James Feistfd9ab9e2020-05-19 13:48:07 -0700190 }
191
Ed Tanous56d23962022-02-14 20:42:02 -0800192 static void sendTaskEvent(const std::string_view state, size_t index)
Sunitha Harishe7686572020-07-15 02:32:44 -0500193 {
194 std::string origin =
195 "/redfish/v1/TaskService/Tasks/" + std::to_string(index);
196 std::string resType = "Task";
197 // TaskState enums which should send out an event are:
198 // "Starting" = taskResumed
199 // "Running" = taskStarted
200 // "Suspended" = taskPaused
201 // "Interrupted" = taskPaused
202 // "Pending" = taskPaused
203 // "Stopping" = taskAborted
204 // "Completed" = taskCompletedOK
205 // "Killed" = taskRemoved
206 // "Exception" = taskCompletedWarning
207 // "Cancelled" = taskCancelled
208 if (state == "Starting")
209 {
210 redfish::EventServiceManager::getInstance().sendEvent(
211 redfish::messages::taskResumed(std::to_string(index)), origin,
212 resType);
213 }
214 else if (state == "Running")
215 {
216 redfish::EventServiceManager::getInstance().sendEvent(
217 redfish::messages::taskStarted(std::to_string(index)), origin,
218 resType);
219 }
220 else if ((state == "Suspended") || (state == "Interrupted") ||
221 (state == "Pending"))
222 {
223 redfish::EventServiceManager::getInstance().sendEvent(
224 redfish::messages::taskPaused(std::to_string(index)), origin,
225 resType);
226 }
227 else if (state == "Stopping")
228 {
229 redfish::EventServiceManager::getInstance().sendEvent(
230 redfish::messages::taskAborted(std::to_string(index)), origin,
231 resType);
232 }
233 else if (state == "Completed")
234 {
235 redfish::EventServiceManager::getInstance().sendEvent(
236 redfish::messages::taskCompletedOK(std::to_string(index)),
237 origin, resType);
238 }
239 else if (state == "Killed")
240 {
241 redfish::EventServiceManager::getInstance().sendEvent(
242 redfish::messages::taskRemoved(std::to_string(index)), origin,
243 resType);
244 }
245 else if (state == "Exception")
246 {
247 redfish::EventServiceManager::getInstance().sendEvent(
248 redfish::messages::taskCompletedWarning(std::to_string(index)),
249 origin, resType);
250 }
251 else if (state == "Cancelled")
252 {
253 redfish::EventServiceManager::getInstance().sendEvent(
254 redfish::messages::taskCancelled(std::to_string(index)), origin,
255 resType);
256 }
257 else
258 {
259 BMCWEB_LOG_INFO << "sendTaskEvent: No events to send";
260 }
261 }
262
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500263 void startTimer(const std::chrono::seconds& timeout)
James Feistfd9ab9e2020-05-19 13:48:07 -0700264 {
265 if (match)
266 {
267 return;
268 }
269 match = std::make_unique<sdbusplus::bus::match::match>(
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500270 static_cast<sdbusplus::bus::bus&>(*crow::connections::systemBus),
James Feistfd9ab9e2020-05-19 13:48:07 -0700271 matchStr,
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500272 [self = shared_from_this()](sdbusplus::message::message& message) {
James Feistfd9ab9e2020-05-19 13:48:07 -0700273 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
Sunitha Harishe7686572020-07-15 02:32:44 -0500282 // Send event
283 self->sendTaskEvent(self->state, self->index);
284
James Feistfd9ab9e2020-05-19 13:48:07 -0700285 // 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);
James Feiste5d50062020-05-11 17:29:00 -0700294 messages.emplace_back(messages::taskStarted(std::to_string(index)));
Sunitha Harishe7686572020-07-15 02:32:44 -0500295 // Send event : TaskStarted
296 sendTaskEvent(state, index);
James Feist46229572020-02-19 15:11:58 -0800297 }
298
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500299 std::function<bool(boost::system::error_code, sdbusplus::message::message&,
300 const std::shared_ptr<TaskData>&)>
James Feist46229572020-02-19 15:11:58 -0800301 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::match> match;
310 std::optional<time_t> endTime;
James Feistfe306722020-03-12 16:32:08 -0700311 std::optional<Payload> payload;
James Feist46229572020-02-19 15:11:58 -0800312 bool gave204 = false;
George Liu6868ff52021-01-02 11:37:41 +0800313 int percentComplete = 0;
James Feist46229572020-02-19 15:11:58 -0800314};
315
316} // namespace task
317
John Edward Broadbent7e860f12021-04-08 15:57:16 -0700318inline void requestRoutesTaskMonitor(App& app)
James Feist46229572020-02-19 15:11:58 -0800319{
John Edward Broadbent7e860f12021-04-08 15:57:16 -0700320 BMCWEB_ROUTE(app, "/redfish/v1/TaskService/Tasks/<str>/Monitor/")
Ed Tanoused398212021-06-09 17:05:54 -0700321 .privileges(redfish::privileges::getTask)
John Edward Broadbent7e860f12021-04-08 15:57:16 -0700322 .methods(boost::beast::http::verb::get)(
Ed Tanous45ca1b82022-03-25 13:07:27 -0700323 [&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->res))
327 {
328 return;
329 }
John Edward Broadbent7e860f12021-04-08 15:57:16 -0700330 auto find = std::find_if(
331 task::tasks.begin(), task::tasks.end(),
332 [&strParam](const std::shared_ptr<task::TaskData>& task) {
333 if (!task)
334 {
335 return false;
336 }
James Feist46229572020-02-19 15:11:58 -0800337
John Edward Broadbent7e860f12021-04-08 15:57:16 -0700338 // we compare against the string version as on failure
339 // strtoul returns 0
340 return std::to_string(task->index) == strParam;
341 });
zhanghch058d1b46d2021-04-01 11:18:24 +0800342
John Edward Broadbent7e860f12021-04-08 15:57:16 -0700343 if (find == task::tasks.end())
James Feist46229572020-02-19 15:11:58 -0800344 {
John Edward Broadbent7e860f12021-04-08 15:57:16 -0700345 messages::resourceNotFound(asyncResp->res, "Monitor",
346 strParam);
347 return;
348 }
349 std::shared_ptr<task::TaskData>& ptr = *find;
350 // monitor expires after 204
351 if (ptr->gave204)
352 {
353 messages::resourceNotFound(asyncResp->res, "Monitor",
354 strParam);
355 return;
356 }
357 ptr->populateResp(asyncResp->res);
358 });
359}
360
361inline void requestRoutesTask(App& app)
362{
363 BMCWEB_ROUTE(app, "/redfish/v1/TaskService/Tasks/<str>/")
Ed Tanoused398212021-06-09 17:05:54 -0700364 .privileges(redfish::privileges::getTask)
John Edward Broadbent7e860f12021-04-08 15:57:16 -0700365 .methods(boost::beast::http::verb::get)(
Ed Tanous45ca1b82022-03-25 13:07:27 -0700366 [&app](const crow::Request& req,
367 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
368 const std::string& strParam) {
369 if (!redfish::setUpRedfishRoute(app, req, asyncResp->res))
370 {
371 return;
372 }
John Edward Broadbent7e860f12021-04-08 15:57:16 -0700373 auto find = std::find_if(
374 task::tasks.begin(), task::tasks.end(),
375 [&strParam](const std::shared_ptr<task::TaskData>& task) {
376 if (!task)
377 {
378 return false;
379 }
380
381 // we compare against the string version as on failure
382 // strtoul returns 0
383 return std::to_string(task->index) == strParam;
384 });
385
386 if (find == task::tasks.end())
387 {
388 messages::resourceNotFound(asyncResp->res, "Tasks",
389 strParam);
390 return;
James Feist46229572020-02-19 15:11:58 -0800391 }
392
John Edward Broadbent7e860f12021-04-08 15:57:16 -0700393 std::shared_ptr<task::TaskData>& ptr = *find;
James Feist46229572020-02-19 15:11:58 -0800394
John Edward Broadbent7e860f12021-04-08 15:57:16 -0700395 asyncResp->res.jsonValue["@odata.type"] = "#Task.v1_4_3.Task";
396 asyncResp->res.jsonValue["Id"] = strParam;
397 asyncResp->res.jsonValue["Name"] = "Task " + strParam;
398 asyncResp->res.jsonValue["TaskState"] = ptr->state;
399 asyncResp->res.jsonValue["StartTime"] =
Nan Zhou1d8782e2021-11-29 22:23:18 -0800400 crow::utility::getDateTimeStdtime(ptr->startTime);
John Edward Broadbent7e860f12021-04-08 15:57:16 -0700401 if (ptr->endTime)
James Feist46229572020-02-19 15:11:58 -0800402 {
John Edward Broadbent7e860f12021-04-08 15:57:16 -0700403 asyncResp->res.jsonValue["EndTime"] =
Nan Zhou1d8782e2021-11-29 22:23:18 -0800404 crow::utility::getDateTimeStdtime(*(ptr->endTime));
James Feist46229572020-02-19 15:11:58 -0800405 }
John Edward Broadbent7e860f12021-04-08 15:57:16 -0700406 asyncResp->res.jsonValue["TaskStatus"] = ptr->status;
407 asyncResp->res.jsonValue["Messages"] = ptr->messages;
408 asyncResp->res.jsonValue["@odata.id"] =
409 "/redfish/v1/TaskService/Tasks/" + strParam;
410 if (!ptr->gave204)
411 {
412 asyncResp->res.jsonValue["TaskMonitor"] =
413 "/redfish/v1/TaskService/Tasks/" + strParam +
414 "/Monitor";
415 }
416 if (ptr->payload)
417 {
418 const task::Payload& p = *(ptr->payload);
419 asyncResp->res.jsonValue["Payload"] = {
420 {"TargetUri", p.targetUri},
421 {"HttpOperation", p.httpOperation},
422 {"HttpHeaders", p.httpHeaders},
423 {"JsonBody",
424 p.jsonBody.dump(
425 2, ' ', true,
426 nlohmann::json::error_handler_t::replace)}};
427 }
428 asyncResp->res.jsonValue["PercentComplete"] =
429 ptr->percentComplete;
James Feist46229572020-02-19 15:11:58 -0800430 });
John Edward Broadbent7e860f12021-04-08 15:57:16 -0700431}
James Feist46229572020-02-19 15:11:58 -0800432
John Edward Broadbent7e860f12021-04-08 15:57:16 -0700433inline void requestRoutesTaskCollection(App& app)
James Feist46229572020-02-19 15:11:58 -0800434{
John Edward Broadbent7e860f12021-04-08 15:57:16 -0700435 BMCWEB_ROUTE(app, "/redfish/v1/TaskService/Tasks/")
Ed Tanoused398212021-06-09 17:05:54 -0700436 .privileges(redfish::privileges::getTaskCollection)
John Edward Broadbent7e860f12021-04-08 15:57:16 -0700437 .methods(boost::beast::http::verb::get)(
Ed Tanous45ca1b82022-03-25 13:07:27 -0700438 [&app](const crow::Request& req,
439 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
440 if (!redfish::setUpRedfishRoute(app, req, asyncResp->res))
441 {
442 return;
443 }
John Edward Broadbent7e860f12021-04-08 15:57:16 -0700444 asyncResp->res.jsonValue["@odata.type"] =
445 "#TaskCollection.TaskCollection";
446 asyncResp->res.jsonValue["@odata.id"] =
447 "/redfish/v1/TaskService/Tasks";
448 asyncResp->res.jsonValue["Name"] = "Task Collection";
449 asyncResp->res.jsonValue["Members@odata.count"] =
450 task::tasks.size();
451 nlohmann::json& members = asyncResp->res.jsonValue["Members"];
452 members = nlohmann::json::array();
James Feist46229572020-02-19 15:11:58 -0800453
John Edward Broadbent7e860f12021-04-08 15:57:16 -0700454 for (const std::shared_ptr<task::TaskData>& task : task::tasks)
455 {
456 if (task == nullptr)
457 {
458 continue; // shouldn't be possible
459 }
460 members.emplace_back(nlohmann::json{
461 {"@odata.id", "/redfish/v1/TaskService/Tasks/" +
462 std::to_string(task->index)}});
463 }
464 });
465}
zhanghch058d1b46d2021-04-01 11:18:24 +0800466
John Edward Broadbent7e860f12021-04-08 15:57:16 -0700467inline void requestRoutesTaskService(App& app)
James Feist46229572020-02-19 15:11:58 -0800468{
John Edward Broadbent7e860f12021-04-08 15:57:16 -0700469 BMCWEB_ROUTE(app, "/redfish/v1/TaskService/")
Ed Tanoused398212021-06-09 17:05:54 -0700470 .privileges(redfish::privileges::getTaskService)
John Edward Broadbent7e860f12021-04-08 15:57:16 -0700471 .methods(boost::beast::http::verb::get)(
Ed Tanous45ca1b82022-03-25 13:07:27 -0700472 [&app](const crow::Request& req,
473 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp) {
474 if (!redfish::setUpRedfishRoute(app, req, asyncResp->res))
475 {
476 return;
477 }
John Edward Broadbent7e860f12021-04-08 15:57:16 -0700478 asyncResp->res.jsonValue["@odata.type"] =
479 "#TaskService.v1_1_4.TaskService";
480 asyncResp->res.jsonValue["@odata.id"] =
481 "/redfish/v1/TaskService";
482 asyncResp->res.jsonValue["Name"] = "Task Service";
483 asyncResp->res.jsonValue["Id"] = "TaskService";
484 asyncResp->res.jsonValue["DateTime"] =
Tejas Patil7c8c4052021-06-04 17:43:14 +0530485 crow::utility::getDateTimeOffsetNow().first;
John Edward Broadbent7e860f12021-04-08 15:57:16 -0700486 asyncResp->res.jsonValue["CompletedTaskOverWritePolicy"] =
487 "Oldest";
James Feist46229572020-02-19 15:11:58 -0800488
John Edward Broadbent7e860f12021-04-08 15:57:16 -0700489 asyncResp->res.jsonValue["LifeCycleEventOnTaskStateChange"] =
490 true;
James Feist46229572020-02-19 15:11:58 -0800491
John Edward Broadbent7e860f12021-04-08 15:57:16 -0700492 auto health = std::make_shared<HealthPopulate>(asyncResp);
493 health->populate();
494 asyncResp->res.jsonValue["Status"]["State"] = "Enabled";
495 asyncResp->res.jsonValue["ServiceEnabled"] = true;
496 asyncResp->res.jsonValue["Tasks"] = {
497 {"@odata.id", "/redfish/v1/TaskService/Tasks"}};
498 });
499}
James Feist46229572020-02-19 15:11:58 -0800500
501} // namespace redfish