1 /* 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 17 18 #include "async_resolve.hpp" 19 #include "http_response.hpp" 20 #include "logging.hpp" 21 #include "ssl_key_handler.hpp" 22 23 #include <boost/asio/connect.hpp> 24 #include <boost/asio/io_context.hpp> 25 #include <boost/asio/ip/address.hpp> 26 #include <boost/asio/ip/basic_endpoint.hpp> 27 #include <boost/asio/ip/tcp.hpp> 28 #include <boost/asio/ssl/context.hpp> 29 #include <boost/asio/ssl/error.hpp> 30 #include <boost/asio/steady_timer.hpp> 31 #include <boost/beast/core/flat_buffer.hpp> 32 #include <boost/beast/core/flat_static_buffer.hpp> 33 #include <boost/beast/http/message.hpp> 34 #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> 38 #include <boost/beast/ssl/ssl_stream.hpp> 39 #include <boost/beast/version.hpp> 40 #include <boost/container/devector.hpp> 41 #include <boost/system/error_code.hpp> 42 43 #include <cstdlib> 44 #include <functional> 45 #include <iostream> 46 #include <memory> 47 #include <queue> 48 #include <string> 49 50 namespace crow 51 { 52 53 // With Redfish Aggregation it is assumed we will connect to another instance 54 // of BMCWeb which can handle 100 simultaneous connections. 55 constexpr size_t maxPoolSize = 20; 56 constexpr size_t maxRequestQueueSize = 500; 57 constexpr unsigned int httpReadBodyLimit = 131072; 58 constexpr unsigned int httpReadBufferSize = 4096; 59 60 enum class ConnState 61 { 62 initialized, 63 resolveInProgress, 64 resolveFailed, 65 connectInProgress, 66 connectFailed, 67 connected, 68 handshakeInProgress, 69 handshakeFailed, 70 sendInProgress, 71 sendFailed, 72 recvInProgress, 73 recvFailed, 74 idle, 75 closed, 76 suspended, 77 terminated, 78 abortConnection, 79 sslInitFailed, 80 retry 81 }; 82 83 static inline boost::system::error_code 84 defaultRetryHandler(unsigned int respCode) 85 { 86 // As a default, assume 200X is alright 87 BMCWEB_LOG_DEBUG("Using default check for response code validity"); 88 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 98 // We need to allow retry information to be set before a message has been sent 99 // and a connection pool has been created 100 struct ConnectionPolicy 101 { 102 uint32_t maxRetryAttempts = 5; 103 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 109 std::string retryPolicyAction = "TerminateAfterRetries"; 110 111 std::chrono::seconds retryIntervalSecs = std::chrono::seconds(0); 112 std::function<boost::system::error_code(unsigned int respCode)> 113 invalidResp = defaultRetryHandler; 114 }; 115 116 struct PendingRequest 117 { 118 boost::beast::http::request<boost::beast::http::string_body> req; 119 std::function<void(bool, uint32_t, Response&)> callback; 120 PendingRequest( 121 boost::beast::http::request<boost::beast::http::string_body>&& reqIn, 122 const std::function<void(bool, uint32_t, Response&)>& callbackIn) : 123 req(std::move(reqIn)), 124 callback(callbackIn) 125 {} 126 }; 127 128 class ConnectionInfo : public std::enable_shared_from_this<ConnectionInfo> 129 { 130 private: 131 ConnState state = ConnState::initialized; 132 uint32_t retryCount = 0; 133 std::string subId; 134 std::shared_ptr<ConnectionPolicy> connPolicy; 135 std::string host; 136 uint16_t port; 137 uint32_t connId; 138 139 // Data buffers 140 boost::beast::http::request<boost::beast::http::string_body> req; 141 std::optional< 142 boost::beast::http::response_parser<boost::beast::http::string_body>> 143 parser; 144 boost::beast::flat_static_buffer<httpReadBufferSize> buffer; 145 Response res; 146 147 // Ascync callables 148 std::function<void(bool, uint32_t, Response&)> callback; 149 150 #ifdef BMCWEB_DBUS_DNS_RESOLVER 151 using Resolver = async_resolve::Resolver; 152 #else 153 using Resolver = boost::asio::ip::tcp::resolver; 154 #endif 155 Resolver resolver; 156 157 boost::asio::ip::tcp::socket conn; 158 std::optional<boost::beast::ssl_stream<boost::asio::ip::tcp::socket&>> 159 sslConn; 160 161 boost::asio::steady_timer timer; 162 163 friend class ConnectionPool; 164 165 void doResolve() 166 { 167 state = ConnState::resolveInProgress; 168 BMCWEB_LOG_DEBUG("Trying to resolve: {}:{}, id: {}", host, 169 std::to_string(port), std::to_string(connId)); 170 171 resolver.async_resolve(host, std::to_string(port), 172 std::bind_front(&ConnectionInfo::afterResolve, 173 this, shared_from_this())); 174 } 175 176 void afterResolve(const std::shared_ptr<ConnectionInfo>& /*self*/, 177 const boost::system::error_code& ec, 178 const Resolver::results_type& endpointList) 179 { 180 if (ec || (endpointList.empty())) 181 { 182 BMCWEB_LOG_ERROR("Resolve failed: {} {}:{}", ec.message(), host, 183 std::to_string(port)); 184 state = ConnState::resolveFailed; 185 waitAndRetry(); 186 return; 187 } 188 BMCWEB_LOG_DEBUG("Resolved {}:{}, id: {}", host, std::to_string(port), 189 std::to_string(connId)); 190 state = ConnState::connectInProgress; 191 192 BMCWEB_LOG_DEBUG("Trying to connect to: {}:{}, id: {}", host, 193 std::to_string(port), std::to_string(connId)); 194 195 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())); 202 } 203 204 void afterConnect(const std::shared_ptr<ConnectionInfo>& /*self*/, 205 const boost::beast::error_code& ec, 206 const boost::asio::ip::tcp::endpoint& endpoint) 207 { 208 // 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 215 timer.cancel(); 216 if (ec) 217 { 218 BMCWEB_LOG_ERROR("Connect {}:{}, id: {} failed: {}", 219 endpoint.address().to_string(), 220 std::to_string(endpoint.port()), 221 std::to_string(connId), ec.message()); 222 state = ConnState::connectFailed; 223 waitAndRetry(); 224 return; 225 } 226 BMCWEB_LOG_DEBUG( 227 "Connected to: {}:{}, id: {}", endpoint.address().to_string(), 228 std::to_string(endpoint.port()), std::to_string(connId)); 229 if (sslConn) 230 { 231 doSslHandshake(); 232 return; 233 } 234 state = ConnState::connected; 235 sendMessage(); 236 } 237 238 void doSslHandshake() 239 { 240 if (!sslConn) 241 { 242 return; 243 } 244 state = ConnState::handshakeInProgress; 245 timer.expires_after(std::chrono::seconds(30)); 246 timer.async_wait(std::bind_front(onTimeout, weak_from_this())); 247 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*/, 254 const boost::beast::error_code& ec) 255 { 256 // 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 263 timer.cancel(); 264 if (ec) 265 { 266 BMCWEB_LOG_ERROR("SSL Handshake failed - id: {} error: {}", 267 std::to_string(connId), ec.message()); 268 state = ConnState::handshakeFailed; 269 waitAndRetry(); 270 return; 271 } 272 BMCWEB_LOG_DEBUG("SSL Handshake successful - id: {}", 273 std::to_string(connId)); 274 state = ConnState::connected; 275 sendMessage(); 276 } 277 278 void sendMessage() 279 { 280 state = ConnState::sendInProgress; 281 282 // Set a timeout on the operation 283 timer.expires_after(std::chrono::seconds(30)); 284 timer.async_wait(std::bind_front(onTimeout, weak_from_this())); 285 286 // Send the HTTP request to the remote host 287 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 } 302 303 void afterWrite(const std::shared_ptr<ConnectionInfo>& /*self*/, 304 const boost::beast::error_code& ec, size_t bytesTransferred) 305 { 306 // 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 313 timer.cancel(); 314 if (ec) 315 { 316 BMCWEB_LOG_ERROR("sendMessage() failed: {} {}:{}", ec.message(), 317 host, std::to_string(port)); 318 state = ConnState::sendFailed; 319 waitAndRetry(); 320 return; 321 } 322 BMCWEB_LOG_DEBUG("sendMessage() bytes transferred: {}", 323 bytesTransferred); 324 325 recvMessage(); 326 } 327 328 void recvMessage() 329 { 330 state = ConnState::recvInProgress; 331 332 parser.emplace(std::piecewise_construct, std::make_tuple()); 333 334 parser->body_limit(connPolicy->requestByteLimit); 335 336 timer.expires_after(std::chrono::seconds(30)); 337 timer.async_wait(std::bind_front(onTimeout, weak_from_this())); 338 339 // Receive the HTTP response 340 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 } 355 356 void afterRead(const std::shared_ptr<ConnectionInfo>& /*self*/, 357 const boost::beast::error_code& ec, 358 const std::size_t& bytesTransferred) 359 { 360 // 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 367 timer.cancel(); 368 if (ec && ec != boost::asio::ssl::error::stream_truncated) 369 { 370 BMCWEB_LOG_ERROR("recvMessage() failed: {} from {}:{}", 371 ec.message(), host, std::to_string(port)); 372 state = ConnState::recvFailed; 373 waitAndRetry(); 374 return; 375 } 376 BMCWEB_LOG_DEBUG("recvMessage() bytes transferred: {}", 377 bytesTransferred); 378 BMCWEB_LOG_DEBUG("recvMessage() data: {}", parser->get().body()); 379 380 unsigned int respCode = parser->get().result_int(); 381 BMCWEB_LOG_DEBUG("recvMessage() Header Response Code: {}", respCode); 382 383 // Make sure the received response code is valid as defined by 384 // the associated retry policy 385 if (connPolicy->invalidResp(respCode)) 386 { 387 // The listener failed to receive the Sent-Event 388 BMCWEB_LOG_ERROR( 389 "recvMessage() Listener Failed to " 390 "receive Sent-Event. Header Response Code: {} from {}:{}", 391 respCode, host, std::to_string(port)); 392 state = ConnState::recvFailed; 393 waitAndRetry(); 394 return; 395 } 396 397 // Send is successful 398 // Reset the counter just in case this was after retrying 399 retryCount = 0; 400 401 // Keep the connection alive if server supports it 402 // Else close the connection 403 BMCWEB_LOG_DEBUG("recvMessage() keepalive : {}", parser->keep_alive()); 404 405 // Copy the response into a Response object so that it can be 406 // processed by the callback function. 407 res.stringResponse = parser->release(); 408 callback(parser->keep_alive(), connId, res); 409 res.clear(); 410 } 411 412 static void onTimeout(const std::weak_ptr<ConnectionInfo>& weakSelf, 413 const boost::system::error_code& ec) 414 { 415 if (ec == boost::asio::error::operation_aborted) 416 { 417 BMCWEB_LOG_DEBUG( 418 "async_wait failed since the operation is aborted"); 419 return; 420 } 421 if (ec) 422 { 423 BMCWEB_LOG_ERROR("async_wait failed: {}", ec.message()); 424 // 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 435 void waitAndRetry() 436 { 437 if ((retryCount >= connPolicy->maxRetryAttempts) || 438 (state == ConnState::sslInitFailed)) 439 { 440 BMCWEB_LOG_ERROR("Maximum number of retries reached. {}:{}", host, 441 std::to_string(port)); 442 BMCWEB_LOG_DEBUG("Retry policy: {}", connPolicy->retryPolicyAction); 443 444 if (connPolicy->retryPolicyAction == "TerminateAfterRetries") 445 { 446 // TODO: delete subscription 447 state = ConnState::terminated; 448 } 449 if (connPolicy->retryPolicyAction == "SuspendRetries") 450 { 451 state = ConnState::suspended; 452 } 453 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 460 // Reset the retrycount to zero so that client can try connecting 461 // again if needed 462 retryCount = 0; 463 return; 464 } 465 466 retryCount++; 467 468 BMCWEB_LOG_DEBUG("Attempt retry after {} seconds. RetryCount = {}", 469 std::to_string(connPolicy->retryIntervalSecs.count()), 470 retryCount); 471 timer.expires_after(connPolicy->retryIntervalSecs); 472 timer.async_wait(std::bind_front(&ConnectionInfo::onTimerDone, this, 473 shared_from_this())); 474 } 475 476 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 { 481 BMCWEB_LOG_DEBUG( 482 "async_wait failed since the operation is aborted{}", 483 ec.message()); 484 } 485 else if (ec) 486 { 487 BMCWEB_LOG_ERROR("async_wait failed: {}", ec.message()); 488 // 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); 494 } 495 496 void shutdownConn(bool retry) 497 { 498 boost::beast::error_code ec; 499 conn.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec); 500 conn.close(); 501 502 // not_connected happens sometimes so don't bother reporting it. 503 if (ec && ec != boost::beast::errc::not_connected) 504 { 505 BMCWEB_LOG_ERROR("{}:{}, id: {} shutdown failed: {}", host, 506 std::to_string(port), std::to_string(connId), 507 ec.message()); 508 } 509 else 510 { 511 BMCWEB_LOG_DEBUG("{}:{}, id: {} closed gracefully", host, 512 std::to_string(port), std::to_string(connId)); 513 } 514 515 if (retry) 516 { 517 // Now let's try to resend the data 518 state = ConnState::retry; 519 doResolve(); 520 } 521 else 522 { 523 state = ConnState::closed; 524 } 525 } 526 527 void doClose(bool retry = false) 528 { 529 if (!sslConn) 530 { 531 shutdownConn(retry); 532 return; 533 } 534 535 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 { 543 if (ec) 544 { 545 BMCWEB_LOG_ERROR("{}:{}, id: {} shutdown failed: {}", host, 546 std::to_string(port), std::to_string(connId), 547 ec.message()); 548 } 549 else 550 { 551 BMCWEB_LOG_DEBUG("{}:{}, id: {} closed gracefully", host, 552 std::to_string(port), std::to_string(connId)); 553 } 554 shutdownConn(retry); 555 } 556 557 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 578 BMCWEB_LOG_ERROR( 579 "SSL_set_tlsext_host_name {}:{}, id: {} failed: {}", host, port, 580 std::to_string(connId), ec.message()); 581 // 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 } 587 } 588 589 public: 590 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) : 595 subId(idIn), 596 connPolicy(connPolicyIn), host(destIPIn), port(destPortIn), 597 connId(connIdIn), resolver(iocIn), conn(iocIn), timer(iocIn) 598 { 599 if (useSSL) 600 { 601 std::optional<boost::asio::ssl::context> sslCtx = 602 ensuressl::getSSLClientContext(); 603 604 if (!sslCtx) 605 { 606 BMCWEB_LOG_ERROR("prepareSSLContext failed - {}:{}, id: {}", 607 host, port, std::to_string(connId)); 608 // 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 } 621 }; 622 623 class ConnectionPool : public std::enable_shared_from_this<ConnectionPool> 624 { 625 private: 626 boost::asio::io_context& ioc; 627 std::string id; 628 std::shared_ptr<ConnectionPolicy> connPolicy; 629 std::string destIP; 630 uint16_t destPort; 631 bool useSSL; 632 std::vector<std::shared_ptr<ConnectionInfo>> connections; 633 boost::container::devector<PendingRequest> requestQueue; 634 635 friend class HttpClient; 636 637 // Configure a connections's request, callback, and retry info in 638 // preparation to begin sending the request 639 void setConnProps(ConnectionInfo& conn) 640 { 641 if (requestQueue.empty()) 642 { 643 BMCWEB_LOG_ERROR( 644 "setConnProps() should not have been called when requestQueue is empty"); 645 return; 646 } 647 648 auto nextReq = requestQueue.front(); 649 conn.req = std::move(nextReq.req); 650 conn.callback = std::move(nextReq.callback); 651 652 BMCWEB_LOG_DEBUG("Setting properties for connection {}:{}, id: {}", 653 conn.host, std::to_string(conn.port), 654 std::to_string(conn.connId)); 655 656 // We can remove the request from the queue at this point 657 requestQueue.pop_front(); 658 } 659 660 // 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]; 666 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 672 // Reuse the connection to send the next request in the queue 673 if (!requestQueue.empty()) 674 { 675 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)); 679 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; 700 } 701 else 702 { 703 // Abort the connection since server is not keep-alive enabled 704 conn->state = ConnState::abortConnection; 705 conn->doClose(); 706 } 707 } 708 709 void sendData(std::string&& data, const std::string& destUri, 710 const boost::beast::http::fields& httpHeader, 711 const boost::beast::http::verb verb, 712 const std::function<void(Response&)>& resHandler) 713 { 714 // 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(); 721 auto cb = std::bind_front(&ConnectionPool::afterSendData, 722 weak_from_this(), resHandler); 723 // 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 { 731 conn->req = std::move(thisReq); 732 conn->callback = std::move(cb); 733 std::string commonMsg = std::to_string(i) + " from pool " + 734 destIP + ":" + std::to_string(destPort); 735 736 if (conn->state == ConnState::idle) 737 { 738 BMCWEB_LOG_DEBUG("Grabbing idle connection {}", commonMsg); 739 conn->sendMessage(); 740 } 741 else 742 { 743 BMCWEB_LOG_DEBUG("Reusing existing connection {}", 744 commonMsg); 745 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 753 if (connections.size() < connPolicy->maxConnections) 754 { 755 BMCWEB_LOG_DEBUG("Adding new connection to pool {}:{}", destIP, 756 std::to_string(destPort)); 757 auto conn = addConnection(); 758 conn->req = std::move(thisReq); 759 conn->callback = std::move(cb); 760 conn->doResolve(); 761 } 762 else if (requestQueue.size() < maxRequestQueueSize) 763 { 764 BMCWEB_LOG_ERROR( 765 "Max pool size reached. Adding data to queue.{}:{}", destIP, 766 std::to_string(destPort)); 767 requestQueue.emplace_back(std::move(thisReq), std::move(cb)); 768 } 769 else 770 { 771 // If we can't buffer the request then we should let the callback 772 // handle a 429 Too Many Requests dummy response 773 BMCWEB_LOG_ERROR("{}:{} request queue full. Dropping request.", 774 destIP, std::to_string(destPort)); 775 Response dummyRes; 776 dummyRes.result(boost::beast::http::status::too_many_requests); 777 resHandler(dummyRes); 778 } 779 } 780 781 // 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 { 795 BMCWEB_LOG_CRITICAL("{} Failed to capture connection", 796 logPtr(self.get())); 797 return; 798 } 799 800 self->sendNext(keepAlive, connId); 801 } 802 803 std::shared_ptr<ConnectionInfo>& addConnection() 804 { 805 unsigned int newId = static_cast<unsigned int>(connections.size()); 806 807 auto& ret = connections.emplace_back(std::make_shared<ConnectionInfo>( 808 ioc, id, connPolicy, destIP, destPort, useSSL, newId)); 809 810 BMCWEB_LOG_DEBUG("Added connection {} to pool {}:{}", 811 std::to_string(connections.size() - 1), destIP, 812 std::to_string(destPort)); 813 814 return ret; 815 } 816 817 public: 818 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) : 822 ioc(iocIn), 823 id(idIn), connPolicy(connPolicyIn), destIP(destIPIn), 824 destPort(destPortIn), useSSL(useSSLIn) 825 { 826 BMCWEB_LOG_DEBUG("Initializing connection pool for {}:{}", destIP, 827 std::to_string(destPort)); 828 829 // Initialize the pool with a single connection 830 addConnection(); 831 } 832 }; 833 834 class HttpClient 835 { 836 private: 837 std::unordered_map<std::string, std::shared_ptr<ConnectionPool>> 838 connectionPools; 839 boost::asio::io_context& ioc; 840 std::shared_ptr<ConnectionPolicy> connPolicy; 841 842 // Used as a dummy callback by sendData() in order to call 843 // sendDataWithCallback() 844 static void genericResHandler(const Response& res) 845 { 846 BMCWEB_LOG_DEBUG("Response handled with return code: {}", 847 std::to_string(res.resultInt())); 848 } 849 850 public: 851 HttpClient() = delete; 852 explicit HttpClient(boost::asio::io_context& iocIn, 853 const std::shared_ptr<ConnectionPolicy>& connPolicyIn) : 854 ioc(iocIn), 855 connPolicy(connPolicyIn) 856 {} 857 858 HttpClient(const HttpClient&) = delete; 859 HttpClient& operator=(const HttpClient&) = delete; 860 HttpClient(HttpClient&&) = delete; 861 HttpClient& operator=(HttpClient&&) = delete; 862 ~HttpClient() = default; 863 864 // Send a request to destIP:destPort where additional processing of the 865 // result is not required 866 void sendData(std::string&& data, const std::string& destIP, 867 uint16_t destPort, const std::string& destUri, bool useSSL, 868 const boost::beast::http::fields& httpHeader, 869 const boost::beast::http::verb verb) 870 { 871 const std::function<void(Response&)> cb = genericResHandler; 872 sendDataWithCallback(std::move(data), destIP, destPort, destUri, useSSL, 873 httpHeader, verb, cb); 874 } 875 876 // Send request to destIP:destPort and use the provided callback to 877 // handle the response 878 void sendDataWithCallback(std::string&& data, const std::string& destIP, 879 uint16_t destPort, const std::string& destUri, 880 bool useSSL, 881 const boost::beast::http::fields& httpHeader, 882 const boost::beast::http::verb verb, 883 const std::function<void(Response&)>& resHandler) 884 { 885 std::string clientKey = useSSL ? "https" : "http"; 886 clientKey += destIP; 887 clientKey += ":"; 888 clientKey += std::to_string(destPort); 889 auto pool = connectionPools.try_emplace(clientKey); 890 if (pool.first->second == nullptr) 891 { 892 pool.first->second = std::make_shared<ConnectionPool>( 893 ioc, clientKey, connPolicy, destIP, destPort, useSSL); 894 } 895 // Send the data using either the existing connection pool or the newly 896 // created connection pool 897 pool.first->second->sendData(std::move(data), destUri, httpHeader, verb, 898 resHandler); 899 } 900 }; 901 } // namespace crow 902