blob: 8083566d455862ec1793411f3e5e1955c92eb80f [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
18#include "node.hpp"
19
Ed Tanousd43cd0c2020-09-30 20:46:53 -070020#include <boost/asio/post.hpp>
21#include <boost/asio/steady_timer.hpp>
James Feist46229572020-02-19 15:11:58 -080022#include <boost/container/flat_map.hpp>
James Feiste5d50062020-05-11 17:29:00 -070023#include <task_messages.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050024
25#include <chrono>
James Feist46229572020-02-19 15:11:58 -080026#include <variant>
27
28namespace redfish
29{
30
31namespace task
32{
33constexpr size_t maxTaskCount = 100; // arbitrary limit
34
35static std::deque<std::shared_ptr<struct TaskData>> tasks;
36
James Feist32898ce2020-03-10 16:16:52 -070037constexpr bool completed = true;
38
James Feistfe306722020-03-12 16:32:08 -070039struct Payload
40{
Gunnar Mills1214b7e2020-06-04 10:11:30 -050041 Payload(const crow::Request& req) :
James Feistfe306722020-03-12 16:32:08 -070042 targetUri(req.url), httpOperation(req.methodString()),
43 httpHeaders(nlohmann::json::array())
44
45 {
46 using field_ns = boost::beast::http::field;
47 constexpr const std::array<boost::beast::http::field, 7>
48 headerWhitelist = {field_ns::accept, field_ns::accept_encoding,
49 field_ns::user_agent, field_ns::host,
50 field_ns::connection, field_ns::content_length,
51 field_ns::upgrade};
52
53 jsonBody = nlohmann::json::parse(req.body, nullptr, false);
54 if (jsonBody.is_discarded())
55 {
56 jsonBody = nullptr;
57 }
58
Gunnar Mills1214b7e2020-06-04 10:11:30 -050059 for (const auto& field : req.fields)
James Feistfe306722020-03-12 16:32:08 -070060 {
61 if (std::find(headerWhitelist.begin(), headerWhitelist.end(),
62 field.name()) == headerWhitelist.end())
63 {
64 continue;
65 }
66 std::string header;
67 header.reserve(field.name_string().size() + 2 +
68 field.value().size());
69 header += field.name_string();
70 header += ": ";
71 header += field.value();
72 httpHeaders.emplace_back(std::move(header));
73 }
74 }
75 Payload() = delete;
76
77 std::string targetUri;
78 std::string httpOperation;
79 nlohmann::json httpHeaders;
80 nlohmann::json jsonBody;
81};
82
Gunnar Mills1214b7e2020-06-04 10:11:30 -050083inline void to_json(nlohmann::json& j, const Payload& p)
James Feistfe306722020-03-12 16:32:08 -070084{
85 j = {{"TargetUri", p.targetUri},
86 {"HttpOperation", p.httpOperation},
87 {"HttpHeaders", p.httpHeaders},
88 {"JsonBody", p.jsonBody.dump()}};
89}
90
James Feist46229572020-02-19 15:11:58 -080091struct TaskData : std::enable_shared_from_this<TaskData>
92{
93 private:
94 TaskData(std::function<bool(boost::system::error_code,
Gunnar Mills1214b7e2020-06-04 10:11:30 -050095 sdbusplus::message::message&,
96 const std::shared_ptr<TaskData>&)>&& handler,
Ed Tanous23a21a12020-07-25 04:45:05 +000097 const std::string& matchIn, size_t idx) :
James Feist46229572020-02-19 15:11:58 -080098 callback(std::move(handler)),
Ed Tanous23a21a12020-07-25 04:45:05 +000099 matchStr(matchIn), index(idx),
James Feist46229572020-02-19 15:11:58 -0800100 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
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500105 {}
James Feist46229572020-02-19 15:11:58 -0800106
107 public:
Ed Tanousd609fd62020-09-28 19:08:03 -0700108 TaskData() = delete;
109
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500110 static std::shared_ptr<TaskData>& createTask(
James Feist46229572020-02-19 15:11:58 -0800111 std::function<bool(boost::system::error_code,
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500112 sdbusplus::message::message&,
113 const std::shared_ptr<TaskData>&)>&& handler,
114 const std::string& match)
James Feist46229572020-02-19 15:11:58 -0800115 {
116 static size_t lastTask = 0;
117 struct MakeSharedHelper : public TaskData
118 {
119 MakeSharedHelper(
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500120 std::function<bool(boost::system::error_code,
121 sdbusplus::message::message&,
122 const std::shared_ptr<TaskData>&)>&& handler,
Ed Tanous23a21a12020-07-25 04:45:05 +0000123 const std::string& match2, size_t idx) :
124 TaskData(std::move(handler), match2, idx)
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500125 {}
James Feist46229572020-02-19 15:11:58 -0800126 };
127
128 if (tasks.size() >= maxTaskCount)
129 {
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500130 auto& last = tasks.front();
James Feist46229572020-02-19 15:11:58 -0800131
132 // destroy all references
133 last->timer.cancel();
134 last->match.reset();
135 tasks.pop_front();
136 }
137
138 return tasks.emplace_back(std::make_shared<MakeSharedHelper>(
139 std::move(handler), match, lastTask++));
140 }
141
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500142 void populateResp(crow::Response& res, size_t retryAfterSeconds = 30)
James Feist46229572020-02-19 15:11:58 -0800143 {
144 if (!endTime)
145 {
146 res.result(boost::beast::http::status::accepted);
147 std::string strIdx = std::to_string(index);
148 std::string uri = "/redfish/v1/TaskService/Tasks/" + strIdx;
149 res.jsonValue = {{"@odata.id", uri},
150 {"@odata.type", "#Task.v1_4_3.Task"},
151 {"Id", strIdx},
152 {"TaskState", state},
153 {"TaskStatus", status}};
154 res.addHeader(boost::beast::http::field::location,
155 uri + "/Monitor");
156 res.addHeader(boost::beast::http::field::retry_after,
157 std::to_string(retryAfterSeconds));
158 }
159 else if (!gave204)
160 {
161 res.result(boost::beast::http::status::no_content);
162 gave204 = true;
163 }
164 }
165
Ed Tanousd609fd62020-09-28 19:08:03 -0700166 void finishTask()
James Feist46229572020-02-19 15:11:58 -0800167 {
168 endTime = std::chrono::system_clock::to_time_t(
169 std::chrono::system_clock::now());
170 }
171
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500172 void extendTimer(const std::chrono::seconds& timeout)
James Feist46229572020-02-19 15:11:58 -0800173 {
James Feist46229572020-02-19 15:11:58 -0800174 timer.expires_after(timeout);
175 timer.async_wait(
176 [self = shared_from_this()](boost::system::error_code ec) {
177 if (ec == boost::asio::error::operation_aborted)
178 {
Gunnar Mills4e0453b2020-07-08 14:00:30 -0500179 return; // completed successfully
James Feist46229572020-02-19 15:11:58 -0800180 }
181 if (!ec)
182 {
183 // change ec to error as timer expired
184 ec = boost::asio::error::operation_aborted;
185 }
186 self->match.reset();
187 sdbusplus::message::message msg;
188 self->finishTask();
189 self->state = "Cancelled";
190 self->status = "Warning";
James Feiste5d50062020-05-11 17:29:00 -0700191 self->messages.emplace_back(
192 messages::taskAborted(std::to_string(self->index)));
Sunitha Harishe7686572020-07-15 02:32:44 -0500193 // Send event :TaskAborted
194 self->sendTaskEvent(self->state, self->index);
James Feist46229572020-02-19 15:11:58 -0800195 self->callback(ec, msg, self);
196 });
James Feistfd9ab9e2020-05-19 13:48:07 -0700197 }
198
Sunitha Harishe7686572020-07-15 02:32:44 -0500199 void sendTaskEvent(const std::string_view state, size_t index)
200 {
201 std::string origin =
202 "/redfish/v1/TaskService/Tasks/" + std::to_string(index);
203 std::string resType = "Task";
204 // TaskState enums which should send out an event are:
205 // "Starting" = taskResumed
206 // "Running" = taskStarted
207 // "Suspended" = taskPaused
208 // "Interrupted" = taskPaused
209 // "Pending" = taskPaused
210 // "Stopping" = taskAborted
211 // "Completed" = taskCompletedOK
212 // "Killed" = taskRemoved
213 // "Exception" = taskCompletedWarning
214 // "Cancelled" = taskCancelled
215 if (state == "Starting")
216 {
217 redfish::EventServiceManager::getInstance().sendEvent(
218 redfish::messages::taskResumed(std::to_string(index)), origin,
219 resType);
220 }
221 else if (state == "Running")
222 {
223 redfish::EventServiceManager::getInstance().sendEvent(
224 redfish::messages::taskStarted(std::to_string(index)), origin,
225 resType);
226 }
227 else if ((state == "Suspended") || (state == "Interrupted") ||
228 (state == "Pending"))
229 {
230 redfish::EventServiceManager::getInstance().sendEvent(
231 redfish::messages::taskPaused(std::to_string(index)), origin,
232 resType);
233 }
234 else if (state == "Stopping")
235 {
236 redfish::EventServiceManager::getInstance().sendEvent(
237 redfish::messages::taskAborted(std::to_string(index)), origin,
238 resType);
239 }
240 else if (state == "Completed")
241 {
242 redfish::EventServiceManager::getInstance().sendEvent(
243 redfish::messages::taskCompletedOK(std::to_string(index)),
244 origin, resType);
245 }
246 else if (state == "Killed")
247 {
248 redfish::EventServiceManager::getInstance().sendEvent(
249 redfish::messages::taskRemoved(std::to_string(index)), origin,
250 resType);
251 }
252 else if (state == "Exception")
253 {
254 redfish::EventServiceManager::getInstance().sendEvent(
255 redfish::messages::taskCompletedWarning(std::to_string(index)),
256 origin, resType);
257 }
258 else if (state == "Cancelled")
259 {
260 redfish::EventServiceManager::getInstance().sendEvent(
261 redfish::messages::taskCancelled(std::to_string(index)), origin,
262 resType);
263 }
264 else
265 {
266 BMCWEB_LOG_INFO << "sendTaskEvent: No events to send";
267 }
268 }
269
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500270 void startTimer(const std::chrono::seconds& timeout)
James Feistfd9ab9e2020-05-19 13:48:07 -0700271 {
272 if (match)
273 {
274 return;
275 }
276 match = std::make_unique<sdbusplus::bus::match::match>(
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500277 static_cast<sdbusplus::bus::bus&>(*crow::connections::systemBus),
James Feistfd9ab9e2020-05-19 13:48:07 -0700278 matchStr,
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500279 [self = shared_from_this()](sdbusplus::message::message& message) {
James Feistfd9ab9e2020-05-19 13:48:07 -0700280 boost::system::error_code ec;
281
282 // callback to return True if callback is done, callback needs
283 // to update status itself if needed
284 if (self->callback(ec, message, self) == task::completed)
285 {
286 self->timer.cancel();
287 self->finishTask();
288
Sunitha Harishe7686572020-07-15 02:32:44 -0500289 // Send event
290 self->sendTaskEvent(self->state, self->index);
291
James Feistfd9ab9e2020-05-19 13:48:07 -0700292 // reset the match after the callback was successful
293 boost::asio::post(
294 crow::connections::systemBus->get_io_context(),
295 [self] { self->match.reset(); });
296 return;
297 }
298 });
299
300 extendTimer(timeout);
James Feiste5d50062020-05-11 17:29:00 -0700301 messages.emplace_back(messages::taskStarted(std::to_string(index)));
Sunitha Harishe7686572020-07-15 02:32:44 -0500302 // Send event : TaskStarted
303 sendTaskEvent(state, index);
James Feist46229572020-02-19 15:11:58 -0800304 }
305
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500306 std::function<bool(boost::system::error_code, sdbusplus::message::message&,
307 const std::shared_ptr<TaskData>&)>
James Feist46229572020-02-19 15:11:58 -0800308 callback;
309 std::string matchStr;
310 size_t index;
311 time_t startTime;
312 std::string status;
313 std::string state;
314 nlohmann::json messages;
315 boost::asio::steady_timer timer;
316 std::unique_ptr<sdbusplus::bus::match::match> match;
317 std::optional<time_t> endTime;
James Feistfe306722020-03-12 16:32:08 -0700318 std::optional<Payload> payload;
James Feist46229572020-02-19 15:11:58 -0800319 bool gave204 = false;
320};
321
322} // namespace task
323
324class TaskMonitor : public Node
325{
326 public:
Ed Tanous52cc1122020-07-18 13:51:21 -0700327 TaskMonitor(App& app) :
Gunnar Mills7af91512020-04-14 22:16:57 -0500328 Node((app), "/redfish/v1/TaskService/Tasks/<str>/Monitor/",
James Feist46229572020-02-19 15:11:58 -0800329 std::string())
330 {
331 entityPrivileges = {
332 {boost::beast::http::verb::get, {{"Login"}}},
333 {boost::beast::http::verb::head, {{"Login"}}},
334 {boost::beast::http::verb::patch, {{"ConfigureManager"}}},
335 {boost::beast::http::verb::put, {{"ConfigureManager"}}},
336 {boost::beast::http::verb::delete_, {{"ConfigureManager"}}},
337 {boost::beast::http::verb::post, {{"ConfigureManager"}}}};
338 }
339
340 private:
Ed Tanouscb13a392020-07-25 19:02:03 +0000341 void doGet(crow::Response& res, const crow::Request&,
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500342 const std::vector<std::string>& params) override
James Feist46229572020-02-19 15:11:58 -0800343 {
344 auto asyncResp = std::make_shared<AsyncResp>(res);
345 if (params.size() != 1)
346 {
347 messages::internalError(asyncResp->res);
348 return;
349 }
350
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500351 const std::string& strParam = params[0];
James Feist46229572020-02-19 15:11:58 -0800352 auto find = std::find_if(
353 task::tasks.begin(), task::tasks.end(),
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500354 [&strParam](const std::shared_ptr<task::TaskData>& task) {
James Feist46229572020-02-19 15:11:58 -0800355 if (!task)
356 {
357 return false;
358 }
359
360 // we compare against the string version as on failure strtoul
361 // returns 0
362 return std::to_string(task->index) == strParam;
363 });
364
365 if (find == task::tasks.end())
366 {
367 messages::resourceNotFound(asyncResp->res, "Monitor", strParam);
368 return;
369 }
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500370 std::shared_ptr<task::TaskData>& ptr = *find;
James Feist46229572020-02-19 15:11:58 -0800371 // monitor expires after 204
372 if (ptr->gave204)
373 {
374 messages::resourceNotFound(asyncResp->res, "Monitor", strParam);
375 return;
376 }
377 ptr->populateResp(asyncResp->res);
378 }
379};
380
381class Task : public Node
382{
383 public:
Ed Tanous52cc1122020-07-18 13:51:21 -0700384 Task(App& app) :
Gunnar Mills7af91512020-04-14 22:16:57 -0500385 Node((app), "/redfish/v1/TaskService/Tasks/<str>/", std::string())
James Feist46229572020-02-19 15:11:58 -0800386 {
387 entityPrivileges = {
388 {boost::beast::http::verb::get, {{"Login"}}},
389 {boost::beast::http::verb::head, {{"Login"}}},
390 {boost::beast::http::verb::patch, {{"ConfigureManager"}}},
391 {boost::beast::http::verb::put, {{"ConfigureManager"}}},
392 {boost::beast::http::verb::delete_, {{"ConfigureManager"}}},
393 {boost::beast::http::verb::post, {{"ConfigureManager"}}}};
394 }
395
396 private:
Ed Tanouscb13a392020-07-25 19:02:03 +0000397 void doGet(crow::Response& res, const crow::Request&,
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500398 const std::vector<std::string>& params) override
James Feist46229572020-02-19 15:11:58 -0800399 {
400 auto asyncResp = std::make_shared<AsyncResp>(res);
401 if (params.size() != 1)
402 {
403 messages::internalError(asyncResp->res);
404 return;
405 }
406
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500407 const std::string& strParam = params[0];
James Feist46229572020-02-19 15:11:58 -0800408 auto find = std::find_if(
409 task::tasks.begin(), task::tasks.end(),
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500410 [&strParam](const std::shared_ptr<task::TaskData>& task) {
James Feist46229572020-02-19 15:11:58 -0800411 if (!task)
412 {
413 return false;
414 }
415
416 // we compare against the string version as on failure strtoul
417 // returns 0
418 return std::to_string(task->index) == strParam;
419 });
420
421 if (find == task::tasks.end())
422 {
423 messages::resourceNotFound(asyncResp->res, "Tasks", strParam);
424 return;
425 }
426
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500427 std::shared_ptr<task::TaskData>& ptr = *find;
James Feist46229572020-02-19 15:11:58 -0800428
429 asyncResp->res.jsonValue["@odata.type"] = "#Task.v1_4_3.Task";
430 asyncResp->res.jsonValue["Id"] = strParam;
431 asyncResp->res.jsonValue["Name"] = "Task " + strParam;
432 asyncResp->res.jsonValue["TaskState"] = ptr->state;
433 asyncResp->res.jsonValue["StartTime"] =
434 crow::utility::getDateTime(ptr->startTime);
435 if (ptr->endTime)
436 {
437 asyncResp->res.jsonValue["EndTime"] =
438 crow::utility::getDateTime(*(ptr->endTime));
439 }
440 asyncResp->res.jsonValue["TaskStatus"] = ptr->status;
441 asyncResp->res.jsonValue["Messages"] = ptr->messages;
442 asyncResp->res.jsonValue["@odata.id"] =
443 "/redfish/v1/TaskService/Tasks/" + strParam;
444 if (!ptr->gave204)
445 {
446 asyncResp->res.jsonValue["TaskMonitor"] =
447 "/redfish/v1/TaskService/Tasks/" + strParam + "/Monitor";
448 }
James Feistfe306722020-03-12 16:32:08 -0700449 if (ptr->payload)
450 {
451 asyncResp->res.jsonValue["Payload"] = *(ptr->payload);
452 }
James Feist46229572020-02-19 15:11:58 -0800453 }
454};
455
456class TaskCollection : public Node
457{
458 public:
Ed Tanous52cc1122020-07-18 13:51:21 -0700459 TaskCollection(App& app) : Node(app, "/redfish/v1/TaskService/Tasks/")
James Feist46229572020-02-19 15:11:58 -0800460 {
461 entityPrivileges = {
462 {boost::beast::http::verb::get, {{"Login"}}},
463 {boost::beast::http::verb::head, {{"Login"}}},
464 {boost::beast::http::verb::patch, {{"ConfigureManager"}}},
465 {boost::beast::http::verb::put, {{"ConfigureManager"}}},
466 {boost::beast::http::verb::delete_, {{"ConfigureManager"}}},
467 {boost::beast::http::verb::post, {{"ConfigureManager"}}}};
468 }
469
470 private:
Ed Tanouscb13a392020-07-25 19:02:03 +0000471 void doGet(crow::Response& res, const crow::Request&,
472 const std::vector<std::string>&) override
James Feist46229572020-02-19 15:11:58 -0800473 {
474 auto asyncResp = std::make_shared<AsyncResp>(res);
475 asyncResp->res.jsonValue["@odata.type"] =
476 "#TaskCollection.TaskCollection";
477 asyncResp->res.jsonValue["@odata.id"] = "/redfish/v1/TaskService/Tasks";
478 asyncResp->res.jsonValue["Name"] = "Task Collection";
479 asyncResp->res.jsonValue["Members@odata.count"] = task::tasks.size();
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500480 nlohmann::json& members = asyncResp->res.jsonValue["Members"];
James Feist46229572020-02-19 15:11:58 -0800481 members = nlohmann::json::array();
482
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500483 for (const std::shared_ptr<task::TaskData>& task : task::tasks)
James Feist46229572020-02-19 15:11:58 -0800484 {
485 if (task == nullptr)
486 {
487 continue; // shouldn't be possible
488 }
489 members.emplace_back(
490 nlohmann::json{{"@odata.id", "/redfish/v1/TaskService/Tasks/" +
491 std::to_string(task->index)}});
492 }
493 }
494};
495
496class TaskService : public Node
497{
498 public:
Ed Tanous52cc1122020-07-18 13:51:21 -0700499 TaskService(App& app) : Node(app, "/redfish/v1/TaskService/")
James Feist46229572020-02-19 15:11:58 -0800500 {
501 entityPrivileges = {
502 {boost::beast::http::verb::get, {{"Login"}}},
503 {boost::beast::http::verb::head, {{"Login"}}},
504 {boost::beast::http::verb::patch, {{"ConfigureManager"}}},
505 {boost::beast::http::verb::put, {{"ConfigureManager"}}},
506 {boost::beast::http::verb::delete_, {{"ConfigureManager"}}},
507 {boost::beast::http::verb::post, {{"ConfigureManager"}}}};
508 }
509
510 private:
Ed Tanouscb13a392020-07-25 19:02:03 +0000511 void doGet(crow::Response& res, const crow::Request&,
512 const std::vector<std::string>&) override
James Feist46229572020-02-19 15:11:58 -0800513 {
514 auto asyncResp = std::make_shared<AsyncResp>(res);
515 asyncResp->res.jsonValue["@odata.type"] =
516 "#TaskService.v1_1_4.TaskService";
517 asyncResp->res.jsonValue["@odata.id"] = "/redfish/v1/TaskService";
518 asyncResp->res.jsonValue["Name"] = "Task Service";
519 asyncResp->res.jsonValue["Id"] = "TaskService";
520 asyncResp->res.jsonValue["DateTime"] = crow::utility::dateTimeNow();
521 asyncResp->res.jsonValue["CompletedTaskOverWritePolicy"] = "Oldest";
522
Sunitha Harishe7686572020-07-15 02:32:44 -0500523 asyncResp->res.jsonValue["LifeCycleEventOnTaskStateChange"] = true;
James Feist46229572020-02-19 15:11:58 -0800524
525 auto health = std::make_shared<HealthPopulate>(asyncResp);
526 health->populate();
527 asyncResp->res.jsonValue["Status"]["State"] = "Enabled";
528 asyncResp->res.jsonValue["ServiceEnabled"] = true;
529 asyncResp->res.jsonValue["Tasks"] = {
530 {"@odata.id", "/redfish/v1/TaskService/Tasks"}};
531 }
532};
533
534} // namespace redfish