blob: 81922c090ea9602e438d040094fbd0871a6887d8 [file] [log] [blame]
Ed Tanous40e9b922024-09-10 13:50:16 -07001// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright OpenBMC Authors
3// SPDX-FileCopyrightText: Copyright 2020 Intel Corporation
AppaRao Pulibd030d02020-03-20 03:34:29 +05304#pragma once
Nan Zhou77665bd2022-10-12 20:28:58 +00005
Ed Tanousd7857202025-01-28 15:32:26 -08006#include "bmcweb_config.h"
7
Nan Zhou77665bd2022-10-12 20:28:58 +00008#include "async_resolve.hpp"
Ed Tanousd7857202025-01-28 15:32:26 -08009#include "boost_formatters.hpp"
Ed Tanousb2896142024-01-31 15:25:47 -080010#include "http_body.hpp"
Nan Zhou77665bd2022-10-12 20:28:58 +000011#include "http_response.hpp"
Ed Tanous3ccb3ad2023-01-13 17:40:03 -080012#include "logging.hpp"
13#include "ssl_key_handler.hpp"
Nan Zhou77665bd2022-10-12 20:28:58 +000014
Ed Tanousd7857202025-01-28 15:32:26 -080015#include <openssl/err.h>
Ed Tanousd7857202025-01-28 15:32:26 -080016#include <openssl/tls1.h>
17
Ed Tanous0d5f5cf2022-03-12 15:30:55 -080018#include <boost/asio/connect.hpp>
Ed Tanousd7857202025-01-28 15:32:26 -080019#include <boost/asio/error.hpp>
Ed Tanousbb49eb52022-06-28 12:02:42 -070020#include <boost/asio/io_context.hpp>
Sunitha Harish29a82b02021-02-18 15:54:16 +053021#include <boost/asio/ip/address.hpp>
Ed Tanousbb49eb52022-06-28 12:02:42 -070022#include <boost/asio/ip/tcp.hpp>
AppaRao Pulie38778a2022-06-27 23:09:03 +000023#include <boost/asio/ssl/context.hpp>
24#include <boost/asio/ssl/error.hpp>
Ed Tanous003301a2024-04-16 09:59:19 -070025#include <boost/asio/ssl/stream.hpp>
Ed Tanousd7857202025-01-28 15:32:26 -080026#include <boost/asio/ssl/stream_base.hpp>
Ed Tanousd43cd0c2020-09-30 20:46:53 -070027#include <boost/asio/steady_timer.hpp>
Ed Tanousd7857202025-01-28 15:32:26 -080028#include <boost/beast/core/error.hpp>
Ed Tanousbb49eb52022-06-28 12:02:42 -070029#include <boost/beast/core/flat_static_buffer.hpp>
Ed Tanousd7857202025-01-28 15:32:26 -080030#include <boost/beast/http/field.hpp>
31#include <boost/beast/http/fields.hpp>
Ed Tanousd43cd0c2020-09-30 20:46:53 -070032#include <boost/beast/http/message.hpp>
Ed Tanousbb49eb52022-06-28 12:02:42 -070033#include <boost/beast/http/parser.hpp>
34#include <boost/beast/http/read.hpp>
Ed Tanousd7857202025-01-28 15:32:26 -080035#include <boost/beast/http/status.hpp>
36#include <boost/beast/http/verb.hpp>
Ed Tanousbb49eb52022-06-28 12:02:42 -070037#include <boost/beast/http/write.hpp>
Carson Labradof52c03c2022-03-23 18:50:15 +000038#include <boost/container/devector.hpp>
Ed Tanousd7857202025-01-28 15:32:26 -080039#include <boost/optional/optional.hpp>
40#include <boost/system/errc.hpp>
Ed Tanousbb49eb52022-06-28 12:02:42 -070041#include <boost/system/error_code.hpp>
Ed Tanousd7857202025-01-28 15:32:26 -080042#include <boost/url/host_type.hpp>
Ed Tanous27b0cf92023-08-07 12:02:40 -070043#include <boost/url/url.hpp>
Ed Tanous4a7fbef2024-04-06 16:03:49 -070044#include <boost/url/url_view_base.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050045
Ed Tanousd7857202025-01-28 15:32:26 -080046#include <chrono>
47#include <cstdint>
AppaRao Pulibd030d02020-03-20 03:34:29 +053048#include <cstdlib>
Ed Tanousd7857202025-01-28 15:32:26 -080049#include <format>
AppaRao Pulibd030d02020-03-20 03:34:29 +053050#include <functional>
AppaRao Pulibd030d02020-03-20 03:34:29 +053051#include <memory>
Ed Tanousd7857202025-01-28 15:32:26 -080052#include <optional>
AppaRao Pulibd030d02020-03-20 03:34:29 +053053#include <string>
Ed Tanousd7857202025-01-28 15:32:26 -080054#include <string_view>
55#include <type_traits>
56#include <unordered_map>
57#include <utility>
58#include <vector>
AppaRao Pulibd030d02020-03-20 03:34:29 +053059
60namespace crow
61{
Ed Tanous27b0cf92023-08-07 12:02:40 -070062// With Redfish Aggregation it is assumed we will connect to another
63// instance of BMCWeb which can handle 100 simultaneous connections.
Carson Labrado66d90c22022-12-07 22:34:33 +000064constexpr size_t maxPoolSize = 20;
65constexpr size_t maxRequestQueueSize = 500;
Carson Labrado17dcc312022-07-28 22:17:28 +000066constexpr unsigned int httpReadBodyLimit = 131072;
Carson Labrado4d942722022-06-22 22:16:10 +000067constexpr unsigned int httpReadBufferSize = 4096;
AppaRao Puli2a5689a2020-04-29 15:24:31 +053068
AppaRao Pulibd030d02020-03-20 03:34:29 +053069enum class ConnState
70{
AppaRao Puli2a5689a2020-04-29 15:24:31 +053071 initialized,
Sunitha Harish29a82b02021-02-18 15:54:16 +053072 resolveInProgress,
73 resolveFailed,
AppaRao Puli2a5689a2020-04-29 15:24:31 +053074 connectInProgress,
75 connectFailed,
AppaRao Pulibd030d02020-03-20 03:34:29 +053076 connected,
AppaRao Pulie38778a2022-06-27 23:09:03 +000077 handshakeInProgress,
78 handshakeFailed,
AppaRao Puli2a5689a2020-04-29 15:24:31 +053079 sendInProgress,
80 sendFailed,
Sunitha Harish6eaa1d22021-02-19 13:38:31 +053081 recvInProgress,
AppaRao Puli2a5689a2020-04-29 15:24:31 +053082 recvFailed,
83 idle,
Ayushi Smritife44eb02020-05-15 15:24:45 +053084 closed,
Sunitha Harish6eaa1d22021-02-19 13:38:31 +053085 suspended,
86 terminated,
87 abortConnection,
AppaRao Pulie38778a2022-06-27 23:09:03 +000088 sslInitFailed,
Sunitha Harish6eaa1d22021-02-19 13:38:31 +053089 retry
AppaRao Pulibd030d02020-03-20 03:34:29 +053090};
91
Ed Tanous4ff0f1f2024-09-04 17:27:37 -070092inline boost::system::error_code defaultRetryHandler(unsigned int respCode)
Carson Labradoa7a80292022-06-01 16:01:52 +000093{
94 // As a default, assume 200X is alright
Ed Tanous62598e32023-07-17 17:06:25 -070095 BMCWEB_LOG_DEBUG("Using default check for response code validity");
Carson Labradoa7a80292022-06-01 16:01:52 +000096 if ((respCode < 200) || (respCode >= 300))
97 {
98 return boost::system::errc::make_error_code(
99 boost::system::errc::result_out_of_range);
100 }
101
102 // Return 0 if the response code is valid
103 return boost::system::errc::make_error_code(boost::system::errc::success);
104};
105
Ed Tanous27b0cf92023-08-07 12:02:40 -0700106// We need to allow retry information to be set before a message has been
107// sent and a connection pool has been created
Carson Labradod14a48f2023-02-22 00:24:54 +0000108struct ConnectionPolicy
Carson Labradof52c03c2022-03-23 18:50:15 +0000109{
110 uint32_t maxRetryAttempts = 5;
Carson Labradod14a48f2023-02-22 00:24:54 +0000111
112 // the max size of requests in bytes. 0 for unlimited
113 boost::optional<uint64_t> requestByteLimit = httpReadBodyLimit;
114
115 size_t maxConnections = 1;
116
Carson Labradof52c03c2022-03-23 18:50:15 +0000117 std::string retryPolicyAction = "TerminateAfterRetries";
Carson Labradod14a48f2023-02-22 00:24:54 +0000118
119 std::chrono::seconds retryIntervalSecs = std::chrono::seconds(0);
Carson Labradoa7a80292022-06-01 16:01:52 +0000120 std::function<boost::system::error_code(unsigned int respCode)>
121 invalidResp = defaultRetryHandler;
Carson Labradof52c03c2022-03-23 18:50:15 +0000122};
123
124struct PendingRequest
125{
Ed Tanousb2896142024-01-31 15:25:47 -0800126 boost::beast::http::request<bmcweb::HttpBody> req;
Carson Labrado039a47e2022-04-05 16:03:20 +0000127 std::function<void(bool, uint32_t, Response&)> callback;
Carson Labrado039a47e2022-04-05 16:03:20 +0000128 PendingRequest(
Ed Tanousb2896142024-01-31 15:25:47 -0800129 boost::beast::http::request<bmcweb::HttpBody>&& reqIn,
Carson Labradod14a48f2023-02-22 00:24:54 +0000130 const std::function<void(bool, uint32_t, Response&)>& callbackIn) :
Patrick Williamsbd79bce2024-08-16 15:22:20 -0400131 req(std::move(reqIn)), callback(callbackIn)
Carson Labradof52c03c2022-03-23 18:50:15 +0000132 {}
133};
134
Ed Tanouse01d0c32023-06-30 13:21:32 -0700135namespace http = boost::beast::http;
Carson Labradof52c03c2022-03-23 18:50:15 +0000136class ConnectionInfo : public std::enable_shared_from_this<ConnectionInfo>
AppaRao Pulibd030d02020-03-20 03:34:29 +0530137{
138 private:
Carson Labradof52c03c2022-03-23 18:50:15 +0000139 ConnState state = ConnState::initialized;
140 uint32_t retryCount = 0;
Carson Labradof52c03c2022-03-23 18:50:15 +0000141 std::string subId;
Carson Labradod14a48f2023-02-22 00:24:54 +0000142 std::shared_ptr<ConnectionPolicy> connPolicy;
Ed Tanousa716aa72023-08-01 11:35:53 -0700143 boost::urls::url host;
Ed Tanous19bb3622024-07-05 10:07:40 -0500144 ensuressl::VerifyCertificate verifyCert;
Carson Labradof52c03c2022-03-23 18:50:15 +0000145 uint32_t connId;
Carson Labradof52c03c2022-03-23 18:50:15 +0000146 // Data buffers
Ed Tanousb2896142024-01-31 15:25:47 -0800147 http::request<bmcweb::HttpBody> req;
148 using parser_type = http::response_parser<bmcweb::HttpBody>;
Ed Tanouse01d0c32023-06-30 13:21:32 -0700149 std::optional<parser_type> parser;
Carson Labrado4d942722022-06-22 22:16:10 +0000150 boost::beast::flat_static_buffer<httpReadBufferSize> buffer;
Carson Labrado039a47e2022-04-05 16:03:20 +0000151 Response res;
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530152
Ed Tanousd0fd3e52025-06-10 09:19:33 -0700153 // Async callables
Carson Labrado039a47e2022-04-05 16:03:20 +0000154 std::function<void(bool, uint32_t, Response&)> callback;
Ed Tanousf8ca6d72022-06-28 12:12:03 -0700155
Abhilash Rajuf3cb5df2023-11-30 03:54:11 -0600156 boost::asio::io_context& ioc;
157
Ed Tanous25b54db2024-04-17 15:40:31 -0700158 using Resolver = std::conditional_t<BMCWEB_DNS_RESOLVER == "systemd-dbus",
159 async_resolve::Resolver,
160 boost::asio::ip::tcp::resolver>;
Ed Tanousf8ca6d72022-06-28 12:12:03 -0700161 Resolver resolver;
162
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800163 boost::asio::ip::tcp::socket conn;
Ed Tanous003301a2024-04-16 09:59:19 -0700164 std::optional<boost::asio::ssl::stream<boost::asio::ip::tcp::socket&>>
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800165 sslConn;
AppaRao Pulie38778a2022-06-27 23:09:03 +0000166
Carson Labradof52c03c2022-03-23 18:50:15 +0000167 boost::asio::steady_timer timer;
Ed Tanous84b35602021-09-08 20:06:32 -0700168
Carson Labradof52c03c2022-03-23 18:50:15 +0000169 friend class ConnectionPool;
AppaRao Pulibd030d02020-03-20 03:34:29 +0530170
Sunitha Harish29a82b02021-02-18 15:54:16 +0530171 void doResolve()
172 {
Sunitha Harish29a82b02021-02-18 15:54:16 +0530173 state = ConnState::resolveInProgress;
Ed Tanousa716aa72023-08-01 11:35:53 -0700174 BMCWEB_LOG_DEBUG("Trying to resolve: {}, id: {}", host, connId);
Sunitha Harish29a82b02021-02-18 15:54:16 +0530175
Ed Tanousa716aa72023-08-01 11:35:53 -0700176 resolver.async_resolve(host.encoded_host_address(), host.port(),
Ed Tanousf8ca6d72022-06-28 12:12:03 -0700177 std::bind_front(&ConnectionInfo::afterResolve,
178 this, shared_from_this()));
Sunitha Harish29a82b02021-02-18 15:54:16 +0530179 }
180
Ed Tanousf8ca6d72022-06-28 12:12:03 -0700181 void afterResolve(const std::shared_ptr<ConnectionInfo>& /*self*/,
182 const boost::system::error_code& ec,
183 const Resolver::results_type& endpointList)
AppaRao Pulibd030d02020-03-20 03:34:29 +0530184 {
Ed Tanous3d36e3a2022-08-19 15:54:04 -0700185 if (ec || (endpointList.empty()))
186 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700187 BMCWEB_LOG_ERROR("Resolve failed: {} {}", ec.message(), host);
Ed Tanous3d36e3a2022-08-19 15:54:04 -0700188 state = ConnState::resolveFailed;
189 waitAndRetry();
190 return;
191 }
Ed Tanousa716aa72023-08-01 11:35:53 -0700192 BMCWEB_LOG_DEBUG("Resolved {}, id: {}", host, connId);
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530193 state = ConnState::connectInProgress;
194
Ed Tanousa716aa72023-08-01 11:35:53 -0700195 BMCWEB_LOG_DEBUG("Trying to connect to: {}, id: {}", host, connId);
Sunitha Harish29a82b02021-02-18 15:54:16 +0530196
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800197 timer.expires_after(std::chrono::seconds(30));
198 timer.async_wait(std::bind_front(onTimeout, weak_from_this()));
199
200 boost::asio::async_connect(
201 conn, endpointList,
202 std::bind_front(&ConnectionInfo::afterConnect, this,
203 shared_from_this()));
AppaRao Pulie38778a2022-06-27 23:09:03 +0000204 }
205
206 void afterConnect(const std::shared_ptr<ConnectionInfo>& /*self*/,
Ed Tanous81c4e332023-05-18 10:30:34 -0700207 const boost::beast::error_code& ec,
AppaRao Pulie38778a2022-06-27 23:09:03 +0000208 const boost::asio::ip::tcp::endpoint& endpoint)
209 {
Carson Labrado513d1ff2022-07-19 00:38:15 +0000210 // The operation already timed out. We don't want do continue down
211 // this branch
212 if (ec && ec == boost::asio::error::operation_aborted)
213 {
214 return;
215 }
216
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800217 timer.cancel();
AppaRao Pulie38778a2022-06-27 23:09:03 +0000218 if (ec)
219 {
Ed Tanous62598e32023-07-17 17:06:25 -0700220 BMCWEB_LOG_ERROR("Connect {}:{}, id: {} failed: {}",
abhilashraju079fbcf2025-04-24 05:24:56 +0000221 host.encoded_host_address(), host.port(), connId,
222 ec.message());
AppaRao Pulie38778a2022-06-27 23:09:03 +0000223 state = ConnState::connectFailed;
224 waitAndRetry();
225 return;
226 }
Ed Tanousa716aa72023-08-01 11:35:53 -0700227 BMCWEB_LOG_DEBUG("Connected to: {}:{}, id: {}",
228 endpoint.address().to_string(), endpoint.port(),
229 connId);
AppaRao Pulie38778a2022-06-27 23:09:03 +0000230 if (sslConn)
231 {
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800232 doSslHandshake();
AppaRao Pulie38778a2022-06-27 23:09:03 +0000233 return;
234 }
235 state = ConnState::connected;
236 sendMessage();
237 }
238
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800239 void doSslHandshake()
AppaRao Pulie38778a2022-06-27 23:09:03 +0000240 {
241 if (!sslConn)
242 {
243 return;
244 }
Ed Tanous3d158642025-05-12 14:20:49 -0700245 auto& ssl = *sslConn;
AppaRao Pulie38778a2022-06-27 23:09:03 +0000246 state = ConnState::handshakeInProgress;
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800247 timer.expires_after(std::chrono::seconds(30));
248 timer.async_wait(std::bind_front(onTimeout, weak_from_this()));
Ed Tanous3d158642025-05-12 14:20:49 -0700249 ssl.async_handshake(boost::asio::ssl::stream_base::client,
250 std::bind_front(&ConnectionInfo::afterSslHandshake,
251 this, shared_from_this()));
AppaRao Pulie38778a2022-06-27 23:09:03 +0000252 }
253
254 void afterSslHandshake(const std::shared_ptr<ConnectionInfo>& /*self*/,
Ed Tanous81c4e332023-05-18 10:30:34 -0700255 const boost::beast::error_code& ec)
AppaRao Pulie38778a2022-06-27 23:09:03 +0000256 {
Carson Labrado513d1ff2022-07-19 00:38:15 +0000257 // The operation already timed out. We don't want do continue down
258 // this branch
259 if (ec && ec == boost::asio::error::operation_aborted)
260 {
261 return;
262 }
263
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800264 timer.cancel();
AppaRao Pulie38778a2022-06-27 23:09:03 +0000265 if (ec)
266 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700267 BMCWEB_LOG_ERROR("SSL Handshake failed - id: {} error: {}", connId,
268 ec.message());
AppaRao Pulie38778a2022-06-27 23:09:03 +0000269 state = ConnState::handshakeFailed;
270 waitAndRetry();
271 return;
272 }
Ed Tanousa716aa72023-08-01 11:35:53 -0700273 BMCWEB_LOG_DEBUG("SSL Handshake successful - id: {}", connId);
AppaRao Pulie38778a2022-06-27 23:09:03 +0000274 state = ConnState::connected;
275 sendMessage();
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530276 }
277
Carson Labradof52c03c2022-03-23 18:50:15 +0000278 void sendMessage()
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530279 {
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530280 state = ConnState::sendInProgress;
281
AppaRao Pulibd030d02020-03-20 03:34:29 +0530282 // Set a timeout on the operation
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800283 timer.expires_after(std::chrono::seconds(30));
284 timer.async_wait(std::bind_front(onTimeout, weak_from_this()));
AppaRao Pulibd030d02020-03-20 03:34:29 +0530285 // Send the HTTP request to the remote host
AppaRao Pulie38778a2022-06-27 23:09:03 +0000286 if (sslConn)
287 {
Ed Tanouscd504a92024-08-19 11:46:20 -0700288 boost::beast::http::async_write(
289 *sslConn, req,
AppaRao Pulie38778a2022-06-27 23:09:03 +0000290 std::bind_front(&ConnectionInfo::afterWrite, this,
291 shared_from_this()));
292 }
293 else
294 {
Ed Tanouscd504a92024-08-19 11:46:20 -0700295 boost::beast::http::async_write(
296 conn, req,
AppaRao Pulie38778a2022-06-27 23:09:03 +0000297 std::bind_front(&ConnectionInfo::afterWrite, this,
298 shared_from_this()));
299 }
300 }
AppaRao Pulibd030d02020-03-20 03:34:29 +0530301
AppaRao Pulie38778a2022-06-27 23:09:03 +0000302 void afterWrite(const std::shared_ptr<ConnectionInfo>& /*self*/,
303 const boost::beast::error_code& ec, size_t bytesTransferred)
304 {
Carson Labrado513d1ff2022-07-19 00:38:15 +0000305 // The operation already timed out. We don't want do continue down
306 // this branch
307 if (ec && ec == boost::asio::error::operation_aborted)
308 {
309 return;
310 }
311
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800312 timer.cancel();
AppaRao Pulie38778a2022-06-27 23:09:03 +0000313 if (ec)
314 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700315 BMCWEB_LOG_ERROR("sendMessage() failed: {} {}", ec.message(), host);
AppaRao Pulie38778a2022-06-27 23:09:03 +0000316 state = ConnState::sendFailed;
317 waitAndRetry();
318 return;
319 }
Ed Tanous62598e32023-07-17 17:06:25 -0700320 BMCWEB_LOG_DEBUG("sendMessage() bytes transferred: {}",
321 bytesTransferred);
AppaRao Pulie38778a2022-06-27 23:09:03 +0000322
323 recvMessage();
AppaRao Pulibd030d02020-03-20 03:34:29 +0530324 }
325
326 void recvMessage()
327 {
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530328 state = ConnState::recvInProgress;
329
Ed Tanous38afdb92024-12-11 23:57:53 -0800330 parser_type& thisParser = parser.emplace();
Carson Labradod14a48f2023-02-22 00:24:54 +0000331
Ed Tanouse01d0c32023-06-30 13:21:32 -0700332 thisParser.body_limit(connPolicy->requestByteLimit);
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530333
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800334 timer.expires_after(std::chrono::seconds(30));
335 timer.async_wait(std::bind_front(onTimeout, weak_from_this()));
336
AppaRao Pulibd030d02020-03-20 03:34:29 +0530337 // Receive the HTTP response
AppaRao Pulie38778a2022-06-27 23:09:03 +0000338 if (sslConn)
339 {
340 boost::beast::http::async_read(
Ed Tanouse01d0c32023-06-30 13:21:32 -0700341 *sslConn, buffer, thisParser,
AppaRao Pulie38778a2022-06-27 23:09:03 +0000342 std::bind_front(&ConnectionInfo::afterRead, this,
343 shared_from_this()));
344 }
345 else
346 {
347 boost::beast::http::async_read(
Ed Tanouse01d0c32023-06-30 13:21:32 -0700348 conn, buffer, thisParser,
AppaRao Pulie38778a2022-06-27 23:09:03 +0000349 std::bind_front(&ConnectionInfo::afterRead, this,
350 shared_from_this()));
351 }
352 }
AppaRao Pulibd030d02020-03-20 03:34:29 +0530353
AppaRao Pulie38778a2022-06-27 23:09:03 +0000354 void afterRead(const std::shared_ptr<ConnectionInfo>& /*self*/,
355 const boost::beast::error_code& ec,
Ed Tanousd0fd3e52025-06-10 09:19:33 -0700356 const std::size_t bytesTransferred)
AppaRao Pulie38778a2022-06-27 23:09:03 +0000357 {
Carson Labrado513d1ff2022-07-19 00:38:15 +0000358 // The operation already timed out. We don't want do continue down
359 // this branch
360 if (ec && ec == boost::asio::error::operation_aborted)
361 {
362 return;
363 }
364
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800365 timer.cancel();
AppaRao Pulie38778a2022-06-27 23:09:03 +0000366 if (ec && ec != boost::asio::ssl::error::stream_truncated)
367 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700368 BMCWEB_LOG_ERROR("recvMessage() failed: {} from {}", ec.message(),
369 host);
AppaRao Pulie38778a2022-06-27 23:09:03 +0000370 state = ConnState::recvFailed;
371 waitAndRetry();
372 return;
373 }
Ed Tanous62598e32023-07-17 17:06:25 -0700374 BMCWEB_LOG_DEBUG("recvMessage() bytes transferred: {}",
375 bytesTransferred);
Ed Tanouse01d0c32023-06-30 13:21:32 -0700376 if (!parser)
377 {
378 return;
379 }
Ed Tanous52e31622024-01-23 16:31:11 -0800380 BMCWEB_LOG_DEBUG("recvMessage() data: {}", parser->get().body().str());
AppaRao Pulie38778a2022-06-27 23:09:03 +0000381
382 unsigned int respCode = parser->get().result_int();
Ed Tanous62598e32023-07-17 17:06:25 -0700383 BMCWEB_LOG_DEBUG("recvMessage() Header Response Code: {}", respCode);
AppaRao Pulie38778a2022-06-27 23:09:03 +0000384
Abhilash Rajuf3cb5df2023-11-30 03:54:11 -0600385 // Handle the case of stream_truncated. Some servers close the ssl
386 // connection uncleanly, so check to see if we got a full response
387 // before we handle this as an error.
388 if (!parser->is_done())
389 {
390 state = ConnState::recvFailed;
391 waitAndRetry();
392 return;
393 }
394
AppaRao Pulie38778a2022-06-27 23:09:03 +0000395 // Make sure the received response code is valid as defined by
396 // the associated retry policy
Carson Labradod14a48f2023-02-22 00:24:54 +0000397 if (connPolicy->invalidResp(respCode))
AppaRao Pulie38778a2022-06-27 23:09:03 +0000398 {
399 // The listener failed to receive the Sent-Event
Ed Tanous62598e32023-07-17 17:06:25 -0700400 BMCWEB_LOG_ERROR(
401 "recvMessage() Listener Failed to "
Ed Tanousa716aa72023-08-01 11:35:53 -0700402 "receive Sent-Event. Header Response Code: {} from {}",
403 respCode, host);
AppaRao Pulie38778a2022-06-27 23:09:03 +0000404 state = ConnState::recvFailed;
405 waitAndRetry();
406 return;
407 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700408
AppaRao Pulie38778a2022-06-27 23:09:03 +0000409 // Send is successful
410 // Reset the counter just in case this was after retrying
411 retryCount = 0;
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530412
AppaRao Pulie38778a2022-06-27 23:09:03 +0000413 // Keep the connection alive if server supports it
414 // Else close the connection
Ed Tanous62598e32023-07-17 17:06:25 -0700415 BMCWEB_LOG_DEBUG("recvMessage() keepalive : {}", parser->keep_alive());
AppaRao Pulibd030d02020-03-20 03:34:29 +0530416
AppaRao Pulie38778a2022-06-27 23:09:03 +0000417 // Copy the response into a Response object so that it can be
418 // processed by the callback function.
Ed Tanous27b0cf92023-08-07 12:02:40 -0700419 res.response = parser->release();
AppaRao Pulie38778a2022-06-27 23:09:03 +0000420 callback(parser->keep_alive(), connId, res);
Carson Labrado513d1ff2022-07-19 00:38:15 +0000421 res.clear();
AppaRao Pulibd030d02020-03-20 03:34:29 +0530422 }
423
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800424 static void onTimeout(const std::weak_ptr<ConnectionInfo>& weakSelf,
Ed Tanous5e7e2dc2023-02-16 10:37:01 -0800425 const boost::system::error_code& ec)
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800426 {
427 if (ec == boost::asio::error::operation_aborted)
428 {
Ed Tanous62598e32023-07-17 17:06:25 -0700429 BMCWEB_LOG_DEBUG(
430 "async_wait failed since the operation is aborted");
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800431 return;
432 }
433 if (ec)
434 {
Ed Tanous62598e32023-07-17 17:06:25 -0700435 BMCWEB_LOG_ERROR("async_wait failed: {}", ec.message());
Ed Tanous27b0cf92023-08-07 12:02:40 -0700436 // If the timer fails, we need to close the socket anyway, same
437 // as if it expired.
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800438 }
439 std::shared_ptr<ConnectionInfo> self = weakSelf.lock();
440 if (self == nullptr)
441 {
442 return;
443 }
444 self->waitAndRetry();
445 }
446
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530447 void waitAndRetry()
AppaRao Pulibd030d02020-03-20 03:34:29 +0530448 {
Carson Labradod14a48f2023-02-22 00:24:54 +0000449 if ((retryCount >= connPolicy->maxRetryAttempts) ||
AppaRao Pulie38778a2022-06-27 23:09:03 +0000450 (state == ConnState::sslInitFailed))
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530451 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700452 BMCWEB_LOG_ERROR("Maximum number of retries reached. {}", host);
Ed Tanous62598e32023-07-17 17:06:25 -0700453 BMCWEB_LOG_DEBUG("Retry policy: {}", connPolicy->retryPolicyAction);
Carson Labrado039a47e2022-04-05 16:03:20 +0000454
Carson Labradod14a48f2023-02-22 00:24:54 +0000455 if (connPolicy->retryPolicyAction == "TerminateAfterRetries")
Ayushi Smritife44eb02020-05-15 15:24:45 +0530456 {
457 // TODO: delete subscription
458 state = ConnState::terminated;
Ayushi Smritife44eb02020-05-15 15:24:45 +0530459 }
Carson Labradod14a48f2023-02-22 00:24:54 +0000460 if (connPolicy->retryPolicyAction == "SuspendRetries")
Ayushi Smritife44eb02020-05-15 15:24:45 +0530461 {
462 state = ConnState::suspended;
Ayushi Smritife44eb02020-05-15 15:24:45 +0530463 }
Carson Labrado513d1ff2022-07-19 00:38:15 +0000464
465 // We want to return a 502 to indicate there was an error with
466 // the external server
467 res.result(boost::beast::http::status::bad_gateway);
468 callback(false, connId, res);
469 res.clear();
470
Ed Tanous27b0cf92023-08-07 12:02:40 -0700471 // Reset the retrycount to zero so that client can try
472 // connecting again if needed
Ed Tanous3174e4d2020-10-07 11:41:22 -0700473 retryCount = 0;
Ayushi Smritife44eb02020-05-15 15:24:45 +0530474 return;
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530475 }
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530476
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530477 retryCount++;
478
Ed Tanous62598e32023-07-17 17:06:25 -0700479 BMCWEB_LOG_DEBUG("Attempt retry after {} seconds. RetryCount = {}",
Ed Tanousa716aa72023-08-01 11:35:53 -0700480 connPolicy->retryIntervalSecs.count(), retryCount);
Carson Labradod14a48f2023-02-22 00:24:54 +0000481 timer.expires_after(connPolicy->retryIntervalSecs);
Ed Tanous3d36e3a2022-08-19 15:54:04 -0700482 timer.async_wait(std::bind_front(&ConnectionInfo::onTimerDone, this,
483 shared_from_this()));
484 }
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530485
Ed Tanous3d36e3a2022-08-19 15:54:04 -0700486 void onTimerDone(const std::shared_ptr<ConnectionInfo>& /*self*/,
487 const boost::system::error_code& ec)
488 {
489 if (ec == boost::asio::error::operation_aborted)
490 {
Ed Tanous62598e32023-07-17 17:06:25 -0700491 BMCWEB_LOG_DEBUG(
492 "async_wait failed since the operation is aborted{}",
493 ec.message());
Ed Tanous3d36e3a2022-08-19 15:54:04 -0700494 }
495 else if (ec)
496 {
Ed Tanous62598e32023-07-17 17:06:25 -0700497 BMCWEB_LOG_ERROR("async_wait failed: {}", ec.message());
Ed Tanous3d36e3a2022-08-19 15:54:04 -0700498 // Ignore the error and continue the retry loop to attempt
499 // sending the event as per the retry policy
500 }
501
502 // Let's close the connection and restart from resolve.
Abhilash Rajuf3cb5df2023-11-30 03:54:11 -0600503 shutdownConn(true);
504 }
505
506 void restartConnection()
507 {
508 BMCWEB_LOG_DEBUG("{}, id: {} restartConnection", host,
509 std::to_string(connId));
510 initializeConnection(host.scheme() == "https");
511 doResolve();
Ayushi Smritife44eb02020-05-15 15:24:45 +0530512 }
513
AppaRao Pulie38778a2022-06-27 23:09:03 +0000514 void shutdownConn(bool retry)
Ayushi Smritife44eb02020-05-15 15:24:45 +0530515 {
Carson Labradof52c03c2022-03-23 18:50:15 +0000516 boost::beast::error_code ec;
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800517 conn.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
Carson Labradof52c03c2022-03-23 18:50:15 +0000518 conn.close();
519
520 // not_connected happens sometimes so don't bother reporting it.
521 if (ec && ec != boost::beast::errc::not_connected)
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530522 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700523 BMCWEB_LOG_ERROR("{}, id: {} shutdown failed: {}", host, connId,
Ed Tanous62598e32023-07-17 17:06:25 -0700524 ec.message());
Carson Labradof52c03c2022-03-23 18:50:15 +0000525 }
Carson Labrado5cab68f2022-07-11 22:26:21 +0000526 else
527 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700528 BMCWEB_LOG_DEBUG("{}, id: {} closed gracefully", host, connId);
Carson Labrado5cab68f2022-07-11 22:26:21 +0000529 }
Ed Tanousca723762022-06-28 19:40:39 -0700530
Carson Labrado513d1ff2022-07-19 00:38:15 +0000531 if (retry)
AppaRao Pulie38778a2022-06-27 23:09:03 +0000532 {
Carson Labrado513d1ff2022-07-19 00:38:15 +0000533 // Now let's try to resend the data
534 state = ConnState::retry;
Abhilash Rajuf3cb5df2023-11-30 03:54:11 -0600535 restartConnection();
Carson Labrado513d1ff2022-07-19 00:38:15 +0000536 }
537 else
538 {
539 state = ConnState::closed;
AppaRao Pulie38778a2022-06-27 23:09:03 +0000540 }
Carson Labradof52c03c2022-03-23 18:50:15 +0000541 }
542
AppaRao Pulie38778a2022-06-27 23:09:03 +0000543 void doClose(bool retry = false)
Carson Labradof52c03c2022-03-23 18:50:15 +0000544 {
AppaRao Pulie38778a2022-06-27 23:09:03 +0000545 if (!sslConn)
546 {
547 shutdownConn(retry);
548 return;
549 }
Carson Labradof52c03c2022-03-23 18:50:15 +0000550
AppaRao Pulie38778a2022-06-27 23:09:03 +0000551 sslConn->async_shutdown(
552 std::bind_front(&ConnectionInfo::afterSslShutdown, this,
553 shared_from_this(), retry));
554 }
555
556 void afterSslShutdown(const std::shared_ptr<ConnectionInfo>& /*self*/,
557 bool retry, const boost::system::error_code& ec)
558 {
AppaRao Pulie38778a2022-06-27 23:09:03 +0000559 if (ec)
Carson Labradof52c03c2022-03-23 18:50:15 +0000560 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700561 BMCWEB_LOG_ERROR("{}, id: {} shutdown failed: {}", host, connId,
Ed Tanous62598e32023-07-17 17:06:25 -0700562 ec.message());
Carson Labradof52c03c2022-03-23 18:50:15 +0000563 }
Carson Labrado5cab68f2022-07-11 22:26:21 +0000564 else
565 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700566 BMCWEB_LOG_DEBUG("{}, id: {} closed gracefully", host, connId);
Carson Labrado5cab68f2022-07-11 22:26:21 +0000567 }
AppaRao Pulie38778a2022-06-27 23:09:03 +0000568 shutdownConn(retry);
569 }
Ed Tanousca723762022-06-28 19:40:39 -0700570
AppaRao Pulie38778a2022-06-27 23:09:03 +0000571 void setCipherSuiteTLSext()
572 {
573 if (!sslConn)
574 {
575 return;
576 }
Ravi Tejae7c29912023-07-31 09:39:32 -0500577
578 if (host.host_type() != boost::urls::host_type::name)
579 {
580 // Avoid setting SNI hostname if its IP address
581 return;
582 }
583 // Create a null terminated string for SSL
Ed Tanousa716aa72023-08-01 11:35:53 -0700584 std::string hostname(host.encoded_host_address());
Ed Tanousd0fd3e52025-06-10 09:19:33 -0700585 if (SSL_set_tlsext_host_name(sslConn->native_handle(),
586 hostname.data()) == 0)
AppaRao Pulie38778a2022-06-27 23:09:03 +0000587
588 {
589 boost::beast::error_code ec{static_cast<int>(::ERR_get_error()),
590 boost::asio::error::get_ssl_category()};
591
Ed Tanousa716aa72023-08-01 11:35:53 -0700592 BMCWEB_LOG_ERROR("SSL_set_tlsext_host_name {}, id: {} failed: {}",
593 host, connId, ec.message());
AppaRao Pulie38778a2022-06-27 23:09:03 +0000594 // Set state as sslInit failed so that we close the connection
595 // and take appropriate action as per retry configuration.
596 state = ConnState::sslInitFailed;
597 waitAndRetry();
598 return;
599 }
AppaRao Pulibd030d02020-03-20 03:34:29 +0530600 }
601
Abhilash Rajuf3cb5df2023-11-30 03:54:11 -0600602 void initializeConnection(bool ssl)
AppaRao Pulie38778a2022-06-27 23:09:03 +0000603 {
Abhilash Rajuf3cb5df2023-11-30 03:54:11 -0600604 conn = boost::asio::ip::tcp::socket(ioc);
605 if (ssl)
AppaRao Pulie38778a2022-06-27 23:09:03 +0000606 {
607 std::optional<boost::asio::ssl::context> sslCtx =
Ed Tanous19bb3622024-07-05 10:07:40 -0500608 ensuressl::getSSLClientContext(verifyCert);
AppaRao Pulie38778a2022-06-27 23:09:03 +0000609
610 if (!sslCtx)
611 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700612 BMCWEB_LOG_ERROR("prepareSSLContext failed - {}, id: {}", host,
613 connId);
AppaRao Pulie38778a2022-06-27 23:09:03 +0000614 // Don't retry if failure occurs while preparing SSL context
Ed Tanous27b0cf92023-08-07 12:02:40 -0700615 // such as certificate is invalid or set cipher failure or
616 // set host name failure etc... Setting conn state to
617 // sslInitFailed and connection state will be transitioned
618 // to next state depending on retry policy set by
619 // subscription.
AppaRao Pulie38778a2022-06-27 23:09:03 +0000620 state = ConnState::sslInitFailed;
621 waitAndRetry();
622 return;
623 }
624 sslConn.emplace(conn, *sslCtx);
625 setCipherSuiteTLSext();
626 }
627 }
Abhilash Rajuf3cb5df2023-11-30 03:54:11 -0600628
629 public:
630 explicit ConnectionInfo(
631 boost::asio::io_context& iocIn, const std::string& idIn,
632 const std::shared_ptr<ConnectionPolicy>& connPolicyIn,
Ed Tanous19bb3622024-07-05 10:07:40 -0500633 const boost::urls::url_view_base& hostIn,
634 ensuressl::VerifyCertificate verifyCertIn, unsigned int connIdIn) :
Patrick Williamsbd79bce2024-08-16 15:22:20 -0400635 subId(idIn), connPolicy(connPolicyIn), host(hostIn),
636 verifyCert(verifyCertIn), connId(connIdIn), ioc(iocIn), resolver(iocIn),
637 conn(iocIn), timer(iocIn)
Abhilash Rajuf3cb5df2023-11-30 03:54:11 -0600638 {
639 initializeConnection(host.scheme() == "https");
640 }
Carson Labradof52c03c2022-03-23 18:50:15 +0000641};
AppaRao Pulibd030d02020-03-20 03:34:29 +0530642
Carson Labradof52c03c2022-03-23 18:50:15 +0000643class ConnectionPool : public std::enable_shared_from_this<ConnectionPool>
644{
645 private:
646 boost::asio::io_context& ioc;
AppaRao Pulie38778a2022-06-27 23:09:03 +0000647 std::string id;
Carson Labradod14a48f2023-02-22 00:24:54 +0000648 std::shared_ptr<ConnectionPolicy> connPolicy;
Ed Tanousa716aa72023-08-01 11:35:53 -0700649 boost::urls::url destIP;
Carson Labradof52c03c2022-03-23 18:50:15 +0000650 std::vector<std::shared_ptr<ConnectionInfo>> connections;
651 boost::container::devector<PendingRequest> requestQueue;
Ed Tanous19bb3622024-07-05 10:07:40 -0500652 ensuressl::VerifyCertificate verifyCert;
Carson Labradof52c03c2022-03-23 18:50:15 +0000653
654 friend class HttpClient;
655
Carson Labrado244256c2022-04-27 17:16:32 +0000656 // Configure a connections's request, callback, and retry info in
657 // preparation to begin sending the request
Carson Labradof52c03c2022-03-23 18:50:15 +0000658 void setConnProps(ConnectionInfo& conn)
AppaRao Pulibd030d02020-03-20 03:34:29 +0530659 {
Carson Labradof52c03c2022-03-23 18:50:15 +0000660 if (requestQueue.empty())
AppaRao Pulibd030d02020-03-20 03:34:29 +0530661 {
Ed Tanous62598e32023-07-17 17:06:25 -0700662 BMCWEB_LOG_ERROR(
663 "setConnProps() should not have been called when requestQueue is empty");
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530664 return;
AppaRao Pulibd030d02020-03-20 03:34:29 +0530665 }
AppaRao Pulibd030d02020-03-20 03:34:29 +0530666
Ed Tanous52e31622024-01-23 16:31:11 -0800667 PendingRequest& nextReq = requestQueue.front();
Carson Labrado244256c2022-04-27 17:16:32 +0000668 conn.req = std::move(nextReq.req);
669 conn.callback = std::move(nextReq.callback);
Carson Labradof52c03c2022-03-23 18:50:15 +0000670
Ed Tanousa716aa72023-08-01 11:35:53 -0700671 BMCWEB_LOG_DEBUG("Setting properties for connection {}, id: {}",
672 conn.host, conn.connId);
Carson Labradof52c03c2022-03-23 18:50:15 +0000673
674 // We can remove the request from the queue at this point
675 requestQueue.pop_front();
676 }
677
Carson Labradof52c03c2022-03-23 18:50:15 +0000678 // Gets called as part of callback after request is sent
679 // Reuses the connection if there are any requests waiting to be sent
680 // Otherwise closes the connection if it is not a keep-alive
681 void sendNext(bool keepAlive, uint32_t connId)
682 {
683 auto conn = connections[connId];
Carson Labrado46a81462022-04-27 21:11:37 +0000684
685 // Allow the connection's handler to be deleted
686 // This is needed because of Redfish Aggregation passing an
687 // AsyncResponse shared_ptr to this callback
688 conn->callback = nullptr;
689
Carson Labradof52c03c2022-03-23 18:50:15 +0000690 // Reuse the connection to send the next request in the queue
691 if (!requestQueue.empty())
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530692 {
Ed Tanous62598e32023-07-17 17:06:25 -0700693 BMCWEB_LOG_DEBUG(
Ed Tanous8ece0e42024-01-02 13:16:50 -0800694 "{} requests remaining in queue for {}, reusing connection {}",
Ed Tanousa716aa72023-08-01 11:35:53 -0700695 requestQueue.size(), destIP, connId);
Carson Labradof52c03c2022-03-23 18:50:15 +0000696
697 setConnProps(*conn);
698
699 if (keepAlive)
700 {
701 conn->sendMessage();
702 }
703 else
704 {
705 // Server is not keep-alive enabled so we need to close the
706 // connection and then start over from resolve
707 conn->doClose();
Abhilash Raju2ecde742024-06-01 02:01:01 -0500708 conn->restartConnection();
Carson Labradof52c03c2022-03-23 18:50:15 +0000709 }
710 return;
711 }
712
713 // No more messages to send so close the connection if necessary
714 if (keepAlive)
715 {
716 conn->state = ConnState::idle;
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530717 }
718 else
719 {
Carson Labradof52c03c2022-03-23 18:50:15 +0000720 // Abort the connection since server is not keep-alive enabled
721 conn->state = ConnState::abortConnection;
722 conn->doClose();
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530723 }
AppaRao Pulibd030d02020-03-20 03:34:29 +0530724 }
725
Ed Tanous4a7fbef2024-04-06 16:03:49 -0700726 void sendData(std::string&& data, const boost::urls::url_view_base& destUri,
Carson Labrado244256c2022-04-27 17:16:32 +0000727 const boost::beast::http::fields& httpHeader,
728 const boost::beast::http::verb verb,
Ed Tanous6b3db602022-06-28 19:41:44 -0700729 const std::function<void(Response&)>& resHandler)
Ayushi Smritife44eb02020-05-15 15:24:45 +0530730 {
Carson Labrado244256c2022-04-27 17:16:32 +0000731 // Construct the request to be sent
Ed Tanousb2896142024-01-31 15:25:47 -0800732 boost::beast::http::request<bmcweb::HttpBody> thisReq(
Ed Tanousa716aa72023-08-01 11:35:53 -0700733 verb, destUri.encoded_target(), 11, "", httpHeader);
734 thisReq.set(boost::beast::http::field::host,
735 destUri.encoded_host_address());
Carson Labrado244256c2022-04-27 17:16:32 +0000736 thisReq.keep_alive(true);
Ed Tanous52e31622024-01-23 16:31:11 -0800737 thisReq.body().str() = std::move(data);
Carson Labrado244256c2022-04-27 17:16:32 +0000738 thisReq.prepare_payload();
Ed Tanous3d36e3a2022-08-19 15:54:04 -0700739 auto cb = std::bind_front(&ConnectionPool::afterSendData,
740 weak_from_this(), resHandler);
Carson Labradof52c03c2022-03-23 18:50:15 +0000741 // Reuse an existing connection if one is available
742 for (unsigned int i = 0; i < connections.size(); i++)
743 {
744 auto conn = connections[i];
745 if ((conn->state == ConnState::idle) ||
746 (conn->state == ConnState::initialized) ||
747 (conn->state == ConnState::closed))
748 {
Carson Labrado244256c2022-04-27 17:16:32 +0000749 conn->req = std::move(thisReq);
Carson Labradof52c03c2022-03-23 18:50:15 +0000750 conn->callback = std::move(cb);
Ed Tanousa716aa72023-08-01 11:35:53 -0700751 std::string commonMsg = std::format("{} from pool {}", i, id);
Carson Labradof52c03c2022-03-23 18:50:15 +0000752
753 if (conn->state == ConnState::idle)
754 {
Ed Tanous62598e32023-07-17 17:06:25 -0700755 BMCWEB_LOG_DEBUG("Grabbing idle connection {}", commonMsg);
Carson Labradof52c03c2022-03-23 18:50:15 +0000756 conn->sendMessage();
757 }
758 else
759 {
Ed Tanous62598e32023-07-17 17:06:25 -0700760 BMCWEB_LOG_DEBUG("Reusing existing connection {}",
761 commonMsg);
Abhilash Raju2ecde742024-06-01 02:01:01 -0500762 conn->restartConnection();
Carson Labradof52c03c2022-03-23 18:50:15 +0000763 }
764 return;
765 }
766 }
767
Ed Tanous27b0cf92023-08-07 12:02:40 -0700768 // All connections in use so create a new connection or add request
769 // to the queue
Carson Labradod14a48f2023-02-22 00:24:54 +0000770 if (connections.size() < connPolicy->maxConnections)
Carson Labradof52c03c2022-03-23 18:50:15 +0000771 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700772 BMCWEB_LOG_DEBUG("Adding new connection to pool {}", id);
Carson Labradof52c03c2022-03-23 18:50:15 +0000773 auto conn = addConnection();
Carson Labrado244256c2022-04-27 17:16:32 +0000774 conn->req = std::move(thisReq);
Carson Labradof52c03c2022-03-23 18:50:15 +0000775 conn->callback = std::move(cb);
Carson Labradof52c03c2022-03-23 18:50:15 +0000776 conn->doResolve();
777 }
778 else if (requestQueue.size() < maxRequestQueueSize)
779 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700780 BMCWEB_LOG_DEBUG("Max pool size reached. Adding data to queue {}",
781 id);
Carson Labradod14a48f2023-02-22 00:24:54 +0000782 requestQueue.emplace_back(std::move(thisReq), std::move(cb));
Carson Labradof52c03c2022-03-23 18:50:15 +0000783 }
784 else
785 {
Ed Tanous27b0cf92023-08-07 12:02:40 -0700786 // If we can't buffer the request then we should let the
787 // callback handle a 429 Too Many Requests dummy response
Ed Tanous6ea90762024-04-07 08:38:44 -0700788 BMCWEB_LOG_ERROR("{} request queue full. Dropping request.", id);
Carson Labrado43e14d32022-11-09 00:25:20 +0000789 Response dummyRes;
790 dummyRes.result(boost::beast::http::status::too_many_requests);
791 resHandler(dummyRes);
Carson Labradof52c03c2022-03-23 18:50:15 +0000792 }
Ayushi Smritife44eb02020-05-15 15:24:45 +0530793 }
794
Ed Tanous3d36e3a2022-08-19 15:54:04 -0700795 // Callback to be called once the request has been sent
796 static void afterSendData(const std::weak_ptr<ConnectionPool>& weakSelf,
797 const std::function<void(Response&)>& resHandler,
798 bool keepAlive, uint32_t connId, Response& res)
799 {
800 // Allow provided callback to perform additional processing of the
801 // request
802 resHandler(res);
803
804 // If requests remain in the queue then we want to reuse this
805 // connection to send the next request
806 std::shared_ptr<ConnectionPool> self = weakSelf.lock();
807 if (!self)
808 {
Ed Tanous62598e32023-07-17 17:06:25 -0700809 BMCWEB_LOG_CRITICAL("{} Failed to capture connection",
810 logPtr(self.get()));
Ed Tanous3d36e3a2022-08-19 15:54:04 -0700811 return;
812 }
813
814 self->sendNext(keepAlive, connId);
815 }
816
Carson Labradof52c03c2022-03-23 18:50:15 +0000817 std::shared_ptr<ConnectionInfo>& addConnection()
Ayushi Smritife44eb02020-05-15 15:24:45 +0530818 {
Carson Labradof52c03c2022-03-23 18:50:15 +0000819 unsigned int newId = static_cast<unsigned int>(connections.size());
820
AppaRao Pulie38778a2022-06-27 23:09:03 +0000821 auto& ret = connections.emplace_back(std::make_shared<ConnectionInfo>(
Ed Tanous19bb3622024-07-05 10:07:40 -0500822 ioc, id, connPolicy, destIP, verifyCert, newId));
Carson Labradof52c03c2022-03-23 18:50:15 +0000823
Ed Tanousa716aa72023-08-01 11:35:53 -0700824 BMCWEB_LOG_DEBUG("Added connection {} to pool {}",
825 connections.size() - 1, id);
Carson Labradof52c03c2022-03-23 18:50:15 +0000826
827 return ret;
828 }
829
830 public:
Carson Labradod14a48f2023-02-22 00:24:54 +0000831 explicit ConnectionPool(
832 boost::asio::io_context& iocIn, const std::string& idIn,
833 const std::shared_ptr<ConnectionPolicy>& connPolicyIn,
Ed Tanous19bb3622024-07-05 10:07:40 -0500834 const boost::urls::url_view_base& destIPIn,
835 ensuressl::VerifyCertificate verifyCertIn) :
Patrick Williamsbd79bce2024-08-16 15:22:20 -0400836 ioc(iocIn), id(idIn), connPolicy(connPolicyIn), destIP(destIPIn),
Ed Tanous19bb3622024-07-05 10:07:40 -0500837 verifyCert(verifyCertIn)
Carson Labradof52c03c2022-03-23 18:50:15 +0000838 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700839 BMCWEB_LOG_DEBUG("Initializing connection pool for {}", id);
Carson Labradof52c03c2022-03-23 18:50:15 +0000840
841 // Initialize the pool with a single connection
842 addConnection();
Ayushi Smritife44eb02020-05-15 15:24:45 +0530843 }
Myung Baea0969c72024-09-19 08:46:45 -0400844
845 // Check whether all connections are terminated
846 bool areAllConnectionsTerminated()
847 {
848 if (connections.empty())
849 {
850 BMCWEB_LOG_DEBUG("There are no connections for pool id:{}", id);
851 return false;
852 }
853 for (const auto& conn : connections)
854 {
855 if (conn != nullptr && conn->state != ConnState::terminated)
856 {
857 BMCWEB_LOG_DEBUG(
858 "Not all connections of pool id:{} are terminated", id);
859 return false;
860 }
861 }
862 BMCWEB_LOG_INFO("All connections of pool id:{} are terminated", id);
863 return true;
864 }
AppaRao Pulibd030d02020-03-20 03:34:29 +0530865};
866
Carson Labradof52c03c2022-03-23 18:50:15 +0000867class HttpClient
868{
869 private:
870 std::unordered_map<std::string, std::shared_ptr<ConnectionPool>>
871 connectionPools;
Ed Tanous4b712a22023-08-02 12:56:52 -0700872
873 // reference_wrapper here makes HttpClient movable
874 std::reference_wrapper<boost::asio::io_context> ioc;
Carson Labradod14a48f2023-02-22 00:24:54 +0000875 std::shared_ptr<ConnectionPolicy> connPolicy;
Carson Labradof52c03c2022-03-23 18:50:15 +0000876
Carson Labrado039a47e2022-04-05 16:03:20 +0000877 // Used as a dummy callback by sendData() in order to call
878 // sendDataWithCallback()
Ed Tanous02cad962022-06-30 16:50:15 -0700879 static void genericResHandler(const Response& res)
Carson Labrado039a47e2022-04-05 16:03:20 +0000880 {
Ed Tanous62598e32023-07-17 17:06:25 -0700881 BMCWEB_LOG_DEBUG("Response handled with return code: {}",
Ed Tanousa716aa72023-08-01 11:35:53 -0700882 res.resultInt());
Ed Tanous4ee8e212022-05-28 09:42:51 -0700883 }
Carson Labrado039a47e2022-04-05 16:03:20 +0000884
Carson Labradof52c03c2022-03-23 18:50:15 +0000885 public:
Carson Labradod14a48f2023-02-22 00:24:54 +0000886 HttpClient() = delete;
Ed Tanousf8ca6d72022-06-28 12:12:03 -0700887 explicit HttpClient(boost::asio::io_context& iocIn,
888 const std::shared_ptr<ConnectionPolicy>& connPolicyIn) :
Patrick Williamsbd79bce2024-08-16 15:22:20 -0400889 ioc(iocIn), connPolicy(connPolicyIn)
Carson Labradod14a48f2023-02-22 00:24:54 +0000890 {}
Ed Tanousf8ca6d72022-06-28 12:12:03 -0700891
Carson Labradof52c03c2022-03-23 18:50:15 +0000892 HttpClient(const HttpClient&) = delete;
893 HttpClient& operator=(const HttpClient&) = delete;
Ed Tanous4b712a22023-08-02 12:56:52 -0700894 HttpClient(HttpClient&& client) = default;
895 HttpClient& operator=(HttpClient&& client) = default;
Carson Labradof52c03c2022-03-23 18:50:15 +0000896 ~HttpClient() = default;
897
Ed Tanousa716aa72023-08-01 11:35:53 -0700898 // Send a request to destIP where additional processing of the
Carson Labrado039a47e2022-04-05 16:03:20 +0000899 // result is not required
Ed Tanous4a7fbef2024-04-06 16:03:49 -0700900 void sendData(std::string&& data, const boost::urls::url_view_base& destUri,
Ed Tanous19bb3622024-07-05 10:07:40 -0500901 ensuressl::VerifyCertificate verifyCert,
Carson Labradof52c03c2022-03-23 18:50:15 +0000902 const boost::beast::http::fields& httpHeader,
Carson Labradod14a48f2023-02-22 00:24:54 +0000903 const boost::beast::http::verb verb)
Carson Labradof52c03c2022-03-23 18:50:15 +0000904 {
AppaRao Pulie38778a2022-06-27 23:09:03 +0000905 const std::function<void(Response&)> cb = genericResHandler;
Ed Tanous19bb3622024-07-05 10:07:40 -0500906 sendDataWithCallback(std::move(data), destUri, verifyCert, httpHeader,
907 verb, cb);
Carson Labrado039a47e2022-04-05 16:03:20 +0000908 }
909
Ed Tanousa716aa72023-08-01 11:35:53 -0700910 // Send request to destIP and use the provided callback to
Carson Labrado039a47e2022-04-05 16:03:20 +0000911 // handle the response
Ed Tanous4a7fbef2024-04-06 16:03:49 -0700912 void sendDataWithCallback(std::string&& data,
913 const boost::urls::url_view_base& destUrl,
Ed Tanous19bb3622024-07-05 10:07:40 -0500914 ensuressl::VerifyCertificate verifyCert,
Carson Labrado039a47e2022-04-05 16:03:20 +0000915 const boost::beast::http::fields& httpHeader,
Carson Labrado244256c2022-04-27 17:16:32 +0000916 const boost::beast::http::verb verb,
Ed Tanous6b3db602022-06-28 19:41:44 -0700917 const std::function<void(Response&)>& resHandler)
Carson Labrado039a47e2022-04-05 16:03:20 +0000918 {
Ed Tanous19bb3622024-07-05 10:07:40 -0500919 std::string_view verify = "ssl_verify";
920 if (verifyCert == ensuressl::VerifyCertificate::NoVerify)
921 {
922 verify = "ssl no verify";
923 }
Patrick Williamsbd79bce2024-08-16 15:22:20 -0400924 std::string clientKey =
925 std::format("{}{}://{}", verify, destUrl.scheme(),
926 destUrl.encoded_host_and_port());
Carson Labradod14a48f2023-02-22 00:24:54 +0000927 auto pool = connectionPools.try_emplace(clientKey);
928 if (pool.first->second == nullptr)
Carson Labradof52c03c2022-03-23 18:50:15 +0000929 {
Carson Labradod14a48f2023-02-22 00:24:54 +0000930 pool.first->second = std::make_shared<ConnectionPool>(
Ed Tanous19bb3622024-07-05 10:07:40 -0500931 ioc, clientKey, connPolicy, destUrl, verifyCert);
Carson Labradof52c03c2022-03-23 18:50:15 +0000932 }
Ed Tanous27b0cf92023-08-07 12:02:40 -0700933 // Send the data using either the existing connection pool or the
934 // newly created connection pool
Ed Tanousa716aa72023-08-01 11:35:53 -0700935 pool.first->second->sendData(std::move(data), destUrl, httpHeader, verb,
Carson Labradod14a48f2023-02-22 00:24:54 +0000936 resHandler);
Carson Labradof52c03c2022-03-23 18:50:15 +0000937 }
Myung Baea0969c72024-09-19 08:46:45 -0400938
939 // Test whether all connections are terminated (after MaxRetryAttempts)
940 bool isTerminated()
941 {
942 for (const auto& pool : connectionPools)
943 {
944 if (pool.second != nullptr &&
945 !pool.second->areAllConnectionsTerminated())
946 {
947 BMCWEB_LOG_DEBUG(
948 "Not all of client connections are terminated");
949 return false;
950 }
951 }
952 BMCWEB_LOG_DEBUG("All client connections are terminated");
953 return true;
954 }
Carson Labradof52c03c2022-03-23 18:50:15 +0000955};
AppaRao Pulibd030d02020-03-20 03:34:29 +0530956} // namespace crow