blob: 14e2cf263f6ece9ea290ac08bad849687a32cc5f [file] [log] [blame]
AppaRao Pulibd030d02020-03-20 03:34:29 +05301/*
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
Ed Tanousbb49eb52022-06-28 12:02:42 -070017#include <boost/asio/io_context.hpp>
Sunitha Harish29a82b02021-02-18 15:54:16 +053018#include <boost/asio/ip/address.hpp>
19#include <boost/asio/ip/basic_endpoint.hpp>
Ed Tanousbb49eb52022-06-28 12:02:42 -070020#include <boost/asio/ip/tcp.hpp>
Ed Tanousd43cd0c2020-09-30 20:46:53 -070021#include <boost/asio/steady_timer.hpp>
22#include <boost/beast/core/flat_buffer.hpp>
Ed Tanousbb49eb52022-06-28 12:02:42 -070023#include <boost/beast/core/flat_static_buffer.hpp>
Ed Tanousd43cd0c2020-09-30 20:46:53 -070024#include <boost/beast/core/tcp_stream.hpp>
25#include <boost/beast/http/message.hpp>
Ed Tanousbb49eb52022-06-28 12:02:42 -070026#include <boost/beast/http/parser.hpp>
27#include <boost/beast/http/read.hpp>
28#include <boost/beast/http/string_body.hpp>
29#include <boost/beast/http/write.hpp>
AppaRao Pulibd030d02020-03-20 03:34:29 +053030#include <boost/beast/version.hpp>
Carson Labradof52c03c2022-03-23 18:50:15 +000031#include <boost/container/devector.hpp>
Ed Tanousbb49eb52022-06-28 12:02:42 -070032#include <boost/system/error_code.hpp>
33#include <http/http_response.hpp>
Sunitha Harish29a82b02021-02-18 15:54:16 +053034#include <include/async_resolve.hpp>
Ed Tanousbb49eb52022-06-28 12:02:42 -070035#include <logging.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050036
AppaRao Pulibd030d02020-03-20 03:34:29 +053037#include <cstdlib>
38#include <functional>
39#include <iostream>
40#include <memory>
AppaRao Puli2a5689a2020-04-29 15:24:31 +053041#include <queue>
AppaRao Pulibd030d02020-03-20 03:34:29 +053042#include <string>
43
44namespace crow
45{
46
Carson Labradof52c03c2022-03-23 18:50:15 +000047// It is assumed that the BMC should be able to handle 4 parallel connections
48constexpr uint8_t maxPoolSize = 4;
49constexpr uint8_t maxRequestQueueSize = 50;
Carson Labrado4d942722022-06-22 22:16:10 +000050constexpr unsigned int httpReadBodyLimit = 16384;
51constexpr unsigned int httpReadBufferSize = 4096;
AppaRao Puli2a5689a2020-04-29 15:24:31 +053052
AppaRao Pulibd030d02020-03-20 03:34:29 +053053enum class ConnState
54{
AppaRao Puli2a5689a2020-04-29 15:24:31 +053055 initialized,
Sunitha Harish29a82b02021-02-18 15:54:16 +053056 resolveInProgress,
57 resolveFailed,
AppaRao Puli2a5689a2020-04-29 15:24:31 +053058 connectInProgress,
59 connectFailed,
AppaRao Pulibd030d02020-03-20 03:34:29 +053060 connected,
AppaRao Puli2a5689a2020-04-29 15:24:31 +053061 sendInProgress,
62 sendFailed,
Sunitha Harish6eaa1d22021-02-19 13:38:31 +053063 recvInProgress,
AppaRao Puli2a5689a2020-04-29 15:24:31 +053064 recvFailed,
65 idle,
Sunitha Harish6eaa1d22021-02-19 13:38:31 +053066 closeInProgress,
Ayushi Smritife44eb02020-05-15 15:24:45 +053067 closed,
Sunitha Harish6eaa1d22021-02-19 13:38:31 +053068 suspended,
69 terminated,
70 abortConnection,
71 retry
AppaRao Pulibd030d02020-03-20 03:34:29 +053072};
73
Carson Labradoa7a80292022-06-01 16:01:52 +000074static inline boost::system::error_code
75 defaultRetryHandler(unsigned int respCode)
76{
77 // As a default, assume 200X is alright
78 BMCWEB_LOG_DEBUG << "Using default check for response code validity";
79 if ((respCode < 200) || (respCode >= 300))
80 {
81 return boost::system::errc::make_error_code(
82 boost::system::errc::result_out_of_range);
83 }
84
85 // Return 0 if the response code is valid
86 return boost::system::errc::make_error_code(boost::system::errc::success);
87};
88
Carson Labradof52c03c2022-03-23 18:50:15 +000089// We need to allow retry information to be set before a message has been sent
90// and a connection pool has been created
91struct RetryPolicyData
92{
93 uint32_t maxRetryAttempts = 5;
94 std::chrono::seconds retryIntervalSecs = std::chrono::seconds(0);
95 std::string retryPolicyAction = "TerminateAfterRetries";
Carson Labradoa7a80292022-06-01 16:01:52 +000096 std::function<boost::system::error_code(unsigned int respCode)>
97 invalidResp = defaultRetryHandler;
Carson Labradof52c03c2022-03-23 18:50:15 +000098};
99
100struct PendingRequest
101{
Carson Labrado244256c2022-04-27 17:16:32 +0000102 boost::beast::http::request<boost::beast::http::string_body> req;
Carson Labrado039a47e2022-04-05 16:03:20 +0000103 std::function<void(bool, uint32_t, Response&)> callback;
Carson Labradof52c03c2022-03-23 18:50:15 +0000104 RetryPolicyData retryPolicy;
Carson Labrado039a47e2022-04-05 16:03:20 +0000105 PendingRequest(
Ed Tanous8a592812022-06-04 09:06:59 -0700106 boost::beast::http::request<boost::beast::http::string_body>&& reqIn,
107 const std::function<void(bool, uint32_t, Response&)>& callbackIn,
108 const RetryPolicyData& retryPolicyIn) :
109 req(std::move(reqIn)),
110 callback(callbackIn), retryPolicy(retryPolicyIn)
Carson Labradof52c03c2022-03-23 18:50:15 +0000111 {}
112};
113
114class ConnectionInfo : public std::enable_shared_from_this<ConnectionInfo>
AppaRao Pulibd030d02020-03-20 03:34:29 +0530115{
116 private:
Carson Labradof52c03c2022-03-23 18:50:15 +0000117 ConnState state = ConnState::initialized;
118 uint32_t retryCount = 0;
119 bool runningTimer = false;
120 std::string subId;
121 std::string host;
122 uint16_t port;
123 uint32_t connId;
124
125 // Retry policy information
126 // This should be updated before each message is sent
127 RetryPolicyData retryPolicy;
128
129 // Data buffers
AppaRao Pulibd030d02020-03-20 03:34:29 +0530130 boost::beast::http::request<boost::beast::http::string_body> req;
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530131 std::optional<
132 boost::beast::http::response_parser<boost::beast::http::string_body>>
133 parser;
Carson Labrado4d942722022-06-22 22:16:10 +0000134 boost::beast::flat_static_buffer<httpReadBufferSize> buffer;
Carson Labrado039a47e2022-04-05 16:03:20 +0000135 Response res;
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530136
Carson Labradof52c03c2022-03-23 18:50:15 +0000137 // Ascync callables
Carson Labrado039a47e2022-04-05 16:03:20 +0000138 std::function<void(bool, uint32_t, Response&)> callback;
Carson Labradof52c03c2022-03-23 18:50:15 +0000139 crow::async_resolve::Resolver resolver;
140 boost::beast::tcp_stream conn;
141 boost::asio::steady_timer timer;
Ed Tanous84b35602021-09-08 20:06:32 -0700142
Carson Labradof52c03c2022-03-23 18:50:15 +0000143 friend class ConnectionPool;
AppaRao Pulibd030d02020-03-20 03:34:29 +0530144
Sunitha Harish29a82b02021-02-18 15:54:16 +0530145 void doResolve()
146 {
Sunitha Harish29a82b02021-02-18 15:54:16 +0530147 state = ConnState::resolveInProgress;
Carson Labradof52c03c2022-03-23 18:50:15 +0000148 BMCWEB_LOG_DEBUG << "Trying to resolve: " << host << ":"
149 << std::to_string(port)
150 << ", id: " << std::to_string(connId);
Sunitha Harish29a82b02021-02-18 15:54:16 +0530151
152 auto respHandler =
153 [self(shared_from_this())](
154 const boost::beast::error_code ec,
155 const std::vector<boost::asio::ip::tcp::endpoint>&
156 endpointList) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700157 if (ec || (endpointList.empty()))
158 {
159 BMCWEB_LOG_ERROR << "Resolve failed: " << ec.message();
160 self->state = ConnState::resolveFailed;
161 self->waitAndRetry();
162 return;
163 }
164 BMCWEB_LOG_DEBUG << "Resolved " << self->host << ":"
165 << std::to_string(self->port)
166 << ", id: " << std::to_string(self->connId);
167 self->doConnect(endpointList);
168 };
Carson Labradof52c03c2022-03-23 18:50:15 +0000169
Sunitha Harish29a82b02021-02-18 15:54:16 +0530170 resolver.asyncResolve(host, port, std::move(respHandler));
171 }
172
173 void doConnect(
174 const std::vector<boost::asio::ip::tcp::endpoint>& endpointList)
AppaRao Pulibd030d02020-03-20 03:34:29 +0530175 {
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530176 state = ConnState::connectInProgress;
177
Carson Labradof52c03c2022-03-23 18:50:15 +0000178 BMCWEB_LOG_DEBUG << "Trying to connect to: " << host << ":"
179 << std::to_string(port)
180 << ", id: " << std::to_string(connId);
Sunitha Harish29a82b02021-02-18 15:54:16 +0530181
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530182 conn.expires_after(std::chrono::seconds(30));
Ed Tanous002d39b2022-05-31 08:59:27 -0700183 conn.async_connect(endpointList,
184 [self(shared_from_this())](
185 const boost::beast::error_code ec,
186 const boost::asio::ip::tcp::endpoint& endpoint) {
187 if (ec)
188 {
189 BMCWEB_LOG_ERROR << "Connect " << endpoint.address().to_string()
190 << ":" << std::to_string(endpoint.port())
191 << ", id: " << std::to_string(self->connId)
192 << " failed: " << ec.message();
193 self->state = ConnState::connectFailed;
194 self->waitAndRetry();
195 return;
196 }
197 BMCWEB_LOG_DEBUG
198 << "Connected to: " << endpoint.address().to_string() << ":"
199 << std::to_string(endpoint.port())
200 << ", id: " << std::to_string(self->connId);
201 self->state = ConnState::connected;
202 self->sendMessage();
203 });
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530204 }
205
Carson Labradof52c03c2022-03-23 18:50:15 +0000206 void sendMessage()
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530207 {
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530208 state = ConnState::sendInProgress;
209
AppaRao Pulibd030d02020-03-20 03:34:29 +0530210 // Set a timeout on the operation
211 conn.expires_after(std::chrono::seconds(30));
212
213 // Send the HTTP request to the remote host
214 boost::beast::http::async_write(
215 conn, req,
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530216 [self(shared_from_this())](const boost::beast::error_code& ec,
AppaRao Pulibd030d02020-03-20 03:34:29 +0530217 const std::size_t& bytesTransferred) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700218 if (ec)
219 {
220 BMCWEB_LOG_ERROR << "sendMessage() failed: " << ec.message();
221 self->state = ConnState::sendFailed;
222 self->waitAndRetry();
223 return;
224 }
225 BMCWEB_LOG_DEBUG << "sendMessage() bytes transferred: "
226 << bytesTransferred;
227 boost::ignore_unused(bytesTransferred);
AppaRao Pulibd030d02020-03-20 03:34:29 +0530228
Ed Tanous002d39b2022-05-31 08:59:27 -0700229 self->recvMessage();
AppaRao Pulibd030d02020-03-20 03:34:29 +0530230 });
231 }
232
233 void recvMessage()
234 {
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530235 state = ConnState::recvInProgress;
236
237 parser.emplace(std::piecewise_construct, std::make_tuple());
238 parser->body_limit(httpReadBodyLimit);
239
AppaRao Pulibd030d02020-03-20 03:34:29 +0530240 // Receive the HTTP response
241 boost::beast::http::async_read(
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530242 conn, buffer, *parser,
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530243 [self(shared_from_this())](const boost::beast::error_code& ec,
AppaRao Pulibd030d02020-03-20 03:34:29 +0530244 const std::size_t& bytesTransferred) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700245 if (ec)
246 {
247 BMCWEB_LOG_ERROR << "recvMessage() failed: " << ec.message();
248 self->state = ConnState::recvFailed;
249 self->waitAndRetry();
250 return;
251 }
252 BMCWEB_LOG_DEBUG << "recvMessage() bytes transferred: "
253 << bytesTransferred;
254 BMCWEB_LOG_DEBUG << "recvMessage() data: "
255 << self->parser->get().body();
AppaRao Pulibd030d02020-03-20 03:34:29 +0530256
Ed Tanous002d39b2022-05-31 08:59:27 -0700257 unsigned int respCode = self->parser->get().result_int();
258 BMCWEB_LOG_DEBUG << "recvMessage() Header Response Code: "
259 << respCode;
260
Carson Labradoa7a80292022-06-01 16:01:52 +0000261 // Make sure the received response code is valid as defined by
262 // the associated retry policy
263 if (self->retryPolicy.invalidResp(respCode))
Ed Tanous002d39b2022-05-31 08:59:27 -0700264 {
265 // The listener failed to receive the Sent-Event
266 BMCWEB_LOG_ERROR << "recvMessage() Listener Failed to "
267 "receive Sent-Event. Header Response Code: "
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530268 << respCode;
Ed Tanous002d39b2022-05-31 08:59:27 -0700269 self->state = ConnState::recvFailed;
270 self->waitAndRetry();
271 return;
272 }
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530273
Ed Tanous002d39b2022-05-31 08:59:27 -0700274 // Send is successful
275 // Reset the counter just in case this was after retrying
276 self->retryCount = 0;
AppaRao Pulibd030d02020-03-20 03:34:29 +0530277
Ed Tanous002d39b2022-05-31 08:59:27 -0700278 // Keep the connection alive if server supports it
279 // Else close the connection
280 BMCWEB_LOG_DEBUG << "recvMessage() keepalive : "
281 << self->parser->keep_alive();
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530282
Ed Tanous002d39b2022-05-31 08:59:27 -0700283 // Copy the response into a Response object so that it can be
284 // processed by the callback function.
285 self->res.clear();
286 self->res.stringResponse = self->parser->release();
287 self->callback(self->parser->keep_alive(), self->connId, self->res);
AppaRao Pulibd030d02020-03-20 03:34:29 +0530288 });
289 }
290
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530291 void waitAndRetry()
AppaRao Pulibd030d02020-03-20 03:34:29 +0530292 {
Carson Labradof52c03c2022-03-23 18:50:15 +0000293 if (retryCount >= retryPolicy.maxRetryAttempts)
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530294 {
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530295 BMCWEB_LOG_ERROR << "Maximum number of retries reached.";
Carson Labradof52c03c2022-03-23 18:50:15 +0000296 BMCWEB_LOG_DEBUG << "Retry policy: "
297 << retryPolicy.retryPolicyAction;
Carson Labrado039a47e2022-04-05 16:03:20 +0000298
299 // We want to return a 502 to indicate there was an error with the
300 // external server
301 res.clear();
302 redfish::messages::operationFailed(res);
303
Carson Labradof52c03c2022-03-23 18:50:15 +0000304 if (retryPolicy.retryPolicyAction == "TerminateAfterRetries")
Ayushi Smritife44eb02020-05-15 15:24:45 +0530305 {
306 // TODO: delete subscription
307 state = ConnState::terminated;
Carson Labrado039a47e2022-04-05 16:03:20 +0000308 callback(false, connId, res);
Ayushi Smritife44eb02020-05-15 15:24:45 +0530309 }
Carson Labradof52c03c2022-03-23 18:50:15 +0000310 if (retryPolicy.retryPolicyAction == "SuspendRetries")
Ayushi Smritife44eb02020-05-15 15:24:45 +0530311 {
312 state = ConnState::suspended;
Carson Labrado039a47e2022-04-05 16:03:20 +0000313 callback(false, connId, res);
Ayushi Smritife44eb02020-05-15 15:24:45 +0530314 }
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530315 // Reset the retrycount to zero so that client can try connecting
316 // again if needed
Ed Tanous3174e4d2020-10-07 11:41:22 -0700317 retryCount = 0;
Ayushi Smritife44eb02020-05-15 15:24:45 +0530318 return;
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530319 }
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530320
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530321 if (runningTimer)
322 {
323 BMCWEB_LOG_DEBUG << "Retry timer is already running.";
324 return;
325 }
326 runningTimer = true;
327
328 retryCount++;
329
Carson Labradof52c03c2022-03-23 18:50:15 +0000330 BMCWEB_LOG_DEBUG << "Attempt retry after "
331 << std::to_string(
332 retryPolicy.retryIntervalSecs.count())
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530333 << " seconds. RetryCount = " << retryCount;
Carson Labradof52c03c2022-03-23 18:50:15 +0000334 timer.expires_after(retryPolicy.retryIntervalSecs);
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530335 timer.async_wait(
Carson Labradof52c03c2022-03-23 18:50:15 +0000336 [self(shared_from_this())](const boost::system::error_code ec) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700337 if (ec == boost::asio::error::operation_aborted)
338 {
339 BMCWEB_LOG_DEBUG
340 << "async_wait failed since the operation is aborted"
341 << ec.message();
342 }
343 else if (ec)
344 {
345 BMCWEB_LOG_ERROR << "async_wait failed: " << ec.message();
346 // Ignore the error and continue the retry loop to attempt
347 // sending the event as per the retry policy
348 }
349 self->runningTimer = false;
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530350
Ed Tanous002d39b2022-05-31 08:59:27 -0700351 // Let's close the connection and restart from resolve.
352 self->doCloseAndRetry();
353 });
Ayushi Smritife44eb02020-05-15 15:24:45 +0530354 }
355
Carson Labradof52c03c2022-03-23 18:50:15 +0000356 void doClose()
Ayushi Smritife44eb02020-05-15 15:24:45 +0530357 {
Carson Labradof52c03c2022-03-23 18:50:15 +0000358 state = ConnState::closeInProgress;
359 boost::beast::error_code ec;
360 conn.socket().shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
361 conn.close();
362
363 // not_connected happens sometimes so don't bother reporting it.
364 if (ec && ec != boost::beast::errc::not_connected)
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530365 {
Carson Labradof52c03c2022-03-23 18:50:15 +0000366 BMCWEB_LOG_ERROR << host << ":" << std::to_string(port)
367 << ", id: " << std::to_string(connId)
368 << "shutdown failed: " << ec.message();
369 return;
370 }
371 BMCWEB_LOG_DEBUG << host << ":" << std::to_string(port)
372 << ", id: " << std::to_string(connId)
373 << " closed gracefully";
374 if ((state != ConnState::suspended) && (state != ConnState::terminated))
375 {
376 state = ConnState::closed;
377 }
378 }
379
380 void doCloseAndRetry()
381 {
382 state = ConnState::closeInProgress;
383 boost::beast::error_code ec;
384 conn.socket().shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
385 conn.close();
386
387 // not_connected happens sometimes so don't bother reporting it.
388 if (ec && ec != boost::beast::errc::not_connected)
389 {
390 BMCWEB_LOG_ERROR << host << ":" << std::to_string(port)
391 << ", id: " << std::to_string(connId)
392 << "shutdown failed: " << ec.message();
393 return;
394 }
395 BMCWEB_LOG_DEBUG << host << ":" << std::to_string(port)
396 << ", id: " << std::to_string(connId)
397 << " closed gracefully";
398 if ((state != ConnState::suspended) && (state != ConnState::terminated))
399 {
400 // Now let's try to resend the data
401 state = ConnState::retry;
402 this->doResolve();
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530403 }
AppaRao Pulibd030d02020-03-20 03:34:29 +0530404 }
405
406 public:
Ed Tanous8a592812022-06-04 09:06:59 -0700407 explicit ConnectionInfo(boost::asio::io_context& ioc,
408 const std::string& idIn, const std::string& destIP,
409 const uint16_t destPort,
410 const unsigned int connIdIn) :
411 subId(idIn),
412 host(destIP), port(destPort), connId(connIdIn), conn(ioc), timer(ioc)
Carson Labrado244256c2022-04-27 17:16:32 +0000413 {}
Carson Labradof52c03c2022-03-23 18:50:15 +0000414};
AppaRao Pulibd030d02020-03-20 03:34:29 +0530415
Carson Labradof52c03c2022-03-23 18:50:15 +0000416class ConnectionPool : public std::enable_shared_from_this<ConnectionPool>
417{
418 private:
419 boost::asio::io_context& ioc;
420 const std::string id;
421 const std::string destIP;
422 const uint16_t destPort;
Carson Labradof52c03c2022-03-23 18:50:15 +0000423 std::vector<std::shared_ptr<ConnectionInfo>> connections;
424 boost::container::devector<PendingRequest> requestQueue;
425
426 friend class HttpClient;
427
Carson Labrado244256c2022-04-27 17:16:32 +0000428 // Configure a connections's request, callback, and retry info in
429 // preparation to begin sending the request
Carson Labradof52c03c2022-03-23 18:50:15 +0000430 void setConnProps(ConnectionInfo& conn)
AppaRao Pulibd030d02020-03-20 03:34:29 +0530431 {
Carson Labradof52c03c2022-03-23 18:50:15 +0000432 if (requestQueue.empty())
AppaRao Pulibd030d02020-03-20 03:34:29 +0530433 {
Carson Labradof52c03c2022-03-23 18:50:15 +0000434 BMCWEB_LOG_ERROR
435 << "setConnProps() should not have been called when requestQueue is empty";
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530436 return;
AppaRao Pulibd030d02020-03-20 03:34:29 +0530437 }
AppaRao Pulibd030d02020-03-20 03:34:29 +0530438
Carson Labrado244256c2022-04-27 17:16:32 +0000439 auto nextReq = requestQueue.front();
440 conn.retryPolicy = std::move(nextReq.retryPolicy);
441 conn.req = std::move(nextReq.req);
442 conn.callback = std::move(nextReq.callback);
Carson Labradof52c03c2022-03-23 18:50:15 +0000443
444 BMCWEB_LOG_DEBUG << "Setting properties for connection " << conn.host
445 << ":" << std::to_string(conn.port)
Carson Labradoa7a80292022-06-01 16:01:52 +0000446 << ", id: " << std::to_string(conn.connId);
Carson Labradof52c03c2022-03-23 18:50:15 +0000447
448 // We can remove the request from the queue at this point
449 requestQueue.pop_front();
450 }
451
452 // Configures a connection to use the specific retry policy.
453 inline void setConnRetryPolicy(ConnectionInfo& conn,
454 const RetryPolicyData& retryPolicy)
455 {
456 BMCWEB_LOG_DEBUG << destIP << ":" << std::to_string(destPort)
Carson Labradoa7a80292022-06-01 16:01:52 +0000457 << ", id: " << std::to_string(conn.connId);
Carson Labradof52c03c2022-03-23 18:50:15 +0000458
459 conn.retryPolicy = retryPolicy;
460 }
461
462 // Gets called as part of callback after request is sent
463 // Reuses the connection if there are any requests waiting to be sent
464 // Otherwise closes the connection if it is not a keep-alive
465 void sendNext(bool keepAlive, uint32_t connId)
466 {
467 auto conn = connections[connId];
468 // Reuse the connection to send the next request in the queue
469 if (!requestQueue.empty())
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530470 {
Carson Labradof52c03c2022-03-23 18:50:15 +0000471 BMCWEB_LOG_DEBUG << std::to_string(requestQueue.size())
472 << " requests remaining in queue for " << destIP
473 << ":" << std::to_string(destPort)
474 << ", reusing connnection "
475 << std::to_string(connId);
476
477 setConnProps(*conn);
478
479 if (keepAlive)
480 {
481 conn->sendMessage();
482 }
483 else
484 {
485 // Server is not keep-alive enabled so we need to close the
486 // connection and then start over from resolve
487 conn->doClose();
488 conn->doResolve();
489 }
490 return;
491 }
492
493 // No more messages to send so close the connection if necessary
494 if (keepAlive)
495 {
496 conn->state = ConnState::idle;
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530497 }
498 else
499 {
Carson Labradof52c03c2022-03-23 18:50:15 +0000500 // Abort the connection since server is not keep-alive enabled
501 conn->state = ConnState::abortConnection;
502 conn->doClose();
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530503 }
AppaRao Pulibd030d02020-03-20 03:34:29 +0530504 }
505
Carson Labrado244256c2022-04-27 17:16:32 +0000506 void sendData(std::string& data, const std::string& destUri,
507 const boost::beast::http::fields& httpHeader,
508 const boost::beast::http::verb verb,
509 const RetryPolicyData& retryPolicy,
Carson Labrado039a47e2022-04-05 16:03:20 +0000510 std::function<void(Response&)>& resHandler)
Ayushi Smritife44eb02020-05-15 15:24:45 +0530511 {
Carson Labradof52c03c2022-03-23 18:50:15 +0000512 std::weak_ptr<ConnectionPool> weakSelf = weak_from_this();
513
514 // Callback to be called once the request has been sent
Carson Labrado039a47e2022-04-05 16:03:20 +0000515 auto cb = [weakSelf, resHandler](bool keepAlive, uint32_t connId,
516 Response& res) {
517 // Allow provided callback to perform additional processing of the
518 // request
519 resHandler(res);
520
Carson Labradof52c03c2022-03-23 18:50:15 +0000521 // If requests remain in the queue then we want to reuse this
522 // connection to send the next request
523 std::shared_ptr<ConnectionPool> self = weakSelf.lock();
524 if (!self)
525 {
526 BMCWEB_LOG_CRITICAL << self << " Failed to capture connection";
527 return;
528 }
529
530 self->sendNext(keepAlive, connId);
531 };
532
Carson Labrado244256c2022-04-27 17:16:32 +0000533 // Construct the request to be sent
534 boost::beast::http::request<boost::beast::http::string_body> thisReq(
535 verb, destUri, 11, "", httpHeader);
536 thisReq.set(boost::beast::http::field::host, destIP);
537 thisReq.keep_alive(true);
538 thisReq.body() = std::move(data);
539 thisReq.prepare_payload();
540
Carson Labradof52c03c2022-03-23 18:50:15 +0000541 // Reuse an existing connection if one is available
542 for (unsigned int i = 0; i < connections.size(); i++)
543 {
544 auto conn = connections[i];
545 if ((conn->state == ConnState::idle) ||
546 (conn->state == ConnState::initialized) ||
547 (conn->state == ConnState::closed))
548 {
Carson Labrado244256c2022-04-27 17:16:32 +0000549 conn->req = std::move(thisReq);
Carson Labradof52c03c2022-03-23 18:50:15 +0000550 conn->callback = std::move(cb);
Carson Labradof52c03c2022-03-23 18:50:15 +0000551 setConnRetryPolicy(*conn, retryPolicy);
552 std::string commonMsg = std::to_string(i) + " from pool " +
553 destIP + ":" + std::to_string(destPort);
554
555 if (conn->state == ConnState::idle)
556 {
557 BMCWEB_LOG_DEBUG << "Grabbing idle connection "
558 << commonMsg;
559 conn->sendMessage();
560 }
561 else
562 {
563 BMCWEB_LOG_DEBUG << "Reusing existing connection "
564 << commonMsg;
565 conn->doResolve();
566 }
567 return;
568 }
569 }
570
571 // All connections in use so create a new connection or add request to
572 // the queue
573 if (connections.size() < maxPoolSize)
574 {
575 BMCWEB_LOG_DEBUG << "Adding new connection to pool " << destIP
576 << ":" << std::to_string(destPort);
577 auto conn = addConnection();
Carson Labrado244256c2022-04-27 17:16:32 +0000578 conn->req = std::move(thisReq);
Carson Labradof52c03c2022-03-23 18:50:15 +0000579 conn->callback = std::move(cb);
580 setConnRetryPolicy(*conn, retryPolicy);
581 conn->doResolve();
582 }
583 else if (requestQueue.size() < maxRequestQueueSize)
584 {
585 BMCWEB_LOG_ERROR << "Max pool size reached. Adding data to queue.";
Carson Labrado244256c2022-04-27 17:16:32 +0000586 requestQueue.emplace_back(std::move(thisReq), std::move(cb),
Carson Labradof52c03c2022-03-23 18:50:15 +0000587 retryPolicy);
588 }
589 else
590 {
591 BMCWEB_LOG_ERROR << destIP << ":" << std::to_string(destPort)
592 << " request queue full. Dropping request.";
593 }
Ayushi Smritife44eb02020-05-15 15:24:45 +0530594 }
595
Carson Labradof52c03c2022-03-23 18:50:15 +0000596 std::shared_ptr<ConnectionInfo>& addConnection()
Ayushi Smritife44eb02020-05-15 15:24:45 +0530597 {
Carson Labradof52c03c2022-03-23 18:50:15 +0000598 unsigned int newId = static_cast<unsigned int>(connections.size());
599
Carson Labrado244256c2022-04-27 17:16:32 +0000600 auto& ret = connections.emplace_back(
601 std::make_shared<ConnectionInfo>(ioc, id, destIP, destPort, newId));
Carson Labradof52c03c2022-03-23 18:50:15 +0000602
603 BMCWEB_LOG_DEBUG << "Added connection "
604 << std::to_string(connections.size() - 1)
605 << " to pool " << destIP << ":"
606 << std::to_string(destPort);
607
608 return ret;
609 }
610
611 public:
Ed Tanous8a592812022-06-04 09:06:59 -0700612 explicit ConnectionPool(boost::asio::io_context& iocIn,
613 const std::string& idIn,
614 const std::string& destIPIn,
615 const uint16_t destPortIn) :
616 ioc(iocIn),
617 id(idIn), destIP(destIPIn), destPort(destPortIn)
Carson Labradof52c03c2022-03-23 18:50:15 +0000618 {
619 std::string clientKey = destIP + ":" + std::to_string(destPort);
620 BMCWEB_LOG_DEBUG << "Initializing connection pool for " << destIP << ":"
621 << std::to_string(destPort);
622
623 // Initialize the pool with a single connection
624 addConnection();
Ayushi Smritife44eb02020-05-15 15:24:45 +0530625 }
AppaRao Pulibd030d02020-03-20 03:34:29 +0530626};
627
Carson Labradof52c03c2022-03-23 18:50:15 +0000628class HttpClient
629{
630 private:
631 std::unordered_map<std::string, std::shared_ptr<ConnectionPool>>
632 connectionPools;
633 boost::asio::io_context& ioc =
634 crow::connections::systemBus->get_io_context();
635 std::unordered_map<std::string, RetryPolicyData> retryInfo;
636 HttpClient() = default;
637
Carson Labrado039a47e2022-04-05 16:03:20 +0000638 // Used as a dummy callback by sendData() in order to call
639 // sendDataWithCallback()
640 static void genericResHandler(Response& res)
641 {
642 BMCWEB_LOG_DEBUG << "Response handled with return code: "
643 << std::to_string(res.resultInt());
Ed Tanous4ee8e212022-05-28 09:42:51 -0700644 }
Carson Labrado039a47e2022-04-05 16:03:20 +0000645
Carson Labradof52c03c2022-03-23 18:50:15 +0000646 public:
647 HttpClient(const HttpClient&) = delete;
648 HttpClient& operator=(const HttpClient&) = delete;
649 HttpClient(HttpClient&&) = delete;
650 HttpClient& operator=(HttpClient&&) = delete;
651 ~HttpClient() = default;
652
653 static HttpClient& getInstance()
654 {
655 static HttpClient handler;
656 return handler;
657 }
658
Carson Labrado039a47e2022-04-05 16:03:20 +0000659 // Send a request to destIP:destPort where additional processing of the
660 // result is not required
Carson Labradof52c03c2022-03-23 18:50:15 +0000661 void sendData(std::string& data, const std::string& id,
662 const std::string& destIP, const uint16_t destPort,
663 const std::string& destUri,
664 const boost::beast::http::fields& httpHeader,
Carson Labrado244256c2022-04-27 17:16:32 +0000665 const boost::beast::http::verb verb,
666 const std::string& retryPolicyName)
Carson Labradof52c03c2022-03-23 18:50:15 +0000667 {
Carson Labrado039a47e2022-04-05 16:03:20 +0000668 std::function<void(Response&)> cb = genericResHandler;
669 sendDataWithCallback(data, id, destIP, destPort, destUri, httpHeader,
Carson Labrado244256c2022-04-27 17:16:32 +0000670 verb, retryPolicyName, cb);
Carson Labrado039a47e2022-04-05 16:03:20 +0000671 }
672
673 // Send request to destIP:destPort and use the provided callback to
674 // handle the response
675 void sendDataWithCallback(std::string& data, const std::string& id,
676 const std::string& destIP,
677 const uint16_t destPort,
678 const std::string& destUri,
679 const boost::beast::http::fields& httpHeader,
Carson Labrado244256c2022-04-27 17:16:32 +0000680 const boost::beast::http::verb verb,
681 const std::string& retryPolicyName,
Carson Labrado039a47e2022-04-05 16:03:20 +0000682 std::function<void(Response&)>& resHandler)
683 {
Carson Labradof52c03c2022-03-23 18:50:15 +0000684 std::string clientKey = destIP + ":" + std::to_string(destPort);
685 // Use nullptr to avoid creating a ConnectionPool each time
686 auto result = connectionPools.try_emplace(clientKey, nullptr);
687 if (result.second)
688 {
689 // Now actually create the ConnectionPool shared_ptr since it does
690 // not already exist
Carson Labrado244256c2022-04-27 17:16:32 +0000691 result.first->second =
692 std::make_shared<ConnectionPool>(ioc, id, destIP, destPort);
Carson Labradof52c03c2022-03-23 18:50:15 +0000693 BMCWEB_LOG_DEBUG << "Created connection pool for " << clientKey;
694 }
695 else
696 {
697 BMCWEB_LOG_DEBUG << "Using existing connection pool for "
698 << clientKey;
699 }
700
701 // Get the associated retry policy
702 auto policy = retryInfo.try_emplace(retryPolicyName);
703 if (policy.second)
704 {
705 BMCWEB_LOG_DEBUG << "Creating retry policy \"" << retryPolicyName
706 << "\" with default values";
Carson Labradof52c03c2022-03-23 18:50:15 +0000707 }
708
709 // Send the data using either the existing connection pool or the newly
710 // created connection pool
Carson Labrado244256c2022-04-27 17:16:32 +0000711 result.first->second->sendData(data, destUri, httpHeader, verb,
712 policy.first->second, resHandler);
Carson Labradof52c03c2022-03-23 18:50:15 +0000713 }
714
Carson Labradoa7a80292022-06-01 16:01:52 +0000715 void setRetryConfig(
716 const uint32_t retryAttempts, const uint32_t retryTimeoutInterval,
717 const std::function<boost::system::error_code(unsigned int respCode)>&
718 invalidResp,
719 const std::string& retryPolicyName)
Carson Labradof52c03c2022-03-23 18:50:15 +0000720 {
721 // We need to create the retry policy if one does not already exist for
722 // the given retryPolicyName
723 auto result = retryInfo.try_emplace(retryPolicyName);
724 if (result.second)
725 {
726 BMCWEB_LOG_DEBUG << "setRetryConfig(): Creating new retry policy \""
727 << retryPolicyName << "\"";
Carson Labradof52c03c2022-03-23 18:50:15 +0000728 }
729 else
730 {
731 BMCWEB_LOG_DEBUG << "setRetryConfig(): Updating retry info for \""
732 << retryPolicyName << "\"";
733 }
734
735 result.first->second.maxRetryAttempts = retryAttempts;
736 result.first->second.retryIntervalSecs =
737 std::chrono::seconds(retryTimeoutInterval);
Carson Labradoa7a80292022-06-01 16:01:52 +0000738 result.first->second.invalidResp = invalidResp;
Carson Labradof52c03c2022-03-23 18:50:15 +0000739 }
740
741 void setRetryPolicy(const std::string& retryPolicy,
742 const std::string& retryPolicyName)
743 {
744 // We need to create the retry policy if one does not already exist for
745 // the given retryPolicyName
746 auto result = retryInfo.try_emplace(retryPolicyName);
747 if (result.second)
748 {
749 BMCWEB_LOG_DEBUG << "setRetryPolicy(): Creating new retry policy \""
750 << retryPolicyName << "\"";
Carson Labradof52c03c2022-03-23 18:50:15 +0000751 }
752 else
753 {
754 BMCWEB_LOG_DEBUG << "setRetryPolicy(): Updating retry policy for \""
755 << retryPolicyName << "\"";
756 }
757
758 result.first->second.retryPolicyAction = retryPolicy;
759 }
760};
AppaRao Pulibd030d02020-03-20 03:34:29 +0530761} // namespace crow