blob: d82c566a06ca3cbfcfab172fecc9a1e72e98605b [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"
19#include "http_response.hpp"
Ed Tanous3ccb3ad2023-01-13 17:40:03 -080020#include "logging.hpp"
21#include "ssl_key_handler.hpp"
Nan Zhou77665bd2022-10-12 20:28:58 +000022
Ed Tanous0d5f5cf2022-03-12 15:30:55 -080023#include <boost/asio/connect.hpp>
Ed Tanousbb49eb52022-06-28 12:02:42 -070024#include <boost/asio/io_context.hpp>
Sunitha Harish29a82b02021-02-18 15:54:16 +053025#include <boost/asio/ip/address.hpp>
26#include <boost/asio/ip/basic_endpoint.hpp>
Ed Tanousbb49eb52022-06-28 12:02:42 -070027#include <boost/asio/ip/tcp.hpp>
AppaRao Pulie38778a2022-06-27 23:09:03 +000028#include <boost/asio/ssl/context.hpp>
29#include <boost/asio/ssl/error.hpp>
Ed Tanousd43cd0c2020-09-30 20:46:53 -070030#include <boost/asio/steady_timer.hpp>
31#include <boost/beast/core/flat_buffer.hpp>
Ed Tanousbb49eb52022-06-28 12:02:42 -070032#include <boost/beast/core/flat_static_buffer.hpp>
Ed Tanousd43cd0c2020-09-30 20:46:53 -070033#include <boost/beast/http/message.hpp>
Ed Tanousbb49eb52022-06-28 12:02:42 -070034#include <boost/beast/http/parser.hpp>
35#include <boost/beast/http/read.hpp>
36#include <boost/beast/http/string_body.hpp>
37#include <boost/beast/http/write.hpp>
AppaRao Pulie38778a2022-06-27 23:09:03 +000038#include <boost/beast/ssl/ssl_stream.hpp>
AppaRao Pulibd030d02020-03-20 03:34:29 +053039#include <boost/beast/version.hpp>
Carson Labradof52c03c2022-03-23 18:50:15 +000040#include <boost/container/devector.hpp>
Ed Tanousbb49eb52022-06-28 12:02:42 -070041#include <boost/system/error_code.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050042
AppaRao Pulibd030d02020-03-20 03:34:29 +053043#include <cstdlib>
44#include <functional>
45#include <iostream>
46#include <memory>
AppaRao Puli2a5689a2020-04-29 15:24:31 +053047#include <queue>
AppaRao Pulibd030d02020-03-20 03:34:29 +053048#include <string>
49
50namespace crow
51{
52
Carson Labrado66d90c22022-12-07 22:34:33 +000053// With Redfish Aggregation it is assumed we will connect to another instance
54// of BMCWeb which can handle 100 simultaneous connections.
55constexpr size_t maxPoolSize = 20;
56constexpr size_t maxRequestQueueSize = 500;
Carson Labrado17dcc312022-07-28 22:17:28 +000057constexpr unsigned int httpReadBodyLimit = 131072;
Carson Labrado4d942722022-06-22 22:16:10 +000058constexpr unsigned int httpReadBufferSize = 4096;
AppaRao Puli2a5689a2020-04-29 15:24:31 +053059
AppaRao Pulibd030d02020-03-20 03:34:29 +053060enum class ConnState
61{
AppaRao Puli2a5689a2020-04-29 15:24:31 +053062 initialized,
Sunitha Harish29a82b02021-02-18 15:54:16 +053063 resolveInProgress,
64 resolveFailed,
AppaRao Puli2a5689a2020-04-29 15:24:31 +053065 connectInProgress,
66 connectFailed,
AppaRao Pulibd030d02020-03-20 03:34:29 +053067 connected,
AppaRao Pulie38778a2022-06-27 23:09:03 +000068 handshakeInProgress,
69 handshakeFailed,
AppaRao Puli2a5689a2020-04-29 15:24:31 +053070 sendInProgress,
71 sendFailed,
Sunitha Harish6eaa1d22021-02-19 13:38:31 +053072 recvInProgress,
AppaRao Puli2a5689a2020-04-29 15:24:31 +053073 recvFailed,
74 idle,
Ayushi Smritife44eb02020-05-15 15:24:45 +053075 closed,
Sunitha Harish6eaa1d22021-02-19 13:38:31 +053076 suspended,
77 terminated,
78 abortConnection,
AppaRao Pulie38778a2022-06-27 23:09:03 +000079 sslInitFailed,
Sunitha Harish6eaa1d22021-02-19 13:38:31 +053080 retry
AppaRao Pulibd030d02020-03-20 03:34:29 +053081};
82
Carson Labradoa7a80292022-06-01 16:01:52 +000083static inline boost::system::error_code
84 defaultRetryHandler(unsigned int respCode)
85{
86 // As a default, assume 200X is alright
Ed Tanous62598e32023-07-17 17:06:25 -070087 BMCWEB_LOG_DEBUG("Using default check for response code validity");
Carson Labradoa7a80292022-06-01 16:01:52 +000088 if ((respCode < 200) || (respCode >= 300))
89 {
90 return boost::system::errc::make_error_code(
91 boost::system::errc::result_out_of_range);
92 }
93
94 // Return 0 if the response code is valid
95 return boost::system::errc::make_error_code(boost::system::errc::success);
96};
97
Carson Labradof52c03c2022-03-23 18:50:15 +000098// We need to allow retry information to be set before a message has been sent
99// and a connection pool has been created
Carson Labradod14a48f2023-02-22 00:24:54 +0000100struct ConnectionPolicy
Carson Labradof52c03c2022-03-23 18:50:15 +0000101{
102 uint32_t maxRetryAttempts = 5;
Carson Labradod14a48f2023-02-22 00:24:54 +0000103
104 // the max size of requests in bytes. 0 for unlimited
105 boost::optional<uint64_t> requestByteLimit = httpReadBodyLimit;
106
107 size_t maxConnections = 1;
108
Carson Labradof52c03c2022-03-23 18:50:15 +0000109 std::string retryPolicyAction = "TerminateAfterRetries";
Carson Labradod14a48f2023-02-22 00:24:54 +0000110
111 std::chrono::seconds retryIntervalSecs = std::chrono::seconds(0);
Carson Labradoa7a80292022-06-01 16:01:52 +0000112 std::function<boost::system::error_code(unsigned int respCode)>
113 invalidResp = defaultRetryHandler;
Carson Labradof52c03c2022-03-23 18:50:15 +0000114};
115
116struct PendingRequest
117{
Carson Labrado244256c2022-04-27 17:16:32 +0000118 boost::beast::http::request<boost::beast::http::string_body> req;
Carson Labrado039a47e2022-04-05 16:03:20 +0000119 std::function<void(bool, uint32_t, Response&)> callback;
Carson Labrado039a47e2022-04-05 16:03:20 +0000120 PendingRequest(
Ed Tanous8a592812022-06-04 09:06:59 -0700121 boost::beast::http::request<boost::beast::http::string_body>&& reqIn,
Carson Labradod14a48f2023-02-22 00:24:54 +0000122 const std::function<void(bool, uint32_t, Response&)>& callbackIn) :
Ed Tanous8a592812022-06-04 09:06:59 -0700123 req(std::move(reqIn)),
Carson Labradod14a48f2023-02-22 00:24:54 +0000124 callback(callbackIn)
Carson Labradof52c03c2022-03-23 18:50:15 +0000125 {}
126};
127
128class ConnectionInfo : public std::enable_shared_from_this<ConnectionInfo>
AppaRao Pulibd030d02020-03-20 03:34:29 +0530129{
130 private:
Carson Labradof52c03c2022-03-23 18:50:15 +0000131 ConnState state = ConnState::initialized;
132 uint32_t retryCount = 0;
Carson Labradof52c03c2022-03-23 18:50:15 +0000133 std::string subId;
Carson Labradod14a48f2023-02-22 00:24:54 +0000134 std::shared_ptr<ConnectionPolicy> connPolicy;
Carson Labradof52c03c2022-03-23 18:50:15 +0000135 std::string host;
136 uint16_t port;
137 uint32_t connId;
138
Carson Labradof52c03c2022-03-23 18:50:15 +0000139 // Data buffers
AppaRao Pulibd030d02020-03-20 03:34:29 +0530140 boost::beast::http::request<boost::beast::http::string_body> req;
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530141 std::optional<
142 boost::beast::http::response_parser<boost::beast::http::string_body>>
143 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
150#ifdef BMCWEB_DBUS_DNS_RESOLVER
Ed Tanouse1452be2021-10-04 17:03:52 -0700151 using Resolver = async_resolve::Resolver;
Ed Tanousf8ca6d72022-06-28 12:12:03 -0700152#else
153 using Resolver = boost::asio::ip::tcp::resolver;
154#endif
155 Resolver resolver;
156
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800157 boost::asio::ip::tcp::socket conn;
158 std::optional<boost::beast::ssl_stream<boost::asio::ip::tcp::socket&>>
159 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 Tanous62598e32023-07-17 17:06:25 -0700168 BMCWEB_LOG_DEBUG("Trying to resolve: {}:{}, id: {}", host,
169 std::to_string(port), std::to_string(connId));
Sunitha Harish29a82b02021-02-18 15:54:16 +0530170
Ed Tanousf8ca6d72022-06-28 12:12:03 -0700171 resolver.async_resolve(host, std::to_string(port),
172 std::bind_front(&ConnectionInfo::afterResolve,
173 this, shared_from_this()));
Sunitha Harish29a82b02021-02-18 15:54:16 +0530174 }
175
Ed Tanousf8ca6d72022-06-28 12:12:03 -0700176 void afterResolve(const std::shared_ptr<ConnectionInfo>& /*self*/,
177 const boost::system::error_code& ec,
178 const Resolver::results_type& endpointList)
AppaRao Pulibd030d02020-03-20 03:34:29 +0530179 {
Ed Tanous3d36e3a2022-08-19 15:54:04 -0700180 if (ec || (endpointList.empty()))
181 {
Ed Tanous62598e32023-07-17 17:06:25 -0700182 BMCWEB_LOG_ERROR("Resolve failed: {} {}:{}", ec.message(), host,
183 std::to_string(port));
Ed Tanous3d36e3a2022-08-19 15:54:04 -0700184 state = ConnState::resolveFailed;
185 waitAndRetry();
186 return;
187 }
Ed Tanous62598e32023-07-17 17:06:25 -0700188 BMCWEB_LOG_DEBUG("Resolved {}:{}, id: {}", host, std::to_string(port),
189 std::to_string(connId));
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530190 state = ConnState::connectInProgress;
191
Ed Tanous62598e32023-07-17 17:06:25 -0700192 BMCWEB_LOG_DEBUG("Trying to connect to: {}:{}, id: {}", host,
193 std::to_string(port), std::to_string(connId));
Sunitha Harish29a82b02021-02-18 15:54:16 +0530194
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800195 timer.expires_after(std::chrono::seconds(30));
196 timer.async_wait(std::bind_front(onTimeout, weak_from_this()));
197
198 boost::asio::async_connect(
199 conn, endpointList,
200 std::bind_front(&ConnectionInfo::afterConnect, this,
201 shared_from_this()));
AppaRao Pulie38778a2022-06-27 23:09:03 +0000202 }
203
204 void afterConnect(const std::shared_ptr<ConnectionInfo>& /*self*/,
Ed Tanous81c4e332023-05-18 10:30:34 -0700205 const boost::beast::error_code& ec,
AppaRao Pulie38778a2022-06-27 23:09:03 +0000206 const boost::asio::ip::tcp::endpoint& endpoint)
207 {
Carson Labrado513d1ff2022-07-19 00:38:15 +0000208 // The operation already timed out. We don't want do continue down
209 // this branch
210 if (ec && ec == boost::asio::error::operation_aborted)
211 {
212 return;
213 }
214
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800215 timer.cancel();
AppaRao Pulie38778a2022-06-27 23:09:03 +0000216 if (ec)
217 {
Ed Tanous62598e32023-07-17 17:06:25 -0700218 BMCWEB_LOG_ERROR("Connect {}:{}, id: {} failed: {}",
219 endpoint.address().to_string(),
220 std::to_string(endpoint.port()),
221 std::to_string(connId), ec.message());
AppaRao Pulie38778a2022-06-27 23:09:03 +0000222 state = ConnState::connectFailed;
223 waitAndRetry();
224 return;
225 }
Ed Tanous62598e32023-07-17 17:06:25 -0700226 BMCWEB_LOG_DEBUG(
227 "Connected to: {}:{}, id: {}", endpoint.address().to_string(),
228 std::to_string(endpoint.port()), std::to_string(connId));
AppaRao Pulie38778a2022-06-27 23:09:03 +0000229 if (sslConn)
230 {
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800231 doSslHandshake();
AppaRao Pulie38778a2022-06-27 23:09:03 +0000232 return;
233 }
234 state = ConnState::connected;
235 sendMessage();
236 }
237
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800238 void doSslHandshake()
AppaRao Pulie38778a2022-06-27 23:09:03 +0000239 {
240 if (!sslConn)
241 {
242 return;
243 }
244 state = ConnState::handshakeInProgress;
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800245 timer.expires_after(std::chrono::seconds(30));
246 timer.async_wait(std::bind_front(onTimeout, weak_from_this()));
AppaRao Pulie38778a2022-06-27 23:09:03 +0000247 sslConn->async_handshake(
248 boost::asio::ssl::stream_base::client,
249 std::bind_front(&ConnectionInfo::afterSslHandshake, this,
250 shared_from_this()));
251 }
252
253 void afterSslHandshake(const std::shared_ptr<ConnectionInfo>& /*self*/,
Ed Tanous81c4e332023-05-18 10:30:34 -0700254 const boost::beast::error_code& ec)
AppaRao Pulie38778a2022-06-27 23:09:03 +0000255 {
Carson Labrado513d1ff2022-07-19 00:38:15 +0000256 // The operation already timed out. We don't want do continue down
257 // this branch
258 if (ec && ec == boost::asio::error::operation_aborted)
259 {
260 return;
261 }
262
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800263 timer.cancel();
AppaRao Pulie38778a2022-06-27 23:09:03 +0000264 if (ec)
265 {
Ed Tanous62598e32023-07-17 17:06:25 -0700266 BMCWEB_LOG_ERROR("SSL Handshake failed - id: {} error: {}",
267 std::to_string(connId), ec.message());
AppaRao Pulie38778a2022-06-27 23:09:03 +0000268 state = ConnState::handshakeFailed;
269 waitAndRetry();
270 return;
271 }
Ed Tanous62598e32023-07-17 17:06:25 -0700272 BMCWEB_LOG_DEBUG("SSL Handshake successful - id: {}",
273 std::to_string(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
286 // Send the HTTP request to the remote host
AppaRao Pulie38778a2022-06-27 23:09:03 +0000287 if (sslConn)
288 {
289 boost::beast::http::async_write(
290 *sslConn, req,
291 std::bind_front(&ConnectionInfo::afterWrite, this,
292 shared_from_this()));
293 }
294 else
295 {
296 boost::beast::http::async_write(
297 conn, req,
298 std::bind_front(&ConnectionInfo::afterWrite, this,
299 shared_from_this()));
300 }
301 }
AppaRao Pulibd030d02020-03-20 03:34:29 +0530302
AppaRao Pulie38778a2022-06-27 23:09:03 +0000303 void afterWrite(const std::shared_ptr<ConnectionInfo>& /*self*/,
304 const boost::beast::error_code& ec, size_t bytesTransferred)
305 {
Carson Labrado513d1ff2022-07-19 00:38:15 +0000306 // The operation already timed out. We don't want do continue down
307 // this branch
308 if (ec && ec == boost::asio::error::operation_aborted)
309 {
310 return;
311 }
312
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800313 timer.cancel();
AppaRao Pulie38778a2022-06-27 23:09:03 +0000314 if (ec)
315 {
Ed Tanous62598e32023-07-17 17:06:25 -0700316 BMCWEB_LOG_ERROR("sendMessage() failed: {} {}:{}", ec.message(),
317 host, std::to_string(port));
AppaRao Pulie38778a2022-06-27 23:09:03 +0000318 state = ConnState::sendFailed;
319 waitAndRetry();
320 return;
321 }
Ed Tanous62598e32023-07-17 17:06:25 -0700322 BMCWEB_LOG_DEBUG("sendMessage() bytes transferred: {}",
323 bytesTransferred);
AppaRao Pulie38778a2022-06-27 23:09:03 +0000324
325 recvMessage();
AppaRao Pulibd030d02020-03-20 03:34:29 +0530326 }
327
328 void recvMessage()
329 {
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530330 state = ConnState::recvInProgress;
331
332 parser.emplace(std::piecewise_construct, std::make_tuple());
Carson Labradod14a48f2023-02-22 00:24:54 +0000333
334 parser->body_limit(connPolicy->requestByteLimit);
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530335
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800336 timer.expires_after(std::chrono::seconds(30));
337 timer.async_wait(std::bind_front(onTimeout, weak_from_this()));
338
AppaRao Pulibd030d02020-03-20 03:34:29 +0530339 // Receive the HTTP response
AppaRao Pulie38778a2022-06-27 23:09:03 +0000340 if (sslConn)
341 {
342 boost::beast::http::async_read(
343 *sslConn, buffer, *parser,
344 std::bind_front(&ConnectionInfo::afterRead, this,
345 shared_from_this()));
346 }
347 else
348 {
349 boost::beast::http::async_read(
350 conn, buffer, *parser,
351 std::bind_front(&ConnectionInfo::afterRead, this,
352 shared_from_this()));
353 }
354 }
AppaRao Pulibd030d02020-03-20 03:34:29 +0530355
AppaRao Pulie38778a2022-06-27 23:09:03 +0000356 void afterRead(const std::shared_ptr<ConnectionInfo>& /*self*/,
357 const boost::beast::error_code& ec,
358 const std::size_t& bytesTransferred)
359 {
Carson Labrado513d1ff2022-07-19 00:38:15 +0000360 // The operation already timed out. We don't want do continue down
361 // this branch
362 if (ec && ec == boost::asio::error::operation_aborted)
363 {
364 return;
365 }
366
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800367 timer.cancel();
AppaRao Pulie38778a2022-06-27 23:09:03 +0000368 if (ec && ec != boost::asio::ssl::error::stream_truncated)
369 {
Ed Tanous62598e32023-07-17 17:06:25 -0700370 BMCWEB_LOG_ERROR("recvMessage() failed: {} from {}:{}",
371 ec.message(), host, std::to_string(port));
AppaRao Pulie38778a2022-06-27 23:09:03 +0000372 state = ConnState::recvFailed;
373 waitAndRetry();
374 return;
375 }
Ed Tanous62598e32023-07-17 17:06:25 -0700376 BMCWEB_LOG_DEBUG("recvMessage() bytes transferred: {}",
377 bytesTransferred);
378 BMCWEB_LOG_DEBUG("recvMessage() data: {}", parser->get().body());
AppaRao Pulie38778a2022-06-27 23:09:03 +0000379
380 unsigned int respCode = parser->get().result_int();
Ed Tanous62598e32023-07-17 17:06:25 -0700381 BMCWEB_LOG_DEBUG("recvMessage() Header Response Code: {}", respCode);
AppaRao Pulie38778a2022-06-27 23:09:03 +0000382
383 // Make sure the received response code is valid as defined by
384 // the associated retry policy
Carson Labradod14a48f2023-02-22 00:24:54 +0000385 if (connPolicy->invalidResp(respCode))
AppaRao Pulie38778a2022-06-27 23:09:03 +0000386 {
387 // The listener failed to receive the Sent-Event
Ed Tanous62598e32023-07-17 17:06:25 -0700388 BMCWEB_LOG_ERROR(
389 "recvMessage() Listener Failed to "
390 "receive Sent-Event. Header Response Code: {} from {}:{}",
391 respCode, host, std::to_string(port));
AppaRao Pulie38778a2022-06-27 23:09:03 +0000392 state = ConnState::recvFailed;
393 waitAndRetry();
394 return;
395 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700396
AppaRao Pulie38778a2022-06-27 23:09:03 +0000397 // Send is successful
398 // Reset the counter just in case this was after retrying
399 retryCount = 0;
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530400
AppaRao Pulie38778a2022-06-27 23:09:03 +0000401 // Keep the connection alive if server supports it
402 // Else close the connection
Ed Tanous62598e32023-07-17 17:06:25 -0700403 BMCWEB_LOG_DEBUG("recvMessage() keepalive : {}", parser->keep_alive());
AppaRao Pulibd030d02020-03-20 03:34:29 +0530404
AppaRao Pulie38778a2022-06-27 23:09:03 +0000405 // Copy the response into a Response object so that it can be
406 // processed by the callback function.
AppaRao Pulie38778a2022-06-27 23:09:03 +0000407 res.stringResponse = parser->release();
408 callback(parser->keep_alive(), connId, res);
Carson Labrado513d1ff2022-07-19 00:38:15 +0000409 res.clear();
AppaRao Pulibd030d02020-03-20 03:34:29 +0530410 }
411
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800412 static void onTimeout(const std::weak_ptr<ConnectionInfo>& weakSelf,
Ed Tanous5e7e2dc2023-02-16 10:37:01 -0800413 const boost::system::error_code& ec)
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800414 {
415 if (ec == boost::asio::error::operation_aborted)
416 {
Ed Tanous62598e32023-07-17 17:06:25 -0700417 BMCWEB_LOG_DEBUG(
418 "async_wait failed since the operation is aborted");
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800419 return;
420 }
421 if (ec)
422 {
Ed Tanous62598e32023-07-17 17:06:25 -0700423 BMCWEB_LOG_ERROR("async_wait failed: {}", ec.message());
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800424 // If the timer fails, we need to close the socket anyway, same as
425 // if it expired.
426 }
427 std::shared_ptr<ConnectionInfo> self = weakSelf.lock();
428 if (self == nullptr)
429 {
430 return;
431 }
432 self->waitAndRetry();
433 }
434
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530435 void waitAndRetry()
AppaRao Pulibd030d02020-03-20 03:34:29 +0530436 {
Carson Labradod14a48f2023-02-22 00:24:54 +0000437 if ((retryCount >= connPolicy->maxRetryAttempts) ||
AppaRao Pulie38778a2022-06-27 23:09:03 +0000438 (state == ConnState::sslInitFailed))
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530439 {
Ed Tanous62598e32023-07-17 17:06:25 -0700440 BMCWEB_LOG_ERROR("Maximum number of retries reached. {}:{}", host,
441 std::to_string(port));
442 BMCWEB_LOG_DEBUG("Retry policy: {}", connPolicy->retryPolicyAction);
Carson Labrado039a47e2022-04-05 16:03:20 +0000443
Carson Labradod14a48f2023-02-22 00:24:54 +0000444 if (connPolicy->retryPolicyAction == "TerminateAfterRetries")
Ayushi Smritife44eb02020-05-15 15:24:45 +0530445 {
446 // TODO: delete subscription
447 state = ConnState::terminated;
Ayushi Smritife44eb02020-05-15 15:24:45 +0530448 }
Carson Labradod14a48f2023-02-22 00:24:54 +0000449 if (connPolicy->retryPolicyAction == "SuspendRetries")
Ayushi Smritife44eb02020-05-15 15:24:45 +0530450 {
451 state = ConnState::suspended;
Ayushi Smritife44eb02020-05-15 15:24:45 +0530452 }
Carson Labrado513d1ff2022-07-19 00:38:15 +0000453
454 // We want to return a 502 to indicate there was an error with
455 // the external server
456 res.result(boost::beast::http::status::bad_gateway);
457 callback(false, connId, res);
458 res.clear();
459
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530460 // Reset the retrycount to zero so that client can try connecting
461 // again if needed
Ed Tanous3174e4d2020-10-07 11:41:22 -0700462 retryCount = 0;
Ayushi Smritife44eb02020-05-15 15:24:45 +0530463 return;
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530464 }
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530465
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530466 retryCount++;
467
Ed Tanous62598e32023-07-17 17:06:25 -0700468 BMCWEB_LOG_DEBUG("Attempt retry after {} seconds. RetryCount = {}",
469 std::to_string(connPolicy->retryIntervalSecs.count()),
470 retryCount);
Carson Labradod14a48f2023-02-22 00:24:54 +0000471 timer.expires_after(connPolicy->retryIntervalSecs);
Ed Tanous3d36e3a2022-08-19 15:54:04 -0700472 timer.async_wait(std::bind_front(&ConnectionInfo::onTimerDone, this,
473 shared_from_this()));
474 }
Sunitha Harish6eaa1d22021-02-19 13:38:31 +0530475
Ed Tanous3d36e3a2022-08-19 15:54:04 -0700476 void onTimerDone(const std::shared_ptr<ConnectionInfo>& /*self*/,
477 const boost::system::error_code& ec)
478 {
479 if (ec == boost::asio::error::operation_aborted)
480 {
Ed Tanous62598e32023-07-17 17:06:25 -0700481 BMCWEB_LOG_DEBUG(
482 "async_wait failed since the operation is aborted{}",
483 ec.message());
Ed Tanous3d36e3a2022-08-19 15:54:04 -0700484 }
485 else if (ec)
486 {
Ed Tanous62598e32023-07-17 17:06:25 -0700487 BMCWEB_LOG_ERROR("async_wait failed: {}", ec.message());
Ed Tanous3d36e3a2022-08-19 15:54:04 -0700488 // Ignore the error and continue the retry loop to attempt
489 // sending the event as per the retry policy
490 }
491
492 // Let's close the connection and restart from resolve.
493 doClose(true);
Ayushi Smritife44eb02020-05-15 15:24:45 +0530494 }
495
AppaRao Pulie38778a2022-06-27 23:09:03 +0000496 void shutdownConn(bool retry)
Ayushi Smritife44eb02020-05-15 15:24:45 +0530497 {
Carson Labradof52c03c2022-03-23 18:50:15 +0000498 boost::beast::error_code ec;
Ed Tanous0d5f5cf2022-03-12 15:30:55 -0800499 conn.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
Carson Labradof52c03c2022-03-23 18:50:15 +0000500 conn.close();
501
502 // not_connected happens sometimes so don't bother reporting it.
503 if (ec && ec != boost::beast::errc::not_connected)
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530504 {
Ed Tanous62598e32023-07-17 17:06:25 -0700505 BMCWEB_LOG_ERROR("{}:{}, id: {} shutdown failed: {}", host,
506 std::to_string(port), std::to_string(connId),
507 ec.message());
Carson Labradof52c03c2022-03-23 18:50:15 +0000508 }
Carson Labrado5cab68f2022-07-11 22:26:21 +0000509 else
510 {
Ed Tanous62598e32023-07-17 17:06:25 -0700511 BMCWEB_LOG_DEBUG("{}:{}, id: {} closed gracefully", host,
512 std::to_string(port), std::to_string(connId));
Carson Labrado5cab68f2022-07-11 22:26:21 +0000513 }
Ed Tanousca723762022-06-28 19:40:39 -0700514
Carson Labrado513d1ff2022-07-19 00:38:15 +0000515 if (retry)
AppaRao Pulie38778a2022-06-27 23:09:03 +0000516 {
Carson Labrado513d1ff2022-07-19 00:38:15 +0000517 // Now let's try to resend the data
518 state = ConnState::retry;
519 doResolve();
520 }
521 else
522 {
523 state = ConnState::closed;
AppaRao Pulie38778a2022-06-27 23:09:03 +0000524 }
Carson Labradof52c03c2022-03-23 18:50:15 +0000525 }
526
AppaRao Pulie38778a2022-06-27 23:09:03 +0000527 void doClose(bool retry = false)
Carson Labradof52c03c2022-03-23 18:50:15 +0000528 {
AppaRao Pulie38778a2022-06-27 23:09:03 +0000529 if (!sslConn)
530 {
531 shutdownConn(retry);
532 return;
533 }
Carson Labradof52c03c2022-03-23 18:50:15 +0000534
AppaRao Pulie38778a2022-06-27 23:09:03 +0000535 sslConn->async_shutdown(
536 std::bind_front(&ConnectionInfo::afterSslShutdown, this,
537 shared_from_this(), retry));
538 }
539
540 void afterSslShutdown(const std::shared_ptr<ConnectionInfo>& /*self*/,
541 bool retry, const boost::system::error_code& ec)
542 {
AppaRao Pulie38778a2022-06-27 23:09:03 +0000543 if (ec)
Carson Labradof52c03c2022-03-23 18:50:15 +0000544 {
Ed Tanous62598e32023-07-17 17:06:25 -0700545 BMCWEB_LOG_ERROR("{}:{}, id: {} shutdown failed: {}", host,
546 std::to_string(port), std::to_string(connId),
547 ec.message());
Carson Labradof52c03c2022-03-23 18:50:15 +0000548 }
Carson Labrado5cab68f2022-07-11 22:26:21 +0000549 else
550 {
Ed Tanous62598e32023-07-17 17:06:25 -0700551 BMCWEB_LOG_DEBUG("{}:{}, id: {} closed gracefully", host,
552 std::to_string(port), std::to_string(connId));
Carson Labrado5cab68f2022-07-11 22:26:21 +0000553 }
AppaRao Pulie38778a2022-06-27 23:09:03 +0000554 shutdownConn(retry);
555 }
Ed Tanousca723762022-06-28 19:40:39 -0700556
AppaRao Pulie38778a2022-06-27 23:09:03 +0000557 void setCipherSuiteTLSext()
558 {
559 if (!sslConn)
560 {
561 return;
562 }
563 // NOTE: The SSL_set_tlsext_host_name is defined in tlsv1.h header
564 // file but its having old style casting (name is cast to void*).
565 // Since bmcweb compiler treats all old-style-cast as error, its
566 // causing the build failure. So replaced the same macro inline and
567 // did corrected the code by doing static_cast to viod*. This has to
568 // be fixed in openssl library in long run. Set SNI Hostname (many
569 // hosts need this to handshake successfully)
570 if (SSL_ctrl(sslConn->native_handle(), SSL_CTRL_SET_TLSEXT_HOSTNAME,
571 TLSEXT_NAMETYPE_host_name,
572 static_cast<void*>(&host.front())) == 0)
573
574 {
575 boost::beast::error_code ec{static_cast<int>(::ERR_get_error()),
576 boost::asio::error::get_ssl_category()};
577
Ed Tanous62598e32023-07-17 17:06:25 -0700578 BMCWEB_LOG_ERROR(
579 "SSL_set_tlsext_host_name {}:{}, id: {} failed: {}", host, port,
580 std::to_string(connId), ec.message());
AppaRao Pulie38778a2022-06-27 23:09:03 +0000581 // Set state as sslInit failed so that we close the connection
582 // and take appropriate action as per retry configuration.
583 state = ConnState::sslInitFailed;
584 waitAndRetry();
585 return;
586 }
AppaRao Pulibd030d02020-03-20 03:34:29 +0530587 }
588
589 public:
Carson Labradod14a48f2023-02-22 00:24:54 +0000590 explicit ConnectionInfo(
591 boost::asio::io_context& iocIn, const std::string& idIn,
592 const std::shared_ptr<ConnectionPolicy>& connPolicyIn,
593 const std::string& destIPIn, uint16_t destPortIn, bool useSSL,
594 unsigned int connIdIn) :
Ed Tanous8a592812022-06-04 09:06:59 -0700595 subId(idIn),
Carson Labradod14a48f2023-02-22 00:24:54 +0000596 connPolicy(connPolicyIn), host(destIPIn), port(destPortIn),
Ed Tanousf8ca6d72022-06-28 12:12:03 -0700597 connId(connIdIn), resolver(iocIn), conn(iocIn), timer(iocIn)
AppaRao Pulie38778a2022-06-27 23:09:03 +0000598 {
599 if (useSSL)
600 {
601 std::optional<boost::asio::ssl::context> sslCtx =
602 ensuressl::getSSLClientContext();
603
604 if (!sslCtx)
605 {
Ed Tanous62598e32023-07-17 17:06:25 -0700606 BMCWEB_LOG_ERROR("prepareSSLContext failed - {}:{}, id: {}",
607 host, port, std::to_string(connId));
AppaRao Pulie38778a2022-06-27 23:09:03 +0000608 // Don't retry if failure occurs while preparing SSL context
609 // such as certificate is invalid or set cipher failure or set
610 // host name failure etc... Setting conn state to sslInitFailed
611 // and connection state will be transitioned to next state
612 // depending on retry policy set by subscription.
613 state = ConnState::sslInitFailed;
614 waitAndRetry();
615 return;
616 }
617 sslConn.emplace(conn, *sslCtx);
618 setCipherSuiteTLSext();
619 }
620 }
Carson Labradof52c03c2022-03-23 18:50:15 +0000621};
AppaRao Pulibd030d02020-03-20 03:34:29 +0530622
Carson Labradof52c03c2022-03-23 18:50:15 +0000623class ConnectionPool : public std::enable_shared_from_this<ConnectionPool>
624{
625 private:
626 boost::asio::io_context& ioc;
AppaRao Pulie38778a2022-06-27 23:09:03 +0000627 std::string id;
Carson Labradod14a48f2023-02-22 00:24:54 +0000628 std::shared_ptr<ConnectionPolicy> connPolicy;
AppaRao Pulie38778a2022-06-27 23:09:03 +0000629 std::string destIP;
630 uint16_t destPort;
631 bool useSSL;
Carson Labradof52c03c2022-03-23 18:50:15 +0000632 std::vector<std::shared_ptr<ConnectionInfo>> connections;
633 boost::container::devector<PendingRequest> requestQueue;
634
635 friend class HttpClient;
636
Carson Labrado244256c2022-04-27 17:16:32 +0000637 // Configure a connections's request, callback, and retry info in
638 // preparation to begin sending the request
Carson Labradof52c03c2022-03-23 18:50:15 +0000639 void setConnProps(ConnectionInfo& conn)
AppaRao Pulibd030d02020-03-20 03:34:29 +0530640 {
Carson Labradof52c03c2022-03-23 18:50:15 +0000641 if (requestQueue.empty())
AppaRao Pulibd030d02020-03-20 03:34:29 +0530642 {
Ed Tanous62598e32023-07-17 17:06:25 -0700643 BMCWEB_LOG_ERROR(
644 "setConnProps() should not have been called when requestQueue is empty");
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530645 return;
AppaRao Pulibd030d02020-03-20 03:34:29 +0530646 }
AppaRao Pulibd030d02020-03-20 03:34:29 +0530647
Carson Labrado244256c2022-04-27 17:16:32 +0000648 auto nextReq = requestQueue.front();
Carson Labrado244256c2022-04-27 17:16:32 +0000649 conn.req = std::move(nextReq.req);
650 conn.callback = std::move(nextReq.callback);
Carson Labradof52c03c2022-03-23 18:50:15 +0000651
Ed Tanous62598e32023-07-17 17:06:25 -0700652 BMCWEB_LOG_DEBUG("Setting properties for connection {}:{}, id: {}",
653 conn.host, std::to_string(conn.port),
654 std::to_string(conn.connId));
Carson Labradof52c03c2022-03-23 18:50:15 +0000655
656 // We can remove the request from the queue at this point
657 requestQueue.pop_front();
658 }
659
Carson Labradof52c03c2022-03-23 18:50:15 +0000660 // Gets called as part of callback after request is sent
661 // Reuses the connection if there are any requests waiting to be sent
662 // Otherwise closes the connection if it is not a keep-alive
663 void sendNext(bool keepAlive, uint32_t connId)
664 {
665 auto conn = connections[connId];
Carson Labrado46a81462022-04-27 21:11:37 +0000666
667 // Allow the connection's handler to be deleted
668 // This is needed because of Redfish Aggregation passing an
669 // AsyncResponse shared_ptr to this callback
670 conn->callback = nullptr;
671
Carson Labradof52c03c2022-03-23 18:50:15 +0000672 // Reuse the connection to send the next request in the queue
673 if (!requestQueue.empty())
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530674 {
Ed Tanous62598e32023-07-17 17:06:25 -0700675 BMCWEB_LOG_DEBUG(
676 "{} requests remaining in queue for {}:{}, reusing connnection {}",
677 std::to_string(requestQueue.size()), destIP,
678 std::to_string(destPort), std::to_string(connId));
Carson Labradof52c03c2022-03-23 18:50:15 +0000679
680 setConnProps(*conn);
681
682 if (keepAlive)
683 {
684 conn->sendMessage();
685 }
686 else
687 {
688 // Server is not keep-alive enabled so we need to close the
689 // connection and then start over from resolve
690 conn->doClose();
691 conn->doResolve();
692 }
693 return;
694 }
695
696 // No more messages to send so close the connection if necessary
697 if (keepAlive)
698 {
699 conn->state = ConnState::idle;
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530700 }
701 else
702 {
Carson Labradof52c03c2022-03-23 18:50:15 +0000703 // Abort the connection since server is not keep-alive enabled
704 conn->state = ConnState::abortConnection;
705 conn->doClose();
AppaRao Puli2a5689a2020-04-29 15:24:31 +0530706 }
AppaRao Pulibd030d02020-03-20 03:34:29 +0530707 }
708
AppaRao Puli5e44e3d2021-03-16 15:37:24 +0000709 void sendData(std::string&& data, const std::string& destUri,
Carson Labrado244256c2022-04-27 17:16:32 +0000710 const boost::beast::http::fields& httpHeader,
711 const boost::beast::http::verb verb,
Ed Tanous6b3db602022-06-28 19:41:44 -0700712 const std::function<void(Response&)>& resHandler)
Ayushi Smritife44eb02020-05-15 15:24:45 +0530713 {
Carson Labrado244256c2022-04-27 17:16:32 +0000714 // Construct the request to be sent
715 boost::beast::http::request<boost::beast::http::string_body> thisReq(
716 verb, destUri, 11, "", httpHeader);
717 thisReq.set(boost::beast::http::field::host, destIP);
718 thisReq.keep_alive(true);
719 thisReq.body() = std::move(data);
720 thisReq.prepare_payload();
Ed Tanous3d36e3a2022-08-19 15:54:04 -0700721 auto cb = std::bind_front(&ConnectionPool::afterSendData,
722 weak_from_this(), resHandler);
Carson Labradof52c03c2022-03-23 18:50:15 +0000723 // Reuse an existing connection if one is available
724 for (unsigned int i = 0; i < connections.size(); i++)
725 {
726 auto conn = connections[i];
727 if ((conn->state == ConnState::idle) ||
728 (conn->state == ConnState::initialized) ||
729 (conn->state == ConnState::closed))
730 {
Carson Labrado244256c2022-04-27 17:16:32 +0000731 conn->req = std::move(thisReq);
Carson Labradof52c03c2022-03-23 18:50:15 +0000732 conn->callback = std::move(cb);
Carson Labradof52c03c2022-03-23 18:50:15 +0000733 std::string commonMsg = std::to_string(i) + " from pool " +
734 destIP + ":" + std::to_string(destPort);
735
736 if (conn->state == ConnState::idle)
737 {
Ed Tanous62598e32023-07-17 17:06:25 -0700738 BMCWEB_LOG_DEBUG("Grabbing idle connection {}", commonMsg);
Carson Labradof52c03c2022-03-23 18:50:15 +0000739 conn->sendMessage();
740 }
741 else
742 {
Ed Tanous62598e32023-07-17 17:06:25 -0700743 BMCWEB_LOG_DEBUG("Reusing existing connection {}",
744 commonMsg);
Carson Labradof52c03c2022-03-23 18:50:15 +0000745 conn->doResolve();
746 }
747 return;
748 }
749 }
750
751 // All connections in use so create a new connection or add request to
752 // the queue
Carson Labradod14a48f2023-02-22 00:24:54 +0000753 if (connections.size() < connPolicy->maxConnections)
Carson Labradof52c03c2022-03-23 18:50:15 +0000754 {
Ed Tanous62598e32023-07-17 17:06:25 -0700755 BMCWEB_LOG_DEBUG("Adding new connection to pool {}:{}", destIP,
756 std::to_string(destPort));
Carson Labradof52c03c2022-03-23 18:50:15 +0000757 auto conn = addConnection();
Carson Labrado244256c2022-04-27 17:16:32 +0000758 conn->req = std::move(thisReq);
Carson Labradof52c03c2022-03-23 18:50:15 +0000759 conn->callback = std::move(cb);
Carson Labradof52c03c2022-03-23 18:50:15 +0000760 conn->doResolve();
761 }
762 else if (requestQueue.size() < maxRequestQueueSize)
763 {
Ed Tanous62598e32023-07-17 17:06:25 -0700764 BMCWEB_LOG_ERROR(
765 "Max pool size reached. Adding data to queue.{}:{}", destIP,
766 std::to_string(destPort));
Carson Labradod14a48f2023-02-22 00:24:54 +0000767 requestQueue.emplace_back(std::move(thisReq), std::move(cb));
Carson Labradof52c03c2022-03-23 18:50:15 +0000768 }
769 else
770 {
Carson Labrado43e14d32022-11-09 00:25:20 +0000771 // If we can't buffer the request then we should let the callback
772 // handle a 429 Too Many Requests dummy response
Ed Tanous62598e32023-07-17 17:06:25 -0700773 BMCWEB_LOG_ERROR("{}:{} request queue full. Dropping request.",
774 destIP, std::to_string(destPort));
Carson Labrado43e14d32022-11-09 00:25:20 +0000775 Response dummyRes;
776 dummyRes.result(boost::beast::http::status::too_many_requests);
777 resHandler(dummyRes);
Carson Labradof52c03c2022-03-23 18:50:15 +0000778 }
Ayushi Smritife44eb02020-05-15 15:24:45 +0530779 }
780
Ed Tanous3d36e3a2022-08-19 15:54:04 -0700781 // Callback to be called once the request has been sent
782 static void afterSendData(const std::weak_ptr<ConnectionPool>& weakSelf,
783 const std::function<void(Response&)>& resHandler,
784 bool keepAlive, uint32_t connId, Response& res)
785 {
786 // Allow provided callback to perform additional processing of the
787 // request
788 resHandler(res);
789
790 // If requests remain in the queue then we want to reuse this
791 // connection to send the next request
792 std::shared_ptr<ConnectionPool> self = weakSelf.lock();
793 if (!self)
794 {
Ed Tanous62598e32023-07-17 17:06:25 -0700795 BMCWEB_LOG_CRITICAL("{} Failed to capture connection",
796 logPtr(self.get()));
Ed Tanous3d36e3a2022-08-19 15:54:04 -0700797 return;
798 }
799
800 self->sendNext(keepAlive, connId);
801 }
802
Carson Labradof52c03c2022-03-23 18:50:15 +0000803 std::shared_ptr<ConnectionInfo>& addConnection()
Ayushi Smritife44eb02020-05-15 15:24:45 +0530804 {
Carson Labradof52c03c2022-03-23 18:50:15 +0000805 unsigned int newId = static_cast<unsigned int>(connections.size());
806
AppaRao Pulie38778a2022-06-27 23:09:03 +0000807 auto& ret = connections.emplace_back(std::make_shared<ConnectionInfo>(
Carson Labradod14a48f2023-02-22 00:24:54 +0000808 ioc, id, connPolicy, destIP, destPort, useSSL, newId));
Carson Labradof52c03c2022-03-23 18:50:15 +0000809
Ed Tanous62598e32023-07-17 17:06:25 -0700810 BMCWEB_LOG_DEBUG("Added connection {} to pool {}:{}",
811 std::to_string(connections.size() - 1), destIP,
812 std::to_string(destPort));
Carson Labradof52c03c2022-03-23 18:50:15 +0000813
814 return ret;
815 }
816
817 public:
Carson Labradod14a48f2023-02-22 00:24:54 +0000818 explicit ConnectionPool(
819 boost::asio::io_context& iocIn, const std::string& idIn,
820 const std::shared_ptr<ConnectionPolicy>& connPolicyIn,
821 const std::string& destIPIn, uint16_t destPortIn, bool useSSLIn) :
Ed Tanous8a592812022-06-04 09:06:59 -0700822 ioc(iocIn),
Carson Labradod14a48f2023-02-22 00:24:54 +0000823 id(idIn), connPolicy(connPolicyIn), destIP(destIPIn),
824 destPort(destPortIn), useSSL(useSSLIn)
Carson Labradof52c03c2022-03-23 18:50:15 +0000825 {
Ed Tanous62598e32023-07-17 17:06:25 -0700826 BMCWEB_LOG_DEBUG("Initializing connection pool for {}:{}", destIP,
827 std::to_string(destPort));
Carson Labradof52c03c2022-03-23 18:50:15 +0000828
829 // Initialize the pool with a single connection
830 addConnection();
Ayushi Smritife44eb02020-05-15 15:24:45 +0530831 }
AppaRao Pulibd030d02020-03-20 03:34:29 +0530832};
833
Carson Labradof52c03c2022-03-23 18:50:15 +0000834class HttpClient
835{
836 private:
837 std::unordered_map<std::string, std::shared_ptr<ConnectionPool>>
838 connectionPools;
Ed Tanousf8ca6d72022-06-28 12:12:03 -0700839 boost::asio::io_context& ioc;
Carson Labradod14a48f2023-02-22 00:24:54 +0000840 std::shared_ptr<ConnectionPolicy> connPolicy;
Carson Labradof52c03c2022-03-23 18:50:15 +0000841
Carson Labrado039a47e2022-04-05 16:03:20 +0000842 // Used as a dummy callback by sendData() in order to call
843 // sendDataWithCallback()
Ed Tanous02cad962022-06-30 16:50:15 -0700844 static void genericResHandler(const Response& res)
Carson Labrado039a47e2022-04-05 16:03:20 +0000845 {
Ed Tanous62598e32023-07-17 17:06:25 -0700846 BMCWEB_LOG_DEBUG("Response handled with return code: {}",
847 std::to_string(res.resultInt()));
Ed Tanous4ee8e212022-05-28 09:42:51 -0700848 }
Carson Labrado039a47e2022-04-05 16:03:20 +0000849
Carson Labradof52c03c2022-03-23 18:50:15 +0000850 public:
Carson Labradod14a48f2023-02-22 00:24:54 +0000851 HttpClient() = delete;
Ed Tanousf8ca6d72022-06-28 12:12:03 -0700852 explicit HttpClient(boost::asio::io_context& iocIn,
853 const std::shared_ptr<ConnectionPolicy>& connPolicyIn) :
854 ioc(iocIn),
Carson Labradod14a48f2023-02-22 00:24:54 +0000855 connPolicy(connPolicyIn)
856 {}
Ed Tanousf8ca6d72022-06-28 12:12:03 -0700857
Carson Labradof52c03c2022-03-23 18:50:15 +0000858 HttpClient(const HttpClient&) = delete;
859 HttpClient& operator=(const HttpClient&) = delete;
860 HttpClient(HttpClient&&) = delete;
861 HttpClient& operator=(HttpClient&&) = delete;
862 ~HttpClient() = default;
863
Carson Labrado039a47e2022-04-05 16:03:20 +0000864 // Send a request to destIP:destPort where additional processing of the
865 // result is not required
AppaRao Puli5e44e3d2021-03-16 15:37:24 +0000866 void sendData(std::string&& data, const std::string& destIP,
Carson Labradod14a48f2023-02-22 00:24:54 +0000867 uint16_t destPort, const std::string& destUri, bool useSSL,
Carson Labradof52c03c2022-03-23 18:50:15 +0000868 const boost::beast::http::fields& httpHeader,
Carson Labradod14a48f2023-02-22 00:24:54 +0000869 const boost::beast::http::verb verb)
Carson Labradof52c03c2022-03-23 18:50:15 +0000870 {
AppaRao Pulie38778a2022-06-27 23:09:03 +0000871 const std::function<void(Response&)> cb = genericResHandler;
AppaRao Puli5e44e3d2021-03-16 15:37:24 +0000872 sendDataWithCallback(std::move(data), destIP, destPort, destUri, useSSL,
Carson Labradod14a48f2023-02-22 00:24:54 +0000873 httpHeader, verb, cb);
Carson Labrado039a47e2022-04-05 16:03:20 +0000874 }
875
876 // Send request to destIP:destPort and use the provided callback to
877 // handle the response
AppaRao Puli5e44e3d2021-03-16 15:37:24 +0000878 void sendDataWithCallback(std::string&& data, const std::string& destIP,
Carson Labradod14a48f2023-02-22 00:24:54 +0000879 uint16_t destPort, const std::string& destUri,
880 bool useSSL,
Carson Labrado039a47e2022-04-05 16:03:20 +0000881 const boost::beast::http::fields& httpHeader,
Carson Labrado244256c2022-04-27 17:16:32 +0000882 const boost::beast::http::verb verb,
Ed Tanous6b3db602022-06-28 19:41:44 -0700883 const std::function<void(Response&)>& resHandler)
Carson Labrado039a47e2022-04-05 16:03:20 +0000884 {
AppaRao Pulie38778a2022-06-27 23:09:03 +0000885 std::string clientKey = useSSL ? "https" : "http";
886 clientKey += destIP;
887 clientKey += ":";
888 clientKey += std::to_string(destPort);
Carson Labradod14a48f2023-02-22 00:24:54 +0000889 auto pool = connectionPools.try_emplace(clientKey);
890 if (pool.first->second == nullptr)
Carson Labradof52c03c2022-03-23 18:50:15 +0000891 {
Carson Labradod14a48f2023-02-22 00:24:54 +0000892 pool.first->second = std::make_shared<ConnectionPool>(
893 ioc, clientKey, connPolicy, destIP, destPort, useSSL);
Carson Labradof52c03c2022-03-23 18:50:15 +0000894 }
Carson Labradof52c03c2022-03-23 18:50:15 +0000895 // Send the data using either the existing connection pool or the newly
896 // created connection pool
AppaRao Puli5e44e3d2021-03-16 15:37:24 +0000897 pool.first->second->sendData(std::move(data), destUri, httpHeader, verb,
Carson Labradod14a48f2023-02-22 00:24:54 +0000898 resHandler);
Carson Labradof52c03c2022-03-23 18:50:15 +0000899 }
900};
AppaRao Pulibd030d02020-03-20 03:34:29 +0530901} // namespace crow