blob: 19973d96add0c55612c90654bd915c43c70b2ff7 [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
James Feist46229572020-02-19 15:11:58 -080083struct TaskData : std::enable_shared_from_this<TaskData>
84{
85 private:
86 TaskData(std::function<bool(boost::system::error_code,
Gunnar Mills1214b7e2020-06-04 10:11:30 -050087 sdbusplus::message::message&,
88 const std::shared_ptr<TaskData>&)>&& handler,
Ed Tanous23a21a12020-07-25 04:45:05 +000089 const std::string& matchIn, size_t idx) :
James Feist46229572020-02-19 15:11:58 -080090 callback(std::move(handler)),
Ed Tanous23a21a12020-07-25 04:45:05 +000091 matchStr(matchIn), index(idx),
James Feist46229572020-02-19 15:11:58 -080092 startTime(std::chrono::system_clock::to_time_t(
93 std::chrono::system_clock::now())),
94 status("OK"), state("Running"), messages(nlohmann::json::array()),
95 timer(crow::connections::systemBus->get_io_context())
96
Gunnar Mills1214b7e2020-06-04 10:11:30 -050097 {}
James Feist46229572020-02-19 15:11:58 -080098
99 public:
Ed Tanousd609fd62020-09-28 19:08:03 -0700100 TaskData() = delete;
101
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500102 static std::shared_ptr<TaskData>& createTask(
James Feist46229572020-02-19 15:11:58 -0800103 std::function<bool(boost::system::error_code,
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500104 sdbusplus::message::message&,
105 const std::shared_ptr<TaskData>&)>&& handler,
106 const std::string& match)
James Feist46229572020-02-19 15:11:58 -0800107 {
108 static size_t lastTask = 0;
109 struct MakeSharedHelper : public TaskData
110 {
111 MakeSharedHelper(
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500112 std::function<bool(boost::system::error_code,
113 sdbusplus::message::message&,
114 const std::shared_ptr<TaskData>&)>&& handler,
Ed Tanous23a21a12020-07-25 04:45:05 +0000115 const std::string& match2, size_t idx) :
116 TaskData(std::move(handler), match2, idx)
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500117 {}
James Feist46229572020-02-19 15:11:58 -0800118 };
119
120 if (tasks.size() >= maxTaskCount)
121 {
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500122 auto& last = tasks.front();
James Feist46229572020-02-19 15:11:58 -0800123
124 // destroy all references
125 last->timer.cancel();
126 last->match.reset();
127 tasks.pop_front();
128 }
129
130 return tasks.emplace_back(std::make_shared<MakeSharedHelper>(
131 std::move(handler), match, lastTask++));
132 }
133
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500134 void populateResp(crow::Response& res, size_t retryAfterSeconds = 30)
James Feist46229572020-02-19 15:11:58 -0800135 {
136 if (!endTime)
137 {
138 res.result(boost::beast::http::status::accepted);
139 std::string strIdx = std::to_string(index);
140 std::string uri = "/redfish/v1/TaskService/Tasks/" + strIdx;
141 res.jsonValue = {{"@odata.id", uri},
142 {"@odata.type", "#Task.v1_4_3.Task"},
143 {"Id", strIdx},
144 {"TaskState", state},
145 {"TaskStatus", status}};
146 res.addHeader(boost::beast::http::field::location,
147 uri + "/Monitor");
148 res.addHeader(boost::beast::http::field::retry_after,
149 std::to_string(retryAfterSeconds));
150 }
151 else if (!gave204)
152 {
153 res.result(boost::beast::http::status::no_content);
154 gave204 = true;
155 }
156 }
157
Ed Tanousd609fd62020-09-28 19:08:03 -0700158 void finishTask()
James Feist46229572020-02-19 15:11:58 -0800159 {
160 endTime = std::chrono::system_clock::to_time_t(
161 std::chrono::system_clock::now());
162 }
163
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500164 void extendTimer(const std::chrono::seconds& timeout)
James Feist46229572020-02-19 15:11:58 -0800165 {
James Feist46229572020-02-19 15:11:58 -0800166 timer.expires_after(timeout);
167 timer.async_wait(
168 [self = shared_from_this()](boost::system::error_code ec) {
169 if (ec == boost::asio::error::operation_aborted)
170 {
Gunnar Mills4e0453b2020-07-08 14:00:30 -0500171 return; // completed successfully
James Feist46229572020-02-19 15:11:58 -0800172 }
173 if (!ec)
174 {
175 // change ec to error as timer expired
176 ec = boost::asio::error::operation_aborted;
177 }
178 self->match.reset();
179 sdbusplus::message::message msg;
180 self->finishTask();
181 self->state = "Cancelled";
182 self->status = "Warning";
James Feiste5d50062020-05-11 17:29:00 -0700183 self->messages.emplace_back(
184 messages::taskAborted(std::to_string(self->index)));
Sunitha Harishe7686572020-07-15 02:32:44 -0500185 // Send event :TaskAborted
186 self->sendTaskEvent(self->state, self->index);
James Feist46229572020-02-19 15:11:58 -0800187 self->callback(ec, msg, self);
188 });
James Feistfd9ab9e2020-05-19 13:48:07 -0700189 }
190
Sunitha Harishe7686572020-07-15 02:32:44 -0500191 void sendTaskEvent(const std::string_view state, size_t index)
192 {
193 std::string origin =
194 "/redfish/v1/TaskService/Tasks/" + std::to_string(index);
195 std::string resType = "Task";
196 // TaskState enums which should send out an event are:
197 // "Starting" = taskResumed
198 // "Running" = taskStarted
199 // "Suspended" = taskPaused
200 // "Interrupted" = taskPaused
201 // "Pending" = taskPaused
202 // "Stopping" = taskAborted
203 // "Completed" = taskCompletedOK
204 // "Killed" = taskRemoved
205 // "Exception" = taskCompletedWarning
206 // "Cancelled" = taskCancelled
207 if (state == "Starting")
208 {
209 redfish::EventServiceManager::getInstance().sendEvent(
210 redfish::messages::taskResumed(std::to_string(index)), origin,
211 resType);
212 }
213 else if (state == "Running")
214 {
215 redfish::EventServiceManager::getInstance().sendEvent(
216 redfish::messages::taskStarted(std::to_string(index)), origin,
217 resType);
218 }
219 else if ((state == "Suspended") || (state == "Interrupted") ||
220 (state == "Pending"))
221 {
222 redfish::EventServiceManager::getInstance().sendEvent(
223 redfish::messages::taskPaused(std::to_string(index)), origin,
224 resType);
225 }
226 else if (state == "Stopping")
227 {
228 redfish::EventServiceManager::getInstance().sendEvent(
229 redfish::messages::taskAborted(std::to_string(index)), origin,
230 resType);
231 }
232 else if (state == "Completed")
233 {
234 redfish::EventServiceManager::getInstance().sendEvent(
235 redfish::messages::taskCompletedOK(std::to_string(index)),
236 origin, resType);
237 }
238 else if (state == "Killed")
239 {
240 redfish::EventServiceManager::getInstance().sendEvent(
241 redfish::messages::taskRemoved(std::to_string(index)), origin,
242 resType);
243 }
244 else if (state == "Exception")
245 {
246 redfish::EventServiceManager::getInstance().sendEvent(
247 redfish::messages::taskCompletedWarning(std::to_string(index)),
248 origin, resType);
249 }
250 else if (state == "Cancelled")
251 {
252 redfish::EventServiceManager::getInstance().sendEvent(
253 redfish::messages::taskCancelled(std::to_string(index)), origin,
254 resType);
255 }
256 else
257 {
258 BMCWEB_LOG_INFO << "sendTaskEvent: No events to send";
259 }
260 }
261
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500262 void startTimer(const std::chrono::seconds& timeout)
James Feistfd9ab9e2020-05-19 13:48:07 -0700263 {
264 if (match)
265 {
266 return;
267 }
268 match = std::make_unique<sdbusplus::bus::match::match>(
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500269 static_cast<sdbusplus::bus::bus&>(*crow::connections::systemBus),
James Feistfd9ab9e2020-05-19 13:48:07 -0700270 matchStr,
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500271 [self = shared_from_this()](sdbusplus::message::message& message) {
James Feistfd9ab9e2020-05-19 13:48:07 -0700272 boost::system::error_code ec;
273
274 // callback to return True if callback is done, callback needs
275 // to update status itself if needed
276 if (self->callback(ec, message, self) == task::completed)
277 {
278 self->timer.cancel();
279 self->finishTask();
280
Sunitha Harishe7686572020-07-15 02:32:44 -0500281 // Send event
282 self->sendTaskEvent(self->state, self->index);
283
James Feistfd9ab9e2020-05-19 13:48:07 -0700284 // reset the match after the callback was successful
285 boost::asio::post(
286 crow::connections::systemBus->get_io_context(),
287 [self] { self->match.reset(); });
288 return;
289 }
290 });
291
292 extendTimer(timeout);
James Feiste5d50062020-05-11 17:29:00 -0700293 messages.emplace_back(messages::taskStarted(std::to_string(index)));
Sunitha Harishe7686572020-07-15 02:32:44 -0500294 // Send event : TaskStarted
295 sendTaskEvent(state, index);
James Feist46229572020-02-19 15:11:58 -0800296 }
297
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500298 std::function<bool(boost::system::error_code, sdbusplus::message::message&,
299 const std::shared_ptr<TaskData>&)>
James Feist46229572020-02-19 15:11:58 -0800300 callback;
301 std::string matchStr;
302 size_t index;
303 time_t startTime;
304 std::string status;
305 std::string state;
306 nlohmann::json messages;
307 boost::asio::steady_timer timer;
308 std::unique_ptr<sdbusplus::bus::match::match> match;
309 std::optional<time_t> endTime;
James Feistfe306722020-03-12 16:32:08 -0700310 std::optional<Payload> payload;
James Feist46229572020-02-19 15:11:58 -0800311 bool gave204 = false;
312};
313
314} // namespace task
315
316class TaskMonitor : public Node
317{
318 public:
Ed Tanous52cc1122020-07-18 13:51:21 -0700319 TaskMonitor(App& app) :
Gunnar Mills7af91512020-04-14 22:16:57 -0500320 Node((app), "/redfish/v1/TaskService/Tasks/<str>/Monitor/",
James Feist46229572020-02-19 15:11:58 -0800321 std::string())
322 {
323 entityPrivileges = {
324 {boost::beast::http::verb::get, {{"Login"}}},
325 {boost::beast::http::verb::head, {{"Login"}}},
326 {boost::beast::http::verb::patch, {{"ConfigureManager"}}},
327 {boost::beast::http::verb::put, {{"ConfigureManager"}}},
328 {boost::beast::http::verb::delete_, {{"ConfigureManager"}}},
329 {boost::beast::http::verb::post, {{"ConfigureManager"}}}};
330 }
331
332 private:
Ed Tanouscb13a392020-07-25 19:02:03 +0000333 void doGet(crow::Response& res, const crow::Request&,
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500334 const std::vector<std::string>& params) override
James Feist46229572020-02-19 15:11:58 -0800335 {
336 auto asyncResp = std::make_shared<AsyncResp>(res);
337 if (params.size() != 1)
338 {
339 messages::internalError(asyncResp->res);
340 return;
341 }
342
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500343 const std::string& strParam = params[0];
James Feist46229572020-02-19 15:11:58 -0800344 auto find = std::find_if(
345 task::tasks.begin(), task::tasks.end(),
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500346 [&strParam](const std::shared_ptr<task::TaskData>& task) {
James Feist46229572020-02-19 15:11:58 -0800347 if (!task)
348 {
349 return false;
350 }
351
352 // we compare against the string version as on failure strtoul
353 // returns 0
354 return std::to_string(task->index) == strParam;
355 });
356
357 if (find == task::tasks.end())
358 {
359 messages::resourceNotFound(asyncResp->res, "Monitor", strParam);
360 return;
361 }
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500362 std::shared_ptr<task::TaskData>& ptr = *find;
James Feist46229572020-02-19 15:11:58 -0800363 // monitor expires after 204
364 if (ptr->gave204)
365 {
366 messages::resourceNotFound(asyncResp->res, "Monitor", strParam);
367 return;
368 }
369 ptr->populateResp(asyncResp->res);
370 }
371};
372
373class Task : public Node
374{
375 public:
Ed Tanous52cc1122020-07-18 13:51:21 -0700376 Task(App& app) :
Gunnar Mills7af91512020-04-14 22:16:57 -0500377 Node((app), "/redfish/v1/TaskService/Tasks/<str>/", std::string())
James Feist46229572020-02-19 15:11:58 -0800378 {
379 entityPrivileges = {
380 {boost::beast::http::verb::get, {{"Login"}}},
381 {boost::beast::http::verb::head, {{"Login"}}},
382 {boost::beast::http::verb::patch, {{"ConfigureManager"}}},
383 {boost::beast::http::verb::put, {{"ConfigureManager"}}},
384 {boost::beast::http::verb::delete_, {{"ConfigureManager"}}},
385 {boost::beast::http::verb::post, {{"ConfigureManager"}}}};
386 }
387
388 private:
Ed Tanouscb13a392020-07-25 19:02:03 +0000389 void doGet(crow::Response& res, const crow::Request&,
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500390 const std::vector<std::string>& params) override
James Feist46229572020-02-19 15:11:58 -0800391 {
392 auto asyncResp = std::make_shared<AsyncResp>(res);
393 if (params.size() != 1)
394 {
395 messages::internalError(asyncResp->res);
396 return;
397 }
398
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500399 const std::string& strParam = params[0];
James Feist46229572020-02-19 15:11:58 -0800400 auto find = std::find_if(
401 task::tasks.begin(), task::tasks.end(),
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500402 [&strParam](const std::shared_ptr<task::TaskData>& task) {
James Feist46229572020-02-19 15:11:58 -0800403 if (!task)
404 {
405 return false;
406 }
407
408 // we compare against the string version as on failure strtoul
409 // returns 0
410 return std::to_string(task->index) == strParam;
411 });
412
413 if (find == task::tasks.end())
414 {
415 messages::resourceNotFound(asyncResp->res, "Tasks", strParam);
416 return;
417 }
418
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500419 std::shared_ptr<task::TaskData>& ptr = *find;
James Feist46229572020-02-19 15:11:58 -0800420
421 asyncResp->res.jsonValue["@odata.type"] = "#Task.v1_4_3.Task";
422 asyncResp->res.jsonValue["Id"] = strParam;
423 asyncResp->res.jsonValue["Name"] = "Task " + strParam;
424 asyncResp->res.jsonValue["TaskState"] = ptr->state;
425 asyncResp->res.jsonValue["StartTime"] =
426 crow::utility::getDateTime(ptr->startTime);
427 if (ptr->endTime)
428 {
429 asyncResp->res.jsonValue["EndTime"] =
430 crow::utility::getDateTime(*(ptr->endTime));
431 }
432 asyncResp->res.jsonValue["TaskStatus"] = ptr->status;
433 asyncResp->res.jsonValue["Messages"] = ptr->messages;
434 asyncResp->res.jsonValue["@odata.id"] =
435 "/redfish/v1/TaskService/Tasks/" + strParam;
436 if (!ptr->gave204)
437 {
438 asyncResp->res.jsonValue["TaskMonitor"] =
439 "/redfish/v1/TaskService/Tasks/" + strParam + "/Monitor";
440 }
James Feistfe306722020-03-12 16:32:08 -0700441 if (ptr->payload)
442 {
Ed Tanous5fb91ba2020-09-28 15:41:28 -0700443 const task::Payload& p = *(ptr->payload);
444 asyncResp->res.jsonValue["Payload"] = {
445 {"TargetUri", p.targetUri},
446 {"HttpOperation", p.httpOperation},
447 {"HttpHeaders", p.httpHeaders},
448 {"JsonBody", p.jsonBody.dump()}};
James Feistfe306722020-03-12 16:32:08 -0700449 }
James Feist46229572020-02-19 15:11:58 -0800450 }
451};
452
453class TaskCollection : public Node
454{
455 public:
Ed Tanous52cc1122020-07-18 13:51:21 -0700456 TaskCollection(App& app) : Node(app, "/redfish/v1/TaskService/Tasks/")
James Feist46229572020-02-19 15:11:58 -0800457 {
458 entityPrivileges = {
459 {boost::beast::http::verb::get, {{"Login"}}},
460 {boost::beast::http::verb::head, {{"Login"}}},
461 {boost::beast::http::verb::patch, {{"ConfigureManager"}}},
462 {boost::beast::http::verb::put, {{"ConfigureManager"}}},
463 {boost::beast::http::verb::delete_, {{"ConfigureManager"}}},
464 {boost::beast::http::verb::post, {{"ConfigureManager"}}}};
465 }
466
467 private:
Ed Tanouscb13a392020-07-25 19:02:03 +0000468 void doGet(crow::Response& res, const crow::Request&,
469 const std::vector<std::string>&) override
James Feist46229572020-02-19 15:11:58 -0800470 {
471 auto asyncResp = std::make_shared<AsyncResp>(res);
472 asyncResp->res.jsonValue["@odata.type"] =
473 "#TaskCollection.TaskCollection";
474 asyncResp->res.jsonValue["@odata.id"] = "/redfish/v1/TaskService/Tasks";
475 asyncResp->res.jsonValue["Name"] = "Task Collection";
476 asyncResp->res.jsonValue["Members@odata.count"] = task::tasks.size();
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500477 nlohmann::json& members = asyncResp->res.jsonValue["Members"];
James Feist46229572020-02-19 15:11:58 -0800478 members = nlohmann::json::array();
479
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500480 for (const std::shared_ptr<task::TaskData>& task : task::tasks)
James Feist46229572020-02-19 15:11:58 -0800481 {
482 if (task == nullptr)
483 {
484 continue; // shouldn't be possible
485 }
486 members.emplace_back(
487 nlohmann::json{{"@odata.id", "/redfish/v1/TaskService/Tasks/" +
488 std::to_string(task->index)}});
489 }
490 }
491};
492
493class TaskService : public Node
494{
495 public:
Ed Tanous52cc1122020-07-18 13:51:21 -0700496 TaskService(App& app) : Node(app, "/redfish/v1/TaskService/")
James Feist46229572020-02-19 15:11:58 -0800497 {
498 entityPrivileges = {
499 {boost::beast::http::verb::get, {{"Login"}}},
500 {boost::beast::http::verb::head, {{"Login"}}},
501 {boost::beast::http::verb::patch, {{"ConfigureManager"}}},
502 {boost::beast::http::verb::put, {{"ConfigureManager"}}},
503 {boost::beast::http::verb::delete_, {{"ConfigureManager"}}},
504 {boost::beast::http::verb::post, {{"ConfigureManager"}}}};
505 }
506
507 private:
Ed Tanouscb13a392020-07-25 19:02:03 +0000508 void doGet(crow::Response& res, const crow::Request&,
509 const std::vector<std::string>&) override
James Feist46229572020-02-19 15:11:58 -0800510 {
511 auto asyncResp = std::make_shared<AsyncResp>(res);
512 asyncResp->res.jsonValue["@odata.type"] =
513 "#TaskService.v1_1_4.TaskService";
514 asyncResp->res.jsonValue["@odata.id"] = "/redfish/v1/TaskService";
515 asyncResp->res.jsonValue["Name"] = "Task Service";
516 asyncResp->res.jsonValue["Id"] = "TaskService";
517 asyncResp->res.jsonValue["DateTime"] = crow::utility::dateTimeNow();
518 asyncResp->res.jsonValue["CompletedTaskOverWritePolicy"] = "Oldest";
519
Sunitha Harishe7686572020-07-15 02:32:44 -0500520 asyncResp->res.jsonValue["LifeCycleEventOnTaskStateChange"] = true;
James Feist46229572020-02-19 15:11:58 -0800521
522 auto health = std::make_shared<HealthPopulate>(asyncResp);
523 health->populate();
524 asyncResp->res.jsonValue["Status"]["State"] = "Enabled";
525 asyncResp->res.jsonValue["ServiceEnabled"] = true;
526 asyncResp->res.jsonValue["Tasks"] = {
527 {"@odata.id", "/redfish/v1/TaskService/Tasks"}};
528 }
529};
530
531} // namespace redfish