22class CurlHandlerSetupError :
public std::runtime_error {
24 CurlHandlerSetupError(
const std::string &msg) :
25 std::runtime_error(msg)
28 virtual ~CurlHandlerSetupError() throw () {}
32class MultiCurlHandler {
34 MultiCurlHandler(std::vector<State*> &states,
XrdSysError &log) :
35 m_handle(curl_multi_init()),
38 m_bytes_transferred(0),
42 if (m_handle == NULL) {
43 throw CurlHandlerSetupError(
"Failed to initialize a libcurl multi-handle");
45 m_avail_handles.reserve(states.size());
46 m_active_handles.reserve(states.size());
47 for (std::vector<State*>::const_iterator state_iter = states.begin();
48 state_iter != states.end();
50 m_avail_handles.push_back((*state_iter)->GetHandle());
56 if (!m_handle) {
return;}
57 for (std::vector<CURL *>::const_iterator it = m_active_handles.begin();
58 it != m_active_handles.end();
60 curl_multi_remove_handle(m_handle, *it);
62 curl_multi_cleanup(m_handle);
65 MultiCurlHandler(
const MultiCurlHandler &) =
delete;
67 CURLM *Get()
const {
return m_handle;}
69 void FinishCurlXfer(
CURL *curl) {
70 CURLMcode mres = curl_multi_remove_handle(m_handle, curl);
73 ss <<
"Failed to remove transfer from set: "
74 << curl_multi_strerror(mres);
75 throw std::runtime_error(ss.str());
77 for (std::vector<State*>::iterator state_iter = m_states.begin();
78 state_iter != m_states.end();
80 if (curl == (*state_iter)->GetHandle()) {
81 m_bytes_transferred += (*state_iter)->BytesTransferred();
82 int error_code = (*state_iter)->GetErrorCode();
83 if (error_code && !m_error_code) {
84 m_error_code = error_code;
85 m_error_message = (*state_iter)->GetErrorMessage();
87 int status_code = (*state_iter)->GetStatusCode();
88 if (status_code >= 400 && !m_status_code) {
89 m_status_code = status_code;
90 m_error_message = (*state_iter)->GetErrorMessage();
92 (*state_iter)->ResetAfterRequest();
96 for (std::vector<CURL *>::iterator iter = m_active_handles.begin();
97 iter != m_active_handles.end();
101 m_active_handles.erase(iter);
105 m_avail_handles.push_back(curl);
108 off_t StartTransfers(off_t current_offset, off_t content_length,
size_t block_size,
109 int &running_handles) {
110 bool started_new_xfer =
false;
112 size_t xfer_size = std::min(content_length - current_offset,
static_cast<off_t
>(block_size));
113 if (xfer_size == 0) {
return current_offset;}
114 if (!(started_new_xfer = StartTransfer(current_offset, xfer_size))) {
116 if (running_handles == 0) {
117 if (!CanStartTransfer(
true)) {
118 m_log.Emsg(
"StartTransfers",
"Unable to start transfers.");
123 running_handles += 1;
125 current_offset += xfer_size;
127 return current_offset;
132 for (std::vector<State*>::iterator state_it = m_states.begin();
133 state_it != m_states.end();
136 int error = (*state_it)->Flush();
137 if (error) {last_error = error;}
142 off_t BytesTransferred()
const {
143 return m_bytes_transferred;
146 int GetStatusCode()
const {
147 return m_status_code;
150 int GetErrorCode()
const {
154 void SetErrorCode(
int error_code) {
155 m_error_code = error_code;
158 std::string GetErrorMessage()
const {
159 return m_error_message;
162 void SetErrorMessage(
const std::string &error_msg) {
163 m_error_message = error_msg;
168 bool StartTransfer(off_t offset,
size_t size) {
169 if (!CanStartTransfer(
false)) {
return false;}
170 for (std::vector<CURL*>::const_iterator handle_it = m_avail_handles.begin();
171 handle_it != m_avail_handles.end();
173 for (std::vector<State*>::iterator state_it = m_states.begin();
174 state_it != m_states.end();
176 if ((*state_it)->GetHandle() == *handle_it) {
177 (*state_it)->SetTransferParameters(offset, size);
178 ActivateHandle(**state_it);
186 void ActivateHandle(
State &state) {
188 m_active_handles.push_back(curl);
190 mres = curl_multi_add_handle(m_handle, curl);
192 std::stringstream ss;
193 ss <<
"Failed to add transfer to libcurl multi-handle"
194 << curl_multi_strerror(mres);
195 throw std::runtime_error(ss.str());
197 for (
auto iter = m_avail_handles.begin();
198 iter != m_avail_handles.end();
202 m_avail_handles.erase(iter);
208 bool CanStartTransfer(
bool log_reason)
const {
209 size_t idle_handles = m_avail_handles.size();
210 size_t transfer_in_progress = 0;
211 for (std::vector<State*>::const_iterator state_iter = m_states.begin();
212 state_iter != m_states.end();
214 for (std::vector<CURL*>::const_iterator handle_iter = m_active_handles.begin();
215 handle_iter != m_active_handles.end();
217 if (*handle_iter == (*state_iter)->GetHandle()) {
218 transfer_in_progress += (*state_iter)->BodyTransferInProgress();
225 m_log.Emsg(
"CanStartTransfer",
"Unable to start transfers as no idle CURL handles are available.");
229 ssize_t available_buffers = m_states[0]->AvailableBuffers();
232 available_buffers -= (m_active_handles.size() - transfer_in_progress);
233 if (log_reason && (available_buffers == 0)) {
234 std::stringstream ss;
235 ss <<
"Unable to start transfers as no buffers are available. Available buffers: " <<
236 m_states[0]->AvailableBuffers() <<
", Active curl handles: " << m_active_handles.size()
237 <<
", Transfers in progress: " << transfer_in_progress;
238 m_log.Emsg(
"CanStartTransfer", ss.str().c_str());
239 if (m_states[0]->AvailableBuffers() == 0) {
240 m_states[0]->DumpBuffers();
243 return available_buffers > 0;
247 std::vector<CURL *> m_avail_handles;
248 std::vector<CURL *> m_active_handles;
249 std::vector<State*> &m_states;
251 off_t m_bytes_transferred;
254 std::string m_error_message;
260 size_t streams, std::vector<State*> &handles,
261 std::vector<ManagedCurlHandle> &curl_handles, TPCLogRecord &rec)
266 if ((result = DetermineXferSize(curl, req, state, success, rec)) || !success) {
270 off_t current_offset = 0;
274 size_t concurrency = streams * m_pipelining_multiplier;
276 handles.reserve(concurrency);
277 handles.push_back(
new State());
278 handles[0]->Move(state);
279 for (
size_t idx = 1; idx < concurrency; idx++) {
280 handles.push_back(handles[0]->
Duplicate());
281 curl_handles.emplace_back(handles.back()->GetHandle());
285 rec.pmarkManager.startTransfer();
288 MultiCurlHandler mch(handles, m_log);
289 CURLM *multi_handle = mch.Get();
292 curl_multi_setopt(multi_handle, CURLMOPT_PIPELINING, 1);
293 curl_multi_setopt(multi_handle, CURLMOPT_MAX_HOST_CONNECTIONS, streams);
297 int retval = req.
StartChunkedResp(201,
"Created",
"Content-Type: text/plain");
299 logTransferEvent(LogMask::Error, rec,
"RESPONSE_FAIL",
300 "Failed to send the initial response to the TPC client");
303 logTransferEvent(LogMask::Debug, rec,
"RESPONSE_START",
304 "Initial transfer response sent to the TPC client");
308 int running_handles = 0;
309 current_offset = mch.StartTransfers(current_offset, content_size, m_block_size, running_handles);
313 time_t last_marker = 0;
315 off_t last_advance_bytes = 0;
316 time_t last_advance_time = time(NULL);
317 time_t transfer_start = last_advance_time;
318 CURLcode res =
static_cast<CURLcode
>(-1);
319 CURLMcode mres = CURLM_OK;
321 time_t now = time(NULL);
322 time_t next_marker = last_marker + m_marker_period;
323 if (now >= next_marker) {
324 if (current_offset > last_advance_bytes) {
325 last_advance_bytes = current_offset;
326 last_advance_time = now;
328 if (SendPerfMarker(req, rec, handles, current_offset)) {
329 logTransferEvent(LogMask::Error, rec,
"PERFMARKER_FAIL",
330 "Failed to send a perf marker to the TPC client");
333 int timeout = (transfer_start == last_advance_time) ? m_first_timeout : m_timeout;
334 if (now > last_advance_time + timeout) {
335 const char *log_prefix = rec.log_prefix.c_str();
336 bool tpc_pull = strncmp(
"Pull", log_prefix, 4) == 0;
338 mch.SetErrorCode(10);
339 std::stringstream ss;
340 ss <<
"Transfer failed because no bytes have been "
341 << (tpc_pull ?
"received from the source (pull mode) in "
342 :
"transmitted to the destination (push mode) in ") << timeout <<
" seconds.";
343 mch.SetErrorMessage(ss.str());
349 mres = curl_multi_perform(multi_handle, &running_handles);
350 if (mres == CURLM_CALL_MULTI_PERFORM) {
354 }
else if (mres != CURLM_OK) {
358 rec.pmarkManager.beginPMarks();
365 msg = curl_multi_info_read(multi_handle, &msgq);
366 if (msg && (msg->msg == CURLMSG_DONE)) {
367 CURL *easy_handle = msg->easy_handle;
368 res = msg->data.result;
369 mch.FinishCurlXfer(easy_handle);
371 if (res != CURLE_OK) {
376 if (res !=
static_cast<CURLcode
>(-1) && res != CURLE_OK) {
377 std::stringstream ss;
378 ss <<
"Breaking loop due to failed curl transfer: " << curl_easy_strerror(res);
379 logTransferEvent(LogMask::Debug, rec,
"MULTISTREAM_CURL_FAILURE",
384 if (running_handles <
static_cast<int>(concurrency)) {
387 if (current_offset != content_size) {
388 current_offset = mch.StartTransfers(current_offset, content_size,
389 m_block_size, running_handles);
390 if (!running_handles) {
391 std::stringstream ss;
392 ss <<
"No handles are able to run. Streams=" << streams <<
", concurrency="
395 logTransferEvent(LogMask::Debug, rec,
"MULTISTREAM_IDLE", ss.str());
397 }
else if (running_handles == 0) {
398 logTransferEvent(LogMask::Debug, rec,
"MULTISTREAM_IDLE",
399 "Unable to start new transfers; breaking loop.");
404 int64_t max_sleep_time = next_marker - time(NULL);
405 if (max_sleep_time <= 0) {
409#ifdef HAVE_CURL_MULTI_WAIT
410 mres = curl_multi_wait(multi_handle, NULL, 0, max_sleep_time*1000,
416 if (mres != CURLM_OK) {
419 }
while (running_handles);
421 if (mres != CURLM_OK) {
422 std::stringstream ss;
423 ss <<
"Internal libcurl multi-handle error: "
424 << curl_multi_strerror(mres);
425 logTransferEvent(LogMask::Error, rec,
"MULTISTREAM_ERROR", ss.str());
426 throw std::runtime_error(ss.str());
433 msg = curl_multi_info_read(multi_handle, &msgq);
434 if (msg && (msg->msg == CURLMSG_DONE)) {
435 CURL *easy_handle = msg->easy_handle;
436 mch.FinishCurlXfer(easy_handle);
437 if (res == CURLE_OK || res ==
static_cast<CURLcode
>(-1))
438 res = msg->data.result;
442 if (!state.
GetErrorCode() && res ==
static_cast<CURLcode
>(-1)) {
443 logTransferEvent(LogMask::Error, rec,
"MULTISTREAM_ERROR",
444 "Internal state error in libcurl");
445 throw std::runtime_error(
"Internal state error in libcurl");
450 rec.bytes_transferred = mch.BytesTransferred();
451 rec.tpc_status = mch.GetStatusCode();
454 std::stringstream ss;
456 if (mch.GetStatusCode() >= 400) {
457 std::string err = mch.GetErrorMessage();
458 std::stringstream ss2;
459 ss2 <<
"Remote side failed with status code " << mch.GetStatusCode();
461 std::replace(err.begin(), err.end(),
'\n',
' ');
462 ss2 <<
"; error message: \"" << err <<
"\"";
464 logTransferEvent(LogMask::Error, rec,
"MULTISTREAM_FAIL", ss.str());
465 ss << generateClientErr(ss2, rec);
466 }
else if (mch.GetErrorCode()) {
467 std::string err = mch.GetErrorMessage();
468 if (err.empty()) {err =
"(no error message provided)";}
469 else {std::replace(err.begin(), err.end(),
'\n',
' ');}
470 std::stringstream ss2;
471 ss2 <<
"Error when interacting with local filesystem: " << err;
472 logTransferEvent(LogMask::Error, rec,
"MULTISTREAM_FAIL", ss2.str());
473 ss << generateClientErr(ss2, rec);
474 }
else if (res != CURLE_OK) {
475 std::stringstream ss2;
476 ss2 <<
"Request failed when processing";
477 std::stringstream ss3;
478 ss3 << ss2.str() <<
":" << curl_easy_strerror(res);
479 logTransferEvent(LogMask::Error, rec,
"MULTISTREAM_FAIL", ss3.str());
480 ss << generateClientErr(ss2, rec, res);
481 }
else if (current_offset != content_size) {
482 std::stringstream ss2;
483 ss2 <<
"Internal logic error led to early abort; current offset is " <<
484 current_offset <<
" while full size is " << content_size;
485 logTransferEvent(LogMask::Error, rec,
"MULTISTREAM_FAIL", ss2.str());
486 ss << generateClientErr(ss2, rec);
488 if (!handles[0]->Finalize()) {
489 std::stringstream ss2;
490 ss2 <<
"Failed to finalize and close file handle.";
491 ss << generateClientErr(ss2, rec);
492 logTransferEvent(LogMask::Error, rec,
"MULTISTREAM_ERROR",
495 ss <<
"success: Created";
500 if ((retval = req.
ChunkResp(ss.str().c_str(), 0))) {
501 logTransferEvent(LogMask::Error, rec,
"TRANSFER_ERROR",
502 "Failed to send last update to remote client");
504 }
else if (success) {
505 logTransferEvent(LogMask::Info, rec,
"TRANSFER_SUCCESS");
513 size_t streams, TPCLogRecord &rec)
515 std::vector<ManagedCurlHandle> curl_handles;
516 std::vector<State*> handles;
517 std::stringstream err_ss;
519 int retval = RunCurlWithStreamsImpl(req, state, streams, handles, curl_handles, rec);
520 for (std::vector<State*>::iterator state_iter = handles.begin();
521 state_iter != handles.end();
526 }
catch (CurlHandlerSetupError &e) {
527 for (std::vector<State*>::iterator state_iter = handles.begin();
528 state_iter != handles.end();
534 logTransferEvent(LogMask::Error, rec,
"MULTISTREAM_ERROR", e.what());
535 std::stringstream ss;
537 err_ss << generateClientErr(ss, rec);
539 }
catch (std::runtime_error &e) {
540 for (std::vector<State*>::iterator state_iter = handles.begin();
541 state_iter != handles.end();
546 logTransferEvent(LogMask::Error, rec,
"MULTISTREAM_ERROR", e.what());
547 std::stringstream ss;
549 err_ss << generateClientErr(ss, rec);
551 if ((retval = req.
ChunkResp(err_ss.str().c_str(), 0))) {
CURLMcode curl_multi_wait_impl(CURLM *multi_handle, int timeout_ms, int *numfds)
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.