blob: ac231b42e78010f5b5ea8ce603e4c066bfc331c1 [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>
47#include <iostream>
48#include <memory>
AppaRao Puli2a5689a2020-04-29 15:24:31 +053049#include <queue>
AppaRao Pulibd030d02020-03-20 03:34:29 +053050#include <string>
51
52namespace crow
53{
Ed Tanous27b0cf92023-08-07 12:02:40 -070054// With Redfish Aggregation it is assumed we will connect to another
55// instance of BMCWeb which can handle 100 simultaneous connections.
Carson Labrado66d90c22022-12-07 22:34:33 +000056constexpr size_t maxPoolSize = 20;
57constexpr size_t maxRequestQueueSize = 500;
Carson Labrado17dcc312022-07-28 22:17:28 +000058constexpr unsigned int httpReadBodyLimit = 131072;
Carson Labrado4d942722022-06-22 22:16:10 +000059constexpr unsigned int httpReadBufferSize = 4096;
AppaRao Puli2a5689a2020-04-29 15:24:31 +053060
AppaRao Pulibd030d02020-03-20 03:34:29 +053061enum class ConnState
62{
AppaRao Puli2a5689a2020-04-29 15:24:31 +053063 initialized,
Sunitha Harish29a82b02021-02-18 15:54:16 +053064 resolveInProgress,
65 resolveFailed,
AppaRao Puli2a5689a2020-04-29 15:24:31 +053066 connectInProgress,
67 connectFailed,
AppaRao Pulibd030d02020-03-20 03:34:29 +053068 connected,
AppaRao Pulie38778a2022-06-27 23:09:03 +000069 handshakeInProgress,
70 handshakeFailed,
AppaRao Puli2a5689a2020-04-29 15:24:31 +053071 sendInProgress,
72 sendFailed,
Sunitha Harish6eaa1d22021-02-19 13:38:31 +053073 recvInProgress,
AppaRao Puli2a5689a2020-04-29 15:24:31 +053074 recvFailed,
75 idle,
Ayushi Smritife44eb02020-05-15 15:24:45 +053076 closed,
Sunitha Harish6eaa1d22021-02-19 13:38:31 +053077 suspended,
78 terminated,
79 abortConnection,
AppaRao Pulie38778a2022-06-27 23:09:03 +000080 sslInitFailed,
Sunitha Harish6eaa1d22021-02-19 13:38:31 +053081 retry
AppaRao Pulibd030d02020-03-20 03:34:29 +053082};
83
Carson Labradoa7a80292022-06-01 16:01:52 +000084static inline boost::system::error_code
85 defaultRetryHandler(unsigned int respCode)
86{
87 // As a default, assume 200X is alright
Ed Tanous62598e32023-07-17 17:06:25 -070088 BMCWEB_LOG_DEBUG("Using default check for response code validity");
Carson Labradoa7a80292022-06-01 16:01:52 +000089 if ((respCode < 200) || (respCode >= 300))
90 {
91 return boost::system::errc::make_error_code(
92 boost::system::errc::result_out_of_range);
93 }
94
95 // Return 0 if the response code is valid
96 return boost::system::errc::make_error_code(boost::system::errc::success);
97};
98
Ed Tanous27b0cf92023-08-07 12:02:40 -070099// We need to allow retry information to be set before a message has been
100// sent and a connection pool has been created
Carson Labradod14a48f2023-02-22 00:24:54 +0000101struct ConnectionPolicy
Carson Labradof52c03c2022-03-23 18:50:15 +0000102{
103 uint32_t maxRetryAttempts = 5;
Carson Labradod14a48f2023-02-22 00:24:54 +0000104
105 // the max size of requests in bytes. 0 for unlimited
106 boost::optional<uint64_t> requestByteLimit = httpReadBodyLimit;
107
108 size_t maxConnections = 1;
109
Carson Labradof52c03c2022-03-23 18:50:15 +0000110 std::string retryPolicyAction = "TerminateAfterRetries";
Carson Labradod14a48f2023-02-22 00:24:54 +0000111
112 std::chrono::seconds retryIntervalSecs = std::chrono::seconds(0);
Carson Labradoa7a80292022-06-01 16:01:52 +0000113 std::function<boost::system::error_code(unsigned int respCode)>
114 invalidResp = defaultRetryHandler;
Carson Labradof52c03c2022-03-23 18:50:15 +0000115};
116
117struct PendingRequest
118{
Ed Tanousb2896142024-01-31 15:25:47 -0800119 boost::beast::http::request<bmcweb::HttpBody> req;
Carson Labrado039a47e2022-04-05 16:03:20 +0000120 std::function<void(bool, uint32_t, Response&)> callback;
Carson Labrado039a47e2022-04-05 16:03:20 +0000121 PendingRequest(
Ed Tanousb2896142024-01-31 15:25:47 -0800122 boost::beast::http::request<bmcweb::HttpBody>&& reqIn,
Carson Labradod14a48f2023-02-22 00:24:54 +0000123 const std::function<void(bool, uint32_t, Response&)>& callbackIn) :
Ed Tanous8a592812022-06-04 09:06:59 -0700124 req(std::move(reqIn)),
Carson Labradod14a48f2023-02-22 00:24:54 +0000125 callback(callbackIn)
Carson Labradof52c03c2022-03-23 18:50:15 +0000126 {}
127};
128
Ed Tanouse01d0c32023-06-30 13:21:32 -0700129namespace http = boost::beast::http;
Carson Labradof52c03c2022-03-23 18:50:15 +0000130class ConnectionInfo : public std::enable_shared_from_this<ConnectionInfo>
AppaRao Pulibd030d02020-03-20 03:34:29 +0530131{
132 private:
Carson Labradof52c03c2022-03-23 18:50:15 +0000133 ConnState state = ConnState::initialized;
134 uint32_t retryCount = 0;
Carson Labradof52c03c2022-03-23 18:50:15 +0000135 std::string subId;
Carson Labradod14a48f2023-02-22 00:24:54 +0000136 std::shared_ptr<ConnectionPolicy> connPolicy;
Ed Tanousa716aa72023-08-01 11:35:53 -0700137 boost::urls::url host;
Carson Labradof52c03c2022-03-23 18:50:15 +0000138 uint32_t connId;
139
Carson Labradof52c03c2022-03-23 18:50:15 +0000140 // Data buffers
Ed Tanousb2896142024-01-31 15:25:47 -0800141 http::request<bmcweb::HttpBody> req;
142 using parser_type = http::response_parser<bmcweb::HttpBody>;
Ed Tanouse01d0c32023-06-30 13:21:32 -0700143 std::optional<parser_type> parser;
Carson Labrado4d942722022-06-22 22:16:10 +0000144 boost::beast::flat_static_buffer<httpReadBufferSize> buffer;
Carson Labrado039a47e2022-04-05 16:03:20 +0000145 Response res;
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530146
Carson Labradof52c03c2022-03-23 18:50:15 +0000147 // Ascync callables
Carson Labrado039a47e2022-04-05 16:03:20 +0000148 std::function<void(bool, uint32_t, Response&)> callback;
Ed Tanousf8ca6d72022-06-28 12:12:03 -0700149
Abhilash Rajuf3cb5df2023-11-30 03:54:11 -0600150 boost::asio::io_context& ioc;
151
Ed Tanous25b54db2024-04-17 15:40:31 -0700152 using Resolver = std::conditional_t<BMCWEB_DNS_RESOLVER == "systemd-dbus",
153 async_resolve::Resolver,
154 boost::asio::ip::tcp::resolver>;
Ed Tanousf8ca6d72022-06-28 12:12:03 -0700155 Resolver resolver;
156
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800157 boost::asio::ip::tcp::socket conn;
Ed Tanous003301a2024-04-16 09:59:19 -0700158 std::optional<boost::asio::ssl::stream<boost::asio::ip::tcp::socket&>>
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800159 sslConn;
AppaRao Pulie38778a2022-06-27 23:09:03 +0000160
Carson Labradof52c03c2022-03-23 18:50:15 +0000161 boost::asio::steady_timer timer;
Ed Tanous84b35602021-09-08 20:06:32 -0700162
Carson Labradof52c03c2022-03-23 18:50:15 +0000163 friend class ConnectionPool;
AppaRao Pulibd030d02020-03-20 03:34:29 +0530164
Sunitha Harish29a82b02021-02-18 15:54:16 +0530165 void doResolve()
166 {
Sunitha Harish29a82b02021-02-18 15:54:16 +0530167 state = ConnState::resolveInProgress;
Ed Tanousa716aa72023-08-01 11:35:53 -0700168 BMCWEB_LOG_DEBUG("Trying to resolve: {}, id: {}", host, connId);
Sunitha Harish29a82b02021-02-18 15:54:16 +0530169
Ed Tanousa716aa72023-08-01 11:35:53 -0700170 resolver.async_resolve(host.encoded_host_address(), host.port(),
Ed Tanousf8ca6d72022-06-28 12:12:03 -0700171 std::bind_front(&ConnectionInfo::afterResolve,
172 this, shared_from_this()));
Sunitha Harish29a82b02021-02-18 15:54:16 +0530173 }
174
Ed Tanousf8ca6d72022-06-28 12:12:03 -0700175 void afterResolve(const std::shared_ptr<ConnectionInfo>& /*self*/,
176 const boost::system::error_code& ec,
177 const Resolver::results_type& endpointList)
AppaRao Pulibd030d02020-03-20 03:34:29 +0530178 {
Ed Tanous3d36e3a2022-08-19 15:54:04 -0700179 if (ec || (endpointList.empty()))
180 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700181 BMCWEB_LOG_ERROR("Resolve failed: {} {}", ec.message(), host);
Ed Tanous3d36e3a2022-08-19 15:54:04 -0700182 state = ConnState::resolveFailed;
183 waitAndRetry();
184 return;
185 }
Ed Tanousa716aa72023-08-01 11:35:53 -0700186 BMCWEB_LOG_DEBUG("Resolved {}, id: {}", host, connId);
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530187 state = ConnState::connectInProgress;
188
Ed Tanousa716aa72023-08-01 11:35:53 -0700189 BMCWEB_LOG_DEBUG("Trying to connect to: {}, id: {}", host, connId);
Sunitha Harish29a82b02021-02-18 15:54:16 +0530190
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800191 timer.expires_after(std::chrono::seconds(30));
192 timer.async_wait(std::bind_front(onTimeout, weak_from_this()));
193
194 boost::asio::async_connect(
195 conn, endpointList,
196 std::bind_front(&ConnectionInfo::afterConnect, this,
197 shared_from_this()));
AppaRao Pulie38778a2022-06-27 23:09:03 +0000198 }
199
200 void afterConnect(const std::shared_ptr<ConnectionInfo>& /*self*/,
Ed Tanous81c4e332023-05-18 10:30:34 -0700201 const boost::beast::error_code& ec,
AppaRao Pulie38778a2022-06-27 23:09:03 +0000202 const boost::asio::ip::tcp::endpoint& endpoint)
203 {
Carson Labrado513d1ff2022-07-19 00:38:15 +0000204 // The operation already timed out. We don't want do continue down
205 // this branch
206 if (ec && ec == boost::asio::error::operation_aborted)
207 {
208 return;
209 }
210
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800211 timer.cancel();
AppaRao Pulie38778a2022-06-27 23:09:03 +0000212 if (ec)
213 {
Ed Tanous62598e32023-07-17 17:06:25 -0700214 BMCWEB_LOG_ERROR("Connect {}:{}, id: {} failed: {}",
Ed Tanousa716aa72023-08-01 11:35:53 -0700215 endpoint.address().to_string(), endpoint.port(),
216 connId, ec.message());
AppaRao Pulie38778a2022-06-27 23:09:03 +0000217 state = ConnState::connectFailed;
218 waitAndRetry();
219 return;
220 }
Ed Tanousa716aa72023-08-01 11:35:53 -0700221 BMCWEB_LOG_DEBUG("Connected to: {}:{}, id: {}",
222 endpoint.address().to_string(), endpoint.port(),
223 connId);
AppaRao Pulie38778a2022-06-27 23:09:03 +0000224 if (sslConn)
225 {
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800226 doSslHandshake();
AppaRao Pulie38778a2022-06-27 23:09:03 +0000227 return;
228 }
229 state = ConnState::connected;
230 sendMessage();
231 }
232
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800233 void doSslHandshake()
AppaRao Pulie38778a2022-06-27 23:09:03 +0000234 {
235 if (!sslConn)
236 {
237 return;
238 }
239 state = ConnState::handshakeInProgress;
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800240 timer.expires_after(std::chrono::seconds(30));
241 timer.async_wait(std::bind_front(onTimeout, weak_from_this()));
AppaRao Pulie38778a2022-06-27 23:09:03 +0000242 sslConn->async_handshake(
243 boost::asio::ssl::stream_base::client,
244 std::bind_front(&ConnectionInfo::afterSslHandshake, this,
245 shared_from_this()));
246 }
247
248 void afterSslHandshake(const std::shared_ptr<ConnectionInfo>& /*self*/,
Ed Tanous81c4e332023-05-18 10:30:34 -0700249 const boost::beast::error_code& ec)
AppaRao Pulie38778a2022-06-27 23:09:03 +0000250 {
Carson Labrado513d1ff2022-07-19 00:38:15 +0000251 // The operation already timed out. We don't want do continue down
252 // this branch
253 if (ec && ec == boost::asio::error::operation_aborted)
254 {
255 return;
256 }
257
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800258 timer.cancel();
AppaRao Pulie38778a2022-06-27 23:09:03 +0000259 if (ec)
260 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700261 BMCWEB_LOG_ERROR("SSL Handshake failed - id: {} error: {}", connId,
262 ec.message());
AppaRao Pulie38778a2022-06-27 23:09:03 +0000263 state = ConnState::handshakeFailed;
264 waitAndRetry();
265 return;
266 }
Ed Tanousa716aa72023-08-01 11:35:53 -0700267 BMCWEB_LOG_DEBUG("SSL Handshake successful - id: {}", connId);
AppaRao Pulie38778a2022-06-27 23:09:03 +0000268 state = ConnState::connected;
269 sendMessage();
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530270 }
271
Carson Labradof52c03c2022-03-23 18:50:15 +0000272 void sendMessage()
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530273 {
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530274 state = ConnState::sendInProgress;
275
AppaRao Pulibd030d02020-03-20 03:34:29 +0530276 // Set a timeout on the operation
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800277 timer.expires_after(std::chrono::seconds(30));
278 timer.async_wait(std::bind_front(onTimeout, weak_from_this()));
Ed Tanous4d698612024-02-06 14:57:24 -0800279 boost::beast::http::message_generator messageGenerator(std::move(req));
AppaRao Pulibd030d02020-03-20 03:34:29 +0530280 // Send the HTTP request to the remote host
AppaRao Pulie38778a2022-06-27 23:09:03 +0000281 if (sslConn)
282 {
Ed Tanous4d698612024-02-06 14:57:24 -0800283 boost::beast::async_write(
284 *sslConn, std::move(messageGenerator),
AppaRao Pulie38778a2022-06-27 23:09:03 +0000285 std::bind_front(&ConnectionInfo::afterWrite, this,
286 shared_from_this()));
287 }
288 else
289 {
Ed Tanous4d698612024-02-06 14:57:24 -0800290 boost::beast::async_write(
291 conn, std::move(messageGenerator),
AppaRao Pulie38778a2022-06-27 23:09:03 +0000292 std::bind_front(&ConnectionInfo::afterWrite, this,
293 shared_from_this()));
294 }
295 }
AppaRao Pulibd030d02020-03-20 03:34:29 +0530296
AppaRao Pulie38778a2022-06-27 23:09:03 +0000297 void afterWrite(const std::shared_ptr<ConnectionInfo>& /*self*/,
298 const boost::beast::error_code& ec, size_t bytesTransferred)
299 {
Carson Labrado513d1ff2022-07-19 00:38:15 +0000300 // The operation already timed out. We don't want do continue down
301 // this branch
302 if (ec && ec == boost::asio::error::operation_aborted)
303 {
304 return;
305 }
306
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800307 timer.cancel();
AppaRao Pulie38778a2022-06-27 23:09:03 +0000308 if (ec)
309 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700310 BMCWEB_LOG_ERROR("sendMessage() failed: {} {}", ec.message(), host);
AppaRao Pulie38778a2022-06-27 23:09:03 +0000311 state = ConnState::sendFailed;
312 waitAndRetry();
313 return;
314 }
Ed Tanous62598e32023-07-17 17:06:25 -0700315 BMCWEB_LOG_DEBUG("sendMessage() bytes transferred: {}",
316 bytesTransferred);
AppaRao Pulie38778a2022-06-27 23:09:03 +0000317
318 recvMessage();
AppaRao Pulibd030d02020-03-20 03:34:29 +0530319 }
320
321 void recvMessage()
322 {
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530323 state = ConnState::recvInProgress;
324
Ed Tanouse01d0c32023-06-30 13:21:32 -0700325 parser_type& thisParser = parser.emplace(std::piecewise_construct,
326 std::make_tuple());
Carson Labradod14a48f2023-02-22 00:24:54 +0000327
Ed Tanouse01d0c32023-06-30 13:21:32 -0700328 thisParser.body_limit(connPolicy->requestByteLimit);
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530329
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800330 timer.expires_after(std::chrono::seconds(30));
331 timer.async_wait(std::bind_front(onTimeout, weak_from_this()));
332
AppaRao Pulibd030d02020-03-20 03:34:29 +0530333 // Receive the HTTP response
AppaRao Pulie38778a2022-06-27 23:09:03 +0000334 if (sslConn)
335 {
336 boost::beast::http::async_read(
Ed Tanouse01d0c32023-06-30 13:21:32 -0700337 *sslConn, buffer, thisParser,
AppaRao Pulie38778a2022-06-27 23:09:03 +0000338 std::bind_front(&ConnectionInfo::afterRead, this,
339 shared_from_this()));
340 }
341 else
342 {
343 boost::beast::http::async_read(
Ed Tanouse01d0c32023-06-30 13:21:32 -0700344 conn, buffer, thisParser,
AppaRao Pulie38778a2022-06-27 23:09:03 +0000345 std::bind_front(&ConnectionInfo::afterRead, this,
346 shared_from_this()));
347 }
348 }
AppaRao Pulibd030d02020-03-20 03:34:29 +0530349
AppaRao Pulie38778a2022-06-27 23:09:03 +0000350 void afterRead(const std::shared_ptr<ConnectionInfo>& /*self*/,
351 const boost::beast::error_code& ec,
352 const std::size_t& bytesTransferred)
353 {
Carson Labrado513d1ff2022-07-19 00:38:15 +0000354 // The operation already timed out. We don't want do continue down
355 // this branch
356 if (ec && ec == boost::asio::error::operation_aborted)
357 {
358 return;
359 }
360
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800361 timer.cancel();
AppaRao Pulie38778a2022-06-27 23:09:03 +0000362 if (ec && ec != boost::asio::ssl::error::stream_truncated)
363 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700364 BMCWEB_LOG_ERROR("recvMessage() failed: {} from {}", ec.message(),
365 host);
AppaRao Pulie38778a2022-06-27 23:09:03 +0000366 state = ConnState::recvFailed;
367 waitAndRetry();
368 return;
369 }
Ed Tanous62598e32023-07-17 17:06:25 -0700370 BMCWEB_LOG_DEBUG("recvMessage() bytes transferred: {}",
371 bytesTransferred);
Ed Tanouse01d0c32023-06-30 13:21:32 -0700372 if (!parser)
373 {
374 return;
375 }
Ed Tanous52e31622024-01-23 16:31:11 -0800376 BMCWEB_LOG_DEBUG("recvMessage() data: {}", parser->get().body().str());
AppaRao Pulie38778a2022-06-27 23:09:03 +0000377
378 unsigned int respCode = parser->get().result_int();
Ed Tanous62598e32023-07-17 17:06:25 -0700379 BMCWEB_LOG_DEBUG("recvMessage() Header Response Code: {}", respCode);
AppaRao Pulie38778a2022-06-27 23:09:03 +0000380
Abhilash Rajuf3cb5df2023-11-30 03:54:11 -0600381 // Handle the case of stream_truncated. Some servers close the ssl
382 // connection uncleanly, so check to see if we got a full response
383 // before we handle this as an error.
384 if (!parser->is_done())
385 {
386 state = ConnState::recvFailed;
387 waitAndRetry();
388 return;
389 }
390
AppaRao Pulie38778a2022-06-27 23:09:03 +0000391 // Make sure the received response code is valid as defined by
392 // the associated retry policy
Carson Labradod14a48f2023-02-22 00:24:54 +0000393 if (connPolicy->invalidResp(respCode))
AppaRao Pulie38778a2022-06-27 23:09:03 +0000394 {
395 // The listener failed to receive the Sent-Event
Ed Tanous62598e32023-07-17 17:06:25 -0700396 BMCWEB_LOG_ERROR(
397 "recvMessage() Listener Failed to "
Ed Tanousa716aa72023-08-01 11:35:53 -0700398 "receive Sent-Event. Header Response Code: {} from {}",
399 respCode, host);
AppaRao Pulie38778a2022-06-27 23:09:03 +0000400 state = ConnState::recvFailed;
401 waitAndRetry();
402 return;
403 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700404
AppaRao Pulie38778a2022-06-27 23:09:03 +0000405 // Send is successful
406 // Reset the counter just in case this was after retrying
407 retryCount = 0;
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530408
AppaRao Pulie38778a2022-06-27 23:09:03 +0000409 // Keep the connection alive if server supports it
410 // Else close the connection
Ed Tanous62598e32023-07-17 17:06:25 -0700411 BMCWEB_LOG_DEBUG("recvMessage() keepalive : {}", parser->keep_alive());
AppaRao Pulibd030d02020-03-20 03:34:29 +0530412
AppaRao Pulie38778a2022-06-27 23:09:03 +0000413 // Copy the response into a Response object so that it can be
414 // processed by the callback function.
Ed Tanous27b0cf92023-08-07 12:02:40 -0700415 res.response = parser->release();
AppaRao Pulie38778a2022-06-27 23:09:03 +0000416 callback(parser->keep_alive(), connId, res);
Carson Labrado513d1ff2022-07-19 00:38:15 +0000417 res.clear();
AppaRao Pulibd030d02020-03-20 03:34:29 +0530418 }
419
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800420 static void onTimeout(const std::weak_ptr<ConnectionInfo>& weakSelf,
Ed Tanous5e7e2dc2023-02-16 10:37:01 -0800421 const boost::system::error_code& ec)
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800422 {
423 if (ec == boost::asio::error::operation_aborted)
424 {
Ed Tanous62598e32023-07-17 17:06:25 -0700425 BMCWEB_LOG_DEBUG(
426 "async_wait failed since the operation is aborted");
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800427 return;
428 }
429 if (ec)
430 {
Ed Tanous62598e32023-07-17 17:06:25 -0700431 BMCWEB_LOG_ERROR("async_wait failed: {}", ec.message());
Ed Tanous27b0cf92023-08-07 12:02:40 -0700432 // If the timer fails, we need to close the socket anyway, same
433 // as if it expired.
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800434 }
435 std::shared_ptr<ConnectionInfo> self = weakSelf.lock();
436 if (self == nullptr)
437 {
438 return;
439 }
440 self->waitAndRetry();
441 }
442
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530443 void waitAndRetry()
AppaRao Pulibd030d02020-03-20 03:34:29 +0530444 {
Carson Labradod14a48f2023-02-22 00:24:54 +0000445 if ((retryCount >= connPolicy->maxRetryAttempts) ||
AppaRao Pulie38778a2022-06-27 23:09:03 +0000446 (state == ConnState::sslInitFailed))
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530447 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700448 BMCWEB_LOG_ERROR("Maximum number of retries reached. {}", host);
Ed Tanous62598e32023-07-17 17:06:25 -0700449 BMCWEB_LOG_DEBUG("Retry policy: {}", connPolicy->retryPolicyAction);
Carson Labrado039a47e2022-04-05 16:03:20 +0000450
Carson Labradod14a48f2023-02-22 00:24:54 +0000451 if (connPolicy->retryPolicyAction == "TerminateAfterRetries")
Ayushi Smritife44eb02020-05-15 15:24:45 +0530452 {
453 // TODO: delete subscription
454 state = ConnState::terminated;
Ayushi Smritife44eb02020-05-15 15:24:45 +0530455 }
Carson Labradod14a48f2023-02-22 00:24:54 +0000456 if (connPolicy->retryPolicyAction == "SuspendRetries")
Ayushi Smritife44eb02020-05-15 15:24:45 +0530457 {
458 state = ConnState::suspended;
Ayushi Smritife44eb02020-05-15 15:24:45 +0530459 }
Carson Labrado513d1ff2022-07-19 00:38:15 +0000460
461 // We want to return a 502 to indicate there was an error with
462 // the external server
463 res.result(boost::beast::http::status::bad_gateway);
464 callback(false, connId, res);
465 res.clear();
466
Ed Tanous27b0cf92023-08-07 12:02:40 -0700467 // Reset the retrycount to zero so that client can try
468 // connecting again if needed
Ed Tanous3174e4d2020-10-07 11:41:22 -0700469 retryCount = 0;
Ayushi Smritife44eb02020-05-15 15:24:45 +0530470 return;
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530471 }
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530472
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530473 retryCount++;
474
Ed Tanous62598e32023-07-17 17:06:25 -0700475 BMCWEB_LOG_DEBUG("Attempt retry after {} seconds. RetryCount = {}",
Ed Tanousa716aa72023-08-01 11:35:53 -0700476 connPolicy->retryIntervalSecs.count(), retryCount);
Carson Labradod14a48f2023-02-22 00:24:54 +0000477 timer.expires_after(connPolicy->retryIntervalSecs);
Ed Tanous3d36e3a2022-08-19 15:54:04 -0700478 timer.async_wait(std::bind_front(&ConnectionInfo::onTimerDone, this,
479 shared_from_this()));
480 }
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530481
Ed Tanous3d36e3a2022-08-19 15:54:04 -0700482 void onTimerDone(const std::shared_ptr<ConnectionInfo>& /*self*/,
483 const boost::system::error_code& ec)
484 {
485 if (ec == boost::asio::error::operation_aborted)
486 {
Ed Tanous62598e32023-07-17 17:06:25 -0700487 BMCWEB_LOG_DEBUG(
488 "async_wait failed since the operation is aborted{}",
489 ec.message());
Ed Tanous3d36e3a2022-08-19 15:54:04 -0700490 }
491 else if (ec)
492 {
Ed Tanous62598e32023-07-17 17:06:25 -0700493 BMCWEB_LOG_ERROR("async_wait failed: {}", ec.message());
Ed Tanous3d36e3a2022-08-19 15:54:04 -0700494 // Ignore the error and continue the retry loop to attempt
495 // sending the event as per the retry policy
496 }
497
498 // Let's close the connection and restart from resolve.
Abhilash Rajuf3cb5df2023-11-30 03:54:11 -0600499 shutdownConn(true);
500 }
501
502 void restartConnection()
503 {
504 BMCWEB_LOG_DEBUG("{}, id: {} restartConnection", host,
505 std::to_string(connId));
506 initializeConnection(host.scheme() == "https");
507 doResolve();
Ayushi Smritife44eb02020-05-15 15:24:45 +0530508 }
509
AppaRao Pulie38778a2022-06-27 23:09:03 +0000510 void shutdownConn(bool retry)
Ayushi Smritife44eb02020-05-15 15:24:45 +0530511 {
Carson Labradof52c03c2022-03-23 18:50:15 +0000512 boost::beast::error_code ec;
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800513 conn.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
Carson Labradof52c03c2022-03-23 18:50:15 +0000514 conn.close();
515
516 // not_connected happens sometimes so don't bother reporting it.
517 if (ec && ec != boost::beast::errc::not_connected)
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530518 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700519 BMCWEB_LOG_ERROR("{}, id: {} shutdown failed: {}", host, connId,
Ed Tanous62598e32023-07-17 17:06:25 -0700520 ec.message());
Carson Labradof52c03c2022-03-23 18:50:15 +0000521 }
Carson Labrado5cab68f2022-07-11 22:26:21 +0000522 else
523 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700524 BMCWEB_LOG_DEBUG("{}, id: {} closed gracefully", host, connId);
Carson Labrado5cab68f2022-07-11 22:26:21 +0000525 }
Ed Tanousca723762022-06-28 19:40:39 -0700526
Carson Labrado513d1ff2022-07-19 00:38:15 +0000527 if (retry)
AppaRao Pulie38778a2022-06-27 23:09:03 +0000528 {
Carson Labrado513d1ff2022-07-19 00:38:15 +0000529 // Now let's try to resend the data
530 state = ConnState::retry;
Abhilash Rajuf3cb5df2023-11-30 03:54:11 -0600531 restartConnection();
Carson Labrado513d1ff2022-07-19 00:38:15 +0000532 }
533 else
534 {
535 state = ConnState::closed;
AppaRao Pulie38778a2022-06-27 23:09:03 +0000536 }
Carson Labradof52c03c2022-03-23 18:50:15 +0000537 }
538
AppaRao Pulie38778a2022-06-27 23:09:03 +0000539 void doClose(bool retry = false)
Carson Labradof52c03c2022-03-23 18:50:15 +0000540 {
AppaRao Pulie38778a2022-06-27 23:09:03 +0000541 if (!sslConn)
542 {
543 shutdownConn(retry);
544 return;
545 }
Carson Labradof52c03c2022-03-23 18:50:15 +0000546
AppaRao Pulie38778a2022-06-27 23:09:03 +0000547 sslConn->async_shutdown(
548 std::bind_front(&ConnectionInfo::afterSslShutdown, this,
549 shared_from_this(), retry));
550 }
551
552 void afterSslShutdown(const std::shared_ptr<ConnectionInfo>& /*self*/,
553 bool retry, const boost::system::error_code& ec)
554 {
AppaRao Pulie38778a2022-06-27 23:09:03 +0000555 if (ec)
Carson Labradof52c03c2022-03-23 18:50:15 +0000556 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700557 BMCWEB_LOG_ERROR("{}, id: {} shutdown failed: {}", host, connId,
Ed Tanous62598e32023-07-17 17:06:25 -0700558 ec.message());
Carson Labradof52c03c2022-03-23 18:50:15 +0000559 }
Carson Labrado5cab68f2022-07-11 22:26:21 +0000560 else
561 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700562 BMCWEB_LOG_DEBUG("{}, id: {} closed gracefully", host, connId);
Carson Labrado5cab68f2022-07-11 22:26:21 +0000563 }
AppaRao Pulie38778a2022-06-27 23:09:03 +0000564 shutdownConn(retry);
565 }
Ed Tanousca723762022-06-28 19:40:39 -0700566
AppaRao Pulie38778a2022-06-27 23:09:03 +0000567 void setCipherSuiteTLSext()
568 {
569 if (!sslConn)
570 {
571 return;
572 }
Ravi Tejae7c29912023-07-31 09:39:32 -0500573
574 if (host.host_type() != boost::urls::host_type::name)
575 {
576 // Avoid setting SNI hostname if its IP address
577 return;
578 }
579 // Create a null terminated string for SSL
Ed Tanousa716aa72023-08-01 11:35:53 -0700580 std::string hostname(host.encoded_host_address());
AppaRao Pulie38778a2022-06-27 23:09:03 +0000581 // NOTE: The SSL_set_tlsext_host_name is defined in tlsv1.h header
582 // file but its having old style casting (name is cast to void*).
583 // Since bmcweb compiler treats all old-style-cast as error, its
584 // causing the build failure. So replaced the same macro inline and
585 // did corrected the code by doing static_cast to viod*. This has to
586 // be fixed in openssl library in long run. Set SNI Hostname (many
587 // hosts need this to handshake successfully)
588 if (SSL_ctrl(sslConn->native_handle(), SSL_CTRL_SET_TLSEXT_HOSTNAME,
589 TLSEXT_NAMETYPE_host_name,
Ed Tanousa716aa72023-08-01 11:35:53 -0700590 static_cast<void*>(hostname.data())) == 0)
AppaRao Pulie38778a2022-06-27 23:09:03 +0000591
592 {
593 boost::beast::error_code ec{static_cast<int>(::ERR_get_error()),
594 boost::asio::error::get_ssl_category()};
595
Ed Tanousa716aa72023-08-01 11:35:53 -0700596 BMCWEB_LOG_ERROR("SSL_set_tlsext_host_name {}, id: {} failed: {}",
597 host, connId, ec.message());
AppaRao Pulie38778a2022-06-27 23:09:03 +0000598 // Set state as sslInit failed so that we close the connection
599 // and take appropriate action as per retry configuration.
600 state = ConnState::sslInitFailed;
601 waitAndRetry();
602 return;
603 }
AppaRao Pulibd030d02020-03-20 03:34:29 +0530604 }
605
Abhilash Rajuf3cb5df2023-11-30 03:54:11 -0600606 void initializeConnection(bool ssl)
AppaRao Pulie38778a2022-06-27 23:09:03 +0000607 {
Abhilash Rajuf3cb5df2023-11-30 03:54:11 -0600608 conn = boost::asio::ip::tcp::socket(ioc);
609 if (ssl)
AppaRao Pulie38778a2022-06-27 23:09:03 +0000610 {
611 std::optional<boost::asio::ssl::context> sslCtx =
612 ensuressl::getSSLClientContext();
613
614 if (!sslCtx)
615 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700616 BMCWEB_LOG_ERROR("prepareSSLContext failed - {}, id: {}", host,
617 connId);
AppaRao Pulie38778a2022-06-27 23:09:03 +0000618 // Don't retry if failure occurs while preparing SSL context
Ed Tanous27b0cf92023-08-07 12:02:40 -0700619 // such as certificate is invalid or set cipher failure or
620 // set host name failure etc... Setting conn state to
621 // sslInitFailed and connection state will be transitioned
622 // to next state depending on retry policy set by
623 // subscription.
AppaRao Pulie38778a2022-06-27 23:09:03 +0000624 state = ConnState::sslInitFailed;
625 waitAndRetry();
626 return;
627 }
628 sslConn.emplace(conn, *sslCtx);
629 setCipherSuiteTLSext();
630 }
631 }
Abhilash Rajuf3cb5df2023-11-30 03:54:11 -0600632
633 public:
634 explicit ConnectionInfo(
635 boost::asio::io_context& iocIn, const std::string& idIn,
636 const std::shared_ptr<ConnectionPolicy>& connPolicyIn,
Ed Tanous4a7fbef2024-04-06 16:03:49 -0700637 const boost::urls::url_view_base& hostIn, unsigned int connIdIn) :
Abhilash Rajuf3cb5df2023-11-30 03:54:11 -0600638 subId(idIn),
639 connPolicy(connPolicyIn), host(hostIn), connId(connIdIn), ioc(iocIn),
640 resolver(iocIn), conn(iocIn), timer(iocIn)
641 {
642 initializeConnection(host.scheme() == "https");
643 }
Carson Labradof52c03c2022-03-23 18:50:15 +0000644};
AppaRao Pulibd030d02020-03-20 03:34:29 +0530645
Carson Labradof52c03c2022-03-23 18:50:15 +0000646class ConnectionPool : public std::enable_shared_from_this<ConnectionPool>
647{
648 private:
649 boost::asio::io_context& ioc;
AppaRao Pulie38778a2022-06-27 23:09:03 +0000650 std::string id;
Carson Labradod14a48f2023-02-22 00:24:54 +0000651 std::shared_ptr<ConnectionPolicy> connPolicy;
Ed Tanousa716aa72023-08-01 11:35:53 -0700652 boost::urls::url destIP;
Carson Labradof52c03c2022-03-23 18:50:15 +0000653 std::vector<std::shared_ptr<ConnectionInfo>> connections;
654 boost::container::devector<PendingRequest> requestQueue;
655
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();
710 conn->doResolve();
711 }
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);
Carson Labradof52c03c2022-03-23 18:50:15 +0000764 conn->doResolve();
765 }
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 Tanousa716aa72023-08-01 11:35:53 -0700824 ioc, id, connPolicy, destIP, 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 Tanous4a7fbef2024-04-06 16:03:49 -0700836 const boost::urls::url_view_base& destIPIn) :
Ed Tanous8a592812022-06-04 09:06:59 -0700837 ioc(iocIn),
Ed Tanousa716aa72023-08-01 11:35:53 -0700838 id(idIn), connPolicy(connPolicyIn), destIP(destIPIn)
Carson Labradof52c03c2022-03-23 18:50:15 +0000839 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700840 BMCWEB_LOG_DEBUG("Initializing connection pool for {}", id);
Carson Labradof52c03c2022-03-23 18:50:15 +0000841
842 // Initialize the pool with a single connection
843 addConnection();
Ayushi Smritife44eb02020-05-15 15:24:45 +0530844 }
AppaRao Pulibd030d02020-03-20 03:34:29 +0530845};
846
Carson Labradof52c03c2022-03-23 18:50:15 +0000847class HttpClient
848{
849 private:
850 std::unordered_map<std::string, std::shared_ptr<ConnectionPool>>
851 connectionPools;
Ed Tanousf8ca6d72022-06-28 12:12:03 -0700852 boost::asio::io_context& ioc;
Carson Labradod14a48f2023-02-22 00:24:54 +0000853 std::shared_ptr<ConnectionPolicy> connPolicy;
Carson Labradof52c03c2022-03-23 18:50:15 +0000854
Carson Labrado039a47e2022-04-05 16:03:20 +0000855 // Used as a dummy callback by sendData() in order to call
856 // sendDataWithCallback()
Ed Tanous02cad962022-06-30 16:50:15 -0700857 static void genericResHandler(const Response& res)
Carson Labrado039a47e2022-04-05 16:03:20 +0000858 {
Ed Tanous62598e32023-07-17 17:06:25 -0700859 BMCWEB_LOG_DEBUG("Response handled with return code: {}",
Ed Tanousa716aa72023-08-01 11:35:53 -0700860 res.resultInt());
Ed Tanous4ee8e212022-05-28 09:42:51 -0700861 }
Carson Labrado039a47e2022-04-05 16:03:20 +0000862
Carson Labradof52c03c2022-03-23 18:50:15 +0000863 public:
Carson Labradod14a48f2023-02-22 00:24:54 +0000864 HttpClient() = delete;
Ed Tanousf8ca6d72022-06-28 12:12:03 -0700865 explicit HttpClient(boost::asio::io_context& iocIn,
866 const std::shared_ptr<ConnectionPolicy>& connPolicyIn) :
867 ioc(iocIn),
Carson Labradod14a48f2023-02-22 00:24:54 +0000868 connPolicy(connPolicyIn)
869 {}
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,
Carson Labradof52c03c2022-03-23 18:50:15 +0000880 const boost::beast::http::fields& httpHeader,
Carson Labradod14a48f2023-02-22 00:24:54 +0000881 const boost::beast::http::verb verb)
Carson Labradof52c03c2022-03-23 18:50:15 +0000882 {
AppaRao Pulie38778a2022-06-27 23:09:03 +0000883 const std::function<void(Response&)> cb = genericResHandler;
Ed Tanousa716aa72023-08-01 11:35:53 -0700884 sendDataWithCallback(std::move(data), destUri, httpHeader, verb, cb);
Carson Labrado039a47e2022-04-05 16:03:20 +0000885 }
886
Ed Tanousa716aa72023-08-01 11:35:53 -0700887 // Send request to destIP and use the provided callback to
Carson Labrado039a47e2022-04-05 16:03:20 +0000888 // handle the response
Ed Tanous4a7fbef2024-04-06 16:03:49 -0700889 void sendDataWithCallback(std::string&& data,
890 const boost::urls::url_view_base& destUrl,
Carson Labrado039a47e2022-04-05 16:03:20 +0000891 const boost::beast::http::fields& httpHeader,
Carson Labrado244256c2022-04-27 17:16:32 +0000892 const boost::beast::http::verb verb,
Ed Tanous6b3db602022-06-28 19:41:44 -0700893 const std::function<void(Response&)>& resHandler)
Carson Labrado039a47e2022-04-05 16:03:20 +0000894 {
Ed Tanousa716aa72023-08-01 11:35:53 -0700895 std::string clientKey = std::format("{}://{}", destUrl.scheme(),
896 destUrl.encoded_host_and_port());
Carson Labradod14a48f2023-02-22 00:24:54 +0000897 auto pool = connectionPools.try_emplace(clientKey);
898 if (pool.first->second == nullptr)
Carson Labradof52c03c2022-03-23 18:50:15 +0000899 {
Carson Labradod14a48f2023-02-22 00:24:54 +0000900 pool.first->second = std::make_shared<ConnectionPool>(
Ed Tanousa716aa72023-08-01 11:35:53 -0700901 ioc, clientKey, connPolicy, destUrl);
Carson Labradof52c03c2022-03-23 18:50:15 +0000902 }
Ed Tanous27b0cf92023-08-07 12:02:40 -0700903 // Send the data using either the existing connection pool or the
904 // newly created connection pool
Ed Tanousa716aa72023-08-01 11:35:53 -0700905 pool.first->second->sendData(std::move(data), destUrl, httpHeader, verb,
Carson Labradod14a48f2023-02-22 00:24:54 +0000906 resHandler);
Carson Labradof52c03c2022-03-23 18:50:15 +0000907 }
908};
AppaRao Pulibd030d02020-03-20 03:34:29 +0530909} // namespace crow