22 std::runtime_error(msg)
29class MultiCurlHandler {
31 MultiCurlHandler(std::vector<State*> &states, XrdSysError &log) :
32 m_handle(curl_multi_init()),
35 m_bytes_transferred(0),
39 if (m_handle == NULL) {
40 throw CurlHandlerSetupError(
"Failed to initialize a libcurl multi-handle");
42 m_avail_handles.reserve(states.size());
43 m_active_handles.reserve(states.size());
44 for (std::vector<State*>::const_iterator state_iter = states.begin();
45 state_iter != states.end();
47 m_avail_handles.push_back((*state_iter)->GetHandle());
53 if (!m_handle) {
return;}
54 for (std::vector<CURL *>::const_iterator it = m_active_handles.begin();
55 it != m_active_handles.end();
57 curl_multi_remove_handle(m_handle, *it);
59 curl_multi_cleanup(m_handle);
62 MultiCurlHandler(
const MultiCurlHandler &) =
delete;
64 CURLM *Get()
const {
return m_handle;}
66 void FinishCurlXfer(
CURL *curl) {
67 CURLMcode mres = curl_multi_remove_handle(m_handle, curl);
70 ss <<
"Failed to remove transfer from set: "
71 << curl_multi_strerror(mres);
72 throw std::runtime_error(ss.str());
74 for (std::vector<State*>::iterator state_iter = m_states.begin();
75 state_iter != m_states.end();
77 if (curl == (*state_iter)->GetHandle()) {
78 m_bytes_transferred += (*state_iter)->BytesTransferred();
79 int error_code = (*state_iter)->GetErrorCode();
80 if (error_code && !m_error_code) {
81 m_error_code = error_code;
82 m_error_message = (*state_iter)->GetErrorMessage();
84 int status_code = (*state_iter)->GetStatusCode();
85 if (status_code >= 400 && !m_status_code) {
86 m_status_code = status_code;
87 m_error_message = (*state_iter)->GetErrorMessage();
89 (*state_iter)->ResetAfterRequest();
93 for (std::vector<CURL *>::iterator iter = m_active_handles.begin();
94 iter != m_active_handles.end();
98 m_active_handles.erase(iter);
102 m_avail_handles.push_back(curl);
105 off_t StartTransfers(off_t current_offset, off_t content_length,
size_t block_size,
106 int &running_handles) {
107 bool started_new_xfer =
false;
109 size_t xfer_size = std::min(content_length - current_offset,
static_cast<off_t
>(block_size));
110 if (xfer_size == 0) {
return current_offset;}
111 if (!(started_new_xfer = StartTransfer(current_offset, xfer_size))) {
113 if (running_handles == 0) {
114 if (!CanStartTransfer(
true)) {
115 m_log.Emsg(
"StartTransfers",
"Unable to start transfers.");
120 running_handles += 1;
122 current_offset += xfer_size;
124 return current_offset;
131 int Flush(std::string &error_msg) {
133 for (std::vector<State*>::iterator state_it = m_states.begin();
134 state_it != m_states.end();
137 if (((*state_it)->Flush() == -1) && !error_code) {
139 error_msg = (*state_it)->GetFinalizeErrorMessage();
140 if (error_msg.empty()) {error_msg =
"(no error message provided)";}
146 off_t BytesTransferred()
const {
147 return m_bytes_transferred;
158 off_t BytesInFlightAndTransferred()
const {
159 off_t bytes = m_bytes_transferred;
160 for (std::vector<State*>::const_iterator state_iter = m_states.begin();
161 state_iter != m_states.end();
163 bytes += (*state_iter)->BytesTransferred();
168 int GetStatusCode()
const {
169 return m_status_code;
172 int GetErrorCode()
const {
176 void SetErrorCode(
int error_code) {
177 m_error_code = error_code;
180 std::string GetErrorMessage()
const {
181 return m_error_message;
184 void SetErrorMessage(
const std::string &error_msg) {
185 m_error_message = error_msg;
190 bool StartTransfer(off_t offset,
size_t size) {
191 if (!CanStartTransfer(
false)) {
return false;}
192 for (std::vector<CURL*>::const_iterator handle_it = m_avail_handles.begin();
193 handle_it != m_avail_handles.end();
195 for (std::vector<State*>::iterator state_it = m_states.begin();
196 state_it != m_states.end();
198 if ((*state_it)->GetHandle() == *handle_it) {
199 (*state_it)->SetTransferParameters(offset, size);
200 ActivateHandle(**state_it);
208 void ActivateHandle(State &state) {
210 m_active_handles.push_back(curl);
212 mres = curl_multi_add_handle(m_handle, curl);
214 std::stringstream ss;
215 ss <<
"Failed to add transfer to libcurl multi-handle"
216 << curl_multi_strerror(mres);
217 throw std::runtime_error(ss.str());
219 for (
auto iter = m_avail_handles.begin();
220 iter != m_avail_handles.end();
224 m_avail_handles.erase(iter);
230 bool CanStartTransfer(
bool log_reason)
const {
231 size_t idle_handles = m_avail_handles.size();
232 size_t transfer_in_progress = 0;
233 for (std::vector<State*>::const_iterator state_iter = m_states.begin();
234 state_iter != m_states.end();
236 for (std::vector<CURL*>::const_iterator handle_iter = m_active_handles.begin();
237 handle_iter != m_active_handles.end();
239 if (*handle_iter == (*state_iter)->GetHandle()) {
240 transfer_in_progress += (*state_iter)->BodyTransferInProgress();
247 m_log.Emsg(
"CanStartTransfer",
"Unable to start transfers as no idle CURL handles are available.");
251 ssize_t available_buffers = m_states[0]->AvailableBuffers();
254 available_buffers -= (m_active_handles.size() - transfer_in_progress);
255 if (log_reason && (available_buffers == 0)) {
256 std::stringstream ss;
257 ss <<
"Unable to start transfers as no buffers are available. Available buffers: " <<
258 m_states[0]->AvailableBuffers() <<
", Active curl handles: " << m_active_handles.size()
259 <<
", Transfers in progress: " << transfer_in_progress;
260 m_log.Emsg(
"CanStartTransfer", ss.str().c_str());
261 if (m_states[0]->AvailableBuffers() == 0) {
262 m_states[0]->DumpBuffers();
265 return available_buffers > 0;
269 std::vector<CURL *> m_avail_handles;
270 std::vector<CURL *> m_active_handles;
271 std::vector<State*> &m_states;
273 off_t m_bytes_transferred;
276 std::string m_error_message;
282 size_t streams, std::vector<State*> &handles,
283 std::vector<ManagedCurlHandle> &curl_handles, TPCLogRecord &rec)
288 off_t current_offset = 0;
290 size_t concurrency = streams * m_pipelining_multiplier;
292 handles.reserve(concurrency);
293 handles.push_back(
new State());
294 handles[0]->Move(state);
295 for (
size_t idx = 1; idx < concurrency; idx++) {
296 handles.push_back(handles[0]->
Duplicate());
297 curl_handles.emplace_back(handles.back()->GetHandle());
301 rec.pmarkManager.startTransfer();
304 MultiCurlHandler mch(handles, m_log);
305 CURLM *multi_handle = mch.Get();
307 curl_multi_setopt(multi_handle, CURLMOPT_PIPELINING, 1);
308 curl_multi_setopt(multi_handle, CURLMOPT_MAX_HOST_CONNECTIONS, streams);
311 int retval = req.
StartChunkedResp(201,
"Created",
"Content-Type: text/plain");
314 "Failed to send the initial response to the TPC client");
318 "Initial transfer response sent to the TPC client");
322 int running_handles = 0;
323 current_offset = mch.StartTransfers(current_offset, content_size, m_block_size, running_handles);
327 time_t last_marker = 0;
329 off_t last_advance_bytes = 0;
330 time_t last_advance_time = time(NULL);
331 time_t transfer_start = last_advance_time;
332 CURLcode res =
static_cast<CURLcode
>(-1);
333 CURLMcode mres = CURLM_OK;
335 time_t now = time(NULL);
336 time_t next_marker = last_marker + m_marker_period;
337 if (now >= next_marker) {
342 const off_t bytes_transferred = mch.BytesInFlightAndTransferred();
343 if (bytes_transferred > last_advance_bytes) {
344 last_advance_bytes = bytes_transferred;
345 last_advance_time = now;
347 if (SendPerfMarker(req, rec, handles, bytes_transferred)) {
349 "Failed to send a perf marker to the TPC client");
352 int timeout = (transfer_start == last_advance_time) ? m_first_timeout : m_timeout;
353 if (now > last_advance_time + timeout) {
354 const char *log_prefix = rec.log_prefix.c_str();
355 bool tpc_pull = strncmp(
"Pull", log_prefix, 4) == 0;
358 std::stringstream ss;
359 ss <<
"Transfer failed because no bytes have been "
360 << (tpc_pull ?
"received from the source (pull mode) in "
361 :
"transmitted to the destination (push mode) in ") << timeout <<
" seconds.";
362 mch.SetErrorMessage(ss.str());
368 mres = curl_multi_perform(multi_handle, &running_handles);
369 if (mres == CURLM_CALL_MULTI_PERFORM) {
373 }
else if (mres != CURLM_OK) {
377 rec.pmarkManager.beginPMarks();
384 msg = curl_multi_info_read(multi_handle, &msgq);
385 if (msg && (msg->msg == CURLMSG_DONE)) {
386 CURL *easy_handle = msg->easy_handle;
387 res = msg->data.result;
388 mch.FinishCurlXfer(easy_handle);
390 if (res != CURLE_OK) {
395 if (res !=
static_cast<CURLcode
>(-1) && res != CURLE_OK) {
396 std::stringstream ss;
397 ss <<
"Breaking loop due to failed curl transfer: " << curl_easy_strerror(res);
403 if (running_handles <
static_cast<int>(concurrency)) {
406 if (current_offset != content_size) {
407 current_offset = mch.StartTransfers(current_offset, content_size,
408 m_block_size, running_handles);
409 if (!running_handles) {
410 std::stringstream ss;
411 ss <<
"No handles are able to run. Streams=" << streams <<
", concurrency="
414 logTransferEvent(
LogMask::Debug, rec,
"MULTISTREAM_IDLE", ss.str());
416 }
else if (running_handles == 0) {
418 "All the ranges have been scheduled and all the handles are done; ending the transfer loop.");
423 int64_t max_sleep_time = next_marker - time(NULL);
424 if (max_sleep_time <= 0) {
428 mres = curl_multi_wait(multi_handle, NULL, 0, max_sleep_time*1000,
430 if (mres != CURLM_OK) {
433 }
while (running_handles);
435 if (mres != CURLM_OK) {
436 std::stringstream ss;
437 ss <<
"Internal libcurl multi-handle error: "
438 << curl_multi_strerror(mres);
439 logTransferEvent(
LogMask::Error, rec,
"MULTISTREAM_ERROR", ss.str());
440 throw std::runtime_error(ss.str());
447 msg = curl_multi_info_read(multi_handle, &msgq);
448 if (msg && (msg->msg == CURLMSG_DONE)) {
449 CURL *easy_handle = msg->easy_handle;
450 mch.FinishCurlXfer(easy_handle);
451 if (res == CURLE_OK || res ==
static_cast<CURLcode
>(-1))
452 res = msg->data.result;
456 if (!state.
GetErrorCode() && res ==
static_cast<CURLcode
>(-1)) {
458 "Internal state error in libcurl");
459 throw std::runtime_error(
"Internal state error in libcurl");
465 std::string flushErrorMsg;
466 const int flushErrorCode = mch.Flush(flushErrorMsg);
467 std::string flushErrorSuffix;
468 if (flushErrorCode) {
469 std::replace(flushErrorMsg.begin(), flushErrorMsg.end(),
'\n',
' ');
470 flushErrorMsg =
"Failed to flush the file to the local filesystem. " + flushErrorMsg;
471 logTransferEvent(
LogMask::Error, rec,
"FLUSH_FAIL", flushErrorMsg);
472 flushErrorSuffix =
"; " + flushErrorMsg;
475 rec.bytes_transferred = mch.BytesTransferred();
476 rec.tpc_status = mch.GetStatusCode();
479 std::stringstream ss;
481 if (mch.GetStatusCode() >= 400) {
482 std::string err = mch.GetErrorMessage();
483 std::stringstream ss2;
484 ss2 <<
"Remote side failed with status code " << mch.GetStatusCode();
486 std::replace(err.begin(), err.end(),
'\n',
' ');
487 ss2 <<
"; error message: \"" << err <<
"\"";
489 logTransferEvent(
LogMask::Error, rec,
"MULTISTREAM_FAIL", ss2.str());
490 ss2 << flushErrorSuffix;
491 ss << generateClientErr(ss2, rec);
495 std::stringstream ss2;
496 ss2 << mch.GetErrorMessage();
497 logTransferEvent(
LogMask::Error, rec,
"MULTISTREAM_FAIL", ss2.str());
498 ss2 << flushErrorSuffix;
499 ss << generateClientErr(ss2, rec);
500 }
else if (mch.GetErrorCode()) {
501 std::string err = mch.GetErrorMessage();
502 if (err.empty()) {err =
"(no error message provided)";}
503 else {std::replace(err.begin(), err.end(),
'\n',
' ');}
504 std::stringstream ss2;
505 ss2 <<
"Error when interacting with local filesystem: " << err;
506 logTransferEvent(
LogMask::Error, rec,
"MULTISTREAM_FAIL", ss2.str());
507 ss2 << flushErrorSuffix;
508 ss << generateClientErr(ss2, rec);
509 }
else if (res != CURLE_OK) {
510 std::stringstream ss2;
511 ss2 <<
"Request failed when processing";
512 std::stringstream ss3;
513 ss3 << ss2.str() <<
":" << curl_easy_strerror(res);
514 logTransferEvent(
LogMask::Error, rec,
"MULTISTREAM_FAIL", ss3.str());
515 ss2 << flushErrorSuffix;
516 ss << generateClientErr(ss2, rec, res);
517 }
else if (current_offset != content_size) {
518 std::stringstream ss2;
519 ss2 <<
"Internal logic error led to early abort; current offset is " <<
520 current_offset <<
" while full size is " << content_size;
521 logTransferEvent(
LogMask::Error, rec,
"MULTISTREAM_FAIL", ss2.str());
522 ss2 << flushErrorSuffix;
523 ss << generateClientErr(ss2, rec);
524 }
else if (flushErrorCode) {
526 std::stringstream ss2;
527 ss2 << flushErrorMsg;
528 ss << generateClientErr(ss2, rec);
530 if (!handles[0]->Finalize()) {
531 std::stringstream ss2;
532 ss2 <<
"Failed to finalize and close file handle.";
533 std::string handleErrMsg = handles[0]->GetFinalizeErrorMessage();
534 if(handleErrMsg.size()) {
535 std::replace(handleErrMsg.begin(), handleErrMsg.end(),
'\n',
' ');
536 ss2 <<
" " << handleErrMsg;
538 ss << generateClientErr(ss2, rec);
542 ss <<
"success: Created";
547 if ((retval = req.
ChunkResp(ss.str().c_str(), 0))) {
549 "Failed to send last update to remote client");
551 }
else if (success) {
559int TPCHandler::RunCurlWithStreams(XrdHttpExtReq &req,
State &state,
560 size_t streams, TPCLogRecord &rec)
562 std::vector<ManagedCurlHandle> curl_handles;
563 std::vector<State*> handles;
564 std::stringstream err_ss;
566 int retval = RunCurlWithStreamsImpl(req, state, streams, handles, curl_handles, rec);
567 for (std::vector<State*>::iterator state_iter = handles.begin();
568 state_iter != handles.end();
573 }
catch (CurlHandlerSetupError &e) {
574 for (std::vector<State*>::iterator state_iter = handles.begin();
575 state_iter != handles.end();
581 logTransferEvent(
LogMask::Error, rec,
"MULTISTREAM_ERROR", e.what());
582 std::stringstream ss;
584 err_ss << generateClientErr(ss, rec);
586 }
catch (std::runtime_error &e) {
587 for (std::vector<State*>::iterator state_iter = handles.begin();
588 state_iter != handles.end();
593 logTransferEvent(
LogMask::Error, rec,
"MULTISTREAM_ERROR", e.what());
594 std::stringstream ss;
596 err_ss << generateClientErr(ss, rec);
598 if ((retval = req.
ChunkResp(err_ss.str().c_str(), 0))) {
CurlHandlerSetupError(const std::string &msg)
virtual ~CurlHandlerSetupError() noexcept
off_t GetContentLength() const
int ChunkResp(const char *body, long long bodylen)
Send a (potentially partial) body in a chunked response; invoking with NULL body.
int StartChunkedResp(int code, const char *desc, const char *header_to_add)
Starts a chunked response; body of request is sent over multiple parts using the SendChunkResp.
int SendSimpleResp(int code, const char *desc, const char *header_to_add, const char *body, long long bodylen)
Sends a basic response. If the length is < 0 then it is calculated internally.