XRootD
Loading...
Searching...
No Matches
XrdClHttpFile.cc
Go to the documentation of this file.
1/***************************************************************
2 *
3 * Copyright (C) 2025, Morgridge Institute for Research
4 *
5 ***************************************************************/
6
7#include "XrdClHttpFile.hh"
9#include "XrdClHttpOps.hh"
11#include "XrdClHttpResponses.hh"
12#include "XrdClHttpUtil.hh"
13#include "XrdClHttpWorker.hh"
14
17#include <XrdCl/XrdClLog.hh>
18#include <XrdCl/XrdClStatus.hh>
19#include <XrdCl/XrdClURL.hh>
20#include <XrdOuc/XrdOucCRC.hh>
22#include <XrdOuc/XrdOucJson.hh>
23
24#include <charconv>
25#include <iostream>
26
27using namespace XrdClHttp;
28
29std::atomic<uint64_t> File::m_prefetch_count = 0;
30std::atomic<uint64_t> File::m_prefetch_expired_count = 0;
31std::atomic<uint64_t> File::m_prefetch_failed_count = 0;
32std::atomic<uint64_t> File::m_prefetch_reads_hit = 0;
33std::atomic<uint64_t> File::m_prefetch_reads_miss = 0;
34std::atomic<uint64_t> File::m_prefetch_bytes_used = 0;
35
36namespace {
37
38// A response handler for the file open operation when "full download" is requested.
39//
40// In this case, the open triggers a GET of the entire object with a zero-sized buffer;
41// that means the response handler is invoked as soon as the GET response is started.
42// Subsequent calls to Read() will return the data from the GET response.
43class OpenFullDownloadResponseHandler : public XrdCl::ResponseHandler {
44public:
45 OpenFullDownloadResponseHandler(bool *is_opened, bool send_response_info, XrdCl::ResponseHandler *handler)
46 : m_send_response_info(send_response_info), m_is_opened(is_opened), m_handler(handler)
47 {}
48
49 virtual void HandleResponse(XrdCl::XRootDStatus *status, XrdCl::AnyObject *response) {
50 std::unique_ptr<OpenFullDownloadResponseHandler> holder(this);
51 std::unique_ptr<XrdCl::AnyObject> response_holder(response);
52 std::unique_ptr<XrdCl::XRootDStatus> status_holder(status);
53
54 if (!status || !status->IsOK()) {
55 if (m_handler) m_handler->HandleResponse(status_holder.release(), response_holder.release());
56 return;
57 }
58 if (m_is_opened) *m_is_opened = true;
59 if (!m_handler) {
60 return;
61 }
62 if (m_send_response_info) {
63 XrdCl::ChunkInfo *ci = nullptr;
64 response->Get(ci);
65 if (!ci) {
66 m_handler->HandleResponse(new XrdCl::XRootDStatus(XrdCl::stError, XrdCl::errInternal, ENOENT, "No ChunkInfo in response"), nullptr);
67 return;
68 }
69 std::unique_ptr<XrdClHttp::ReadResponseInfo> read_response_info(static_cast<XrdClHttp::ReadResponseInfo *>(ci));
70 auto info = read_response_info->GetResponseInfo();
71 XrdClHttp::OpenResponseInfo *open_info(new XrdClHttp::OpenResponseInfo());
72 open_info->SetResponseInfo(std::move(info));
73 auto obj = new XrdCl::AnyObject();
74 obj->Set(open_info);
75 m_handler->HandleResponse(status_holder.release(), obj);
76 } else {
77 m_handler->HandleResponse(status_holder.release(), nullptr);
78 }
79 }
80private:
81 bool m_send_response_info; // If true, the response handler will set the response info object.
82 bool *m_is_opened; // If the file-open is successful, this will be set to true.
83 XrdCl::ResponseHandler *m_handler; // The handler to call with the final result
84};
85
86// A response handler for the "normal" open mode (which typically translates
87// to a HEAD or PROPFIND).
88class OpenResponseHandler : public XrdCl::ResponseHandler {
89public:
90 OpenResponseHandler(bool *is_opened, XrdCl::ResponseHandler *handler)
91 : m_is_opened(is_opened), m_handler(handler)
92 {}
93
94 virtual void HandleResponse(XrdCl::XRootDStatus *status, XrdCl::AnyObject *response) {
95 std::unique_ptr<OpenResponseHandler> holder(this);
96 std::unique_ptr<XrdCl::AnyObject> response_holder(response);
97 std::unique_ptr<XrdCl::XRootDStatus> status_holder(status);
98
99 if (!status || !status->IsOK()) {
100 if (m_handler) m_handler->HandleResponse(status_holder.release(), response_holder.release());
101 return;
102 }
103 if (m_is_opened) *m_is_opened = true;
104 if (!m_handler) {
105 return;
106 }
107 m_handler->HandleResponse(status_holder.release(), response_holder.release());
108 }
109
110private:
111 bool *m_is_opened; // If the file-open is successful, this will be set to true.
112 XrdCl::ResponseHandler *m_handler; // The handler to call with the final result
113};
114
115// A response handler that transforms the read result into a PageInfo object.
116// This is used for page reads which require a checksum of each page; note
117// this is computed client-side whereas for the xroot protocol the checksum is computed server-side.
118class PgReadResponseHandler : public XrdCl::ResponseHandler {
119public:
120 PgReadResponseHandler(XrdCl::ResponseHandler *handler)
121 : m_handler(handler)
122 {}
123
124 virtual void HandleResponse(XrdCl::XRootDStatus *status, XrdCl::AnyObject *response) {
125 std::unique_ptr<PgReadResponseHandler> holder(this);
126 if (!status || !status->IsOK()) {
127 if (m_handler) m_handler->HandleResponse(status, response);
128 else delete response;
129 return;
130 }
131 if (!m_handler) {
132 delete response;
133 return;
134 }
135
136 // Transform the read result ChunkInfo into a PageInfo.
137 XrdCl::ChunkInfo *ci = nullptr;
138 response->Get(ci);
139 if (!ci) {
140 delete response;
141 if (m_handler) m_handler->HandleResponse(status, nullptr);
142 return;
143 }
144 std::vector<uint32_t> cksums;
145 size_t nbpages = ci->GetLength() / XrdSys::PageSize;
146 if (ci->GetLength() % XrdSys::PageSize) ++nbpages;
147 cksums.reserve(nbpages);
148
149 auto buffer = static_cast<const char *>(ci->GetBuffer());
150 size_t size = ci->GetLength();
151 for (size_t pg=0; pg<nbpages; ++pg)
152 {
153 auto pgsize = static_cast<size_t>(XrdSys::PageSize);
154 if (pgsize > size) pgsize = size;
155 cksums.push_back(XrdOucCRC::Calc32C(buffer, pgsize));
156 buffer += pgsize;
157 size -= pgsize;
158 }
159
160 auto page_info = new XrdCl::PageInfo(ci->GetOffset(), ci->GetLength(), ci->GetBuffer(), std::move(cksums));
161 auto obj = new XrdCl::AnyObject();
162 obj->Set(page_info);
163 delete response;
164 auto handle = m_handler;
165 m_handler = nullptr;
166 handle->HandleResponse(status, obj);
167 }
168
169private:
170 XrdCl::ResponseHandler *m_handler;
171};
172
173// A response handler for close operations that require creating a zero-length
174// object.
175class CloseCreateHandler : public XrdCl::ResponseHandler {
176public:
177 CloseCreateHandler(XrdCl::ResponseHandler *handler)
178 : m_handler(handler)
179 {}
180
181 virtual void HandleResponse(XrdCl::XRootDStatus *status_raw, XrdCl::AnyObject *response_raw) {
182 std::unique_ptr<CloseCreateHandler> self(this);
183 std::unique_ptr<XrdCl::XRootDStatus> status(status_raw);
184 std::unique_ptr<XrdCl::AnyObject> response(response_raw);
185
186 if (m_handler) m_handler->HandleResponse(status.release(), nullptr);
187 }
188
189private:
190 XrdCl::ResponseHandler *m_handler;
191};
192
193} // anonymous namespace
194
195// Note: these values are typically overwritten by `CurlFactory::CurlFactory`;
196// they are set here just to avoid uninitialized globals.
197struct timespec XrdClHttp::File::m_min_client_timeout = {2, 0};
198struct timespec XrdClHttp::File::m_default_header_timeout = {9, 5};
199struct timespec XrdClHttp::File::m_fed_timeout = {5, 0};
200
201
202File::~File() noexcept {
203 auto handler = m_put_handler.load(std::memory_order_acquire);
204 if (handler) {
205 // We must wait for all ongoing writes to complete; the XrdCl::File
206 // destructor will trigger a Close() operation when it is called without
207 // waiting for the Close to finish, then invoke our destructor.
208 // If the Close() is still ongoing, then the handler will receive a
209 // callback after its memory is freed.
210 handler->WaitForCompletion();
211 delete handler;
212 }
213}
214
216File::GetConnCallout() const {
217 std::string pointer_str;
218 if (!GetProperty("XrdClConnectionCallout", pointer_str) && pointer_str.empty()) {
219 return nullptr;
220 }
221 long long pointer;
222 try {
223 pointer = std::stoll(pointer_str, nullptr, 16);
224 } catch (...) {
225 return nullptr;
226 }
227 if (!pointer) {
228 return nullptr;
229 }
230 return reinterpret_cast<CreateConnCalloutType>(pointer);
231}
232
233struct timespec
234File::ParseHeaderTimeout(const std::string &timeout_string, XrdCl::Log *logger)
235{
236 struct timespec ts = File::GetDefaultHeaderTimeout();
237 if (!timeout_string.empty()) {
238 std::string errmsg;
239 // Parse the provided timeout and decrease by a second if we can (if it's below a second, halve it).
240 // The thinking is that if the client needs a response in N seconds, then we ought to set the internal
241 // timeout to (N-1) seconds to provide enough time for our response to arrive at the client.
242 if (!XrdClHttp::ParseTimeout(timeout_string, ts, errmsg)) {
243 logger->Error(kLogXrdClHttp, "Failed to parse xrdclhttp.timeout parameter: %s", errmsg.c_str());
244 } else if (ts.tv_sec >= 1) {
245 ts.tv_sec--;
246 } else {
247 ts.tv_nsec /= 2;
248 }
249 }
250 const auto mct = File::GetMinimumHeaderTimeout();
251 if (ts.tv_sec < mct.tv_sec ||
252 (ts.tv_sec == mct.tv_sec && ts.tv_nsec < mct.tv_nsec))
253 {
254 ts.tv_sec = mct.tv_sec;
255 ts.tv_nsec = mct.tv_nsec;
256 }
257
258 return ts;
259}
260
261struct timespec
262File::GetHeaderTimeoutWithDefault(time_t oper_timeout, const struct timespec &header_timeout)
263{
264 if (oper_timeout == 0) {
266 XrdCl::DefaultEnv::GetEnv()->GetInt( "RequestTimeout", val );
267 oper_timeout = val;
268 }
269 if (oper_timeout <= 0) {
270 return header_timeout;
271 }
272 if (oper_timeout == header_timeout.tv_sec) {
273 return {header_timeout.tv_sec, 0};
274 } else if (header_timeout.tv_sec < oper_timeout) {
275 return header_timeout;
276 } else { // header timeout is larger than the operation timeout
277 return {oper_timeout, 0};
278 }
279}
280
281struct timespec
282File::GetHeaderTimeout(time_t oper_timeout) const
283{
284 return GetHeaderTimeoutWithDefault(oper_timeout, m_header_timeout);
285}
286
287std::string
289{
290 return "{\"prefetch\": {"
291 "\"count\": " + std::to_string(m_prefetch_count) + ","
292 "\"expired\": " + std::to_string(m_prefetch_expired_count) + ","
293 "\"failed\": " + std::to_string(m_prefetch_failed_count) + ","
294 "\"reads_hit\": " + std::to_string(m_prefetch_reads_hit) + ","
295 "\"reads_miss\": " + std::to_string(m_prefetch_reads_miss) + ","
296 "\"bytes_used\": " + std::to_string(m_prefetch_bytes_used) +
297 "}}";
298}
299
301File::Open(const std::string &url,
304 XrdCl::ResponseHandler *handler,
305 time_t timeout)
306{
307 if (m_is_opened) {
308 m_logger->Error(kLogXrdClHttp, "URL %s already open", url.c_str());
310 }
311
312 m_open_flags = flags;
313
314 m_header_timeout.tv_nsec = m_default_header_timeout.tv_nsec;
315 m_header_timeout.tv_sec = m_default_header_timeout.tv_sec;
316 auto parsed_url = XrdCl::URL();
317 parsed_url.SetPort(0);
318 if (!parsed_url.FromString(url)) {
319 m_logger->Error(kLogXrdClHttp, "Failed to parse provided URL as a valid URL: %s", url.c_str());
321 }
322 auto pm = parsed_url.GetParams();
323 auto iter = pm.find("xrdclhttp.timeout");
324 std::string timeout_string = (iter == pm.end()) ? "" : iter->second;
325 m_header_timeout = ParseHeaderTimeout(timeout_string, m_logger);
326 pm["xrdclhttp.timeout"] = XrdClHttp::MarshalDuration(m_header_timeout);
327 parsed_url.SetParams(pm);
328 iter = pm.find("oss.asize");
329 if (iter != pm.end()) {
330 off_t asize;
331 auto ec = std::from_chars(iter->second.c_str(), iter->second.c_str() + iter->second.size(), asize);
332 if ((ec.ec == std::errc()) && (ec.ptr == iter->second.c_str() + iter->second.size()) && asize >= 0) {
333 m_asize = asize;
334 } else {
335 return XrdCl::XRootDStatus(XrdCl::stError, XrdCl::errInvalidOp, 0, "Unable to parse oss.asize to a valid size");
336 }
337 pm.erase(iter);
338 parsed_url.SetParams(pm);
339 }
340
341 m_url = parsed_url.GetURL();
342 m_last_url = "";
343 m_url_current = "";
344
345 auto ts = GetHeaderTimeout(timeout);
346
347 bool full_download = m_full_download.load(std::memory_order_relaxed);
348 m_default_prefetch_handler.reset(new PrefetchDefaultHandler(*this));
349 if (full_download) {
350 m_default_prefetch_handler->m_prefetch_enabled.store(true, std::memory_order_relaxed);
351 }
352
353 if (full_download && !(flags & XrdCl::OpenFlags::Write)) {
354 m_logger->Debug(kLogXrdClHttp, "Opening %s in full download mode", m_url.c_str());
355
356 handler = new OpenFullDownloadResponseHandler(&m_is_opened, SendResponseInfo(), handler);
357 m_prefetch_size = std::numeric_limits<off_t>::max();
358 auto [status, ok] = ReadPrefetch(0, 0, nullptr, handler, timeout, false);
359 if (ok) {
360 return status;
361 } else {
362 m_logger->Error(kLogXrdClHttp, "Failed to start prefetch of data at open (URL %s): %s", m_url.c_str(), status.ToString().c_str());
363 return status;
364 }
365 }
366
367
368 m_logger->Debug(kLogXrdClHttp, "Opening %s (with timeout %lld)", m_url.c_str(), (long long) timeout);
369
370 // This response handler sets the m_is_opened flag to true if the open callback is successfully invoked.
371 handler = new OpenResponseHandler(&m_is_opened, handler);
372
373 std::shared_ptr<XrdClHttp::CurlOpenOp> openOp(
375 handler, GetCurrentURL(), ts, m_logger, this, SendResponseInfo(), GetConnCallout(),
376 &m_default_header_callout
377 )
378 );
379 try {
380 m_queue->Produce(std::move(openOp));
381 } catch (...) {
382 m_logger->Warning(kLogXrdClHttp, "Failed to add open op to queue");
384 }
385
386 return XrdCl::XRootDStatus();
387}
388
391 time_t timeout)
392{
393 if (!m_is_opened) {
394 m_logger->Error(kLogXrdClHttp, "Cannot close. URL isn't open");
396 }
397 m_is_opened = false;
398
399 std::unique_ptr<XrdCl::XRootDStatus> status(new XrdCl::XRootDStatus{});
400 if (m_put_op && !m_put_op->HasFailed()) {
401 auto put_size = m_put_offset.load(std::memory_order_relaxed);
402 if (m_asize >= 0 && put_size == m_asize) {
403 if (put_size == m_asize) {
404 m_logger->Debug(kLogXrdClHttp, "Closing a finished file %s", m_url.c_str());
405 } else {
406 m_logger->Debug(kLogXrdClHttp, "Closing a file %s with partial size (offset %llu, expected %lld)",
407 m_url.c_str(), static_cast<unsigned long long>(put_size), static_cast<long long>(m_asize));
409 0, "Cannot close file with partial size"));
410 }
411 } else {
412 m_logger->Debug(kLogXrdClHttp, "Flushing final write buffer on close");
413 auto put_handler = m_put_handler.load(std::memory_order_acquire);
414 if (put_handler) {
415 return put_handler->QueueWrite(std::make_pair(nullptr, 0), handler);
416 } else {
417 m_logger->Error(kLogXrdClHttp, "Internal state error - put operation ongoing without handle");
419 }
420 }
421 } else if (!m_put_op && m_open_flags & XrdCl::OpenFlags::Write) {
422 timespec ts;
423 timespec_get(&ts, TIME_UTC);
424 ts.tv_sec += timeout;
425 m_asize = 0;
426 auto handler_wrapper = new PutResponseHandler(new CloseCreateHandler(handler));
427 m_put_handler.store(handler_wrapper, std::memory_order_release);
428 m_put_op.reset(new XrdClHttp::CurlPutOp(
429 handler_wrapper, m_default_put_handler, m_url, nullptr, 0, ts, m_logger,
430 GetConnCallout(), &m_default_header_callout
431 ));
432 handler_wrapper->SetOp(m_put_op);
433 m_url_current = "";
434 m_last_url = "";
435 m_logger->Debug(kLogXrdClHttp, "Creating a zero-sized object at %s for close", m_url.c_str());
436 try {
437 m_queue->Produce(m_put_op);
438 } catch (...) {
439 m_put_handler.store(nullptr, std::memory_order_release);
440 m_logger->Warning(kLogXrdClHttp, "Failed to add put op to queue");
442 }
443 return {};
444 }
445
446 m_logger->Debug(kLogXrdClHttp, "Closed %s", m_url.c_str());
447 m_url_current = "";
448 m_last_url = "";
449
450 if (handler) {
451 handler->HandleResponse(status.release(), nullptr);
452 }
453 return XrdCl::XRootDStatus();
454}
455
457File::Stat(bool /*force*/,
458 XrdCl::ResponseHandler *handler,
459 time_t timeout)
460{
461 if (!m_is_opened) {
462 m_logger->Error(kLogXrdClHttp, "Cannot stat. URL isn't open");
464 }
465
466 std::string content_length_str;
467 int64_t content_length;
468 if (!GetProperty("ContentLength", content_length_str)) {
469 m_logger->Error(kLogXrdClHttp, "Content length missing for %s", m_url.c_str());
471 }
472 try {
473 content_length = std::stoll(content_length_str);
474 } catch (...) {
475 m_logger->Error(kLogXrdClHttp, "Content length not an integer for %s", m_url.c_str());
477 }
478 if (content_length < 0) {
479 m_logger->Error(kLogXrdClHttp, "Content length negative for %s", m_url.c_str());
481 }
482
483 m_logger->Debug(kLogXrdClHttp, "Successful stat operation on %s (size %lld)", m_url.c_str(), static_cast<long long>(content_length));
484 auto stat_info = new XrdCl::StatInfo("nobody", content_length,
486 auto obj = new XrdCl::AnyObject();
487 obj->Set(stat_info);
488
489 handler->HandleResponse(new XrdCl::XRootDStatus(), obj);
490 return XrdCl::XRootDStatus();
491}
492
495 time_t timeout)
496{
497 if (!m_is_opened) {
498 m_logger->Error(kLogXrdClHttp, "Cannot run fcntl. URL isn't open");
500 }
501
502 auto obj = new XrdCl::AnyObject();
503 std::string as = arg.ToString();
504 try
505 {
507 if (code == XrdCl::QueryCode::XAttr)
508 {
509 nlohmann::json xatt;
510 std::string etagRes;
511 if (GetProperty("ETag", etagRes))
512 {
513 xatt["ETag"] = etagRes;
514 }
515 std::string cc;
516 if (GetProperty("Cache-Control", cc))
517 {
518 if (cc.find("must-revalidate") != std::string::npos)
519 {
520 xatt["revalidate"] = true;
521 }
522 size_t fm = cc.find("max-age=");
523 if (fm != std::string::npos)
524 {
525 fm += 9; // idx of the first character after the make-age= match
526 for (size_t i = fm; i < cc.length(); i++)
527 {
528 if (!std::isdigit(cc[i]))
529 {
530 std::string sa = cc.substr(fm, i);
531 long int a = std::stol(sa);
532 time_t t = time(NULL) + a;
533 xatt["expire"] = t;
534 break;
535 }
536 }
537 }
538 }
539 XrdCl::Buffer *respBuff = new XrdCl::Buffer();
540 m_logger->Debug(kLogXrdClHttp, "Fcntl content %s", xatt.dump().c_str());
541 respBuff->FromString(xatt.dump());
542 obj->Set(respBuff);
543 }
544 //
545 // Query codes supported by XrdCl::File::Fctnl
546 //
547 else {
548 std::string msg;
550 switch (code) {
552 msg = "Server status query not supported.";
553 break;
554 case XrdCl::QueryCode::Checksum: // fallthrough
556 msg = "Checksum query not supported.";
557 break;
559 msg = "Server configuration query not supported.";
560 break;
562 msg = "Local space stats query not supported.";
563 break;
564 case XrdCl::QueryCode::Opaque: // fallthrough
566 // XrdCl implementation dependent
567 msg = "Opaque query not supported.";
568 break;
570 msg = "Prepare status query not supported.";
571 break;
572 default:
573 msg = "Invalid information query type code";
574 }
575 m_logger->Error(kLogXrdClHttp, "%s", msg.c_str());
576 return status;
577 }
578 }
579 catch (const std::exception& e)
580 {
581 m_logger->Warning(kLogXrdClHttp, "Failed to parse query code %s", e.what());
583 }
584
585 handler->HandleResponse(new XrdCl::XRootDStatus(), obj);
586 return XrdCl::XRootDStatus();
587}
588
590File::Read(uint64_t offset,
591 uint32_t size,
592 void *buffer,
593 XrdCl::ResponseHandler *handler,
594 time_t timeout)
595{
596 if (!m_is_opened) {
597 m_logger->Error(kLogXrdClHttp, "Cannot read. URL isn't open");
599 }
600 auto [status, ok] = ReadPrefetch(offset, size, buffer, handler, timeout, false);
601 if (ok) {
602 if (status.IsOK()) {
603 m_logger->Debug(kLogXrdClHttp, "Read %s (%d bytes at offset %lld) will be served from prefetch handler", m_url.c_str(), size, static_cast<long long>(offset));
604 } else {
605 m_logger->Warning(kLogXrdClHttp, "Read %s (%d bytes at offset %lld) failed: %s", m_url.c_str(), size, static_cast<long long>(offset), status.GetErrorMessage().c_str());
606 }
607 return status;
608 } else if (m_full_download.load(std::memory_order_relaxed)) {
609 std::unique_lock lock(m_default_prefetch_handler->m_prefetch_mutex);
610 if (m_prefetch_op && m_prefetch_op->IsDone() && (static_cast<off_t>(offset) == m_prefetch_offset.load(std::memory_order_acquire))) {
611 if (handler) {
612 auto ci = new XrdCl::ChunkInfo(offset, 0, buffer);
613 auto obj = new XrdCl::AnyObject();
614 obj->Set(ci);
615 handler->HandleResponse(new XrdCl::XRootDStatus{}, obj);
616 }
617 return XrdCl::XRootDStatus{};
618 }
619 return XrdCl::XRootDStatus(XrdCl::stError, XrdCl::errInvalidOp, 0, "Non-sequential read detected when in full-download mode");
620 }
621
622 auto ts = GetHeaderTimeout(timeout);
623 auto url = GetCurrentURL();
624 m_logger->Debug(kLogXrdClHttp, "Read %s (%d bytes at offset %lld with timeout %lld)", url.c_str(), size, static_cast<long long>(offset), static_cast<long long>(ts.tv_sec));
625
626 std::shared_ptr<XrdClHttp::CurlReadOp> readOp(
628 handler, m_default_prefetch_handler, url, ts, std::make_pair(offset, size),
629 static_cast<char*>(buffer), size, m_logger,
630 GetConnCallout(), &m_default_header_callout
631 )
632 );
633 try {
634 m_queue->Produce(std::move(readOp));
635 } catch (...) {
636 m_logger->Warning(kLogXrdClHttp, "Failed to add read op to queue");
638 }
639
640 return XrdCl::XRootDStatus();
641}
642
643std::tuple<XrdCl::XRootDStatus, bool>
644File::ReadPrefetch(uint64_t offset, uint64_t size, void *buffer, XrdCl::ResponseHandler *handler, time_t timeout, bool isPgRead)
645{
646 // Check if prefetching is enabled; if not, return early.
647 auto prefetch_enabled = m_default_prefetch_handler->m_prefetch_enabled.load(std::memory_order_relaxed);
648 if (!prefetch_enabled) {
649 m_prefetch_reads_miss.fetch_add(1, std::memory_order_relaxed);
650 m_logger->Dump(kLogXrdClHttp, "%sRead prefetch skipping due to prefetching being disabled", isPgRead ? "Pg": "");
651 return std::make_tuple(XrdCl::XRootDStatus{}, false);
652 }
653 std::unique_lock lock(m_default_prefetch_handler->m_prefetch_mutex);
654 // In full-download mode the transfer is a single GET whose end is detected on transfer completion
655 // This is similar to a read to end case
656 if (m_prefetch_size == -1 && !m_full_download.load(std::memory_order_relaxed)) {
657 m_logger->Debug(kLogXrdClHttp, "%sRead prefetch skipping due to unknown file size", isPgRead ? "Pg": "");
658 m_prefetch_reads_miss.fetch_add(1, std::memory_order_relaxed);
659 m_default_prefetch_handler->m_prefetch_enabled = false;
660 }
661 prefetch_enabled = m_default_prefetch_handler->m_prefetch_enabled;
662 if (!prefetch_enabled) {
663 m_prefetch_reads_miss.fetch_add(1, std::memory_order_relaxed);
664 return std::make_tuple(XrdCl::XRootDStatus{}, false);
665 }
666
667 if (isPgRead) {
668 handler = new PgReadResponseHandler(handler);
669 }
670
671 auto url = GetCurrentURL();
672 if (!m_prefetch_op) {
673 auto ts = GetHeaderTimeout(timeout);
674 if (m_prefetch_size == INT64_MAX) {
675 m_logger->Debug(kLogXrdClHttp, "%sRead %s (%llu bytes at offset %lld with timeout %lld; starting prefetch full object)", isPgRead ? "Pg" : "", url.c_str(), static_cast<unsigned long long>(size), static_cast<long long>(offset), static_cast<long long>(ts.tv_sec));
676 } else {
677 m_logger->Debug(kLogXrdClHttp, "%sRead %s (%llu bytes at offset %lld with timeout %lld; starting prefetch of size %lld)", isPgRead ? "Pg" : "", url.c_str(), static_cast<unsigned long long>(size), static_cast<long long>(offset), static_cast<long long>(ts.tv_sec), static_cast<long long>(m_prefetch_size));
678 }
679
680 try {
681 // Note we don't set m_last_prefetch_handler here; the constructor will do this automatically if necessary.
682 new PrefetchResponseHandler(*this, offset, size, &m_prefetch_offset, static_cast<char *>(buffer), handler, nullptr, timeout);
683 } catch (std::runtime_error &exc) {
684 m_logger->Warning(kLogXrdClHttp, "Failed to create prefetch response handler: %s", exc.what());
685 m_default_prefetch_handler->m_prefetch_enabled = false;
686 m_prefetch_reads_miss.fetch_add(1, std::memory_order_relaxed);
687 return std::make_tuple(XrdCl::XRootDStatus(XrdCl::stError, XrdCl::errOSError), true);
688 }
689
690 // If we are prefetching as part of an open (i.e., a "full download"), there's special handling logic
691 // to pass along the response headers as file properties.
692 m_prefetch_op.reset(
693 m_is_opened ?
694 new XrdClHttp::CurlReadOp(
695 m_last_prefetch_handler, m_default_prefetch_handler, url, ts, std::make_pair(offset, m_prefetch_size),
696 static_cast<char*>(buffer), size, m_logger,
697 GetConnCallout(), &m_default_header_callout
698 )
699 :
700 new XrdClHttp::CurlPrefetchOpenOp(
701 *this, m_last_prefetch_handler, m_default_prefetch_handler, url, ts,
702 std::make_pair(offset, m_prefetch_size), static_cast<char*>(buffer), size, m_logger,
703 GetConnCallout(), &m_default_header_callout
704 )
705 );
706 lock.unlock();
707 m_prefetch_count.fetch_add(1, std::memory_order_relaxed);
708 m_prefetch_reads_hit.fetch_add(1, std::memory_order_relaxed);
709 m_prefetch_offset.store(offset + size, std::memory_order_release);
710 try {
711 m_queue->Produce(m_prefetch_op);
712 } catch (...) {
713 m_logger->Warning(kLogXrdClHttp, "Failed to add prefetch read op to queue");
714 lock.lock();
715 m_prefetch_op.reset();
716 m_default_prefetch_handler->m_prefetch_enabled = false;
717 m_prefetch_reads_miss.fetch_add(1, std::memory_order_relaxed);
718 return std::make_tuple(XrdCl::XRootDStatus(XrdCl::stError, XrdCl::errOSError), true);
719 }
720 return std::make_tuple(XrdCl::XRootDStatus{}, true);
721 }
722 if (m_prefetch_op->IsDone()) {
723 // Prefetch operation has completed (maybe failed); cannot re-use it.
724 m_default_prefetch_handler->m_prefetch_enabled = false;
725 m_prefetch_reads_miss.fetch_add(1, std::memory_order_relaxed);
726 m_logger->Dump(kLogXrdClHttp, "%sRead prefetch skipping due to prefetching being already complete", isPgRead ? "Pg": "");
727 return std::make_tuple(XrdCl::XRootDStatus{}, false);
728 }
729
730 auto expected_offset = static_cast<off_t>(offset);
731 if (!m_prefetch_offset.compare_exchange_strong(expected_offset, static_cast<off_t>(offset + size), std::memory_order_acq_rel)) {
732 // Out-of-order read; can't handle the prefetch.
733 m_prefetch_reads_miss.fetch_add(1, std::memory_order_relaxed);
734 m_logger->Dump(kLogXrdClHttp, "%sRead prefetch skipping due to out-of-order reads (requested %lld; current offset %lld)", isPgRead ? "Pg": "", static_cast<long long>(offset), static_cast<long long>(expected_offset));
735 return std::make_tuple(XrdCl::XRootDStatus{}, false);
736 }
737 if (m_logger->GetLevel() >= XrdCl::Log::LogLevel::DebugMsg) {
738 m_logger->Debug(kLogXrdClHttp, "%sRead %s (%llu bytes at offset %lld; using ongoing prefetch)", isPgRead ? "Pg" : "", GetCurrentURL().c_str(), static_cast<unsigned long long>(size), static_cast<long long>(offset));
739 }
740 try {
741 // Notice we don't set m_last_prefetch_handler here; as soon as the constructor is invoked, another thread could have
742 // invoked the handler's callback and deleted it.
743 new PrefetchResponseHandler(*this, offset, size, &m_prefetch_offset, static_cast<char *>(buffer), handler, &lock, timeout);
744 } catch (std::runtime_error &exc) {
745 m_logger->Warning(kLogXrdClHttp, "Failed to create prefetch response handler: %s", exc.what());
746 m_default_prefetch_handler->m_prefetch_enabled = false;
747 m_prefetch_reads_miss.fetch_add(1, std::memory_order_relaxed);
748 return std::make_tuple(XrdCl::XRootDStatus(XrdCl::stError, XrdCl::errOSError), true);
749 }
750
751 return std::make_tuple(XrdCl::XRootDStatus{}, true);
752}
753
754XrdCl::XRootDStatus
756 void *buffer,
757 XrdCl::ResponseHandler *handler,
758 time_t timeout )
759{
760 if (!m_is_opened) {
761 m_logger->Error(kLogXrdClHttp, "Cannot do vector read: URL isn't open");
763 } else if (m_full_download.load(std::memory_order_relaxed)) {
764 return XrdCl::XRootDStatus(XrdCl::stError, XrdCl::errInvalidOp, 0, "Only sequential reads are supported when in full-download mode");
765 }
766 if (chunks.empty()) {
767 if (handler) {
768 auto status = new XrdCl::XRootDStatus();
769 auto vr = std::make_unique<XrdCl::VectorReadInfo>();
770 vr->SetSize(0);
771 auto obj = new XrdCl::AnyObject();
772 obj->Set(vr.release());
773 handler->HandleResponse(status, obj);
774 }
775 return XrdCl::XRootDStatus();
776 }
777
778 auto ts = GetHeaderTimeout(timeout);
779 auto url = GetCurrentURL();
780 m_logger->Debug(kLogXrdClHttp, "Read %s (%lld chunks; first chunk is %u bytes at offset %lld with timeout %lld)", url.c_str(), static_cast<long long>(chunks.size()), static_cast<unsigned>(chunks[0].GetLength()), static_cast<long long>(chunks[0].GetOffset()), static_cast<long long>(ts.tv_sec));
781
782 std::shared_ptr<XrdClHttp::CurlVectorReadOp> readOp(
784 handler, url, ts, chunks, m_logger, GetConnCallout(), &m_default_header_callout
785 )
786 );
787 try {
788 m_queue->Produce(std::move(readOp));
789 } catch (...) {
790 m_logger->Warning(kLogXrdClHttp, "Failed to add vector read op to queue");
792 }
793
794 return XrdCl::XRootDStatus();
795}
796
798File::Write(uint64_t offset,
799 uint32_t size,
800 const void *buffer,
801 XrdCl::ResponseHandler *handler,
802 time_t timeout)
803{
804 if (!m_is_opened) {
805 m_logger->Error(kLogXrdClHttp, "Cannot write: URL isn't open");
807 } else if (m_full_download.load(std::memory_order_relaxed)) {
808 return XrdCl::XRootDStatus(XrdCl::stError, XrdCl::errInvalidOp, 0, "Only sequential reads are supported when in full-download mode");
809 }
810 m_default_prefetch_handler->DisablePrefetch();
811
812 auto ts = GetHeaderTimeout(timeout);
813 auto url = GetCurrentURL();
814 m_logger->Debug(kLogXrdClHttp, "Write %s (%d bytes at offset %lld with timeout %lld)", url.c_str(), size, static_cast<long long>(offset), static_cast<long long>(ts.tv_sec));
815
816 auto handler_wrapper = m_put_handler.load(std::memory_order_relaxed);
817 if (!handler_wrapper) {
818 handler_wrapper = new PutResponseHandler(handler);
819 PutResponseHandler *expected_value = nullptr;
820 if (!m_put_handler.compare_exchange_strong(expected_value, handler_wrapper, std::memory_order_acq_rel)) {
821 delete handler_wrapper;
822 return expected_value->QueueWrite(std::make_pair(buffer, size), handler);
823 }
824
825 if (offset != 0) {
826 m_put_handler.store(nullptr, std::memory_order_release);
827 delete handler_wrapper;
828 m_logger->Warning(kLogXrdClHttp, "Cannot start PUT operation at non-zero offset");
829 return XrdCl::XRootDStatus(XrdCl::stError, XrdCl::errInvalidArgs, 0, "HTTP uploads must start at offset 0");
830 }
831 m_put_op.reset(new XrdClHttp::CurlPutOp(
832 handler_wrapper, m_default_put_handler, url, static_cast<const char*>(buffer), size, ts, m_logger,
833 GetConnCallout(), &m_default_header_callout
834 ));
835 handler_wrapper->SetOp(m_put_op);
836 m_put_offset.fetch_add(size, std::memory_order_acq_rel);
837 try {
838 m_queue->Produce(m_put_op);
839 } catch (...) {
840 m_put_handler.store(nullptr, std::memory_order_release);
841 delete handler_wrapper;
842 m_logger->Warning(kLogXrdClHttp, "Failed to add put op to queue");
844 }
845 return XrdCl::XRootDStatus();
846 }
847
848 auto old_offset = m_put_offset.fetch_add(size, std::memory_order_acq_rel);
849 if (static_cast<off_t>(offset) != old_offset) {
850 m_put_offset.fetch_sub(size, std::memory_order_acq_rel);
851 m_logger->Warning(kLogXrdClHttp, "Requested write offset at %lld does not match current file descriptor offset at %lld",
852 static_cast<long long>(offset), static_cast<long long>(old_offset));
853 return XrdCl::XRootDStatus(XrdCl::stError, XrdCl::errInvalidArgs, 0, "Requested write offset does not match current offset");
854 }
855 return handler_wrapper->QueueWrite(std::make_pair(buffer, size), handler);
856}
857
859File::Write(uint64_t offset,
860 XrdCl::Buffer &&buffer,
861 XrdCl::ResponseHandler *handler,
862 time_t timeout)
863{
864 if (!m_is_opened) {
865 m_logger->Error(kLogXrdClHttp, "Cannot write: URL isn't open");
867 }
868 m_default_prefetch_handler->DisablePrefetch();
869
870 auto ts = GetHeaderTimeout(timeout);
871 auto url = GetCurrentURL();
872 m_logger->Debug(kLogXrdClHttp, "Write %s (%d bytes at offset %lld with timeout %lld)", url.c_str(), static_cast<int>(buffer.GetSize()), static_cast<long long>(offset), static_cast<long long>(ts.tv_sec));
873
874 auto handler_wrapper = m_put_handler.load(std::memory_order_relaxed);
875 if (!handler_wrapper) {
876 handler_wrapper = new PutResponseHandler(handler);
877 PutResponseHandler *expected_value = nullptr;
878 if (!m_put_handler.compare_exchange_strong(expected_value, handler_wrapper, std::memory_order_acq_rel)) {
879 delete handler_wrapper;
880 return expected_value->QueueWrite(std::move(buffer), handler);
881 }
882
883 if (offset != 0) {
884 m_put_handler.store(nullptr, std::memory_order_release);
885 delete handler_wrapper;
886 return XrdCl::XRootDStatus(XrdCl::stError, XrdCl::errInvalidArgs, 0, "HTTP uploads must start at offset 0");
887 }
888 m_put_op.reset(new XrdClHttp::CurlPutOp(
889 handler_wrapper, m_default_put_handler, url, std::move(buffer), ts, m_logger,
890 GetConnCallout(), &m_default_header_callout
891 ));
892 handler_wrapper->SetOp(m_put_op);
893 m_put_offset.fetch_add(buffer.GetSize(), std::memory_order_acq_rel);
894 try {
895 m_queue->Produce(m_put_op);
896 } catch (...) {
897 m_put_handler.store(nullptr, std::memory_order_release);
898 delete handler_wrapper;
899 m_logger->Warning(kLogXrdClHttp, "Failed to add put op to queue");
901 }
902 return XrdCl::XRootDStatus();
903 }
904
905 auto old_offset = m_put_offset.fetch_add(buffer.GetSize(), std::memory_order_acq_rel);
906 if (static_cast<off_t>(offset) != old_offset) {
907 m_put_offset.fetch_sub(buffer.GetSize(), std::memory_order_acq_rel);
908 m_logger->Warning(kLogXrdClHttp, "Requested write offset at %lld does not match current file descriptor offset at %lld",
909 static_cast<long long>(offset), static_cast<long long>(old_offset));
910 return XrdCl::XRootDStatus(XrdCl::stError, XrdCl::errInvalidArgs, 0, "Requested write offset does not match current offset");
911 }
912 return handler_wrapper->QueueWrite(std::move(buffer), handler);
913}
914
916File::PgRead(uint64_t offset,
917 uint32_t size,
918 void *buffer,
919 XrdCl::ResponseHandler *handler,
920 time_t timeout)
921{
922 if (!m_is_opened) {
923 m_logger->Error(kLogXrdClHttp, "Cannot pgread. URL isn't open");
925 }
926 auto [status, ok] = ReadPrefetch(offset, size, buffer, handler, timeout, true);
927 if (ok) {
928 if (status.IsOK()) {
929 m_logger->Debug(kLogXrdClHttp, "PgRead %s (%d bytes at offset %lld) will be served from prefetch handler", m_url.c_str(), size, static_cast<long long>(offset));
930 } else {
931 m_logger->Warning(kLogXrdClHttp, "PgRead %s (%d bytes at offset %lld) failed: %s", m_url.c_str(), size, static_cast<long long>(offset), status.GetErrorMessage().c_str());
932 }
933 return status;
934 } else if (m_full_download.load(std::memory_order_relaxed)) {
935 return XrdCl::XRootDStatus(XrdCl::stError, XrdCl::errInvalidOp, 0, "Non-sequential read detected when in full-download mode");
936 }
937
938 auto ts = GetHeaderTimeout(timeout);
939 auto url = GetCurrentURL();
940 m_logger->Debug(kLogXrdClHttp, "PgRead %s (%d bytes at offset %lld)", url.c_str(), size, static_cast<long long>(offset));
941
942 std::shared_ptr<XrdClHttp::CurlPgReadOp> readOp(
944 handler, m_default_prefetch_handler, url, ts, std::make_pair(offset, size),
945 static_cast<char*>(buffer), size, m_logger,
946 GetConnCallout(), &m_default_header_callout
947 )
948 );
949
950 try {
951 m_queue->Produce(std::move(readOp));
952 } catch (...) {
953 m_logger->Warning(kLogXrdClHttp, "Failed to add read op to queue");
955 }
956
957 return XrdCl::XRootDStatus();
958}
959
960bool
962{
963 return m_is_opened;
964}
965
966bool
967File::GetProperty(const std::string &name,
968 std::string &value) const
969{
970 if (name == "CurrentURL") {
971 value = GetCurrentURL();
972 return true;
973 }
974
975 if (name == "IsPrefetching") {
976 value = m_default_prefetch_handler->IsPrefetching() ? "true" : "false";
977 return true;
978 }
979
980 std::shared_lock lock(m_properties_mutex);
981 if (name == "LastURL") {
982 value = m_last_url;
983 return true;
984 }
985
986 const auto p = m_properties.find(name);
987 if (p == std::end(m_properties)) {
988 return false;
989 }
990
991 value = p->second;
992 return true;
993}
994
995bool File::SendResponseInfo() const {
996 std::string val;
997 return GetProperty(ResponseInfoProperty, val) && val == "true";
998}
999
1000bool
1001File::SetProperty(const std::string &name,
1002 const std::string &value)
1003{
1004 if (name == "XrdClHttpHeaderCallout") {
1005 long long pointer;
1006 try {
1007 pointer = std::stoll(value, nullptr, 16);
1008 } catch (...) {
1009 pointer = 0;
1010 }
1011 m_header_callout.store(reinterpret_cast<XrdClHttp::HeaderCallout*>(pointer), std::memory_order_release);
1012 } else if (name == "XrdClHttpFullDownload") {
1013 if (value == "true") {
1014 auto prefetch_handler = m_default_prefetch_handler;
1015 if (prefetch_handler) {
1016 std::unique_lock lock(prefetch_handler->m_prefetch_mutex);
1017 prefetch_handler->m_prefetch_enabled.store(true, std::memory_order_relaxed);
1018 }
1019 m_full_download.store(true, std::memory_order_relaxed);
1020 }
1021 }
1022
1023 std::unique_lock lock(m_properties_mutex);
1024
1025 m_properties[name] = value;
1026 if (name == "LastURL") {
1027 m_last_url = value;
1028 m_url_current = "";
1029 }
1030 else if (name == "XrdClHttpQueryParam") {
1031 CalculateCurrentURL(value);
1032 }
1033 else if (name == "XrdClHttpMaintenancePeriod") {
1034 unsigned period;
1035 auto ec = std::from_chars(value.c_str(), value.c_str() + value.size(), period);
1036 if ((ec.ec == std::errc()) && (ec.ptr == value.c_str() + value.size()) && period > 0) {
1037 m_logger->Debug(kLogXrdClHttp, "Setting maintenance period to %u", period);
1039 }
1040 }
1041 else if (name == "XrdClHttpStallTimeout") {
1042 std::string errmsg;
1043 timespec ts;
1044 if (!ParseTimeout(value, ts, errmsg)) {
1045 m_logger->Debug(kLogXrdClHttp, "Failed to parse timeout value (%s): %s", value.c_str(), errmsg.c_str());
1046 } else {
1047 CurlOperation::SetStallTimeout(std::chrono::seconds{ts.tv_sec} + std::chrono::nanoseconds{ts.tv_nsec});
1048 }
1049 }
1050 else if (name == "XrdClHttpPrefetchSize") {
1051 off_t size;
1052 auto ec = std::from_chars(value.c_str(), value.c_str() + value.size(), size);
1053 if ((ec.ec == std::errc()) && (ec.ptr == value.c_str() + value.size())) {
1054 lock.unlock();
1055 std::unique_lock lock2(m_default_prefetch_handler->m_prefetch_mutex);
1056 m_prefetch_size = size;
1057 } else {
1058 m_logger->Debug(kLogXrdClHttp, "XrdClHttpPrefetchSize value (%s) was not parseable", value.c_str());
1059 }
1060 }
1061 return true;
1062}
1063
1064const std::string
1065File::GetCurrentURL() const {
1066 {
1067 std::shared_lock lock(m_properties_mutex);
1068
1069 if (!m_url_current.empty()) {
1070 return m_url_current;
1071 } else if (m_url.empty() && m_last_url.empty()) {
1072 return "";
1073 }
1074 }
1075 std::unique_lock lock(m_properties_mutex);
1076
1077 auto iter = m_properties.find("XrdClHttpQueryParam");
1078 if (iter == m_properties.end()) {
1079 return m_last_url.empty() ? m_url : m_last_url;
1080 }
1081 CalculateCurrentURL(iter->second);
1082
1083 return m_url_current;
1084}
1085
1086void
1087File::CalculateCurrentURL(const std::string &value) const {
1088 const auto &last_url = m_last_url.empty() ? m_url : m_last_url;
1089 if (value.empty()) {
1090 m_url_current = last_url;
1091 } else {
1092 auto loc = last_url.find('?');
1093 if (loc == std::string::npos) {
1094 m_url_current = last_url + '?' + value;
1095 } else {
1096 XrdCl::URL url(last_url);
1097 auto map = url.GetParams(); // Make a copy of the pre-existing parameters
1098 url.SetParams(value); // Parse the new value
1099 auto update_map = url.GetParams();
1100 for (const auto &entry : map) {
1101 if (update_map.find(entry.first) == update_map.end()) {
1102 update_map[entry.first] = entry.second;
1103 }
1104 }
1105 bool first = true;
1106 std::stringstream ss;
1107 for (const auto &entry : update_map) {
1108 ss << (first ? "?" : "&") << entry.first << "=" << entry.second;
1109 first = false;
1110 }
1111 m_url_current = last_url.substr(0, loc) + ss.str();
1112 }
1113 }
1114}
1115
1116File::PrefetchResponseHandler::PrefetchResponseHandler(
1117 File &parent, off_t offset, size_t size, std::atomic<off_t> *prefetch_offset, char *buffer,
1118 XrdCl::ResponseHandler *handler, std::unique_lock<std::mutex> *lock, time_t timeout
1119)
1120 : m_parent(parent),
1121 m_handler(handler),
1122 m_buffer(buffer),
1123 m_size(size),
1124 m_offset(offset),
1125 m_prefetch_offset(prefetch_offset),
1126 m_timeout(timeout)
1127{
1128 if (parent.m_last_prefetch_handler) {
1129 parent.m_last_prefetch_handler->m_next = this;
1130 parent.m_last_prefetch_handler = this;
1131 } else {
1132 m_parent.m_last_prefetch_handler = this;
1133 // If lock is nullptr, then we are guaranteed that this is called during the creation
1134 // of the m_prefetch_op and can skip this check.
1135 if (lock && m_parent.m_prefetch_op) {
1136 // If continuing the prefetch operation fails, then the failure callback
1137 // will be invoked; the callback requires the mutex and hence we need to unlock it
1138 // here to avoid a deadlock.
1139 lock->unlock();
1140 if (!parent.m_prefetch_op->Continue(parent.m_prefetch_op, this, buffer, size)) {
1141 lock->lock();
1142 // As soon as we unlock the lock, another thread could have used finished the
1143 // operation (which deletes the object); we must be careful to not touch the
1144 // object (reference m_*) in the meantime.
1145 if (parent.m_last_prefetch_handler == this)
1146 parent.m_last_prefetch_handler = nullptr;
1147 throw std::runtime_error("Failed to continue prefetch operation");
1148 }
1149 }
1150 }
1151}
1152
1153void
1154File::PrefetchResponseHandler::HandleResponse(XrdCl::XRootDStatus *status, XrdCl::AnyObject *response) {
1155 // Ensure that we are deleted once the callback is done.
1156 std::unique_ptr<PrefetchResponseHandler> owner(this);
1157
1158 bool mismatched_size = false;
1159 if (status) {
1160 if (status->IsOK() && response) {
1161 XrdCl::ChunkInfo *ci = nullptr;
1162 response->Get(ci);
1163 if (ci) {
1164 auto missing_bytes = m_size - ci->GetLength();
1165 if (missing_bytes) {
1166 mismatched_size = true;
1167 m_prefetch_offset->fetch_sub(missing_bytes, std::memory_order_relaxed);
1168 }
1169 m_prefetch_bytes_used.fetch_add(ci->GetLength(), std::memory_order_relaxed);
1170 }
1171 } else if (!status->IsOK()) {
1172 m_prefetch_failed_count.fetch_add(1, std::memory_order_relaxed);
1173 }
1174 }
1175
1176 PrefetchResponseHandler *next;
1177 {
1178 std::unique_lock lock(m_parent.m_default_prefetch_handler->m_prefetch_mutex);
1179 next = m_next;
1180 }
1181 if (next) {
1182 if (status && status->IsOK() && !mismatched_size) {
1183 m_parent.m_prefetch_op->Continue(m_parent.m_prefetch_op, next, next->m_buffer, next->m_size);
1184 } else {
1185 // On failure resubmit subsequent operations.
1186 // All the subsequent ops also depend on us having the expected read length (otherwise the
1187 // file offsets are incorrect). If there's a mismatched read size (shorter actual bytes available
1188 // than what is originally requested), then that's another sign of potential issue and we disable
1189 // the prefetch mechanism.
1190 m_parent.m_default_prefetch_handler->DisablePrefetch();
1191 next->ResubmitOperation();
1192 }
1193 }
1194
1195 {
1196 std::unique_lock lock(m_parent.m_default_prefetch_handler->m_prefetch_mutex);
1197 if (m_parent.m_last_prefetch_handler == this) {
1198 m_parent.m_last_prefetch_handler = nullptr;
1199 }
1200 if (!status || !status->IsOK()) {
1201 m_parent.m_prefetch_op.reset();
1202 m_parent.m_default_prefetch_handler->m_prefetch_enabled = false;
1203 }
1204 }
1205
1206 if (m_handler) m_handler->HandleResponse(status, response);
1207 else delete response;
1208}
1209
1210void
1211File::PrefetchResponseHandler::ResubmitOperation()
1212{
1213 m_parent.m_logger->Debug(kLogXrdClHttp, "Resubmitting waiting prefetch operations as new reads due to prefetch failure");
1214 PrefetchResponseHandler *next = this;
1215 while (next) {
1216 auto cur = next;
1217 auto st = next->m_parent.Read(next->m_offset, next->m_size, next->m_buffer, next->m_handler, next->m_timeout);
1218 if (!st.IsOK() && next->m_handler) {
1219 next->m_handler->HandleResponse(new XrdCl::XRootDStatus(st), nullptr);
1220 }
1221 {
1222 std::unique_lock lock(next->m_parent.m_default_prefetch_handler->m_prefetch_mutex);
1223 next = next->m_next;
1224 }
1225 delete cur;
1226 }
1227}
1228
1229void
1230File::PrefetchDefaultHandler::HandleResponse(XrdCl::XRootDStatus *status_raw, XrdCl::AnyObject *response_raw) {
1231 std::unique_ptr<XrdCl::AnyObject> response(response_raw);
1232 std::unique_ptr<XrdCl::XRootDStatus> status(status_raw);
1233 if (status && !status->IsOK()) {
1234 if ((status->code == XrdCl::errOperationExpired) && (status->GetErrorMessage().find("Transfer stalled for too long") != std::string::npos)) {
1235 m_prefetch_expired_count.fetch_add(1, std::memory_order_relaxed);
1236 m_logger->Debug(kLogXrdClHttp, "Prefetch data for %s went unused; disabling.", m_url.c_str());
1237 } else {
1238 m_prefetch_failed_count.fetch_add(1, std::memory_order_relaxed);
1239 m_logger->Warning(kLogXrdClHttp, "Disabling prefetch of %s due to error: %s", m_url.c_str(), status->ToStr().c_str());
1240 }
1241 }
1242 DisablePrefetch();
1243}
1244
1245void
1246File::PutDefaultHandler::HandleResponse(XrdCl::XRootDStatus *status, XrdCl::AnyObject *response) {
1247 delete response;
1248 if (status) {
1249 m_logger->Warning(kLogXrdClHttp, "Failing future write calls due to error: %s", status->ToStr().c_str());
1250 delete status;
1251 }
1252}
1253
1254std::shared_ptr<XrdClHttp::HeaderCallout::HeaderList>
1255File::HeaderCallout::GetHeaders(const std::string &verb,
1256 const std::string &url,
1257 const HeaderList &headers)
1258{
1259 auto parent_callout = m_parent.m_header_callout.load(std::memory_order_acquire);
1260 std::shared_ptr<std::vector<std::pair<std::string, std::string>>> result_headers;
1261 if (parent_callout != nullptr) {
1262 result_headers = parent_callout->GetHeaders(verb, url, headers);
1263 } else {
1264 result_headers.reset(new std::vector<std::pair<std::string, std::string>>{});
1265 for (const auto & info : headers) {
1266 result_headers->emplace_back(info.first, info.second);
1267 }
1268 }
1269 if (m_parent.m_asize >= 0 && verb == "PUT") {
1270 if (!result_headers) {
1271 result_headers.reset(new std::vector<std::pair<std::string, std::string>>{});
1272 }
1273 auto iter = std::find_if(result_headers->begin(), result_headers->end(),
1274 [](const auto &pair) { return !strcasecmp(pair.first.c_str(), "Content-Length"); });
1275 if (iter == result_headers->end()) {
1276 result_headers->emplace_back("Content-Length", std::to_string(m_parent.m_asize));
1277 }
1278 } else if (!result_headers) {
1279 result_headers.reset(new std::vector<std::pair<std::string, std::string>>{});
1280 }
1281 return result_headers;
1282}
1283
1284File::PutResponseHandler::PutResponseHandler(XrdCl::ResponseHandler *handler)
1285 : m_active_handler(handler)
1286{}
1287
1288void
1289File::PutResponseHandler::HandleResponse(XrdCl::XRootDStatus *status_raw, XrdCl::AnyObject *response_raw)
1290{
1291 std::unique_ptr<XrdCl::XRootDStatus> status(status_raw);
1292 std::unique_ptr<XrdCl::AnyObject> response(response_raw);
1293
1294 // Note: if the handler owns the file object (as in the case of Pelican's writeback
1295 // response handler), then the callback may cause the file to be deleted - and hence
1296 // this instance of PutResponseHandler to be deleted. However, if m_active is true,
1297 // the destructor will wait until it's set to false; that cannot occur until we clear
1298 // m_active (in ProcessQueue or in the cleanup path for pending writes).
1299 //
1300 // Hence, we must ensure that we clear m_active and run any queue logic before invoking
1301 // callback handlers, which may delete this object or generate work in other threads.
1302
1303 XrdCl::ResponseHandler *current_handler = nullptr;
1304 if (!status->IsOK()) {
1305 // Fail remaining (pending) handlers with the same error
1306 // Any writes attempts by the client after failure are set
1307 // are prompty declined
1308 std::vector<XrdCl::ResponseHandler *> pending_handlers;
1309 {
1310 std::lock_guard<std::mutex> lg(m_mutex);
1311 current_handler = m_active_handler;
1312 for (auto &[_, h] : m_pending_writes) {
1313 if (h) pending_handlers.push_back(h);
1314 }
1315
1316 m_pending_writes.clear();
1317 m_active = false;
1318 m_active_handler = nullptr;
1319 m_cv.notify_all();
1320 }
1321
1322 XrdCl::XRootDStatus status_copy(*status);
1323 if (current_handler) {
1324 current_handler->HandleResponse(status.release(), response.release());
1325 }
1326
1327 for (auto *h : pending_handlers) {
1328 h->HandleResponse(new XrdCl::XRootDStatus(status_copy), nullptr);
1329 }
1330 return;
1331 }
1332
1333 current_handler = m_active_handler;
1334 if (ProcessQueue() && current_handler) {
1335 current_handler->HandleResponse(status.release(), response.release());
1336 }
1337}
1338
1339XrdCl::XRootDStatus
1340File::PutResponseHandler::QueueWrite(std::variant<std::pair<const void *, size_t>, XrdCl::Buffer> buffer, XrdCl::ResponseHandler *handler)
1341{
1342 if (m_op->HasFailed()) {
1343 auto sc = m_op->GetStatusCode();
1344 if (HTTPStatusIsError(sc)){
1345 auto httpErr = HTTPStatusConvert(sc);
1346 auto err_msg = m_op->GetCurlErrorMessage();
1347 if (err_msg.empty()) {
1348 err_msg = m_op->GetStatusMessage();
1349 }
1350 return XrdCl::XRootDStatus(XrdCl::stError, httpErr.first, httpErr.second, err_msg);
1351 }
1352 return XrdCl::XRootDStatus(XrdCl::stError, XrdCl::errInvalidOp, 0, "Cannot continue writing to open file after error");
1353 }
1354 std::lock_guard<std::mutex> lg(m_mutex);
1355 if (!m_active) {
1356 m_active = true;
1357 m_active_handler = handler;
1358 if (std::holds_alternative<XrdCl::Buffer>(buffer)) {
1359 if (!m_op->Continue(m_op, this, std::move(std::get<XrdCl::Buffer>(buffer)))) {
1360 m_active = false;
1361 m_cv.notify_all();
1362 return XrdCl::XRootDStatus(XrdCl::stError, XrdCl::errOSError, ENOSPC, "Cannot continue PUT operation");
1363 }
1364 } else {
1365 auto buffer_info = std::get<std::pair<const void *, size_t>>(buffer);
1366 if (!m_op->Continue(m_op, this, static_cast<const char *>(buffer_info.first), buffer_info.second)) {
1367 m_active = false;
1368 m_cv.notify_all();
1369 return XrdCl::XRootDStatus(XrdCl::stError, XrdCl::errOSError, ENOSPC, "Cannot continue PUT operation");
1370 }
1371 }
1372 } else {
1373 m_pending_writes.emplace_back(std::move(buffer), handler);
1374 }
1375 return XrdCl::XRootDStatus{};
1376}
1377
1378// Start the next pending write operation.
1379bool
1380File::PutResponseHandler::ProcessQueue() {
1381 std::lock_guard<std::mutex> lg(m_mutex);
1382 if (m_pending_writes.empty()) {
1383 // No pending writes; mark the operation as inactive.
1384 m_active = false;
1385 m_active_handler = nullptr;
1386 m_cv.notify_all();
1387 return true;
1388 }
1389
1390 // Start the next pending write.
1391 auto & [buffer, handler] = m_pending_writes.front();
1392 bool rv;
1393 m_active_handler = handler;
1394 if (std::holds_alternative<XrdCl::Buffer>(buffer)) {
1395 rv = m_op->Continue(m_op, this, std::move(std::get<XrdCl::Buffer>(buffer)));
1396 } else {
1397 auto buffer_info = std::get<std::pair<const void *, size_t>>(buffer);
1398 rv = m_op->Continue(m_op, this, static_cast<const char *>(buffer_info.first), buffer_info.second);
1399 }
1400 m_pending_writes.pop_front();
1401 if (!rv) {
1402 // The continuation failed; mark the operation as inactive and
1403 // invoke all pending handlers with the error.
1404 if (m_active_handler) {
1405 m_active_handler->HandleResponse(new XrdCl::XRootDStatus(XrdCl::stError, XrdCl::errOSError, ENOSPC, "Cannot continue PUT operation"), nullptr);
1406 }
1407 for (auto& [_, h] : m_pending_writes) {
1408 if (h) {
1409 h->HandleResponse(new XrdCl::XRootDStatus(XrdCl::stError, XrdCl::errOSError, ENOSPC, "Cannot continue PUT operation"), nullptr);
1410 }
1411 }
1412 m_active = false;
1413 m_cv.notify_all();
1414 return false;
1415 }
1416 return true;
1417}
1418
1419void
1420File::PutResponseHandler::WaitForCompletion() {
1421 std::unique_lock lock(m_mutex);
1422 m_cv.wait(lock, [&]{return !m_active;});
1423}
static std::string ts()
timestamp output for logging messages
Definition XrdCephOss.cc:53
static void parent()
#define ResponseInfoProperty
static void SetStallTimeout(int stall_interval)
static void SetMaintenancePeriod(unsigned maint)
virtual XrdCl::XRootDStatus Open(const std::string &url, XrdCl::OpenFlags::Flags flags, XrdCl::Access::Mode mode, XrdCl::ResponseHandler *handler, time_t timeout) override
static struct timespec ParseHeaderTimeout(const std::string &header_value, XrdCl::Log *logger)
File(std::shared_ptr< XrdClHttp::HandlerQueue > queue, XrdCl::Log *log)
static const struct timespec & GetDefaultHeaderTimeout()
static struct timespec GetHeaderTimeoutWithDefault(time_t oper_timeout, const struct timespec &header_timeout)
virtual bool SetProperty(const std::string &name, const std::string &value) override
virtual bool IsOpen() const override
virtual XrdCl::XRootDStatus VectorRead(const XrdCl::ChunkList &chunks, void *buffer, XrdCl::ResponseHandler *handler, time_t timeout) override
virtual XrdCl::XRootDStatus Fcntl(const XrdCl::Buffer &arg, XrdCl::ResponseHandler *handler, time_t timeout) override
virtual XrdCl::XRootDStatus Write(uint64_t offset, uint32_t size, const void *buffer, XrdCl::ResponseHandler *handler, time_t timeout) override
virtual ~File() noexcept
static std::string GetMonitoringJson()
virtual bool GetProperty(const std::string &name, std::string &value) const override
static const struct timespec & GetMinimumHeaderTimeout()
virtual XrdCl::XRootDStatus PgRead(uint64_t offset, uint32_t size, void *buffer, XrdCl::ResponseHandler *handler, time_t timeout) override
virtual XrdCl::XRootDStatus Read(uint64_t offset, uint32_t size, void *buffer, XrdCl::ResponseHandler *handler, time_t timeout) override
virtual XrdCl::XRootDStatus Stat(bool force, XrdCl::ResponseHandler *handler, time_t timeout) override
struct timespec GetHeaderTimeout(time_t oper_timeout) const
virtual XrdCl::XRootDStatus Close(XrdCl::ResponseHandler *handler, time_t timeout) override
void Get(Type &object)
Retrieve the object being held.
Binary blob representation.
void FromString(const std::string str)
Fill the buffer from a string.
std::string ToString() const
Convert the buffer to a string.
static Env * GetEnv()
Get default client environment.
bool GetInt(const std::string &key, int &value)
Definition XrdClEnv.cc:115
@ DebugMsg
print debug info
Definition XrdClLog.hh:112
void Dump(uint64_t topic, const char *format,...)
Print a dump message.
Definition XrdClLog.cc:299
Handle an async response.
virtual void HandleResponse(XRootDStatus *status, AnyObject *response)
Object stat info.
@ IsReadable
Read access is allowed.
URL representation.
Definition XrdClURL.hh:31
const std::string & GetErrorMessage() const
Get error message.
std::string ToStr() const
Convert to string.
static uint32_t Calc32C(const void *data, size_t count, uint32_t prevcs=0)
Definition XrdOucCRC.cc:190
ConnectionCallout *(*)(const std::string &, const ResponseInfo &) CreateConnCalloutType
std::pair< uint16_t, uint32_t > HTTPStatusConvert(unsigned status)
bool ParseTimeout(const std::string &duration, struct timespec &, std::string &errmsg)
bool HTTPStatusIsError(unsigned status)
const uint64_t kLogXrdClHttp
std::string MarshalDuration(const struct timespec &timeout)
const uint16_t errOperationExpired
const uint16_t stError
An error occurred that could potentially be retried.
const uint16_t errDataError
data is corrupted
const uint16_t errInternal
Internal error.
const uint16_t errInvalidOp
const uint16_t errOSError
const uint16_t errInvalidResponse
const uint16_t errInvalidArgs
const int DefaultRequestTimeout
std::vector< ChunkInfo > ChunkList
List of chunks.
static const int PageSize
Describe a data chunk for vector read.
uint64_t GetOffset() const
Get the offset.
uint32_t GetLength() const
Get the data length.
void * GetBuffer()
Get the buffer.
Flags
Open flags, may be or'd when appropriate.
@ Write
Open only for writing.
Code
XRootD query request codes.
@ OpaqueFile
Implementation dependent.
@ XAttr
Query file extended attributes.
@ Opaque
Implementation dependent.
@ Config
Query server configuration.
@ Stats
Query server stats.
@ ChecksumCancel
Query file checksum cancellation.
@ Checksum
Query file checksum.
@ Space
Query logical space stats.
@ Prepare
Query prepare status.
uint16_t code
Error type, or additional hints on what to do.
bool IsOK() const
We're fine.
std::string ToString() const
Create a string representation.