XRootD
XrdClHttp::CurlWorker Class Reference

#include <XrdClHttpWorker.hh>

+ Collaboration diagram for XrdClHttp::CurlWorker:

Public Member Functions

 CurlWorker (const CurlWorker &)=delete
 
 CurlWorker (std::shared_ptr< HandlerQueue > queue, VerbsCache &cache, XrdCl::Log *logger)
 
std::tuple< std::string, std::string > ClientX509CertKeyFile () const
 
void Run ()
 
void Start (std::unique_ptr< XrdClHttp::CurlWorker > self, std::thread tid)
 

Static Public Member Functions

static std::string GetMonitoringJson ()
 
static void RunStatic (CurlWorker *myself)
 
static void SetMaintenancePeriod (unsigned maint)
 

Detailed Description

Definition at line 52 of file XrdClHttpWorker.hh.

Constructor & Destructor Documentation

◆ CurlWorker() [1/2]

CurlWorker::CurlWorker ( std::shared_ptr< HandlerQueue >  queue,
VerbsCache &  cache,
XrdCl::Log *  logger 
)

Definition at line 1027 of file XrdClHttpUtil.cc.

1027  :
1028  m_cache(cache),
1029  m_queue(queue),
1030  m_logger(logger)
1031 {
1032  {
1033  std::unique_lock lk(m_worker_stats_mutex);
1034  m_stats_offset = m_workers_last_completed_cycle.size();
1035  m_workers_last_completed_cycle.push_back(&m_last_completed_cycle);
1036  m_workers_oldest_op.push_back(&m_oldest_op);
1037  }
1038  int pipeInfo[2];
1039  if ((pipe(pipeInfo) == -1) || (fcntl(pipeInfo[0], F_SETFD, FD_CLOEXEC)) || (fcntl(pipeInfo[1], F_SETFD, FD_CLOEXEC))) {
1040  throw std::runtime_error("Failed to create shutdown monitoring pipe for curl worker");
1041  }
1042  m_shutdown_pipe_r = pipeInfo[0];
1043  m_shutdown_pipe_w = pipeInfo[1];
1044 
1045  // Handle setup of the X509 authentication
1046  auto env = XrdCl::DefaultEnv::GetEnv();
1047  env->GetString("HttpClientCertFile", m_x509_client_cert_file);
1048  env->GetString("HttpClientKeyFile", m_x509_client_key_file);
1049 }
static Env * GetEnv()
Get default client environment.

References XrdCl::DefaultEnv::GetEnv().

+ Here is the call graph for this function:

◆ CurlWorker() [2/2]

XrdClHttp::CurlWorker::CurlWorker ( const CurlWorker &  )
delete

Member Function Documentation

◆ ClientX509CertKeyFile()

std::tuple< std::string, std::string > CurlWorker::ClientX509CertKeyFile ( ) const

Definition at line 1051 of file XrdClHttpUtil.cc.

1052 {
1053  return std::make_tuple(m_x509_client_cert_file, m_x509_client_key_file);
1054 }

Referenced by XrdClHttp::CurlOperation::Setup().

+ Here is the caller graph for this function:

◆ GetMonitoringJson()

std::string CurlWorker::GetMonitoringJson ( )
static

Definition at line 1057 of file XrdClHttpUtil.cc.

1058 {
1059  auto now = std::chrono::system_clock::now().time_since_epoch().count();
1060  auto oldest_op = now;
1061  auto oldest_cycle = now;
1062  {
1063  std::unique_lock lk(m_worker_stats_mutex);
1064  for (const auto &entry : m_workers_last_completed_cycle) {
1065  if (!entry) {continue;}
1066  auto cycle = entry->load(std::memory_order_relaxed);
1067  if (cycle < oldest_cycle) oldest_cycle = cycle;
1068  }
1069  for (const auto &entry : m_workers_oldest_op) {
1070  if (!entry) {continue;}
1071  auto op = entry->load(std::memory_order_relaxed);
1072  if (op < oldest_op) oldest_op = op;
1073  }
1074  }
1075  auto oldest_op_dbl = std::chrono::duration<double>(std::chrono::system_clock::time_point(std::chrono::system_clock::duration(oldest_op)).time_since_epoch()).count();
1076  auto oldest_cycle_dbl = std::chrono::duration<double>(std::chrono::system_clock::time_point(std::chrono::system_clock::duration(oldest_cycle)).time_since_epoch()).count();
1077  std::string retval = "{"
1078  "\"oldest_op\":" + std::to_string(oldest_op_dbl) + ","
1079  "\"oldest_cycle\":" + std::to_string(oldest_cycle_dbl) + ","
1080  ;
1081 
1082  for (size_t verb_idx = 0; verb_idx < static_cast<int>(XrdClHttp::CurlOperation::HttpVerb::Count); verb_idx++) {
1083  const auto &verb_str = XrdClHttp::CurlOperation::GetVerbString(static_cast<XrdClHttp::CurlOperation::HttpVerb>(verb_idx));
1084  for (size_t op_idx = 0; op_idx < 402; op_idx++) {
1085  if (op_idx == 401) continue;
1086 
1087  auto &op_stats = m_ops[verb_idx][op_idx];
1088  auto duration = op_stats.m_duration.load(std::memory_order_relaxed);
1089  if (duration == 0) continue;
1090 
1091  std::string prefix = "http_" + verb_str + "_" + ((op_idx == 402) ? "invalid" : std::to_string(200 + op_idx)) + "_";
1092 
1093  auto duration_dbl = std::chrono::duration<double>(std::chrono::steady_clock::duration(duration)).count();
1094  retval += "\"" + prefix + "duration\":" + std::to_string(duration_dbl) + ",";
1095 
1096  duration = op_stats.m_pause_duration.load(std::memory_order_relaxed);
1097  if (duration > 0) {
1098  duration_dbl = std::chrono::duration<double>(std::chrono::steady_clock::duration(duration)).count();
1099  retval += "\"" + prefix + "pause_duration\":" + std::to_string(duration_dbl) + ",";
1100  }
1101 
1102  auto count = op_stats.m_bytes.load(std::memory_order_relaxed);
1103  if (count) retval += "\"" + prefix + "bytes\":" + std::to_string(count) + ",";
1104  count = op_stats.m_error.load(std::memory_order_relaxed);
1105  if (count) retval += "\"" + prefix + "error\":" + std::to_string(count) + ",";
1106  count = op_stats.m_finished.load(std::memory_order_relaxed);
1107  if (count) retval += "\"" + prefix + "finished\":" + std::to_string(count) + ",";
1108  count = op_stats.m_client_timeout.load(std::memory_order_relaxed);
1109  if (count) retval += "\"" + prefix + "client_timeout\":" + std::to_string(count) + ",";
1110  count = op_stats.m_server_timeout.load(std::memory_order_relaxed);
1111  if (count) retval += "\"" + prefix + "server_timeout\":" + std::to_string(count) + ",";
1112  }
1113  {
1114  auto &op_stats = m_ops[verb_idx][401];
1115  auto duration = op_stats.m_duration.load(std::memory_order_relaxed);
1116  if (duration == 0) continue;
1117 
1118  std::string prefix = "http_" + verb_str + "_";
1119 
1120  auto duration_dbl = std::chrono::duration<double>(std::chrono::steady_clock::duration(duration)).count();
1121  retval += "\"" + prefix + "preheader_duration\":" + std::to_string(duration_dbl) + ",";
1122 
1123  auto count = op_stats.m_started.load(std::memory_order_relaxed);
1124  if (count) retval += "\"" + prefix + "started\":" + std::to_string(count) + ",";
1125  count = op_stats.m_error.load(std::memory_order_relaxed);
1126  if (count) retval += "\"" + prefix + "preheader_error\":" + std::to_string(count) + ",";
1127  count = op_stats.m_finished.load(std::memory_order_relaxed);
1128  if (count) retval += "\"" + prefix + "preheader_finished\":" + std::to_string(count) + ",";
1129  count = op_stats.m_server_timeout.load(std::memory_order_relaxed);
1130  if (count) retval += "\"" + prefix + "preheader_timeout\":" + std::to_string(count) + ",";
1131  count = op_stats.m_conncall_timeout.load(std::memory_order_relaxed);
1132  if (count) retval += "\"" + prefix + "conncall_timeout\":" + std::to_string(count) + ",";
1133  }
1134  }
1135 
1136  retval +=
1137  "\"conncall_error\":" + std::to_string(m_conncall_errors.load(std::memory_order_relaxed)) + ","
1138  "\"conncall_started\":" + std::to_string(m_conncall_req.load(std::memory_order_relaxed)) + ","
1139  "\"conncall_success\":" + std::to_string(m_conncall_success.load(std::memory_order_relaxed)) + ","
1140  "\"conncall_timeout\":" + std::to_string(m_conncall_timeout.load(std::memory_order_relaxed)) +
1141  "}";
1142 
1143  return retval;
1144 }
static const std::string GetVerbString(HttpVerb)
XrdClHttp::HttpVerb HttpVerb
Definition: XrdClHttpOps.hh:63

References XrdClHttp::CurlOperation::GetVerbString().

+ Here is the call graph for this function:

◆ Run()

void CurlWorker::Run ( )

Definition at line 1226 of file XrdClHttpUtil.cc.

1226  {
1227  int max_pending = 50;
1228  XrdCl::DefaultEnv::GetEnv()->GetInt("HttpMaxPendingOps", max_pending);
1229  m_continue_queue.reset(new HandlerQueue(max_pending));
1230  auto &queue = *m_queue.get();
1231  m_logger->Debug(kLogXrdClHttp, "Started a curl worker");
1232 
1233  CURLM *multi_handle = curl_multi_init();
1234  if (multi_handle == nullptr) {
1235  throw std::runtime_error("Failed to create curl multi-handle");
1236  }
1237 
1238  int running_handles = 0;
1239  time_t last_maintenance = time(NULL);
1240  CURLMcode mres = CURLM_OK;
1241 
1242  // Map from a file descriptor that has an outstanding broker request
1243  // to the corresponding CURL handle.
1244  std::unordered_map<int, WaitingForBroker> broker_reqs;
1245  std::vector<struct curl_waitfd> waitfds;
1246 
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;
1255  }
1256  }
1257  m_oldest_op.store(oldest_op.time_since_epoch().count());
1258 
1259  // Try continuing any available handles that have more data
1260  while (true) {
1261  auto op = m_continue_queue->TryConsume();
1262  if (!op) {
1263  break;
1264  }
1265  // Avoid race condition where external thread added a continue operation to queue
1266  // while the curl worker thread failed the transfer.
1267  if (op->IsDone()) {
1268  m_logger->Debug(kLogXrdClHttp, "Ignoring continuation of operation that has already completed");
1269  continue;
1270  }
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");
1275  OpRecord(*op, OpKind::Error);
1276  op->ReleaseHandle();
1277  if (curl) {
1278  curl_multi_remove_handle(multi_handle, curl);
1279  curl_easy_cleanup(curl);
1280  m_op_map.erase(curl);
1281  }
1282  running_handles -= 1;
1283  continue;
1284  } else {
1285  auto iter = m_op_map.find(curl);
1286  if (iter != m_op_map.end()) iter->second.second = std::chrono::system_clock::now();
1287  }
1288  }
1289  // Consume from the shared new operation queue
1290  while (running_handles < static_cast<int>(m_max_ops)) {
1291  auto op = running_handles == 0 ? queue.Consume(std::chrono::seconds(1)) : queue.TryConsume();
1292  if (!op) {
1293  break;
1294  }
1295  auto curl = queue.GetHandle();
1296  if (curl == nullptr) {
1297  m_logger->Debug(kLogXrdClHttp, "Unable to allocate a curl handle");
1298  op->Fail(XrdCl::errInternal, ENOMEM, "Unable to get allocate a curl handle");
1299  continue;
1300  }
1301  try {
1302  auto rv = op->Setup(curl, *this);
1303  if (!rv) {
1304  m_logger->Debug(kLogXrdClHttp, "Failed to setup the curl handle");
1305  op->Fail(XrdCl::errInternal, ENOMEM, "Failed to setup the curl handle for the operation");
1306  continue;
1307  }
1308  if (!op->FinishSetup(curl)) {
1309  m_logger->Debug(kLogXrdClHttp, "Failed to finish setup of the curl handle");
1310  op->Fail(XrdCl::errInternal, ENOMEM, "Failed to finish setup of the curl handle for the operation");
1311  continue;
1312  }
1313  } catch (...) {
1314  m_logger->Debug(kLogXrdClHttp, "Unable to setup the curl handle");
1315  op->Fail(XrdCl::errInternal, ENOMEM, "Failed to setup the curl handle for the operation");
1316  continue;
1317  }
1318  op->SetContinueQueue(m_continue_queue);
1319 
1320  if (op->IsDone()) {
1321  op->ReleaseHandle();
1322  queue.RecycleHandle(curl);
1323  continue;
1324  }
1325  m_op_map[curl] = {op, std::chrono::system_clock::now()};
1326 
1327  // If the operation requires the result of the OPTIONS verb to function, then
1328  // we add that to the multi-handle instead, chaining the two calls together.
1329  if (op->RequiresOptions()) {
1330  std::string modified_url;
1331  std::shared_ptr<CurlOptionsOp> options_op(
1332  new CurlOptionsOp(
1333  curl, op,
1334  std::string(
1335  VerbsCache::GetUrlKey(op->GetUrl(), modified_url)
1336  ),
1337  m_logger, op->GetConnCalloutFunc()
1338  )
1339  );
1340  // Note this `curl` variable is not local to the conditional; it is the curl handle of the
1341  // CurlOptionsOp and will be added below to the multi-handle, causing it - not the parent's
1342  // curl handle - to be executed.
1343  curl = queue.GetHandle();
1344  if (curl == nullptr) {
1345  m_logger->Debug(kLogXrdClHttp, "Unable to allocate a curl handle");
1346  op->Fail(XrdCl::errInternal, ENOMEM, "Unable to get allocate a curl handle");
1347  OpRecord(*op, OpKind::Error);
1348  continue;
1349  }
1350  auto rv = options_op->Setup(curl, *this);
1351  if (!rv) {
1352  m_logger->Debug(kLogXrdClHttp, "Failed to allocate a curl handle for OPTIONS");
1353  continue;
1354  }
1355  m_op_map[curl] = {options_op, std::chrono::system_clock::now()};
1356  OpRecord(*options_op, OpKind::Start);
1357  running_handles += 1;
1358  } else {
1359  OpRecord(*op, OpKind::Start);
1360  }
1361 
1362  auto mres = curl_multi_add_handle(multi_handle, curl);
1363  if (mres != CURLM_OK) {
1364  m_logger->Debug(kLogXrdClHttp, "Unable to add operation to the curl multi-handle");
1365  op->Fail(XrdCl::errInternal, mres, "Unable to add operation to the curl multi-handle");
1366  OpRecord(*op, OpKind::Error);
1367  continue;
1368  }
1369  m_logger->Debug(kLogXrdClHttp, "Added request for URL %s to worker thread for processing", op->GetUrl().c_str());
1370  running_handles += 1;
1371  }
1372 
1373  // Maintain the periodic reporting of thread activity and fail any operations
1374  // that have expired / timed out.
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) {
1378  m_queue->Expire();
1379  m_continue_queue->Expire();
1380  m_logger->Debug(kLogXrdClHttp, "Curl worker thread %d is running %d operations",
1381  getthreadid(), running_handles);
1382  last_maintenance = now;
1383 
1384  // Timeout all the pending broker requests.
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);
1389  }
1390  }
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!");
1395  } else {
1396 
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()) {
1402  std::string target;
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()) {
1406  OpRecord(*iter->second.first, OpKind::Error);
1407  iter->second.first->Fail(XrdCl::errErrorResponse, 0, "Failed to send OPTIONS to redirect target");
1408  m_op_map.erase(iter);
1409  running_handles -= 1;
1410  }
1411  parent_op_failed = true;
1412  } else {
1413  OpRecord(*parent_op, OpKind::Start);
1414  }
1415  } else {
1416  OpRecord(*parent_op, OpKind::Start);
1417  }
1418  if (!parent_op_failed){
1419  curl_multi_add_handle(multi_handle, options_op->GetParentCurlHandle());
1420  }
1421  }
1422 
1423  iter->second.first->Fail(XrdCl::errConnectionError, 1, "Timeout: connection never provided for request");
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;
1429  }
1430  broker_reqs.erase(entry.first);
1431  m_conncall_timeout.fetch_add(1, std::memory_order_relaxed);
1432  }
1433 
1434  // Cleanup the fake connection cache entries.
1436  }
1437 
1438  waitfds.clear();
1439  waitfds.resize(3 + broker_reqs.size());
1440 
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;
1450 
1451  int idx = 3;
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;
1456  idx += 1;
1457  }
1458 
1459  long timeo;
1460  curl_multi_timeout(multi_handle, &timeo);
1461  // These commented-out lines are purposely left; will need to revisit after the 0.9.1 release;
1462  // for now, they are too verbose on RHEL7.
1463  //m_logger->Debug(kLogXrdClHttp, "Curl advises a timeout of %ld ms", timeo);
1464  if (running_handles && timeo == -1) {
1465  // Bug workaround: we've seen RHEL7 libcurl have a race condition where it'll not
1466  // set a timeout while doing the DNS lookup; assume that if there are running handles
1467  // but no timeout, we've hit this bug.
1468  //m_logger->Debug(kLogXrdClHttp, "Will sleep for up to 50ms");
1469  mres = curl_multi_wait(multi_handle, &waitfds[0], waitfds.size(), 50, nullptr);
1470  } else {
1471  //m_logger->Debug(kLogXrdClHttp, "Will sleep for up to %d seconds", max_sleep_time);
1472  //mres = curl_multi_wait(multi_handle, &waitfds[0], waitfds.size(), max_sleep_time*1000, nullptr);
1473  // Temporary test: we've been seeing DNS lookups timeout on additional platforms. Switch to always
1474  // poll as curl_multi_wait doesn't seem to get notified when DNS lookups are done.
1475  mres = curl_multi_wait(multi_handle, &waitfds[0], waitfds.size(), 50, nullptr);
1476  }
1477  if (mres != CURLM_OK) {
1478  m_logger->Warning(kLogXrdClHttp, "Failed to wait on multi-handle: %d", mres);
1479  }
1480 
1481  // Iterate through the waiting broker callbacks.
1482  for (const auto &entry : waitfds) {
1483  // Ignore the queue's poll fd.
1484  if (waitfds[0].fd == entry.fd || waitfds[1].fd == entry.fd) {
1485  continue;
1486  }
1487  // Handle shutdown requests
1488  if ((waitfds[2].fd == entry.fd) && entry.revents) {
1489  want_shutdown = true;
1490  break;
1491  }
1492  if ((entry.revents & CURL_WAIT_POLLIN) != CURL_WAIT_POLLIN) {
1493  continue;
1494  }
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);
1501  continue;
1502  }
1503  std::string err;
1504  auto result = iter->second.first->WaitSocketCallback(err);
1505  if (result == -1) {
1506  m_logger->Warning(kLogXrdClHttp, "Error when invoking the broker callback: %s", err.c_str());
1507 
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()) {
1513  std::string target;
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()) {
1517  OpRecord(*iter->second.first, OpKind::Error);
1518  iter->second.first->Fail(XrdCl::errErrorResponse, 0, "Failed to send OPTIONS to redirect target");
1519  m_op_map.erase(iter);
1520  running_handles -= 1;
1521  }
1522  parent_op_failed = true;
1523  } else {
1524  OpRecord(*parent_op, OpKind::Start);
1525  }
1526  } else {
1527  OpRecord(*parent_op, OpKind::Start);
1528  }
1529  if (!parent_op_failed){
1530  curl_multi_add_handle(multi_handle, options_op->GetParentCurlHandle());
1531  }
1532  }
1533 
1534  iter->second.first->Fail(XrdCl::errErrorResponse, 1, err);
1535  OpRecord(*iter->second.first, OpKind::Error);
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;
1540  } else {
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);
1544  }
1545  }
1546 
1547  // Do maintenance on the multi-handle
1548  int still_running;
1549  auto mres = curl_multi_perform(multi_handle, &still_running);
1550  if (mres == CURLM_CALL_MULTI_PERFORM) {
1551  continue;
1552  } else if (mres != CURLM_OK) {
1553  m_logger->Warning(kLogXrdClHttp, "Failed to perform multi-handle operation: %d", mres);
1554  break;
1555  }
1556 
1557  CURLMsg *msg;
1558  do {
1559  int msgq = 0;
1560  msg = curl_multi_info_read(multi_handle, &msgq);
1561  if (msg && (msg->msg == CURLMSG_DONE)) {
1562  if (!msg->easy_handle) {
1563  m_logger->Warning(kLogXrdClHttp, "Logic error: got a callback for a null handle");
1564  mres = CURLM_BAD_EASY_HANDLE;
1565  break;
1566  }
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;
1571  break;
1572  }
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);
1580  if (HTTPStatusIsError(sc)) {
1581  auto httpErr = HTTPStatusConvert(sc);
1582  op->Fail(httpErr.first, httpErr.second, op->GetStatusMessage());
1583  op->ReleaseHandle();
1584  // If this was a failed CurlOptionsOp, then we re-activate the parent handle.
1585  // If the parent handle was stopped at a redirect that now returns failure, then
1586  // we'll clean it up.
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()) {
1592  std::string target;
1593  if (parent_op->Redirect(target) == CurlOperation::RedirectAction::Fail) {
1594  OpRecord(*parent_op, OpKind::Error);
1595  m_op_map.erase(options_op->GetParentCurlHandle());
1596  running_handles -= 1;
1597  parent_op_failed = true;
1598  } else {
1599  OpRecord(*parent_op, OpKind::Start);
1600  }
1601  } else {
1602  OpRecord(*parent_op, OpKind::Start);
1603  }
1604  // Have curl execute the parent operation
1605  if (!parent_op_failed) {
1606  curl_multi_add_handle(multi_handle, options_op->GetParentCurlHandle());
1607  }
1608  }
1609  // The curl operation was successful, it's just the HTTP request failed; recycle the handle.
1610  queue.RecycleHandle(iter->first);
1611  } else {
1612  CurlOptionsOp *options_op = nullptr;
1613  // If this was a successful OPTIONS op, invoke the parent operation.
1614  if ((options_op = dynamic_cast<CurlOptionsOp*>(op.get()))) {
1615  options_op->Success();
1616  options_op->ReleaseHandle();
1617  // Note: op is scoped external to the conditional block
1618  op = options_op->GetOperation();
1619  op->OptionsDone();
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);
1624  }
1625  // Check to see if the operation ended in a redirect (note: this might)
1626  // be invoked a second time if this was the parent operation of an OPTIONS
1627  // op.
1628  if (op->IsRedirect()) {
1629  std::string target;
1630  switch (op->Redirect(target)) {
1631  case CurlOperation::RedirectAction::Fail:
1632  if (options_op) {
1633  // In this case, we failed immediately after an OPTIONS finished.
1634  // Since there's a Start recorded after the OPTIONS processing, we
1635  // must record an error.
1636  // In the non-OPTIONS case, we never recorded a second start and
1637  // don't need a matching failure.
1638  OpRecord(*op, OpKind::Error);
1639  }
1640  keep_handle = false;
1641  break;
1642  case CurlOperation::RedirectAction::Reinvoke:
1643  if (!options_op) {
1644  // In this case, the redirect occurred without any prior
1645  // OPTIONS call. This implies that `op` is the original call
1646  // and we need to restart it later and record another op start.
1647  keep_handle = true;
1648  OpRecord(*op, OpKind::Start);
1649  }
1650  break;
1651  case CurlOperation::RedirectAction::ReinvokeAfterAllow:
1652  {
1653  // The redirect resulted in a new endpoint where the cache lookup failed;
1654  // we need to know what HTTP verbs are in the server's Allow list before this
1655  // operation can continue. Inject a new CurlOptionsOp and chain it to the one
1656  // being processed. Once the OPTIONS request is done, then we'll restart this
1657  // operation.
1658  std::string modified_url;
1659  target = VerbsCache::GetUrlKey(target, 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) {
1664  m_logger->Debug(kLogXrdClHttp, "Unable to allocate a curl handle");
1665  op->Fail(XrdCl::errInternal, ENOMEM, "Unable to get allocate a curl handle");
1666  keep_handle = false;
1667  options_op = nullptr;
1668  break;
1669  }
1670  OpRecord(*new_op, OpKind::Start);
1671  try {
1672  auto rv = new_op->Setup(curl, *this);
1673  if (!rv) {
1674  m_logger->Debug(kLogXrdClHttp, "Unable to configure a curl handle for OPTIONS");
1675  keep_handle = false;
1676  options_op = nullptr;
1677  break;
1678  }
1679  } catch (...) {
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");
1682  OpRecord(*new_op, OpKind::Error);
1683  keep_handle = false;
1684  break;
1685  }
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");
1692  OpRecord(*new_op, OpKind::Error);
1693  break;
1694  }
1695  running_handles += 1;
1696  m_logger->Debug(kLogXrdClHttp, "Invoking the OPTIONS operation before redirect to %s", target.c_str());
1697  // The original curl operation needs to be kept around. Note that because options_op
1698  // is non-nil, we won't re-add the handle to the multi-handle.
1699  keep_handle = true;
1700  }
1701  }
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);
1708  }
1709  } else if (options_op) {
1710  // In this case, the OPTIONS call happened before the parent operation was started.
1711  curl_multi_add_handle(multi_handle, options_op->GetParentCurlHandle());
1712  }
1713  if (keep_handle) {
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);
1717  }
1718  } else if (!options_op) {
1719  // A multi-step operation may reset and reconfigure its
1720  // easy handle from Success(). Remove the completed
1721  // request before invoking it so libcurl no longer owns
1722  // the request configuration being replaced.
1723  curl_multi_remove_handle(multi_handle, iter->first);
1724  op->Success();
1725  if (op->IsDone()) {
1726  op->ReleaseHandle();
1727  // If the handle was successful, then we can recycle it.
1728  queue.RecycleHandle(iter->first);
1729  } else {
1730  // Multi-step operations may configure their easy handle
1731  // for another request from Success(). Keep ownership of
1732  // the handle and run the next request through this worker's
1733  // multi-handle like any other operation.
1734  auto next_res = curl_multi_add_handle(multi_handle, iter->first);
1735  if (next_res == CURLM_OK) {
1736  keep_handle = true;
1737  OpRecord(*op, OpKind::Start);
1738  } else {
1739  op->Fail(XrdCl::errInternal, next_res,
1740  "Unable to add the next operation request to the curl multi-handle");
1741  OpRecord(*op, OpKind::Error);
1742  op->ReleaseHandle();
1743  queue.RecycleHandle(iter->first);
1744  }
1745  }
1746  }
1747  }
1748  } else if (res == CURLE_COULDNT_CONNECT && op->UseConnectionCallout() && !op->GetTriedBoker()) {
1749  // In this case, we need to use the broker and the curl handle couldn't reuse
1750  // an existing socket.
1751  keep_handle = true;
1752  op->SetTriedBoker(); // Flag to ensure we try a connection only once per operation.
1753  std::string err;
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;
1759  } else {
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);
1765  }
1766  } else {
1767  if (res == CURLE_ABORTED_BY_CALLBACK || res == CURLE_WRITE_ERROR) {
1768  // We cannot invoke the failure from within a callback as the curl thread and
1769  // original thread of execution may fight over the ownership of the handle memory.
1770  switch (op->GetError()) {
1771  case CurlOperation::OpError::ErrHeaderTimeout:
1772 #ifdef HAVE_XPROTOCOL_TIMEREXPIRED
1773  op->Fail(XrdCl::errOperationExpired, 0, "Origin did not respond with headers within timeout");
1774 #else
1775  op->Fail(XrdCl::errOperationExpired, 0, "Origin did not respond within timeout");
1776 #endif
1777  OpRecord(*op, OpKind::Error);
1778  break;
1779  case CurlOperation::OpError::ErrCallback: {
1780  auto [ecode, emsg] = op->GetCallbackError();
1781  op->Fail(XrdCl::errErrorResponse, ecode, emsg);
1782  OpRecord(*op, OpKind::Error);
1783  break;
1784  }
1785  case CurlOperation::OpError::ErrOperationTimeout:
1786  op->Fail(XrdCl::errOperationExpired, 0, "Operation timed out");
1787  OpRecord(*op, op->IsPaused() ? OpKind::ClientTimeout : OpKind::ServerTimeout);
1788  break;
1789  case CurlOperation::OpError::ErrTransferSlow:
1790  op->Fail(XrdCl::errOperationExpired, 0, "Transfer speed below minimum threshold");
1791  OpRecord(*op, OpKind::ServerTimeout);
1792  break;
1793  case CurlOperation::OpError::ErrTransferClientStall:
1794  op->Fail(XrdCl::errOperationExpired, 0, "Transfer stalled for too long");
1795  OpRecord(*op, OpKind::ClientTimeout);
1796  break;
1797  case CurlOperation::OpError::ErrTransferStall:
1798  op->Fail(XrdCl::errOperationExpired, 0, "Transfer stalled for too long");
1799  OpRecord(*op, OpKind::ServerTimeout);
1800  break;
1801  case CurlOperation::OpError::ErrNone:
1802  op->Fail(XrdCl::errInternal, 0, "Operation was aborted without recording an abort reason");
1803  OpRecord(*op, OpKind::Error);
1804  break;
1805  };
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()) {
1811  std::string target;
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()) {
1815  OpRecord(*iter->second.first, OpKind::Error);
1816  iter->second.first->Fail(XrdCl::errErrorResponse, 0, "Failed to send OPTIONS to redirect target");
1817  m_op_map.erase(iter);
1818  running_handles -= 1;
1819  }
1820  parent_op_failed = true;
1821  } else {
1822  OpRecord(*parent_op, OpKind::Start);
1823  }
1824  } else {
1825  OpRecord(*parent_op, OpKind::Start);
1826  }
1827  if (!parent_op_failed){
1828  curl_multi_add_handle(multi_handle, options_op->GetParentCurlHandle());
1829  }
1830  }
1831  } else {
1832  auto xrdCode = CurlCodeConvert(res);
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);
1838  OpRecord(*op, OpKind::Error);
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()) {
1844  std::string target;
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()) {
1848  OpRecord(*iter->second.first, OpKind::Error);
1849  iter->second.first->Fail(XrdCl::errErrorResponse, 0, "Failed to send OPTIONS to redirect target");
1850  m_op_map.erase(iter);
1851  running_handles -= 1;
1852  }
1853  parent_op_failed = true;
1854  }
1855  }
1856  if (!parent_op_failed){
1857  curl_multi_add_handle(multi_handle, options_op->GetParentCurlHandle());
1858  }
1859  }
1860  }
1861  op->ReleaseHandle();
1862  }
1863  if (!keep_handle) {
1864  curl_multi_remove_handle(multi_handle, iter->first);
1865  if (res != CURLE_OK) {
1866  curl_easy_cleanup(iter->first);
1867  }
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);
1872  }
1873  }
1874  m_op_map.erase(iter);
1875  running_handles -= 1;
1876  }
1877  }
1878  } while (msg);
1879  }
1880 
1881  for (auto map_entry : m_op_map) {
1882  if (mres) {
1883  map_entry.second.first->Fail(XrdCl::errInternal, mres, curl_multi_strerror(mres));
1884  OpRecord(*map_entry.second.first, OpKind::Error);
1885  }
1886  if (multi_handle && map_entry.first) curl_multi_remove_handle(multi_handle, map_entry.first);
1887  }
1888 
1889  m_queue->ReleaseHandles();
1890  curl_multi_cleanup(multi_handle);
1891 }
std::pair< uint16_t, uint32_t > CurlCodeConvert(CURLcode res)
int emsg(int rc, char *msg)
@ Error
static void CleanupDnsCache()
static std::string_view GetUrlKey(const std::string &url, std::string &modified_url)
bool GetInt(const std::string &key, int &value)
Definition: XrdClEnv.cc:115
void Error(uint64_t topic, const char *format,...)
Report an error.
Definition: XrdClLog.cc:231
void Warning(uint64_t topic, const char *format,...)
Report a warning.
Definition: XrdClLog.cc:248
void Debug(uint64_t topic, const char *format,...)
Print a debug message.
Definition: XrdClLog.cc:282
std::pair< uint16_t, uint32_t > HTTPStatusConvert(unsigned status)
bool HTTPStatusIsError(unsigned status)
const uint16_t errErrorResponse
Definition: XrdClStatus.hh:105
const uint16_t errOperationExpired
Definition: XrdClStatus.hh:90
const uint16_t errInternal
Internal error.
Definition: XrdClStatus.hh:56
const uint16_t errConnectionError
Definition: XrdClStatus.hh:78
const uint64_t kLogXrdClHttp

References XrdClHttp::CurlOperation::CleanupDnsCache(), XrdClHttp::CurlOperation::ContinueHandle(), CurlCodeConvert(), XrdCl::Log::Debug(), emsg(), XrdCl::errConnectionError, XrdCl::errErrorResponse, XrdCl::errInternal, XrdCl::errOperationExpired, XrdCl::Log::Error(), Error, XrdClHttp::CurlOperation::Fail(), XrdClHttp::CurlOperation::FinishSetup(), XrdClHttp::CurlOperation::GetCallbackError(), XrdClHttp::CurlOperation::GetConnCalloutFunc(), XrdClHttp::CurlOperation::GetCurlErrorMessage(), XrdClHttp::CurlOperation::GetCurlHandle(), XrdCl::DefaultEnv::GetEnv(), XrdClHttp::CurlOperation::GetError(), XrdCl::Env::GetInt(), XrdClHttp::CurlOptionsOp::GetOperation(), XrdClHttp::CurlOptionsOp::GetParentCurlHandle(), XrdClHttp::CurlOperation::GetStatusCode(), XrdClHttp::CurlOperation::GetStatusMessage(), XrdClHttp::CurlOperation::GetTriedBoker(), XrdClHttp::CurlOperation::GetUrl(), XrdClHttp::VerbsCache::GetUrlKey(), XrdClHttp::HTTPStatusConvert(), XrdClHttp::HTTPStatusIsError(), XrdClHttp::CurlOperation::IsDone(), XrdClHttp::CurlOperation::IsPaused(), XrdClHttp::CurlOperation::IsRedirect(), XrdClHttp::kLogXrdClHttp, XrdClHttp::CurlOperation::OptionsDone(), XrdClHttp::CurlOperation::Redirect(), XrdClHttp::CurlOperation::ReleaseHandle(), XrdClHttp::CurlOptionsOp::ReleaseHandle(), XrdClHttp::CurlOperation::RequiresOptions(), XrdClHttp::CurlOperation::SetContinueQueue(), XrdClHttp::CurlOperation::SetTriedBoker(), XrdClHttp::CurlOperation::Setup(), XrdClHttp::CurlOperation::StartConnectionCallout(), XrdClHttp::CurlOptionsOp::Success(), XrdClHttp::CurlOperation::Success(), XrdClHttp::CurlOperation::UseConnectionCallout(), XrdClHttp::CurlOperation::WaitSocket(), and XrdCl::Log::Warning().

Referenced by RunStatic().

+ Here is the call graph for this function:
+ Here is the caller graph for this function:

◆ RunStatic()

void CurlWorker::RunStatic ( CurlWorker *  myself)
static

Definition at line 1207 of file XrdClHttpUtil.cc.

1208 {
1209  {
1210  std::unique_lock lock(myself->m_start_lock);
1211  myself->m_start_complete_cv.wait(lock, [&]{return myself->m_start_complete;});
1212  }
1213  try {
1214  myself->Run();
1215  } catch (...) {
1216  myself->m_logger->Warning(kLogXrdClHttp, "Curl worker got an exception");
1217  {
1218  std::unique_lock lock(m_workers_mutex);
1219  auto iter = std::remove_if(m_workers.begin(), m_workers.end(), [&](std::unique_ptr<XrdClHttp::CurlWorker> &worker){return worker.get() == myself;});
1220  m_workers.erase(iter);
1221  }
1222  }
1223 }

References XrdClHttp::kLogXrdClHttp, Run(), and XrdCl::Log::Warning().

+ Here is the call graph for this function:

◆ SetMaintenancePeriod()

static void XrdClHttp::CurlWorker::SetMaintenancePeriod ( unsigned  maint)
inlinestatic

Definition at line 70 of file XrdClHttpWorker.hh.

70  {
71  m_maintenance_period.store(maint, std::memory_order_relaxed);
72  }

◆ Start()

void CurlWorker::Start ( std::unique_ptr< XrdClHttp::CurlWorker >  self,
std::thread  tid 
)

Definition at line 1194 of file XrdClHttpUtil.cc.

1195 {
1196  {
1197  std::unique_lock lock(m_workers_mutex);
1198  m_workers.emplace_back(std::move(self));
1199  m_self_tid = std::move(tid);
1200  }
1201  std::unique_lock lock(m_start_lock);
1202  m_start_complete = true;
1203  m_start_complete_cv.notify_one();
1204 }

The documentation for this class was generated from the following files: