1227 int max_pending = 50;
1229 m_continue_queue.reset(
new HandlerQueue(max_pending));
1230 auto &queue = *m_queue.get();
1233 CURLM *multi_handle = curl_multi_init();
1234 if (multi_handle ==
nullptr) {
1235 throw std::runtime_error(
"Failed to create curl multi-handle");
1238 int running_handles = 0;
1239 time_t last_maintenance = time(NULL);
1240 CURLMcode mres = CURLM_OK;
1244 std::unordered_map<int, WaitingForBroker> broker_reqs;
1245 std::vector<struct curl_waitfd> waitfds;
1247 bool want_shutdown =
false;
1248 while (!want_shutdown) {
1249 m_last_completed_cycle.store(std::chrono::system_clock::now().time_since_epoch().count());
1250 auto oldest_op = std::chrono::system_clock::now();
1251 for (
const auto &entry : m_op_map) {
1252 OpRecord(*entry.second.first, OpKind::Update);
1253 if (entry.second.second < oldest_op) {
1254 oldest_op = entry.second.second;
1257 m_oldest_op.store(oldest_op.time_since_epoch().count());
1261 auto op = m_continue_queue->TryConsume();
1268 m_logger->
Debug(
kLogXrdClHttp,
"Ignoring continuation of operation that has already completed");
1271 m_logger->
Debug(
kLogXrdClHttp,
"Continuing the curl handle from op %p on thread %d", op.get(), getthreadid());
1272 auto curl = op->GetCurlHandle();
1273 if (!op->ContinueHandle()) {
1274 op->Fail(
XrdCl::errInternal, 0,
"Failed to continue the curl handle for the operation");
1276 op->ReleaseHandle();
1278 curl_multi_remove_handle(multi_handle, curl);
1279 curl_easy_cleanup(curl);
1280 m_op_map.erase(curl);
1282 running_handles -= 1;
1285 auto iter = m_op_map.find(curl);
1286 if (iter != m_op_map.end()) iter->second.second = std::chrono::system_clock::now();
1290 while (running_handles <
static_cast<int>(m_max_ops)) {
1291 auto op = running_handles == 0 ? queue.Consume(std::chrono::seconds(1)) : queue.TryConsume();
1295 auto curl = queue.GetHandle();
1296 if (curl ==
nullptr) {
1302 auto rv = op->Setup(curl, *
this);
1305 op->Fail(
XrdCl::errInternal, ENOMEM,
"Failed to setup the curl handle for the operation");
1308 if (!op->FinishSetup(curl)) {
1310 op->Fail(
XrdCl::errInternal, ENOMEM,
"Failed to finish setup of the curl handle for the operation");
1315 op->Fail(
XrdCl::errInternal, ENOMEM,
"Failed to setup the curl handle for the operation");
1318 op->SetContinueQueue(m_continue_queue);
1321 op->ReleaseHandle();
1322 queue.RecycleHandle(curl);
1325 m_op_map[curl] = {op, std::chrono::system_clock::now()};
1329 if (op->RequiresOptions()) {
1330 std::string modified_url;
1331 std::shared_ptr<CurlOptionsOp> options_op(
1337 m_logger, op->GetConnCalloutFunc()
1343 curl = queue.GetHandle();
1344 if (curl ==
nullptr) {
1350 auto rv = options_op->Setup(curl, *
this);
1355 m_op_map[curl] = {options_op, std::chrono::system_clock::now()};
1356 OpRecord(*options_op, OpKind::Start);
1357 running_handles += 1;
1359 OpRecord(*op, OpKind::Start);
1362 auto mres = curl_multi_add_handle(multi_handle, curl);
1363 if (mres != CURLM_OK) {
1365 op->Fail(
XrdCl::errInternal, mres,
"Unable to add operation to the curl multi-handle");
1369 m_logger->
Debug(
kLogXrdClHttp,
"Added request for URL %s to worker thread for processing", op->GetUrl().c_str());
1370 running_handles += 1;
1375 time_t now = time(NULL);
1376 time_t next_maintenance = last_maintenance + m_maintenance_period.load(std::memory_order_relaxed);
1377 if (now >= next_maintenance) {
1379 m_continue_queue->Expire();
1381 getthreadid(), running_handles);
1382 last_maintenance = now;
1385 std::vector<std::pair<int, CURL *>> expired_ops;
1386 for (
const auto &entry : broker_reqs) {
1387 if (entry.second.expiry < now) {
1388 expired_ops.emplace_back(entry.first, entry.second.curl);
1391 for (
const auto &entry : expired_ops) {
1392 auto iter = m_op_map.find(entry.second);
1393 if (iter == m_op_map.end()) {
1394 m_logger->
Warning(
kLogXrdClHttp,
"Found an expired curl handle with no corresponding operation!");
1397 CurlOptionsOp *options_op =
nullptr;
1398 if ((options_op =
dynamic_cast<CurlOptionsOp*
>(iter->second.first.get())) !=
nullptr) {
1399 auto parent_op = options_op->GetOperation();
1400 bool parent_op_failed =
false;
1401 if (parent_op->IsRedirect()) {
1403 if (parent_op->Redirect(target) == CurlOperation::RedirectAction::Fail) {
1404 auto iter = m_op_map.find(options_op->GetParentCurlHandle());
1405 if (iter != m_op_map.end()) {
1408 m_op_map.erase(iter);
1409 running_handles -= 1;
1411 parent_op_failed =
true;
1413 OpRecord(*parent_op, OpKind::Start);
1416 OpRecord(*parent_op, OpKind::Start);
1418 if (!parent_op_failed){
1419 curl_multi_add_handle(multi_handle, options_op->GetParentCurlHandle());
1424 iter->second.first->ReleaseHandle();
1425 OpRecord(*(iter->second.first), OpKind::ConncallTimeout);
1426 m_op_map.erase(entry.second);
1427 curl_easy_cleanup(entry.second);
1428 running_handles -= 1;
1430 broker_reqs.erase(entry.first);
1431 m_conncall_timeout.fetch_add(1, std::memory_order_relaxed);
1439 waitfds.resize(3 + broker_reqs.size());
1441 waitfds[0].fd = queue.PollFD();
1442 waitfds[0].events = CURL_WAIT_POLLIN;
1443 waitfds[0].revents = 0;
1444 waitfds[1].fd = m_continue_queue->PollFD();
1445 waitfds[1].events = CURL_WAIT_POLLIN;
1446 waitfds[1].revents = 0;
1447 waitfds[2].fd = m_shutdown_pipe_r;
1448 waitfds[2].revents = 0;
1449 waitfds[2].events = CURL_WAIT_POLLIN | CURL_WAIT_POLLPRI;
1452 for (
const auto &entry : broker_reqs) {
1453 waitfds[idx].fd = entry.first;
1454 waitfds[idx].events = CURL_WAIT_POLLIN|CURL_WAIT_POLLPRI;
1455 waitfds[idx].revents = 0;
1460 curl_multi_timeout(multi_handle, &timeo);
1464 if (running_handles && timeo == -1) {
1469 mres = curl_multi_wait(multi_handle, &waitfds[0], waitfds.size(), 50,
nullptr);
1475 mres = curl_multi_wait(multi_handle, &waitfds[0], waitfds.size(), 50,
nullptr);
1477 if (mres != CURLM_OK) {
1482 for (
const auto &entry : waitfds) {
1484 if (waitfds[0].fd == entry.fd || waitfds[1].fd == entry.fd) {
1488 if ((waitfds[2].fd == entry.fd) && entry.revents) {
1489 want_shutdown =
true;
1492 if ((entry.revents & CURL_WAIT_POLLIN) != CURL_WAIT_POLLIN) {
1495 auto handle = broker_reqs[entry.fd].curl;
1496 auto iter = m_op_map.find(handle);
1497 if (iter == m_op_map.end()) {
1498 m_logger->
Warning(
kLogXrdClHttp,
"Internal error: broker responded on FD %d but no corresponding curl operation", entry.fd);
1499 broker_reqs.erase(entry.fd);
1500 m_conncall_errors.fetch_add(1, std::memory_order_relaxed);
1504 auto result = iter->second.first->WaitSocketCallback(err);
1508 CurlOptionsOp *options_op =
nullptr;
1509 if ((options_op =
dynamic_cast<CurlOptionsOp*
>(iter->second.first.get())) !=
nullptr) {
1510 auto parent_op = options_op->GetOperation();
1511 bool parent_op_failed =
false;
1512 if (parent_op->IsRedirect()) {
1514 if (parent_op->Redirect(target) == CurlOperation::RedirectAction::Fail) {
1515 auto iter = m_op_map.find(options_op->GetParentCurlHandle());
1516 if (iter != m_op_map.end()) {
1519 m_op_map.erase(iter);
1520 running_handles -= 1;
1522 parent_op_failed =
true;
1524 OpRecord(*parent_op, OpKind::Start);
1527 OpRecord(*parent_op, OpKind::Start);
1529 if (!parent_op_failed){
1530 curl_multi_add_handle(multi_handle, options_op->GetParentCurlHandle());
1536 m_op_map.erase(handle);
1537 broker_reqs.erase(entry.fd);
1538 m_conncall_errors.fetch_add(1, std::memory_order_relaxed);
1539 running_handles -= 1;
1541 broker_reqs.erase(entry.fd);
1542 curl_multi_add_handle(multi_handle, handle);
1543 m_conncall_success.fetch_add(1, std::memory_order_relaxed);
1549 auto mres = curl_multi_perform(multi_handle, &still_running);
1550 if (mres == CURLM_CALL_MULTI_PERFORM) {
1552 }
else if (mres != CURLM_OK) {
1560 msg = curl_multi_info_read(multi_handle, &msgq);
1561 if (msg && (msg->msg == CURLMSG_DONE)) {
1562 if (!msg->easy_handle) {
1564 mres = CURLM_BAD_EASY_HANDLE;
1567 auto iter = m_op_map.find(msg->easy_handle);
1568 if (iter == m_op_map.end()) {
1569 m_logger->
Error(
kLogXrdClHttp,
"Logic error: got a callback for an entry that doesn't exist");
1570 mres = CURLM_BAD_EASY_HANDLE;
1573 auto op = iter->second.first;
1574 auto res = msg->data.result;
1575 bool keep_handle =
false;
1576 bool waiting_on_callout =
false;
1577 if (res == CURLE_OK) {
1578 auto sc = op->GetStatusCode();
1579 OpRecord(*op, OpKind::Finish);
1582 op->Fail(httpErr.first, httpErr.second, op->GetStatusMessage());
1583 op->ReleaseHandle();
1587 CurlOptionsOp *options_op =
nullptr;
1588 if ((options_op =
dynamic_cast<CurlOptionsOp*
>(op.get())) !=
nullptr) {
1589 auto parent_op = options_op->GetOperation();
1590 bool parent_op_failed =
false;
1591 if (parent_op->IsRedirect()) {
1593 if (parent_op->Redirect(target) == CurlOperation::RedirectAction::Fail) {
1595 m_op_map.erase(options_op->GetParentCurlHandle());
1596 running_handles -= 1;
1597 parent_op_failed =
true;
1599 OpRecord(*parent_op, OpKind::Start);
1602 OpRecord(*parent_op, OpKind::Start);
1605 if (!parent_op_failed) {
1606 curl_multi_add_handle(multi_handle, options_op->GetParentCurlHandle());
1610 queue.RecycleHandle(iter->first);
1612 CurlOptionsOp *options_op =
nullptr;
1614 if ((options_op =
dynamic_cast<CurlOptionsOp*
>(op.get()))) {
1615 options_op->Success();
1616 options_op->ReleaseHandle();
1618 op = options_op->GetOperation();
1620 OpRecord(*op, OpKind::Start);
1621 curl_multi_add_handle(multi_handle, options_op->GetParentCurlHandle());
1622 curl_multi_remove_handle(multi_handle, iter->first);
1623 queue.RecycleHandle(iter->first);
1628 if (op->IsRedirect()) {
1630 switch (op->Redirect(target)) {
1631 case CurlOperation::RedirectAction::Fail:
1640 keep_handle =
false;
1642 case CurlOperation::RedirectAction::Reinvoke:
1648 OpRecord(*op, OpKind::Start);
1651 case CurlOperation::RedirectAction::ReinvokeAfterAllow:
1658 std::string modified_url;
1660 options_op =
new CurlOptionsOp(iter->first, op, target, m_logger, op->GetConnCalloutFunc());
1661 std::shared_ptr<CurlOperation> new_op(options_op);
1662 auto curl = queue.GetHandle();
1663 if (curl ==
nullptr) {
1666 keep_handle =
false;
1667 options_op =
nullptr;
1670 OpRecord(*new_op, OpKind::Start);
1672 auto rv = new_op->Setup(curl, *
this);
1675 keep_handle =
false;
1676 options_op =
nullptr;
1680 m_logger->
Debug(
kLogXrdClHttp,
"Unable to setup the curl handle for the OPTIONS operation");
1681 new_op->Fail(
XrdCl::errInternal, ENOMEM,
"Failed to setup the curl handle for the OPTIONS operation");
1683 keep_handle =
false;
1686 new_op->SetContinueQueue(m_continue_queue);
1687 m_op_map[curl] = {new_op, std::chrono::system_clock::now()};
1688 auto mres = curl_multi_add_handle(multi_handle, curl);
1689 if (mres != CURLM_OK) {
1690 m_logger->
Debug(
kLogXrdClHttp,
"Unable to add OPTIONS operation to the curl multi-handle: %s", curl_multi_strerror(mres));
1691 op->Fail(
XrdCl::errInternal, mres,
"Unable to add OPTIONS operation to the curl multi-handle");
1695 running_handles += 1;
1696 m_logger->
Debug(
kLogXrdClHttp,
"Invoking the OPTIONS operation before redirect to %s", target.c_str());
1702 int callout_socket = op->WaitSocket();
1703 if ((waiting_on_callout = callout_socket >= 0)) {
1704 auto expiry = time(
nullptr) + 20;
1705 m_logger->
Debug(
kLogXrdClHttp,
"Creating a callout wait request on socket %d", callout_socket);
1706 broker_reqs[callout_socket] = {iter->first, expiry};
1707 m_conncall_req.fetch_add(1, std::memory_order_relaxed);
1709 }
else if (options_op) {
1711 curl_multi_add_handle(multi_handle, options_op->GetParentCurlHandle());
1714 curl_multi_remove_handle(multi_handle, iter->first);
1715 if (!waiting_on_callout && !options_op) {
1716 curl_multi_add_handle(multi_handle, iter->first);
1718 }
else if (!options_op) {
1723 curl_multi_remove_handle(multi_handle, iter->first);
1726 op->ReleaseHandle();
1728 queue.RecycleHandle(iter->first);
1734 auto next_res = curl_multi_add_handle(multi_handle, iter->first);
1735 if (next_res == CURLM_OK) {
1737 OpRecord(*op, OpKind::Start);
1740 "Unable to add the next operation request to the curl multi-handle");
1742 op->ReleaseHandle();
1743 queue.RecycleHandle(iter->first);
1748 }
else if (res == CURLE_COULDNT_CONNECT && op->UseConnectionCallout() && !op->GetTriedBoker()) {
1752 op->SetTriedBoker();
1754 int wait_socket = -1;
1755 if (!op->StartConnectionCallout(err) || (wait_socket=op->WaitSocket()) == -1) {
1756 m_logger->
Error(
kLogXrdClHttp,
"Failed to start broker-based connection: %s", err.c_str());
1757 op->ReleaseHandle();
1758 keep_handle =
false;
1760 curl_multi_remove_handle(multi_handle, iter->first);
1761 auto expiry = time(
nullptr) + 20;
1762 m_logger->
Debug(
kLogXrdClHttp,
"Curl operation requires a new TCP socket; waiting for callout to respond on socket %d", wait_socket);
1763 broker_reqs[wait_socket] = {iter->first, expiry};
1764 m_conncall_req.fetch_add(1, std::memory_order_relaxed);
1767 if (res == CURLE_ABORTED_BY_CALLBACK || res == CURLE_WRITE_ERROR) {
1770 switch (op->GetError()) {
1771 case CurlOperation::OpError::ErrHeaderTimeout:
1772 #ifdef HAVE_XPROTOCOL_TIMEREXPIRED
1779 case CurlOperation::OpError::ErrCallback: {
1780 auto [ecode,
emsg] = op->GetCallbackError();
1785 case CurlOperation::OpError::ErrOperationTimeout:
1787 OpRecord(*op, op->IsPaused() ? OpKind::ClientTimeout : OpKind::ServerTimeout);
1789 case CurlOperation::OpError::ErrTransferSlow:
1791 OpRecord(*op, OpKind::ServerTimeout);
1793 case CurlOperation::OpError::ErrTransferClientStall:
1795 OpRecord(*op, OpKind::ClientTimeout);
1797 case CurlOperation::OpError::ErrTransferStall:
1799 OpRecord(*op, OpKind::ServerTimeout);
1801 case CurlOperation::OpError::ErrNone:
1802 op->Fail(
XrdCl::errInternal, 0,
"Operation was aborted without recording an abort reason");
1806 CurlOptionsOp *options_op =
nullptr;
1807 if ((options_op =
dynamic_cast<CurlOptionsOp*
>(op.get())) !=
nullptr) {
1808 auto parent_op = options_op->GetOperation();
1809 bool parent_op_failed =
false;
1810 if (parent_op->IsRedirect()) {
1812 if (parent_op->Redirect(target) == CurlOperation::RedirectAction::Fail) {
1813 auto iter = m_op_map.find(options_op->GetParentCurlHandle());
1814 if (iter != m_op_map.end()) {
1817 m_op_map.erase(iter);
1818 running_handles -= 1;
1820 parent_op_failed =
true;
1822 OpRecord(*parent_op, OpKind::Start);
1825 OpRecord(*parent_op, OpKind::Start);
1827 if (!parent_op_failed){
1828 curl_multi_add_handle(multi_handle, options_op->GetParentCurlHandle());
1833 const auto curl_err = op->GetCurlErrorMessage();
1834 const char *curl_easy_err = curl_easy_strerror(res);
1835 const std::string fail_err = !curl_err.empty() ? curl_err : curl_easy_err;
1836 m_logger->
Debug(
kLogXrdClHttp,
"Curl generated an error: %s (%d)", fail_err.c_str(), res);
1837 op->Fail(xrdCode.first, xrdCode.second, fail_err);
1839 CurlOptionsOp *options_op =
nullptr;
1840 if ((options_op =
dynamic_cast<CurlOptionsOp*
>(op.get())) !=
nullptr) {
1841 auto parent_op = options_op->GetOperation();
1842 bool parent_op_failed =
false;
1843 if (parent_op->IsRedirect()) {
1845 if (parent_op->Redirect(target) == CurlOperation::RedirectAction::Fail) {
1846 auto iter = m_op_map.find(options_op->GetParentCurlHandle());
1847 if (iter != m_op_map.end()) {
1850 m_op_map.erase(iter);
1851 running_handles -= 1;
1853 parent_op_failed =
true;
1856 if (!parent_op_failed){
1857 curl_multi_add_handle(multi_handle, options_op->GetParentCurlHandle());
1861 op->ReleaseHandle();
1864 curl_multi_remove_handle(multi_handle, iter->first);
1865 if (res != CURLE_OK) {
1866 curl_easy_cleanup(iter->first);
1868 for (
auto &req : broker_reqs) {
1869 if (req.second.curl == iter->first) {
1870 m_logger->
Warning(
kLogXrdClHttp,
"Curl handle finished while a broker operation was outstanding");
1871 m_conncall_errors.fetch_add(1, std::memory_order_relaxed);
1874 m_op_map.erase(iter);
1875 running_handles -= 1;
1881 for (
auto map_entry : m_op_map) {
1886 if (multi_handle && map_entry.first) curl_multi_remove_handle(multi_handle, map_entry.first);
1889 m_queue->ReleaseHandles();
1890 curl_multi_cleanup(multi_handle);
std::pair< uint16_t, uint32_t > CurlCodeConvert(CURLcode res)
int emsg(int rc, char *msg)
static void CleanupDnsCache()
static std::string_view GetUrlKey(const std::string &url, std::string &modified_url)
bool GetInt(const std::string &key, int &value)
void Error(uint64_t topic, const char *format,...)
Report an error.
void Warning(uint64_t topic, const char *format,...)
Report a warning.
void Debug(uint64_t topic, const char *format,...)
Print a debug message.
std::pair< uint16_t, uint32_t > HTTPStatusConvert(unsigned status)
bool HTTPStatusIsError(unsigned status)
const uint16_t errErrorResponse
const uint16_t errOperationExpired
const uint16_t errInternal
Internal error.
const uint16_t errConnectionError
const uint64_t kLogXrdClHttp