blob: 28aeb1c96e05dc7b051186551eeb92b4992af584 [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
Nan Zhou77665bd2022-10-12 20:28:58 +000017
18#include "async_resolve.hpp"
Ed Tanousb2896142024-01-31 15:25:47 -080019#include "http_body.hpp"
Nan Zhou77665bd2022-10-12 20:28:58 +000020#include "http_response.hpp"
Ed Tanous3ccb3ad2023-01-13 17:40:03 -080021#include "logging.hpp"
22#include "ssl_key_handler.hpp"
Nan Zhou77665bd2022-10-12 20:28:58 +000023
Ed Tanous0d5f5cf2022-03-12 15:30:55 -080024#include <boost/asio/connect.hpp>
Ed Tanousbb49eb52022-06-28 12:02:42 -070025#include <boost/asio/io_context.hpp>
Sunitha Harish29a82b02021-02-18 15:54:16 +053026#include <boost/asio/ip/address.hpp>
27#include <boost/asio/ip/basic_endpoint.hpp>
Ed Tanousbb49eb52022-06-28 12:02:42 -070028#include <boost/asio/ip/tcp.hpp>
AppaRao Pulie38778a2022-06-27 23:09:03 +000029#include <boost/asio/ssl/context.hpp>
30#include <boost/asio/ssl/error.hpp>
Ed Tanous003301a2024-04-16 09:59:19 -070031#include <boost/asio/ssl/stream.hpp>
Ed Tanousd43cd0c2020-09-30 20:46:53 -070032#include <boost/asio/steady_timer.hpp>
Ed Tanousbb49eb52022-06-28 12:02:42 -070033#include <boost/beast/core/flat_static_buffer.hpp>
Ed Tanousd43cd0c2020-09-30 20:46:53 -070034#include <boost/beast/http/message.hpp>
Ed Tanous4d698612024-02-06 14:57:24 -080035#include <boost/beast/http/message_generator.hpp>
Ed Tanousbb49eb52022-06-28 12:02:42 -070036#include <boost/beast/http/parser.hpp>
37#include <boost/beast/http/read.hpp>
Ed Tanousbb49eb52022-06-28 12:02:42 -070038#include <boost/beast/http/write.hpp>
Carson Labradof52c03c2022-03-23 18:50:15 +000039#include <boost/container/devector.hpp>
Ed Tanousbb49eb52022-06-28 12:02:42 -070040#include <boost/system/error_code.hpp>
Ed Tanous27b0cf92023-08-07 12:02:40 -070041#include <boost/url/format.hpp>
42#include <boost/url/url.hpp>
Ed Tanous4a7fbef2024-04-06 16:03:49 -070043#include <boost/url/url_view_base.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050044
AppaRao Pulibd030d02020-03-20 03:34:29 +053045#include <cstdlib>
46#include <functional>
AppaRao Pulibd030d02020-03-20 03:34:29 +053047#include <memory>
AppaRao Puli2a5689a2020-04-29 15:24:31 +053048#include <queue>
AppaRao Pulibd030d02020-03-20 03:34:29 +053049#include <string>
50
51namespace crow
52{
Ed Tanous27b0cf92023-08-07 12:02:40 -070053// With Redfish Aggregation it is assumed we will connect to another
54// instance of BMCWeb which can handle 100 simultaneous connections.
Carson Labrado66d90c22022-12-07 22:34:33 +000055constexpr size_t maxPoolSize = 20;
56constexpr size_t maxRequestQueueSize = 500;
Carson Labrado17dcc312022-07-28 22:17:28 +000057constexpr unsigned int httpReadBodyLimit = 131072;
Carson Labrado4d942722022-06-22 22:16:10 +000058constexpr unsigned int httpReadBufferSize = 4096;
AppaRao Puli2a5689a2020-04-29 15:24:31 +053059
AppaRao Pulibd030d02020-03-20 03:34:29 +053060enum class ConnState
61{
AppaRao Puli2a5689a2020-04-29 15:24:31 +053062 initialized,
Sunitha Harish29a82b02021-02-18 15:54:16 +053063 resolveInProgress,
64 resolveFailed,
AppaRao Puli2a5689a2020-04-29 15:24:31 +053065 connectInProgress,
66 connectFailed,
AppaRao Pulibd030d02020-03-20 03:34:29 +053067 connected,
AppaRao Pulie38778a2022-06-27 23:09:03 +000068 handshakeInProgress,
69 handshakeFailed,
AppaRao Puli2a5689a2020-04-29 15:24:31 +053070 sendInProgress,
71 sendFailed,
Sunitha Harish6eaa1d22021-02-19 13:38:31 +053072 recvInProgress,
AppaRao Puli2a5689a2020-04-29 15:24:31 +053073 recvFailed,
74 idle,
Ayushi Smritife44eb02020-05-15 15:24:45 +053075 closed,
Sunitha Harish6eaa1d22021-02-19 13:38:31 +053076 suspended,
77 terminated,
78 abortConnection,
AppaRao Pulie38778a2022-06-27 23:09:03 +000079 sslInitFailed,
Sunitha Harish6eaa1d22021-02-19 13:38:31 +053080 retry
AppaRao Pulibd030d02020-03-20 03:34:29 +053081};
82
Carson Labradoa7a80292022-06-01 16:01:52 +000083static inline boost::system::error_code
84 defaultRetryHandler(unsigned int respCode)
85{
86 // As a default, assume 200X is alright
Ed Tanous62598e32023-07-17 17:06:25 -070087 BMCWEB_LOG_DEBUG("Using default check for response code validity");
Carson Labradoa7a80292022-06-01 16:01:52 +000088 if ((respCode < 200) || (respCode >= 300))
89 {
90 return boost::system::errc::make_error_code(
91 boost::system::errc::result_out_of_range);
92 }
93
94 // Return 0 if the response code is valid
95 return boost::system::errc::make_error_code(boost::system::errc::success);
96};
97
Ed Tanous27b0cf92023-08-07 12:02:40 -070098// We need to allow retry information to be set before a message has been
99// sent and a connection pool has been created
Carson Labradod14a48f2023-02-22 00:24:54 +0000100struct ConnectionPolicy
Carson Labradof52c03c2022-03-23 18:50:15 +0000101{
102 uint32_t maxRetryAttempts = 5;
Carson Labradod14a48f2023-02-22 00:24:54 +0000103
104 // the max size of requests in bytes. 0 for unlimited
105 boost::optional<uint64_t> requestByteLimit = httpReadBodyLimit;
106
107 size_t maxConnections = 1;
108
Carson Labradof52c03c2022-03-23 18:50:15 +0000109 std::string retryPolicyAction = "TerminateAfterRetries";
Carson Labradod14a48f2023-02-22 00:24:54 +0000110
111 std::chrono::seconds retryIntervalSecs = std::chrono::seconds(0);
Carson Labradoa7a80292022-06-01 16:01:52 +0000112 std::function<boost::system::error_code(unsigned int respCode)>
113 invalidResp = defaultRetryHandler;
Carson Labradof52c03c2022-03-23 18:50:15 +0000114};
115
116struct PendingRequest
117{
Ed Tanousb2896142024-01-31 15:25:47 -0800118 boost::beast::http::request<bmcweb::HttpBody> req;
Carson Labrado039a47e2022-04-05 16:03:20 +0000119 std::function<void(bool, uint32_t, Response&)> callback;
Carson Labrado039a47e2022-04-05 16:03:20 +0000120 PendingRequest(
Ed Tanousb2896142024-01-31 15:25:47 -0800121 boost::beast::http::request<bmcweb::HttpBody>&& reqIn,
Carson Labradod14a48f2023-02-22 00:24:54 +0000122 const std::function<void(bool, uint32_t, Response&)>& callbackIn) :
Patrick Williamsbd79bce2024-08-16 15:22:20 -0400123 req(std::move(reqIn)), callback(callbackIn)
Carson Labradof52c03c2022-03-23 18:50:15 +0000124 {}
125};
126
Ed Tanouse01d0c32023-06-30 13:21:32 -0700127namespace http = boost::beast::http;
Carson Labradof52c03c2022-03-23 18:50:15 +0000128class ConnectionInfo : public std::enable_shared_from_this<ConnectionInfo>
AppaRao Pulibd030d02020-03-20 03:34:29 +0530129{
130 private:
Carson Labradof52c03c2022-03-23 18:50:15 +0000131 ConnState state = ConnState::initialized;
132 uint32_t retryCount = 0;
Carson Labradof52c03c2022-03-23 18:50:15 +0000133 std::string subId;
Carson Labradod14a48f2023-02-22 00:24:54 +0000134 std::shared_ptr<ConnectionPolicy> connPolicy;
Ed Tanousa716aa72023-08-01 11:35:53 -0700135 boost::urls::url host;
Ed Tanous19bb3622024-07-05 10:07:40 -0500136 ensuressl::VerifyCertificate verifyCert;
Carson Labradof52c03c2022-03-23 18:50:15 +0000137 uint32_t connId;
Carson Labradof52c03c2022-03-23 18:50:15 +0000138 // Data buffers
Ed Tanousb2896142024-01-31 15:25:47 -0800139 http::request<bmcweb::HttpBody> req;
140 using parser_type = http::response_parser<bmcweb::HttpBody>;
Ed Tanouse01d0c32023-06-30 13:21:32 -0700141 std::optional<parser_type> parser;
Carson Labrado4d942722022-06-22 22:16:10 +0000142 boost::beast::flat_static_buffer<httpReadBufferSize> buffer;
Carson Labrado039a47e2022-04-05 16:03:20 +0000143 Response res;
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530144
Carson Labradof52c03c2022-03-23 18:50:15 +0000145 // Ascync callables
Carson Labrado039a47e2022-04-05 16:03:20 +0000146 std::function<void(bool, uint32_t, Response&)> callback;
Ed Tanousf8ca6d72022-06-28 12:12:03 -0700147
Abhilash Rajuf3cb5df2023-11-30 03:54:11 -0600148 boost::asio::io_context& ioc;
149
Ed Tanous25b54db2024-04-17 15:40:31 -0700150 using Resolver = std::conditional_t<BMCWEB_DNS_RESOLVER == "systemd-dbus",
151 async_resolve::Resolver,
152 boost::asio::ip::tcp::resolver>;
Ed Tanousf8ca6d72022-06-28 12:12:03 -0700153 Resolver resolver;
154
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800155 boost::asio::ip::tcp::socket conn;
Ed Tanous003301a2024-04-16 09:59:19 -0700156 std::optional<boost::asio::ssl::stream<boost::asio::ip::tcp::socket&>>
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800157 sslConn;
AppaRao Pulie38778a2022-06-27 23:09:03 +0000158
Carson Labradof52c03c2022-03-23 18:50:15 +0000159 boost::asio::steady_timer timer;
Ed Tanous84b35602021-09-08 20:06:32 -0700160
Carson Labradof52c03c2022-03-23 18:50:15 +0000161 friend class ConnectionPool;
AppaRao Pulibd030d02020-03-20 03:34:29 +0530162
Sunitha Harish29a82b02021-02-18 15:54:16 +0530163 void doResolve()
164 {
Sunitha Harish29a82b02021-02-18 15:54:16 +0530165 state = ConnState::resolveInProgress;
Ed Tanousa716aa72023-08-01 11:35:53 -0700166 BMCWEB_LOG_DEBUG("Trying to resolve: {}, id: {}", host, connId);
Sunitha Harish29a82b02021-02-18 15:54:16 +0530167
Ed Tanousa716aa72023-08-01 11:35:53 -0700168 resolver.async_resolve(host.encoded_host_address(), host.port(),
Ed Tanousf8ca6d72022-06-28 12:12:03 -0700169 std::bind_front(&ConnectionInfo::afterResolve,
170 this, shared_from_this()));
Sunitha Harish29a82b02021-02-18 15:54:16 +0530171 }
172
Ed Tanousf8ca6d72022-06-28 12:12:03 -0700173 void afterResolve(const std::shared_ptr<ConnectionInfo>& /*self*/,
174 const boost::system::error_code& ec,
175 const Resolver::results_type& endpointList)
AppaRao Pulibd030d02020-03-20 03:34:29 +0530176 {
Ed Tanous3d36e3a2022-08-19 15:54:04 -0700177 if (ec || (endpointList.empty()))
178 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700179 BMCWEB_LOG_ERROR("Resolve failed: {} {}", ec.message(), host);
Ed Tanous3d36e3a2022-08-19 15:54:04 -0700180 state = ConnState::resolveFailed;
181 waitAndRetry();
182 return;
183 }
Ed Tanousa716aa72023-08-01 11:35:53 -0700184 BMCWEB_LOG_DEBUG("Resolved {}, id: {}", host, connId);
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530185 state = ConnState::connectInProgress;
186
Ed Tanousa716aa72023-08-01 11:35:53 -0700187 BMCWEB_LOG_DEBUG("Trying to connect to: {}, id: {}", host, connId);
Sunitha Harish29a82b02021-02-18 15:54:16 +0530188
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800189 timer.expires_after(std::chrono::seconds(30));
190 timer.async_wait(std::bind_front(onTimeout, weak_from_this()));
191
192 boost::asio::async_connect(
193 conn, endpointList,
194 std::bind_front(&ConnectionInfo::afterConnect, this,
195 shared_from_this()));
AppaRao Pulie38778a2022-06-27 23:09:03 +0000196 }
197
198 void afterConnect(const std::shared_ptr<ConnectionInfo>& /*self*/,
Ed Tanous81c4e332023-05-18 10:30:34 -0700199 const boost::beast::error_code& ec,
AppaRao Pulie38778a2022-06-27 23:09:03 +0000200 const boost::asio::ip::tcp::endpoint& endpoint)
201 {
Carson Labrado513d1ff2022-07-19 00:38:15 +0000202 // The operation already timed out. We don't want do continue down
203 // this branch
204 if (ec && ec == boost::asio::error::operation_aborted)
205 {
206 return;
207 }
208
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800209 timer.cancel();
AppaRao Pulie38778a2022-06-27 23:09:03 +0000210 if (ec)
211 {
Ed Tanous62598e32023-07-17 17:06:25 -0700212 BMCWEB_LOG_ERROR("Connect {}:{}, id: {} failed: {}",
Ed Tanousa716aa72023-08-01 11:35:53 -0700213 endpoint.address().to_string(), endpoint.port(),
214 connId, ec.message());
AppaRao Pulie38778a2022-06-27 23:09:03 +0000215 state = ConnState::connectFailed;
216 waitAndRetry();
217 return;
218 }
Ed Tanousa716aa72023-08-01 11:35:53 -0700219 BMCWEB_LOG_DEBUG("Connected to: {}:{}, id: {}",
220 endpoint.address().to_string(), endpoint.port(),
221 connId);
AppaRao Pulie38778a2022-06-27 23:09:03 +0000222 if (sslConn)
223 {
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800224 doSslHandshake();
AppaRao Pulie38778a2022-06-27 23:09:03 +0000225 return;
226 }
227 state = ConnState::connected;
228 sendMessage();
229 }
230
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800231 void doSslHandshake()
AppaRao Pulie38778a2022-06-27 23:09:03 +0000232 {
233 if (!sslConn)
234 {
235 return;
236 }
237 state = ConnState::handshakeInProgress;
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800238 timer.expires_after(std::chrono::seconds(30));
239 timer.async_wait(std::bind_front(onTimeout, weak_from_this()));
AppaRao Pulie38778a2022-06-27 23:09:03 +0000240 sslConn->async_handshake(
241 boost::asio::ssl::stream_base::client,
242 std::bind_front(&ConnectionInfo::afterSslHandshake, this,
243 shared_from_this()));
244 }
245
246 void afterSslHandshake(const std::shared_ptr<ConnectionInfo>& /*self*/,
Ed Tanous81c4e332023-05-18 10:30:34 -0700247 const boost::beast::error_code& ec)
AppaRao Pulie38778a2022-06-27 23:09:03 +0000248 {
Carson Labrado513d1ff2022-07-19 00:38:15 +0000249 // The operation already timed out. We don't want do continue down
250 // this branch
251 if (ec && ec == boost::asio::error::operation_aborted)
252 {
253 return;
254 }
255
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800256 timer.cancel();
AppaRao Pulie38778a2022-06-27 23:09:03 +0000257 if (ec)
258 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700259 BMCWEB_LOG_ERROR("SSL Handshake failed - id: {} error: {}", connId,
260 ec.message());
AppaRao Pulie38778a2022-06-27 23:09:03 +0000261 state = ConnState::handshakeFailed;
262 waitAndRetry();
263 return;
264 }
Ed Tanousa716aa72023-08-01 11:35:53 -0700265 BMCWEB_LOG_DEBUG("SSL Handshake successful - id: {}", connId);
AppaRao Pulie38778a2022-06-27 23:09:03 +0000266 state = ConnState::connected;
267 sendMessage();
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530268 }
269
Carson Labradof52c03c2022-03-23 18:50:15 +0000270 void sendMessage()
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530271 {
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530272 state = ConnState::sendInProgress;
273
AppaRao Pulibd030d02020-03-20 03:34:29 +0530274 // Set a timeout on the operation
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800275 timer.expires_after(std::chrono::seconds(30));
276 timer.async_wait(std::bind_front(onTimeout, weak_from_this()));
Ed Tanous4d698612024-02-06 14:57:24 -0800277 boost::beast::http::message_generator messageGenerator(std::move(req));
AppaRao Pulibd030d02020-03-20 03:34:29 +0530278 // Send the HTTP request to the remote host
AppaRao Pulie38778a2022-06-27 23:09:03 +0000279 if (sslConn)
280 {
Ed Tanous4d698612024-02-06 14:57:24 -0800281 boost::beast::async_write(
282 *sslConn, std::move(messageGenerator),
AppaRao Pulie38778a2022-06-27 23:09:03 +0000283 std::bind_front(&ConnectionInfo::afterWrite, this,
284 shared_from_this()));
285 }
286 else
287 {
Ed Tanous4d698612024-02-06 14:57:24 -0800288 boost::beast::async_write(
289 conn, std::move(messageGenerator),
AppaRao Pulie38778a2022-06-27 23:09:03 +0000290 std::bind_front(&ConnectionInfo::afterWrite, this,
291 shared_from_this()));
292 }
293 }
AppaRao Pulibd030d02020-03-20 03:34:29 +0530294
AppaRao Pulie38778a2022-06-27 23:09:03 +0000295 void afterWrite(const std::shared_ptr<ConnectionInfo>& /*self*/,
296 const boost::beast::error_code& ec, size_t bytesTransferred)
297 {
Carson Labrado513d1ff2022-07-19 00:38:15 +0000298 // The operation already timed out. We don't want do continue down
299 // this branch
300 if (ec && ec == boost::asio::error::operation_aborted)
301 {
302 return;
303 }
304
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800305 timer.cancel();
AppaRao Pulie38778a2022-06-27 23:09:03 +0000306 if (ec)
307 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700308 BMCWEB_LOG_ERROR("sendMessage() failed: {} {}", ec.message(), host);
AppaRao Pulie38778a2022-06-27 23:09:03 +0000309 state = ConnState::sendFailed;
310 waitAndRetry();
311 return;
312 }
Ed Tanous62598e32023-07-17 17:06:25 -0700313 BMCWEB_LOG_DEBUG("sendMessage() bytes transferred: {}",
314 bytesTransferred);
AppaRao Pulie38778a2022-06-27 23:09:03 +0000315
316 recvMessage();
AppaRao Pulibd030d02020-03-20 03:34:29 +0530317 }
318
319 void recvMessage()
320 {
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530321 state = ConnState::recvInProgress;
322
Patrick Williamsbd79bce2024-08-16 15:22:20 -0400323 parser_type& thisParser =
324 parser.emplace(std::piecewise_construct, std::make_tuple());
Carson Labradod14a48f2023-02-22 00:24:54 +0000325
Ed Tanouse01d0c32023-06-30 13:21:32 -0700326 thisParser.body_limit(connPolicy->requestByteLimit);
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530327
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800328 timer.expires_after(std::chrono::seconds(30));
329 timer.async_wait(std::bind_front(onTimeout, weak_from_this()));
330
AppaRao Pulibd030d02020-03-20 03:34:29 +0530331 // Receive the HTTP response
AppaRao Pulie38778a2022-06-27 23:09:03 +0000332 if (sslConn)
333 {
334 boost::beast::http::async_read(
Ed Tanouse01d0c32023-06-30 13:21:32 -0700335 *sslConn, buffer, thisParser,
AppaRao Pulie38778a2022-06-27 23:09:03 +0000336 std::bind_front(&ConnectionInfo::afterRead, this,
337 shared_from_this()));
338 }
339 else
340 {
341 boost::beast::http::async_read(
Ed Tanouse01d0c32023-06-30 13:21:32 -0700342 conn, buffer, thisParser,
AppaRao Pulie38778a2022-06-27 23:09:03 +0000343 std::bind_front(&ConnectionInfo::afterRead, this,
344 shared_from_this()));
345 }
346 }
AppaRao Pulibd030d02020-03-20 03:34:29 +0530347
AppaRao Pulie38778a2022-06-27 23:09:03 +0000348 void afterRead(const std::shared_ptr<ConnectionInfo>& /*self*/,
349 const boost::beast::error_code& ec,
350 const std::size_t& bytesTransferred)
351 {
Carson Labrado513d1ff2022-07-19 00:38:15 +0000352 // The operation already timed out. We don't want do continue down
353 // this branch
354 if (ec && ec == boost::asio::error::operation_aborted)
355 {
356 return;
357 }
358
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800359 timer.cancel();
AppaRao Pulie38778a2022-06-27 23:09:03 +0000360 if (ec && ec != boost::asio::ssl::error::stream_truncated)
361 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700362 BMCWEB_LOG_ERROR("recvMessage() failed: {} from {}", ec.message(),
363 host);
AppaRao Pulie38778a2022-06-27 23:09:03 +0000364 state = ConnState::recvFailed;
365 waitAndRetry();
366 return;
367 }
Ed Tanous62598e32023-07-17 17:06:25 -0700368 BMCWEB_LOG_DEBUG("recvMessage() bytes transferred: {}",
369 bytesTransferred);
Ed Tanouse01d0c32023-06-30 13:21:32 -0700370 if (!parser)
371 {
372 return;
373 }
Ed Tanous52e31622024-01-23 16:31:11 -0800374 BMCWEB_LOG_DEBUG("recvMessage() data: {}", parser->get().body().str());
AppaRao Pulie38778a2022-06-27 23:09:03 +0000375
376 unsigned int respCode = parser->get().result_int();
Ed Tanous62598e32023-07-17 17:06:25 -0700377 BMCWEB_LOG_DEBUG("recvMessage() Header Response Code: {}", respCode);
AppaRao Pulie38778a2022-06-27 23:09:03 +0000378
Abhilash Rajuf3cb5df2023-11-30 03:54:11 -0600379 // Handle the case of stream_truncated. Some servers close the ssl
380 // connection uncleanly, so check to see if we got a full response
381 // before we handle this as an error.
382 if (!parser->is_done())
383 {
384 state = ConnState::recvFailed;
385 waitAndRetry();
386 return;
387 }
388
AppaRao Pulie38778a2022-06-27 23:09:03 +0000389 // Make sure the received response code is valid as defined by
390 // the associated retry policy
Carson Labradod14a48f2023-02-22 00:24:54 +0000391 if (connPolicy->invalidResp(respCode))
AppaRao Pulie38778a2022-06-27 23:09:03 +0000392 {
393 // The listener failed to receive the Sent-Event
Ed Tanous62598e32023-07-17 17:06:25 -0700394 BMCWEB_LOG_ERROR(
395 "recvMessage() Listener Failed to "
Ed Tanousa716aa72023-08-01 11:35:53 -0700396 "receive Sent-Event. Header Response Code: {} from {}",
397 respCode, host);
AppaRao Pulie38778a2022-06-27 23:09:03 +0000398 state = ConnState::recvFailed;
399 waitAndRetry();
400 return;
401 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700402
AppaRao Pulie38778a2022-06-27 23:09:03 +0000403 // Send is successful
404 // Reset the counter just in case this was after retrying
405 retryCount = 0;
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530406
AppaRao Pulie38778a2022-06-27 23:09:03 +0000407 // Keep the connection alive if server supports it
408 // Else close the connection
Ed Tanous62598e32023-07-17 17:06:25 -0700409 BMCWEB_LOG_DEBUG("recvMessage() keepalive : {}", parser->keep_alive());
AppaRao Pulibd030d02020-03-20 03:34:29 +0530410
AppaRao Pulie38778a2022-06-27 23:09:03 +0000411 // Copy the response into a Response object so that it can be
412 // processed by the callback function.
Ed Tanous27b0cf92023-08-07 12:02:40 -0700413 res.response = parser->release();
AppaRao Pulie38778a2022-06-27 23:09:03 +0000414 callback(parser->keep_alive(), connId, res);
Carson Labrado513d1ff2022-07-19 00:38:15 +0000415 res.clear();
AppaRao Pulibd030d02020-03-20 03:34:29 +0530416 }
417
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800418 static void onTimeout(const std::weak_ptr<ConnectionInfo>& weakSelf,
Ed Tanous5e7e2dc2023-02-16 10:37:01 -0800419 const boost::system::error_code& ec)
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800420 {
421 if (ec == boost::asio::error::operation_aborted)
422 {
Ed Tanous62598e32023-07-17 17:06:25 -0700423 BMCWEB_LOG_DEBUG(
424 "async_wait failed since the operation is aborted");
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800425 return;
426 }
427 if (ec)
428 {
Ed Tanous62598e32023-07-17 17:06:25 -0700429 BMCWEB_LOG_ERROR("async_wait failed: {}", ec.message());
Ed Tanous27b0cf92023-08-07 12:02:40 -0700430 // If the timer fails, we need to close the socket anyway, same
431 // as if it expired.
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800432 }
433 std::shared_ptr<ConnectionInfo> self = weakSelf.lock();
434 if (self == nullptr)
435 {
436 return;
437 }
438 self->waitAndRetry();
439 }
440
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530441 void waitAndRetry()
AppaRao Pulibd030d02020-03-20 03:34:29 +0530442 {
Carson Labradod14a48f2023-02-22 00:24:54 +0000443 if ((retryCount >= connPolicy->maxRetryAttempts) ||
AppaRao Pulie38778a2022-06-27 23:09:03 +0000444 (state == ConnState::sslInitFailed))
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530445 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700446 BMCWEB_LOG_ERROR("Maximum number of retries reached. {}", host);
Ed Tanous62598e32023-07-17 17:06:25 -0700447 BMCWEB_LOG_DEBUG("Retry policy: {}", connPolicy->retryPolicyAction);
Carson Labrado039a47e2022-04-05 16:03:20 +0000448
Carson Labradod14a48f2023-02-22 00:24:54 +0000449 if (connPolicy->retryPolicyAction == "TerminateAfterRetries")
Ayushi Smritife44eb02020-05-15 15:24:45 +0530450 {
451 // TODO: delete subscription
452 state = ConnState::terminated;
Ayushi Smritife44eb02020-05-15 15:24:45 +0530453 }
Carson Labradod14a48f2023-02-22 00:24:54 +0000454 if (connPolicy->retryPolicyAction == "SuspendRetries")
Ayushi Smritife44eb02020-05-15 15:24:45 +0530455 {
456 state = ConnState::suspended;
Ayushi Smritife44eb02020-05-15 15:24:45 +0530457 }
Carson Labrado513d1ff2022-07-19 00:38:15 +0000458
459 // We want to return a 502 to indicate there was an error with
460 // the external server
461 res.result(boost::beast::http::status::bad_gateway);
462 callback(false, connId, res);
463 res.clear();
464
Ed Tanous27b0cf92023-08-07 12:02:40 -0700465 // Reset the retrycount to zero so that client can try
466 // connecting again if needed
Ed Tanous3174e4d2020-10-07 11:41:22 -0700467 retryCount = 0;
Ayushi Smritife44eb02020-05-15 15:24:45 +0530468 return;
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530469 }
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530470
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530471 retryCount++;
472
Ed Tanous62598e32023-07-17 17:06:25 -0700473 BMCWEB_LOG_DEBUG("Attempt retry after {} seconds. RetryCount = {}",
Ed Tanousa716aa72023-08-01 11:35:53 -0700474 connPolicy->retryIntervalSecs.count(), retryCount);
Carson Labradod14a48f2023-02-22 00:24:54 +0000475 timer.expires_after(connPolicy->retryIntervalSecs);
Ed Tanous3d36e3a2022-08-19 15:54:04 -0700476 timer.async_wait(std::bind_front(&ConnectionInfo::onTimerDone, this,
477 shared_from_this()));
478 }
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530479
Ed Tanous3d36e3a2022-08-19 15:54:04 -0700480 void onTimerDone(const std::shared_ptr<ConnectionInfo>& /*self*/,
481 const boost::system::error_code& ec)
482 {
483 if (ec == boost::asio::error::operation_aborted)
484 {
Ed Tanous62598e32023-07-17 17:06:25 -0700485 BMCWEB_LOG_DEBUG(
486 "async_wait failed since the operation is aborted{}",
487 ec.message());
Ed Tanous3d36e3a2022-08-19 15:54:04 -0700488 }
489 else if (ec)
490 {
Ed Tanous62598e32023-07-17 17:06:25 -0700491 BMCWEB_LOG_ERROR("async_wait failed: {}", ec.message());
Ed Tanous3d36e3a2022-08-19 15:54:04 -0700492 // Ignore the error and continue the retry loop to attempt
493 // sending the event as per the retry policy
494 }
495
496 // Let's close the connection and restart from resolve.
Abhilash Rajuf3cb5df2023-11-30 03:54:11 -0600497 shutdownConn(true);
498 }
499
500 void restartConnection()
501 {
502 BMCWEB_LOG_DEBUG("{}, id: {} restartConnection", host,
503 std::to_string(connId));
504 initializeConnection(host.scheme() == "https");
505 doResolve();
Ayushi Smritife44eb02020-05-15 15:24:45 +0530506 }
507
AppaRao Pulie38778a2022-06-27 23:09:03 +0000508 void shutdownConn(bool retry)
Ayushi Smritife44eb02020-05-15 15:24:45 +0530509 {
Carson Labradof52c03c2022-03-23 18:50:15 +0000510 boost::beast::error_code ec;
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800511 conn.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
Carson Labradof52c03c2022-03-23 18:50:15 +0000512 conn.close();
513
514 // not_connected happens sometimes so don't bother reporting it.
515 if (ec && ec != boost::beast::errc::not_connected)
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530516 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700517 BMCWEB_LOG_ERROR("{}, id: {} shutdown failed: {}", host, connId,
Ed Tanous62598e32023-07-17 17:06:25 -0700518 ec.message());
Carson Labradof52c03c2022-03-23 18:50:15 +0000519 }
Carson Labrado5cab68f2022-07-11 22:26:21 +0000520 else
521 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700522 BMCWEB_LOG_DEBUG("{}, id: {} closed gracefully", host, connId);
Carson Labrado5cab68f2022-07-11 22:26:21 +0000523 }
Ed Tanousca723762022-06-28 19:40:39 -0700524
Carson Labrado513d1ff2022-07-19 00:38:15 +0000525 if (retry)
AppaRao Pulie38778a2022-06-27 23:09:03 +0000526 {
Carson Labrado513d1ff2022-07-19 00:38:15 +0000527 // Now let's try to resend the data
528 state = ConnState::retry;
Abhilash Rajuf3cb5df2023-11-30 03:54:11 -0600529 restartConnection();
Carson Labrado513d1ff2022-07-19 00:38:15 +0000530 }
531 else
532 {
533 state = ConnState::closed;
AppaRao Pulie38778a2022-06-27 23:09:03 +0000534 }
Carson Labradof52c03c2022-03-23 18:50:15 +0000535 }
536
AppaRao Pulie38778a2022-06-27 23:09:03 +0000537 void doClose(bool retry = false)
Carson Labradof52c03c2022-03-23 18:50:15 +0000538 {
AppaRao Pulie38778a2022-06-27 23:09:03 +0000539 if (!sslConn)
540 {
541 shutdownConn(retry);
542 return;
543 }
Carson Labradof52c03c2022-03-23 18:50:15 +0000544
AppaRao Pulie38778a2022-06-27 23:09:03 +0000545 sslConn->async_shutdown(
546 std::bind_front(&ConnectionInfo::afterSslShutdown, this,
547 shared_from_this(), retry));
548 }
549
550 void afterSslShutdown(const std::shared_ptr<ConnectionInfo>& /*self*/,
551 bool retry, const boost::system::error_code& ec)
552 {
AppaRao Pulie38778a2022-06-27 23:09:03 +0000553 if (ec)
Carson Labradof52c03c2022-03-23 18:50:15 +0000554 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700555 BMCWEB_LOG_ERROR("{}, id: {} shutdown failed: {}", host, connId,
Ed Tanous62598e32023-07-17 17:06:25 -0700556 ec.message());
Carson Labradof52c03c2022-03-23 18:50:15 +0000557 }
Carson Labrado5cab68f2022-07-11 22:26:21 +0000558 else
559 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700560 BMCWEB_LOG_DEBUG("{}, id: {} closed gracefully", host, connId);
Carson Labrado5cab68f2022-07-11 22:26:21 +0000561 }
AppaRao Pulie38778a2022-06-27 23:09:03 +0000562 shutdownConn(retry);
563 }
Ed Tanousca723762022-06-28 19:40:39 -0700564
AppaRao Pulie38778a2022-06-27 23:09:03 +0000565 void setCipherSuiteTLSext()
566 {
567 if (!sslConn)
568 {
569 return;
570 }
Ravi Tejae7c29912023-07-31 09:39:32 -0500571
572 if (host.host_type() != boost::urls::host_type::name)
573 {
574 // Avoid setting SNI hostname if its IP address
575 return;
576 }
577 // Create a null terminated string for SSL
Ed Tanousa716aa72023-08-01 11:35:53 -0700578 std::string hostname(host.encoded_host_address());
AppaRao Pulie38778a2022-06-27 23:09:03 +0000579 // NOTE: The SSL_set_tlsext_host_name is defined in tlsv1.h header
580 // file but its having old style casting (name is cast to void*).
581 // Since bmcweb compiler treats all old-style-cast as error, its
582 // causing the build failure. So replaced the same macro inline and
583 // did corrected the code by doing static_cast to viod*. This has to
584 // be fixed in openssl library in long run. Set SNI Hostname (many
585 // hosts need this to handshake successfully)
586 if (SSL_ctrl(sslConn->native_handle(), SSL_CTRL_SET_TLSEXT_HOSTNAME,
587 TLSEXT_NAMETYPE_host_name,
Ed Tanousa716aa72023-08-01 11:35:53 -0700588 static_cast<void*>(hostname.data())) == 0)
AppaRao Pulie38778a2022-06-27 23:09:03 +0000589
590 {
591 boost::beast::error_code ec{static_cast<int>(::ERR_get_error()),
592 boost::asio::error::get_ssl_category()};
593
Ed Tanousa716aa72023-08-01 11:35:53 -0700594 BMCWEB_LOG_ERROR("SSL_set_tlsext_host_name {}, id: {} failed: {}",
595 host, connId, ec.message());
AppaRao Pulie38778a2022-06-27 23:09:03 +0000596 // Set state as sslInit failed so that we close the connection
597 // and take appropriate action as per retry configuration.
598 state = ConnState::sslInitFailed;
599 waitAndRetry();
600 return;
601 }
AppaRao Pulibd030d02020-03-20 03:34:29 +0530602 }
603
Abhilash Rajuf3cb5df2023-11-30 03:54:11 -0600604 void initializeConnection(bool ssl)
AppaRao Pulie38778a2022-06-27 23:09:03 +0000605 {
Abhilash Rajuf3cb5df2023-11-30 03:54:11 -0600606 conn = boost::asio::ip::tcp::socket(ioc);
607 if (ssl)
AppaRao Pulie38778a2022-06-27 23:09:03 +0000608 {
609 std::optional<boost::asio::ssl::context> sslCtx =
Ed Tanous19bb3622024-07-05 10:07:40 -0500610 ensuressl::getSSLClientContext(verifyCert);
AppaRao Pulie38778a2022-06-27 23:09:03 +0000611
612 if (!sslCtx)
613 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700614 BMCWEB_LOG_ERROR("prepareSSLContext failed - {}, id: {}", host,
615 connId);
AppaRao Pulie38778a2022-06-27 23:09:03 +0000616 // Don't retry if failure occurs while preparing SSL context
Ed Tanous27b0cf92023-08-07 12:02:40 -0700617 // such as certificate is invalid or set cipher failure or
618 // set host name failure etc... Setting conn state to
619 // sslInitFailed and connection state will be transitioned
620 // to next state depending on retry policy set by
621 // subscription.
AppaRao Pulie38778a2022-06-27 23:09:03 +0000622 state = ConnState::sslInitFailed;
623 waitAndRetry();
624 return;
625 }
626 sslConn.emplace(conn, *sslCtx);
627 setCipherSuiteTLSext();
628 }
629 }
Abhilash Rajuf3cb5df2023-11-30 03:54:11 -0600630
631 public:
632 explicit ConnectionInfo(
633 boost::asio::io_context& iocIn, const std::string& idIn,
634 const std::shared_ptr<ConnectionPolicy>& connPolicyIn,
Ed Tanous19bb3622024-07-05 10:07:40 -0500635 const boost::urls::url_view_base& hostIn,
636 ensuressl::VerifyCertificate verifyCertIn, unsigned int connIdIn) :
Patrick Williamsbd79bce2024-08-16 15:22:20 -0400637 subId(idIn), connPolicy(connPolicyIn), host(hostIn),
638 verifyCert(verifyCertIn), connId(connIdIn), ioc(iocIn), resolver(iocIn),
639 conn(iocIn), timer(iocIn)
Abhilash Rajuf3cb5df2023-11-30 03:54:11 -0600640 {
641 initializeConnection(host.scheme() == "https");
642 }
Carson Labradof52c03c2022-03-23 18:50:15 +0000643};
AppaRao Pulibd030d02020-03-20 03:34:29 +0530644
Carson Labradof52c03c2022-03-23 18:50:15 +0000645class ConnectionPool : public std::enable_shared_from_this<ConnectionPool>
646{
647 private:
648 boost::asio::io_context& ioc;
AppaRao Pulie38778a2022-06-27 23:09:03 +0000649 std::string id;
Carson Labradod14a48f2023-02-22 00:24:54 +0000650 std::shared_ptr<ConnectionPolicy> connPolicy;
Ed Tanousa716aa72023-08-01 11:35:53 -0700651 boost::urls::url destIP;
Carson Labradof52c03c2022-03-23 18:50:15 +0000652 std::vector<std::shared_ptr<ConnectionInfo>> connections;
653 boost::container::devector<PendingRequest> requestQueue;
Ed Tanous19bb3622024-07-05 10:07:40 -0500654 ensuressl::VerifyCertificate verifyCert;
Carson Labradof52c03c2022-03-23 18:50:15 +0000655
656 friend class HttpClient;
657
Carson Labrado244256c2022-04-27 17:16:32 +0000658 // Configure a connections's request, callback, and retry info in
659 // preparation to begin sending the request
Carson Labradof52c03c2022-03-23 18:50:15 +0000660 void setConnProps(ConnectionInfo& conn)
AppaRao Pulibd030d02020-03-20 03:34:29 +0530661 {
Carson Labradof52c03c2022-03-23 18:50:15 +0000662 if (requestQueue.empty())
AppaRao Pulibd030d02020-03-20 03:34:29 +0530663 {
Ed Tanous62598e32023-07-17 17:06:25 -0700664 BMCWEB_LOG_ERROR(
665 "setConnProps() should not have been called when requestQueue is empty");
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530666 return;
AppaRao Pulibd030d02020-03-20 03:34:29 +0530667 }
AppaRao Pulibd030d02020-03-20 03:34:29 +0530668
Ed Tanous52e31622024-01-23 16:31:11 -0800669 PendingRequest& nextReq = requestQueue.front();
Carson Labrado244256c2022-04-27 17:16:32 +0000670 conn.req = std::move(nextReq.req);
671 conn.callback = std::move(nextReq.callback);
Carson Labradof52c03c2022-03-23 18:50:15 +0000672
Ed Tanousa716aa72023-08-01 11:35:53 -0700673 BMCWEB_LOG_DEBUG("Setting properties for connection {}, id: {}",
674 conn.host, conn.connId);
Carson Labradof52c03c2022-03-23 18:50:15 +0000675
676 // We can remove the request from the queue at this point
677 requestQueue.pop_front();
678 }
679
Carson Labradof52c03c2022-03-23 18:50:15 +0000680 // Gets called as part of callback after request is sent
681 // Reuses the connection if there are any requests waiting to be sent
682 // Otherwise closes the connection if it is not a keep-alive
683 void sendNext(bool keepAlive, uint32_t connId)
684 {
685 auto conn = connections[connId];
Carson Labrado46a81462022-04-27 21:11:37 +0000686
687 // Allow the connection's handler to be deleted
688 // This is needed because of Redfish Aggregation passing an
689 // AsyncResponse shared_ptr to this callback
690 conn->callback = nullptr;
691
Carson Labradof52c03c2022-03-23 18:50:15 +0000692 // Reuse the connection to send the next request in the queue
693 if (!requestQueue.empty())
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530694 {
Ed Tanous62598e32023-07-17 17:06:25 -0700695 BMCWEB_LOG_DEBUG(
Ed Tanous8ece0e42024-01-02 13:16:50 -0800696 "{} requests remaining in queue for {}, reusing connection {}",
Ed Tanousa716aa72023-08-01 11:35:53 -0700697 requestQueue.size(), destIP, connId);
Carson Labradof52c03c2022-03-23 18:50:15 +0000698
699 setConnProps(*conn);
700
701 if (keepAlive)
702 {
703 conn->sendMessage();
704 }
705 else
706 {
707 // Server is not keep-alive enabled so we need to close the
708 // connection and then start over from resolve
709 conn->doClose();
Abhilash Raju2ecde742024-06-01 02:01:01 -0500710 conn->restartConnection();
Carson Labradof52c03c2022-03-23 18:50:15 +0000711 }
712 return;
713 }
714
715 // No more messages to send so close the connection if necessary
716 if (keepAlive)
717 {
718 conn->state = ConnState::idle;
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530719 }
720 else
721 {
Carson Labradof52c03c2022-03-23 18:50:15 +0000722 // Abort the connection since server is not keep-alive enabled
723 conn->state = ConnState::abortConnection;
724 conn->doClose();
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530725 }
AppaRao Pulibd030d02020-03-20 03:34:29 +0530726 }
727
Ed Tanous4a7fbef2024-04-06 16:03:49 -0700728 void sendData(std::string&& data, const boost::urls::url_view_base& destUri,
Carson Labrado244256c2022-04-27 17:16:32 +0000729 const boost::beast::http::fields& httpHeader,
730 const boost::beast::http::verb verb,
Ed Tanous6b3db602022-06-28 19:41:44 -0700731 const std::function<void(Response&)>& resHandler)
Ayushi Smritife44eb02020-05-15 15:24:45 +0530732 {
Carson Labrado244256c2022-04-27 17:16:32 +0000733 // Construct the request to be sent
Ed Tanousb2896142024-01-31 15:25:47 -0800734 boost::beast::http::request<bmcweb::HttpBody> thisReq(
Ed Tanousa716aa72023-08-01 11:35:53 -0700735 verb, destUri.encoded_target(), 11, "", httpHeader);
736 thisReq.set(boost::beast::http::field::host,
737 destUri.encoded_host_address());
Carson Labrado244256c2022-04-27 17:16:32 +0000738 thisReq.keep_alive(true);
Ed Tanous52e31622024-01-23 16:31:11 -0800739 thisReq.body().str() = std::move(data);
Carson Labrado244256c2022-04-27 17:16:32 +0000740 thisReq.prepare_payload();
Ed Tanous3d36e3a2022-08-19 15:54:04 -0700741 auto cb = std::bind_front(&ConnectionPool::afterSendData,
742 weak_from_this(), resHandler);
Carson Labradof52c03c2022-03-23 18:50:15 +0000743 // Reuse an existing connection if one is available
744 for (unsigned int i = 0; i < connections.size(); i++)
745 {
746 auto conn = connections[i];
747 if ((conn->state == ConnState::idle) ||
748 (conn->state == ConnState::initialized) ||
749 (conn->state == ConnState::closed))
750 {
Carson Labrado244256c2022-04-27 17:16:32 +0000751 conn->req = std::move(thisReq);
Carson Labradof52c03c2022-03-23 18:50:15 +0000752 conn->callback = std::move(cb);
Ed Tanousa716aa72023-08-01 11:35:53 -0700753 std::string commonMsg = std::format("{} from pool {}", i, id);
Carson Labradof52c03c2022-03-23 18:50:15 +0000754
755 if (conn->state == ConnState::idle)
756 {
Ed Tanous62598e32023-07-17 17:06:25 -0700757 BMCWEB_LOG_DEBUG("Grabbing idle connection {}", commonMsg);
Carson Labradof52c03c2022-03-23 18:50:15 +0000758 conn->sendMessage();
759 }
760 else
761 {
Ed Tanous62598e32023-07-17 17:06:25 -0700762 BMCWEB_LOG_DEBUG("Reusing existing connection {}",
763 commonMsg);
Abhilash Raju2ecde742024-06-01 02:01:01 -0500764 conn->restartConnection();
Carson Labradof52c03c2022-03-23 18:50:15 +0000765 }
766 return;
767 }
768 }
769
Ed Tanous27b0cf92023-08-07 12:02:40 -0700770 // All connections in use so create a new connection or add request
771 // to the queue
Carson Labradod14a48f2023-02-22 00:24:54 +0000772 if (connections.size() < connPolicy->maxConnections)
Carson Labradof52c03c2022-03-23 18:50:15 +0000773 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700774 BMCWEB_LOG_DEBUG("Adding new connection to pool {}", id);
Carson Labradof52c03c2022-03-23 18:50:15 +0000775 auto conn = addConnection();
Carson Labrado244256c2022-04-27 17:16:32 +0000776 conn->req = std::move(thisReq);
Carson Labradof52c03c2022-03-23 18:50:15 +0000777 conn->callback = std::move(cb);
Carson Labradof52c03c2022-03-23 18:50:15 +0000778 conn->doResolve();
779 }
780 else if (requestQueue.size() < maxRequestQueueSize)
781 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700782 BMCWEB_LOG_DEBUG("Max pool size reached. Adding data to queue {}",
783 id);
Carson Labradod14a48f2023-02-22 00:24:54 +0000784 requestQueue.emplace_back(std::move(thisReq), std::move(cb));
Carson Labradof52c03c2022-03-23 18:50:15 +0000785 }
786 else
787 {
Ed Tanous27b0cf92023-08-07 12:02:40 -0700788 // If we can't buffer the request then we should let the
789 // callback handle a 429 Too Many Requests dummy response
Ed Tanous6ea90762024-04-07 08:38:44 -0700790 BMCWEB_LOG_ERROR("{} request queue full. Dropping request.", id);
Carson Labrado43e14d32022-11-09 00:25:20 +0000791 Response dummyRes;
792 dummyRes.result(boost::beast::http::status::too_many_requests);
793 resHandler(dummyRes);
Carson Labradof52c03c2022-03-23 18:50:15 +0000794 }
Ayushi Smritife44eb02020-05-15 15:24:45 +0530795 }
796
Ed Tanous3d36e3a2022-08-19 15:54:04 -0700797 // Callback to be called once the request has been sent
798 static void afterSendData(const std::weak_ptr<ConnectionPool>& weakSelf,
799 const std::function<void(Response&)>& resHandler,
800 bool keepAlive, uint32_t connId, Response& res)
801 {
802 // Allow provided callback to perform additional processing of the
803 // request
804 resHandler(res);
805
806 // If requests remain in the queue then we want to reuse this
807 // connection to send the next request
808 std::shared_ptr<ConnectionPool> self = weakSelf.lock();
809 if (!self)
810 {
Ed Tanous62598e32023-07-17 17:06:25 -0700811 BMCWEB_LOG_CRITICAL("{} Failed to capture connection",
812 logPtr(self.get()));
Ed Tanous3d36e3a2022-08-19 15:54:04 -0700813 return;
814 }
815
816 self->sendNext(keepAlive, connId);
817 }
818
Carson Labradof52c03c2022-03-23 18:50:15 +0000819 std::shared_ptr<ConnectionInfo>& addConnection()
Ayushi Smritife44eb02020-05-15 15:24:45 +0530820 {
Carson Labradof52c03c2022-03-23 18:50:15 +0000821 unsigned int newId = static_cast<unsigned int>(connections.size());
822
AppaRao Pulie38778a2022-06-27 23:09:03 +0000823 auto& ret = connections.emplace_back(std::make_shared<ConnectionInfo>(
Ed Tanous19bb3622024-07-05 10:07:40 -0500824 ioc, id, connPolicy, destIP, verifyCert, newId));
Carson Labradof52c03c2022-03-23 18:50:15 +0000825
Ed Tanousa716aa72023-08-01 11:35:53 -0700826 BMCWEB_LOG_DEBUG("Added connection {} to pool {}",
827 connections.size() - 1, id);
Carson Labradof52c03c2022-03-23 18:50:15 +0000828
829 return ret;
830 }
831
832 public:
Carson Labradod14a48f2023-02-22 00:24:54 +0000833 explicit ConnectionPool(
834 boost::asio::io_context& iocIn, const std::string& idIn,
835 const std::shared_ptr<ConnectionPolicy>& connPolicyIn,
Ed Tanous19bb3622024-07-05 10:07:40 -0500836 const boost::urls::url_view_base& destIPIn,
837 ensuressl::VerifyCertificate verifyCertIn) :
Patrick Williamsbd79bce2024-08-16 15:22:20 -0400838 ioc(iocIn), id(idIn), connPolicy(connPolicyIn), destIP(destIPIn),
Ed Tanous19bb3622024-07-05 10:07:40 -0500839 verifyCert(verifyCertIn)
Carson Labradof52c03c2022-03-23 18:50:15 +0000840 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700841 BMCWEB_LOG_DEBUG("Initializing connection pool for {}", id);
Carson Labradof52c03c2022-03-23 18:50:15 +0000842
843 // Initialize the pool with a single connection
844 addConnection();
Ayushi Smritife44eb02020-05-15 15:24:45 +0530845 }
AppaRao Pulibd030d02020-03-20 03:34:29 +0530846};
847
Carson Labradof52c03c2022-03-23 18:50:15 +0000848class HttpClient
849{
850 private:
851 std::unordered_map<std::string, std::shared_ptr<ConnectionPool>>
852 connectionPools;
Ed Tanousf8ca6d72022-06-28 12:12:03 -0700853 boost::asio::io_context& ioc;
Carson Labradod14a48f2023-02-22 00:24:54 +0000854 std::shared_ptr<ConnectionPolicy> connPolicy;
Carson Labradof52c03c2022-03-23 18:50:15 +0000855
Carson Labrado039a47e2022-04-05 16:03:20 +0000856 // Used as a dummy callback by sendData() in order to call
857 // sendDataWithCallback()
Ed Tanous02cad962022-06-30 16:50:15 -0700858 static void genericResHandler(const Response& res)
Carson Labrado039a47e2022-04-05 16:03:20 +0000859 {
Ed Tanous62598e32023-07-17 17:06:25 -0700860 BMCWEB_LOG_DEBUG("Response handled with return code: {}",
Ed Tanousa716aa72023-08-01 11:35:53 -0700861 res.resultInt());
Ed Tanous4ee8e212022-05-28 09:42:51 -0700862 }
Carson Labrado039a47e2022-04-05 16:03:20 +0000863
Carson Labradof52c03c2022-03-23 18:50:15 +0000864 public:
Carson Labradod14a48f2023-02-22 00:24:54 +0000865 HttpClient() = delete;
Ed Tanousf8ca6d72022-06-28 12:12:03 -0700866 explicit HttpClient(boost::asio::io_context& iocIn,
867 const std::shared_ptr<ConnectionPolicy>& connPolicyIn) :
Patrick Williamsbd79bce2024-08-16 15:22:20 -0400868 ioc(iocIn), connPolicy(connPolicyIn)
Carson Labradod14a48f2023-02-22 00:24:54 +0000869 {}
Ed Tanousf8ca6d72022-06-28 12:12:03 -0700870
Carson Labradof52c03c2022-03-23 18:50:15 +0000871 HttpClient(const HttpClient&) = delete;
872 HttpClient& operator=(const HttpClient&) = delete;
873 HttpClient(HttpClient&&) = delete;
874 HttpClient& operator=(HttpClient&&) = delete;
875 ~HttpClient() = default;
876
Ed Tanousa716aa72023-08-01 11:35:53 -0700877 // Send a request to destIP where additional processing of the
Carson Labrado039a47e2022-04-05 16:03:20 +0000878 // result is not required
Ed Tanous4a7fbef2024-04-06 16:03:49 -0700879 void sendData(std::string&& data, const boost::urls::url_view_base& destUri,
Ed Tanous19bb3622024-07-05 10:07:40 -0500880 ensuressl::VerifyCertificate verifyCert,
Carson Labradof52c03c2022-03-23 18:50:15 +0000881 const boost::beast::http::fields& httpHeader,
Carson Labradod14a48f2023-02-22 00:24:54 +0000882 const boost::beast::http::verb verb)
Carson Labradof52c03c2022-03-23 18:50:15 +0000883 {
AppaRao Pulie38778a2022-06-27 23:09:03 +0000884 const std::function<void(Response&)> cb = genericResHandler;
Ed Tanous19bb3622024-07-05 10:07:40 -0500885 sendDataWithCallback(std::move(data), destUri, verifyCert, httpHeader,
886 verb, cb);
Carson Labrado039a47e2022-04-05 16:03:20 +0000887 }
888
Ed Tanousa716aa72023-08-01 11:35:53 -0700889 // Send request to destIP and use the provided callback to
Carson Labrado039a47e2022-04-05 16:03:20 +0000890 // handle the response
Ed Tanous4a7fbef2024-04-06 16:03:49 -0700891 void sendDataWithCallback(std::string&& data,
892 const boost::urls::url_view_base& destUrl,
Ed Tanous19bb3622024-07-05 10:07:40 -0500893 ensuressl::VerifyCertificate verifyCert,
Carson Labrado039a47e2022-04-05 16:03:20 +0000894 const boost::beast::http::fields& httpHeader,
Carson Labrado244256c2022-04-27 17:16:32 +0000895 const boost::beast::http::verb verb,
Ed Tanous6b3db602022-06-28 19:41:44 -0700896 const std::function<void(Response&)>& resHandler)
Carson Labrado039a47e2022-04-05 16:03:20 +0000897 {
Ed Tanous19bb3622024-07-05 10:07:40 -0500898 std::string_view verify = "ssl_verify";
899 if (verifyCert == ensuressl::VerifyCertificate::NoVerify)
900 {
901 verify = "ssl no verify";
902 }
Patrick Williamsbd79bce2024-08-16 15:22:20 -0400903 std::string clientKey =
904 std::format("{}{}://{}", verify, destUrl.scheme(),
905 destUrl.encoded_host_and_port());
Carson Labradod14a48f2023-02-22 00:24:54 +0000906 auto pool = connectionPools.try_emplace(clientKey);
907 if (pool.first->second == nullptr)
Carson Labradof52c03c2022-03-23 18:50:15 +0000908 {
Carson Labradod14a48f2023-02-22 00:24:54 +0000909 pool.first->second = std::make_shared<ConnectionPool>(
Ed Tanous19bb3622024-07-05 10:07:40 -0500910 ioc, clientKey, connPolicy, destUrl, verifyCert);
Carson Labradof52c03c2022-03-23 18:50:15 +0000911 }
Ed Tanous27b0cf92023-08-07 12:02:40 -0700912 // Send the data using either the existing connection pool or the
913 // newly created connection pool
Ed Tanousa716aa72023-08-01 11:35:53 -0700914 pool.first->second->sendData(std::move(data), destUrl, httpHeader, verb,
Carson Labradod14a48f2023-02-22 00:24:54 +0000915 resHandler);
Carson Labradof52c03c2022-03-23 18:50:15 +0000916 }
917};
AppaRao Pulibd030d02020-03-20 03:34:29 +0530918} // namespace crow