blob: ae077ef07bd1d73dcdfd5f82f311ad0308188372 [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
Sunitha Harish29a82b02021-02-18 15:54:16 +053017#include <boost/asio/ip/address.hpp>
18#include <boost/asio/ip/basic_endpoint.hpp>
Ed Tanousd43cd0c2020-09-30 20:46:53 -070019#include <boost/asio/steady_timer.hpp>
20#include <boost/beast/core/flat_buffer.hpp>
21#include <boost/beast/core/tcp_stream.hpp>
22#include <boost/beast/http/message.hpp>
AppaRao Pulibd030d02020-03-20 03:34:29 +053023#include <boost/beast/version.hpp>
Carson Labradof52c03c2022-03-23 18:50:15 +000024#include <boost/container/devector.hpp>
Sunitha Harish29a82b02021-02-18 15:54:16 +053025#include <include/async_resolve.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050026
AppaRao Pulibd030d02020-03-20 03:34:29 +053027#include <cstdlib>
28#include <functional>
29#include <iostream>
30#include <memory>
AppaRao Puli2a5689a2020-04-29 15:24:31 +053031#include <queue>
AppaRao Pulibd030d02020-03-20 03:34:29 +053032#include <string>
33
34namespace crow
35{
36
Carson Labradof52c03c2022-03-23 18:50:15 +000037// It is assumed that the BMC should be able to handle 4 parallel connections
38constexpr uint8_t maxPoolSize = 4;
39constexpr uint8_t maxRequestQueueSize = 50;
Carson Labrado4d942722022-06-22 22:16:10 +000040constexpr unsigned int httpReadBodyLimit = 16384;
41constexpr unsigned int httpReadBufferSize = 4096;
AppaRao Puli2a5689a2020-04-29 15:24:31 +053042
AppaRao Pulibd030d02020-03-20 03:34:29 +053043enum class ConnState
44{
AppaRao Puli2a5689a2020-04-29 15:24:31 +053045 initialized,
Sunitha Harish29a82b02021-02-18 15:54:16 +053046 resolveInProgress,
47 resolveFailed,
AppaRao Puli2a5689a2020-04-29 15:24:31 +053048 connectInProgress,
49 connectFailed,
AppaRao Pulibd030d02020-03-20 03:34:29 +053050 connected,
AppaRao Puli2a5689a2020-04-29 15:24:31 +053051 sendInProgress,
52 sendFailed,
Sunitha Harish6eaa1d22021-02-19 13:38:31 +053053 recvInProgress,
AppaRao Puli2a5689a2020-04-29 15:24:31 +053054 recvFailed,
55 idle,
Sunitha Harish6eaa1d22021-02-19 13:38:31 +053056 closeInProgress,
Ayushi Smritife44eb02020-05-15 15:24:45 +053057 closed,
Sunitha Harish6eaa1d22021-02-19 13:38:31 +053058 suspended,
59 terminated,
60 abortConnection,
61 retry
AppaRao Pulibd030d02020-03-20 03:34:29 +053062};
63
Carson Labradoa7a80292022-06-01 16:01:52 +000064static inline boost::system::error_code
65 defaultRetryHandler(unsigned int respCode)
66{
67 // As a default, assume 200X is alright
68 BMCWEB_LOG_DEBUG << "Using default check for response code validity";
69 if ((respCode < 200) || (respCode >= 300))
70 {
71 return boost::system::errc::make_error_code(
72 boost::system::errc::result_out_of_range);
73 }
74
75 // Return 0 if the response code is valid
76 return boost::system::errc::make_error_code(boost::system::errc::success);
77};
78
Carson Labradof52c03c2022-03-23 18:50:15 +000079// We need to allow retry information to be set before a message has been sent
80// and a connection pool has been created
81struct RetryPolicyData
82{
83 uint32_t maxRetryAttempts = 5;
84 std::chrono::seconds retryIntervalSecs = std::chrono::seconds(0);
85 std::string retryPolicyAction = "TerminateAfterRetries";
Carson Labradoa7a80292022-06-01 16:01:52 +000086 std::function<boost::system::error_code(unsigned int respCode)>
87 invalidResp = defaultRetryHandler;
Carson Labradof52c03c2022-03-23 18:50:15 +000088};
89
90struct PendingRequest
91{
Carson Labrado244256c2022-04-27 17:16:32 +000092 boost::beast::http::request<boost::beast::http::string_body> req;
Carson Labrado039a47e2022-04-05 16:03:20 +000093 std::function<void(bool, uint32_t, Response&)> callback;
Carson Labradof52c03c2022-03-23 18:50:15 +000094 RetryPolicyData retryPolicy;
Carson Labrado039a47e2022-04-05 16:03:20 +000095 PendingRequest(
Ed Tanous8a592812022-06-04 09:06:59 -070096 boost::beast::http::request<boost::beast::http::string_body>&& reqIn,
97 const std::function<void(bool, uint32_t, Response&)>& callbackIn,
98 const RetryPolicyData& retryPolicyIn) :
99 req(std::move(reqIn)),
100 callback(callbackIn), retryPolicy(retryPolicyIn)
Carson Labradof52c03c2022-03-23 18:50:15 +0000101 {}
102};
103
104class ConnectionInfo : public std::enable_shared_from_this<ConnectionInfo>
AppaRao Pulibd030d02020-03-20 03:34:29 +0530105{
106 private:
Carson Labradof52c03c2022-03-23 18:50:15 +0000107 ConnState state = ConnState::initialized;
108 uint32_t retryCount = 0;
109 bool runningTimer = false;
110 std::string subId;
111 std::string host;
112 uint16_t port;
113 uint32_t connId;
114
115 // Retry policy information
116 // This should be updated before each message is sent
117 RetryPolicyData retryPolicy;
118
119 // Data buffers
AppaRao Pulibd030d02020-03-20 03:34:29 +0530120 boost::beast::http::request<boost::beast::http::string_body> req;
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530121 std::optional<
122 boost::beast::http::response_parser<boost::beast::http::string_body>>
123 parser;
Carson Labrado4d942722022-06-22 22:16:10 +0000124 boost::beast::flat_static_buffer<httpReadBufferSize> buffer;
Carson Labrado039a47e2022-04-05 16:03:20 +0000125 Response res;
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530126
Carson Labradof52c03c2022-03-23 18:50:15 +0000127 // Ascync callables
Carson Labrado039a47e2022-04-05 16:03:20 +0000128 std::function<void(bool, uint32_t, Response&)> callback;
Carson Labradof52c03c2022-03-23 18:50:15 +0000129 crow::async_resolve::Resolver resolver;
130 boost::beast::tcp_stream conn;
131 boost::asio::steady_timer timer;
Ed Tanous84b35602021-09-08 20:06:32 -0700132
Carson Labradof52c03c2022-03-23 18:50:15 +0000133 friend class ConnectionPool;
AppaRao Pulibd030d02020-03-20 03:34:29 +0530134
Sunitha Harish29a82b02021-02-18 15:54:16 +0530135 void doResolve()
136 {
Sunitha Harish29a82b02021-02-18 15:54:16 +0530137 state = ConnState::resolveInProgress;
Carson Labradof52c03c2022-03-23 18:50:15 +0000138 BMCWEB_LOG_DEBUG << "Trying to resolve: " << host << ":"
139 << std::to_string(port)
140 << ", id: " << std::to_string(connId);
Sunitha Harish29a82b02021-02-18 15:54:16 +0530141
142 auto respHandler =
143 [self(shared_from_this())](
144 const boost::beast::error_code ec,
145 const std::vector<boost::asio::ip::tcp::endpoint>&
146 endpointList) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700147 if (ec || (endpointList.empty()))
148 {
149 BMCWEB_LOG_ERROR << "Resolve failed: " << ec.message();
150 self->state = ConnState::resolveFailed;
151 self->waitAndRetry();
152 return;
153 }
154 BMCWEB_LOG_DEBUG << "Resolved " << self->host << ":"
155 << std::to_string(self->port)
156 << ", id: " << std::to_string(self->connId);
157 self->doConnect(endpointList);
158 };
Carson Labradof52c03c2022-03-23 18:50:15 +0000159
Sunitha Harish29a82b02021-02-18 15:54:16 +0530160 resolver.asyncResolve(host, port, std::move(respHandler));
161 }
162
163 void doConnect(
164 const std::vector<boost::asio::ip::tcp::endpoint>& endpointList)
AppaRao Pulibd030d02020-03-20 03:34:29 +0530165 {
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530166 state = ConnState::connectInProgress;
167
Carson Labradof52c03c2022-03-23 18:50:15 +0000168 BMCWEB_LOG_DEBUG << "Trying to connect to: " << host << ":"
169 << std::to_string(port)
170 << ", id: " << std::to_string(connId);
Sunitha Harish29a82b02021-02-18 15:54:16 +0530171
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530172 conn.expires_after(std::chrono::seconds(30));
Ed Tanous002d39b2022-05-31 08:59:27 -0700173 conn.async_connect(endpointList,
174 [self(shared_from_this())](
175 const boost::beast::error_code ec,
176 const boost::asio::ip::tcp::endpoint& endpoint) {
177 if (ec)
178 {
179 BMCWEB_LOG_ERROR << "Connect " << endpoint.address().to_string()
180 << ":" << std::to_string(endpoint.port())
181 << ", id: " << std::to_string(self->connId)
182 << " failed: " << ec.message();
183 self->state = ConnState::connectFailed;
184 self->waitAndRetry();
185 return;
186 }
187 BMCWEB_LOG_DEBUG
188 << "Connected to: " << endpoint.address().to_string() << ":"
189 << std::to_string(endpoint.port())
190 << ", id: " << std::to_string(self->connId);
191 self->state = ConnState::connected;
192 self->sendMessage();
193 });
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530194 }
195
Carson Labradof52c03c2022-03-23 18:50:15 +0000196 void sendMessage()
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530197 {
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530198 state = ConnState::sendInProgress;
199
AppaRao Pulibd030d02020-03-20 03:34:29 +0530200 // Set a timeout on the operation
201 conn.expires_after(std::chrono::seconds(30));
202
203 // Send the HTTP request to the remote host
204 boost::beast::http::async_write(
205 conn, req,
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530206 [self(shared_from_this())](const boost::beast::error_code& ec,
AppaRao Pulibd030d02020-03-20 03:34:29 +0530207 const std::size_t& bytesTransferred) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700208 if (ec)
209 {
210 BMCWEB_LOG_ERROR << "sendMessage() failed: " << ec.message();
211 self->state = ConnState::sendFailed;
212 self->waitAndRetry();
213 return;
214 }
215 BMCWEB_LOG_DEBUG << "sendMessage() bytes transferred: "
216 << bytesTransferred;
217 boost::ignore_unused(bytesTransferred);
AppaRao Pulibd030d02020-03-20 03:34:29 +0530218
Ed Tanous002d39b2022-05-31 08:59:27 -0700219 self->recvMessage();
AppaRao Pulibd030d02020-03-20 03:34:29 +0530220 });
221 }
222
223 void recvMessage()
224 {
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530225 state = ConnState::recvInProgress;
226
227 parser.emplace(std::piecewise_construct, std::make_tuple());
228 parser->body_limit(httpReadBodyLimit);
229
AppaRao Pulibd030d02020-03-20 03:34:29 +0530230 // Receive the HTTP response
231 boost::beast::http::async_read(
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530232 conn, buffer, *parser,
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530233 [self(shared_from_this())](const boost::beast::error_code& ec,
AppaRao Pulibd030d02020-03-20 03:34:29 +0530234 const std::size_t& bytesTransferred) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700235 if (ec)
236 {
237 BMCWEB_LOG_ERROR << "recvMessage() failed: " << ec.message();
238 self->state = ConnState::recvFailed;
239 self->waitAndRetry();
240 return;
241 }
242 BMCWEB_LOG_DEBUG << "recvMessage() bytes transferred: "
243 << bytesTransferred;
244 BMCWEB_LOG_DEBUG << "recvMessage() data: "
245 << self->parser->get().body();
AppaRao Pulibd030d02020-03-20 03:34:29 +0530246
Ed Tanous002d39b2022-05-31 08:59:27 -0700247 unsigned int respCode = self->parser->get().result_int();
248 BMCWEB_LOG_DEBUG << "recvMessage() Header Response Code: "
249 << respCode;
250
Carson Labradoa7a80292022-06-01 16:01:52 +0000251 // Make sure the received response code is valid as defined by
252 // the associated retry policy
253 if (self->retryPolicy.invalidResp(respCode))
Ed Tanous002d39b2022-05-31 08:59:27 -0700254 {
255 // The listener failed to receive the Sent-Event
256 BMCWEB_LOG_ERROR << "recvMessage() Listener Failed to "
257 "receive Sent-Event. Header Response Code: "
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530258 << respCode;
Ed Tanous002d39b2022-05-31 08:59:27 -0700259 self->state = ConnState::recvFailed;
260 self->waitAndRetry();
261 return;
262 }
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530263
Ed Tanous002d39b2022-05-31 08:59:27 -0700264 // Send is successful
265 // Reset the counter just in case this was after retrying
266 self->retryCount = 0;
AppaRao Pulibd030d02020-03-20 03:34:29 +0530267
Ed Tanous002d39b2022-05-31 08:59:27 -0700268 // Keep the connection alive if server supports it
269 // Else close the connection
270 BMCWEB_LOG_DEBUG << "recvMessage() keepalive : "
271 << self->parser->keep_alive();
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530272
Ed Tanous002d39b2022-05-31 08:59:27 -0700273 // Copy the response into a Response object so that it can be
274 // processed by the callback function.
275 self->res.clear();
276 self->res.stringResponse = self->parser->release();
277 self->callback(self->parser->keep_alive(), self->connId, self->res);
AppaRao Pulibd030d02020-03-20 03:34:29 +0530278 });
279 }
280
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530281 void waitAndRetry()
AppaRao Pulibd030d02020-03-20 03:34:29 +0530282 {
Carson Labradof52c03c2022-03-23 18:50:15 +0000283 if (retryCount >= retryPolicy.maxRetryAttempts)
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530284 {
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530285 BMCWEB_LOG_ERROR << "Maximum number of retries reached.";
Carson Labradof52c03c2022-03-23 18:50:15 +0000286 BMCWEB_LOG_DEBUG << "Retry policy: "
287 << retryPolicy.retryPolicyAction;
Carson Labrado039a47e2022-04-05 16:03:20 +0000288
289 // We want to return a 502 to indicate there was an error with the
290 // external server
291 res.clear();
292 redfish::messages::operationFailed(res);
293
Carson Labradof52c03c2022-03-23 18:50:15 +0000294 if (retryPolicy.retryPolicyAction == "TerminateAfterRetries")
Ayushi Smritife44eb02020-05-15 15:24:45 +0530295 {
296 // TODO: delete subscription
297 state = ConnState::terminated;
Carson Labrado039a47e2022-04-05 16:03:20 +0000298 callback(false, connId, res);
Ayushi Smritife44eb02020-05-15 15:24:45 +0530299 }
Carson Labradof52c03c2022-03-23 18:50:15 +0000300 if (retryPolicy.retryPolicyAction == "SuspendRetries")
Ayushi Smritife44eb02020-05-15 15:24:45 +0530301 {
302 state = ConnState::suspended;
Carson Labrado039a47e2022-04-05 16:03:20 +0000303 callback(false, connId, res);
Ayushi Smritife44eb02020-05-15 15:24:45 +0530304 }
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530305 // Reset the retrycount to zero so that client can try connecting
306 // again if needed
Ed Tanous3174e4d2020-10-07 11:41:22 -0700307 retryCount = 0;
Ayushi Smritife44eb02020-05-15 15:24:45 +0530308 return;
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530309 }
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530310
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530311 if (runningTimer)
312 {
313 BMCWEB_LOG_DEBUG << "Retry timer is already running.";
314 return;
315 }
316 runningTimer = true;
317
318 retryCount++;
319
Carson Labradof52c03c2022-03-23 18:50:15 +0000320 BMCWEB_LOG_DEBUG << "Attempt retry after "
321 << std::to_string(
322 retryPolicy.retryIntervalSecs.count())
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530323 << " seconds. RetryCount = " << retryCount;
Carson Labradof52c03c2022-03-23 18:50:15 +0000324 timer.expires_after(retryPolicy.retryIntervalSecs);
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530325 timer.async_wait(
Carson Labradof52c03c2022-03-23 18:50:15 +0000326 [self(shared_from_this())](const boost::system::error_code ec) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700327 if (ec == boost::asio::error::operation_aborted)
328 {
329 BMCWEB_LOG_DEBUG
330 << "async_wait failed since the operation is aborted"
331 << ec.message();
332 }
333 else if (ec)
334 {
335 BMCWEB_LOG_ERROR << "async_wait failed: " << ec.message();
336 // Ignore the error and continue the retry loop to attempt
337 // sending the event as per the retry policy
338 }
339 self->runningTimer = false;
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530340
Ed Tanous002d39b2022-05-31 08:59:27 -0700341 // Let's close the connection and restart from resolve.
342 self->doCloseAndRetry();
343 });
Ayushi Smritife44eb02020-05-15 15:24:45 +0530344 }
345
Carson Labradof52c03c2022-03-23 18:50:15 +0000346 void doClose()
Ayushi Smritife44eb02020-05-15 15:24:45 +0530347 {
Carson Labradof52c03c2022-03-23 18:50:15 +0000348 state = ConnState::closeInProgress;
349 boost::beast::error_code ec;
350 conn.socket().shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
351 conn.close();
352
353 // not_connected happens sometimes so don't bother reporting it.
354 if (ec && ec != boost::beast::errc::not_connected)
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530355 {
Carson Labradof52c03c2022-03-23 18:50:15 +0000356 BMCWEB_LOG_ERROR << host << ":" << std::to_string(port)
357 << ", id: " << std::to_string(connId)
358 << "shutdown failed: " << ec.message();
359 return;
360 }
361 BMCWEB_LOG_DEBUG << host << ":" << std::to_string(port)
362 << ", id: " << std::to_string(connId)
363 << " closed gracefully";
364 if ((state != ConnState::suspended) && (state != ConnState::terminated))
365 {
366 state = ConnState::closed;
367 }
368 }
369
370 void doCloseAndRetry()
371 {
372 state = ConnState::closeInProgress;
373 boost::beast::error_code ec;
374 conn.socket().shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
375 conn.close();
376
377 // not_connected happens sometimes so don't bother reporting it.
378 if (ec && ec != boost::beast::errc::not_connected)
379 {
380 BMCWEB_LOG_ERROR << host << ":" << std::to_string(port)
381 << ", id: " << std::to_string(connId)
382 << "shutdown failed: " << ec.message();
383 return;
384 }
385 BMCWEB_LOG_DEBUG << host << ":" << std::to_string(port)
386 << ", id: " << std::to_string(connId)
387 << " closed gracefully";
388 if ((state != ConnState::suspended) && (state != ConnState::terminated))
389 {
390 // Now let's try to resend the data
391 state = ConnState::retry;
392 this->doResolve();
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530393 }
AppaRao Pulibd030d02020-03-20 03:34:29 +0530394 }
395
396 public:
Ed Tanous8a592812022-06-04 09:06:59 -0700397 explicit ConnectionInfo(boost::asio::io_context& ioc,
398 const std::string& idIn, const std::string& destIP,
399 const uint16_t destPort,
400 const unsigned int connIdIn) :
401 subId(idIn),
402 host(destIP), port(destPort), connId(connIdIn), conn(ioc), timer(ioc)
Carson Labrado244256c2022-04-27 17:16:32 +0000403 {}
Carson Labradof52c03c2022-03-23 18:50:15 +0000404};
AppaRao Pulibd030d02020-03-20 03:34:29 +0530405
Carson Labradof52c03c2022-03-23 18:50:15 +0000406class ConnectionPool : public std::enable_shared_from_this<ConnectionPool>
407{
408 private:
409 boost::asio::io_context& ioc;
410 const std::string id;
411 const std::string destIP;
412 const uint16_t destPort;
Carson Labradof52c03c2022-03-23 18:50:15 +0000413 std::vector<std::shared_ptr<ConnectionInfo>> connections;
414 boost::container::devector<PendingRequest> requestQueue;
415
416 friend class HttpClient;
417
Carson Labrado244256c2022-04-27 17:16:32 +0000418 // Configure a connections's request, callback, and retry info in
419 // preparation to begin sending the request
Carson Labradof52c03c2022-03-23 18:50:15 +0000420 void setConnProps(ConnectionInfo& conn)
AppaRao Pulibd030d02020-03-20 03:34:29 +0530421 {
Carson Labradof52c03c2022-03-23 18:50:15 +0000422 if (requestQueue.empty())
AppaRao Pulibd030d02020-03-20 03:34:29 +0530423 {
Carson Labradof52c03c2022-03-23 18:50:15 +0000424 BMCWEB_LOG_ERROR
425 << "setConnProps() should not have been called when requestQueue is empty";
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530426 return;
AppaRao Pulibd030d02020-03-20 03:34:29 +0530427 }
AppaRao Pulibd030d02020-03-20 03:34:29 +0530428
Carson Labrado244256c2022-04-27 17:16:32 +0000429 auto nextReq = requestQueue.front();
430 conn.retryPolicy = std::move(nextReq.retryPolicy);
431 conn.req = std::move(nextReq.req);
432 conn.callback = std::move(nextReq.callback);
Carson Labradof52c03c2022-03-23 18:50:15 +0000433
434 BMCWEB_LOG_DEBUG << "Setting properties for connection " << conn.host
435 << ":" << std::to_string(conn.port)
Carson Labradoa7a80292022-06-01 16:01:52 +0000436 << ", id: " << std::to_string(conn.connId);
Carson Labradof52c03c2022-03-23 18:50:15 +0000437
438 // We can remove the request from the queue at this point
439 requestQueue.pop_front();
440 }
441
442 // Configures a connection to use the specific retry policy.
443 inline void setConnRetryPolicy(ConnectionInfo& conn,
444 const RetryPolicyData& retryPolicy)
445 {
446 BMCWEB_LOG_DEBUG << destIP << ":" << std::to_string(destPort)
Carson Labradoa7a80292022-06-01 16:01:52 +0000447 << ", id: " << std::to_string(conn.connId);
Carson Labradof52c03c2022-03-23 18:50:15 +0000448
449 conn.retryPolicy = retryPolicy;
450 }
451
452 // Gets called as part of callback after request is sent
453 // Reuses the connection if there are any requests waiting to be sent
454 // Otherwise closes the connection if it is not a keep-alive
455 void sendNext(bool keepAlive, uint32_t connId)
456 {
457 auto conn = connections[connId];
458 // Reuse the connection to send the next request in the queue
459 if (!requestQueue.empty())
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530460 {
Carson Labradof52c03c2022-03-23 18:50:15 +0000461 BMCWEB_LOG_DEBUG << std::to_string(requestQueue.size())
462 << " requests remaining in queue for " << destIP
463 << ":" << std::to_string(destPort)
464 << ", reusing connnection "
465 << std::to_string(connId);
466
467 setConnProps(*conn);
468
469 if (keepAlive)
470 {
471 conn->sendMessage();
472 }
473 else
474 {
475 // Server is not keep-alive enabled so we need to close the
476 // connection and then start over from resolve
477 conn->doClose();
478 conn->doResolve();
479 }
480 return;
481 }
482
483 // No more messages to send so close the connection if necessary
484 if (keepAlive)
485 {
486 conn->state = ConnState::idle;
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530487 }
488 else
489 {
Carson Labradof52c03c2022-03-23 18:50:15 +0000490 // Abort the connection since server is not keep-alive enabled
491 conn->state = ConnState::abortConnection;
492 conn->doClose();
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530493 }
AppaRao Pulibd030d02020-03-20 03:34:29 +0530494 }
495
Carson Labrado244256c2022-04-27 17:16:32 +0000496 void sendData(std::string& data, const std::string& destUri,
497 const boost::beast::http::fields& httpHeader,
498 const boost::beast::http::verb verb,
499 const RetryPolicyData& retryPolicy,
Carson Labrado039a47e2022-04-05 16:03:20 +0000500 std::function<void(Response&)>& resHandler)
Ayushi Smritife44eb02020-05-15 15:24:45 +0530501 {
Carson Labradof52c03c2022-03-23 18:50:15 +0000502 std::weak_ptr<ConnectionPool> weakSelf = weak_from_this();
503
504 // Callback to be called once the request has been sent
Carson Labrado039a47e2022-04-05 16:03:20 +0000505 auto cb = [weakSelf, resHandler](bool keepAlive, uint32_t connId,
506 Response& res) {
507 // Allow provided callback to perform additional processing of the
508 // request
509 resHandler(res);
510
Carson Labradof52c03c2022-03-23 18:50:15 +0000511 // If requests remain in the queue then we want to reuse this
512 // connection to send the next request
513 std::shared_ptr<ConnectionPool> self = weakSelf.lock();
514 if (!self)
515 {
516 BMCWEB_LOG_CRITICAL << self << " Failed to capture connection";
517 return;
518 }
519
520 self->sendNext(keepAlive, connId);
521 };
522
Carson Labrado244256c2022-04-27 17:16:32 +0000523 // Construct the request to be sent
524 boost::beast::http::request<boost::beast::http::string_body> thisReq(
525 verb, destUri, 11, "", httpHeader);
526 thisReq.set(boost::beast::http::field::host, destIP);
527 thisReq.keep_alive(true);
528 thisReq.body() = std::move(data);
529 thisReq.prepare_payload();
530
Carson Labradof52c03c2022-03-23 18:50:15 +0000531 // Reuse an existing connection if one is available
532 for (unsigned int i = 0; i < connections.size(); i++)
533 {
534 auto conn = connections[i];
535 if ((conn->state == ConnState::idle) ||
536 (conn->state == ConnState::initialized) ||
537 (conn->state == ConnState::closed))
538 {
Carson Labrado244256c2022-04-27 17:16:32 +0000539 conn->req = std::move(thisReq);
Carson Labradof52c03c2022-03-23 18:50:15 +0000540 conn->callback = std::move(cb);
Carson Labradof52c03c2022-03-23 18:50:15 +0000541 setConnRetryPolicy(*conn, retryPolicy);
542 std::string commonMsg = std::to_string(i) + " from pool " +
543 destIP + ":" + std::to_string(destPort);
544
545 if (conn->state == ConnState::idle)
546 {
547 BMCWEB_LOG_DEBUG << "Grabbing idle connection "
548 << commonMsg;
549 conn->sendMessage();
550 }
551 else
552 {
553 BMCWEB_LOG_DEBUG << "Reusing existing connection "
554 << commonMsg;
555 conn->doResolve();
556 }
557 return;
558 }
559 }
560
561 // All connections in use so create a new connection or add request to
562 // the queue
563 if (connections.size() < maxPoolSize)
564 {
565 BMCWEB_LOG_DEBUG << "Adding new connection to pool " << destIP
566 << ":" << std::to_string(destPort);
567 auto conn = addConnection();
Carson Labrado244256c2022-04-27 17:16:32 +0000568 conn->req = std::move(thisReq);
Carson Labradof52c03c2022-03-23 18:50:15 +0000569 conn->callback = std::move(cb);
570 setConnRetryPolicy(*conn, retryPolicy);
571 conn->doResolve();
572 }
573 else if (requestQueue.size() < maxRequestQueueSize)
574 {
575 BMCWEB_LOG_ERROR << "Max pool size reached. Adding data to queue.";
Carson Labrado244256c2022-04-27 17:16:32 +0000576 requestQueue.emplace_back(std::move(thisReq), std::move(cb),
Carson Labradof52c03c2022-03-23 18:50:15 +0000577 retryPolicy);
578 }
579 else
580 {
581 BMCWEB_LOG_ERROR << destIP << ":" << std::to_string(destPort)
582 << " request queue full. Dropping request.";
583 }
Ayushi Smritife44eb02020-05-15 15:24:45 +0530584 }
585
Carson Labradof52c03c2022-03-23 18:50:15 +0000586 std::shared_ptr<ConnectionInfo>& addConnection()
Ayushi Smritife44eb02020-05-15 15:24:45 +0530587 {
Carson Labradof52c03c2022-03-23 18:50:15 +0000588 unsigned int newId = static_cast<unsigned int>(connections.size());
589
Carson Labrado244256c2022-04-27 17:16:32 +0000590 auto& ret = connections.emplace_back(
591 std::make_shared<ConnectionInfo>(ioc, id, destIP, destPort, newId));
Carson Labradof52c03c2022-03-23 18:50:15 +0000592
593 BMCWEB_LOG_DEBUG << "Added connection "
594 << std::to_string(connections.size() - 1)
595 << " to pool " << destIP << ":"
596 << std::to_string(destPort);
597
598 return ret;
599 }
600
601 public:
Ed Tanous8a592812022-06-04 09:06:59 -0700602 explicit ConnectionPool(boost::asio::io_context& iocIn,
603 const std::string& idIn,
604 const std::string& destIPIn,
605 const uint16_t destPortIn) :
606 ioc(iocIn),
607 id(idIn), destIP(destIPIn), destPort(destPortIn)
Carson Labradof52c03c2022-03-23 18:50:15 +0000608 {
609 std::string clientKey = destIP + ":" + std::to_string(destPort);
610 BMCWEB_LOG_DEBUG << "Initializing connection pool for " << destIP << ":"
611 << std::to_string(destPort);
612
613 // Initialize the pool with a single connection
614 addConnection();
Ayushi Smritife44eb02020-05-15 15:24:45 +0530615 }
AppaRao Pulibd030d02020-03-20 03:34:29 +0530616};
617
Carson Labradof52c03c2022-03-23 18:50:15 +0000618class HttpClient
619{
620 private:
621 std::unordered_map<std::string, std::shared_ptr<ConnectionPool>>
622 connectionPools;
623 boost::asio::io_context& ioc =
624 crow::connections::systemBus->get_io_context();
625 std::unordered_map<std::string, RetryPolicyData> retryInfo;
626 HttpClient() = default;
627
Carson Labrado039a47e2022-04-05 16:03:20 +0000628 // Used as a dummy callback by sendData() in order to call
629 // sendDataWithCallback()
630 static void genericResHandler(Response& res)
631 {
632 BMCWEB_LOG_DEBUG << "Response handled with return code: "
633 << std::to_string(res.resultInt());
Ed Tanous4ee8e212022-05-28 09:42:51 -0700634 }
Carson Labrado039a47e2022-04-05 16:03:20 +0000635
Carson Labradof52c03c2022-03-23 18:50:15 +0000636 public:
637 HttpClient(const HttpClient&) = delete;
638 HttpClient& operator=(const HttpClient&) = delete;
639 HttpClient(HttpClient&&) = delete;
640 HttpClient& operator=(HttpClient&&) = delete;
641 ~HttpClient() = default;
642
643 static HttpClient& getInstance()
644 {
645 static HttpClient handler;
646 return handler;
647 }
648
Carson Labrado039a47e2022-04-05 16:03:20 +0000649 // Send a request to destIP:destPort where additional processing of the
650 // result is not required
Carson Labradof52c03c2022-03-23 18:50:15 +0000651 void sendData(std::string& data, const std::string& id,
652 const std::string& destIP, const uint16_t destPort,
653 const std::string& destUri,
654 const boost::beast::http::fields& httpHeader,
Carson Labrado244256c2022-04-27 17:16:32 +0000655 const boost::beast::http::verb verb,
656 const std::string& retryPolicyName)
Carson Labradof52c03c2022-03-23 18:50:15 +0000657 {
Carson Labrado039a47e2022-04-05 16:03:20 +0000658 std::function<void(Response&)> cb = genericResHandler;
659 sendDataWithCallback(data, id, destIP, destPort, destUri, httpHeader,
Carson Labrado244256c2022-04-27 17:16:32 +0000660 verb, retryPolicyName, cb);
Carson Labrado039a47e2022-04-05 16:03:20 +0000661 }
662
663 // Send request to destIP:destPort and use the provided callback to
664 // handle the response
665 void sendDataWithCallback(std::string& data, const std::string& id,
666 const std::string& destIP,
667 const uint16_t destPort,
668 const std::string& destUri,
669 const boost::beast::http::fields& httpHeader,
Carson Labrado244256c2022-04-27 17:16:32 +0000670 const boost::beast::http::verb verb,
671 const std::string& retryPolicyName,
Carson Labrado039a47e2022-04-05 16:03:20 +0000672 std::function<void(Response&)>& resHandler)
673 {
Carson Labradof52c03c2022-03-23 18:50:15 +0000674 std::string clientKey = destIP + ":" + std::to_string(destPort);
675 // Use nullptr to avoid creating a ConnectionPool each time
676 auto result = connectionPools.try_emplace(clientKey, nullptr);
677 if (result.second)
678 {
679 // Now actually create the ConnectionPool shared_ptr since it does
680 // not already exist
Carson Labrado244256c2022-04-27 17:16:32 +0000681 result.first->second =
682 std::make_shared<ConnectionPool>(ioc, id, destIP, destPort);
Carson Labradof52c03c2022-03-23 18:50:15 +0000683 BMCWEB_LOG_DEBUG << "Created connection pool for " << clientKey;
684 }
685 else
686 {
687 BMCWEB_LOG_DEBUG << "Using existing connection pool for "
688 << clientKey;
689 }
690
691 // Get the associated retry policy
692 auto policy = retryInfo.try_emplace(retryPolicyName);
693 if (policy.second)
694 {
695 BMCWEB_LOG_DEBUG << "Creating retry policy \"" << retryPolicyName
696 << "\" with default values";
Carson Labradof52c03c2022-03-23 18:50:15 +0000697 }
698
699 // Send the data using either the existing connection pool or the newly
700 // created connection pool
Carson Labrado244256c2022-04-27 17:16:32 +0000701 result.first->second->sendData(data, destUri, httpHeader, verb,
702 policy.first->second, resHandler);
Carson Labradof52c03c2022-03-23 18:50:15 +0000703 }
704
Carson Labradoa7a80292022-06-01 16:01:52 +0000705 void setRetryConfig(
706 const uint32_t retryAttempts, const uint32_t retryTimeoutInterval,
707 const std::function<boost::system::error_code(unsigned int respCode)>&
708 invalidResp,
709 const std::string& retryPolicyName)
Carson Labradof52c03c2022-03-23 18:50:15 +0000710 {
711 // We need to create the retry policy if one does not already exist for
712 // the given retryPolicyName
713 auto result = retryInfo.try_emplace(retryPolicyName);
714 if (result.second)
715 {
716 BMCWEB_LOG_DEBUG << "setRetryConfig(): Creating new retry policy \""
717 << retryPolicyName << "\"";
Carson Labradof52c03c2022-03-23 18:50:15 +0000718 }
719 else
720 {
721 BMCWEB_LOG_DEBUG << "setRetryConfig(): Updating retry info for \""
722 << retryPolicyName << "\"";
723 }
724
725 result.first->second.maxRetryAttempts = retryAttempts;
726 result.first->second.retryIntervalSecs =
727 std::chrono::seconds(retryTimeoutInterval);
Carson Labradoa7a80292022-06-01 16:01:52 +0000728 result.first->second.invalidResp = invalidResp;
Carson Labradof52c03c2022-03-23 18:50:15 +0000729 }
730
731 void setRetryPolicy(const std::string& retryPolicy,
732 const std::string& retryPolicyName)
733 {
734 // We need to create the retry policy if one does not already exist for
735 // the given retryPolicyName
736 auto result = retryInfo.try_emplace(retryPolicyName);
737 if (result.second)
738 {
739 BMCWEB_LOG_DEBUG << "setRetryPolicy(): Creating new retry policy \""
740 << retryPolicyName << "\"";
Carson Labradof52c03c2022-03-23 18:50:15 +0000741 }
742 else
743 {
744 BMCWEB_LOG_DEBUG << "setRetryPolicy(): Updating retry policy for \""
745 << retryPolicyName << "\"";
746 }
747
748 result.first->second.retryPolicyAction = retryPolicy;
749 }
750};
AppaRao Pulibd030d02020-03-20 03:34:29 +0530751} // namespace crow