32#include <TStreamerInfo.h>
36#include <fairlogger/Logger.h>
42#include <boost/algorithm/string.hpp>
45#include <boost/interprocess/sync/named_semaphore.hpp>
51#include <TAlienUserAgent.h>
52#include <unordered_set>
53#include "rapidjson/document.h"
54#include "rapidjson/writer.h"
55#include "rapidjson/stringbuffer.h"
63unique_ptr<TJAlienCredentials> CcdbApi::mJAlienCredentials =
nullptr;
71std::string_view trimHeaderValue(std::string_view
value)
73 constexpr std::string_view whitespace =
" \t\r\n";
74 const auto first =
value.find_first_not_of(whitespace);
75 return first == std::string_view::npos
86const std::vector<std::pair<std::string, std::string>>& gateTokenTable()
88 static const auto table = []() {
89 std::vector<std::pair<std::string, std::string>> entries;
90 const char* spec = getenv(
"ALICEO2_CCDB_AUTH_TOKENS");
91 std::string_view rest = spec ? spec :
"";
92 while (!rest.empty()) {
93 const auto sep = rest.find(
';');
94 const auto entry = trimHeaderValue(rest.substr(0, sep));
95 rest = (sep == std::string_view::npos) ? std::string_view{} : rest.substr(sep + 1);
96 const auto eq =
entry.find(
'=');
97 if (eq == std::string_view::npos) {
100 auto url = trimHeaderValue(
entry.substr(0, eq));
103 const auto token = trimHeaderValue(
entry.substr(eq + 1));
104 while (
url.size() > 1 &&
url.back() ==
'/') {
105 url.remove_suffix(1);
107 if (!
url.empty() && !token.empty()) {
108 entries.emplace_back(std::string(
url), std::string(
"Authorization: Bearer ").append(token));
111 std::sort(entries.begin(), entries.end(),
112 [](
const auto&
a,
const auto&
b) { return a.first.size() > b.first.size(); });
126curl_slist* appendGateToken(curl_slist* list, std::string_view
url)
128 for (
const auto& [prefix, header] : gateTokenTable()) {
129 if (
url.substr(0, prefix.size()) == prefix &&
130 (
url.size() == prefix.size() ||
url[prefix.size()] ==
'/')) {
131 return curl_slist_append(list, header.c_str());
151 boost::interprocess::named_semaphore* mSem =
nullptr;
152 std::string mSemName{};
167 std::unordered_set<CCDBSemaphore const*> mStore;
177 mIsCCDBDownloaderPreferred = 0;
178 if (deploymentMode == DeploymentMode::OnlineDDS && deploymentMode == DeploymentMode::OnlineECS && deploymentMode == DeploymentMode::OnlineAUX && deploymentMode == DeploymentMode::FST) {
179 mIsCCDBDownloaderPreferred = 1;
181 if (getenv(
"ALICEO2_ENABLE_MULTIHANDLE_CCDBAPI")) {
182 mIsCCDBDownloaderPreferred = atoi(getenv(
"ALICEO2_ENABLE_MULTIHANDLE_CCDBAPI"));
189 curl_global_cleanup();
193void CcdbApi::setUniqueAgentID()
195 mUniqueAgentID = TAlienUserAgent::BasedOnEnvironment().ToString();
201 LOG(
debug) <<
"On macOS we simply rely on TGrid::Connect(\"alien\").";
204 if (getenv(
"ALICEO2_CCDB_NOTOKENCHECK") && atoi(getenv(
"ALICEO2_CCDB_NOTOKENCHECK"))) {
207 if (getenv(
"JALIEN_TOKEN_CERT")) {
210 auto returncode = system(
"LD_PRELOAD= alien-token-info &> /dev/null");
211 if (returncode == -1) {
214 return returncode == 0;
217void CcdbApi::curlInit()
220 curl_global_init(CURL_GLOBAL_DEFAULT);
221 CcdbApi::mJAlienCredentials = std::make_unique<TJAlienCredentials>();
222 CcdbApi::mJAlienCredentials->loadCredentials();
223 CcdbApi::mJAlienCredentials->selectPreferedCredentials();
226 if (getenv(
"ALICEO2_CCDB_SOCKET_TIMEOUT")) {
227 auto timeoutMS = atoi(getenv(
"ALICEO2_CCDB_SOCKET_TIMEOUT"));
228 if (timeoutMS >= 0) {
229 LOG(info) <<
"Setting socket timeout to " << timeoutMS <<
" milliseconds";
238 throw std::invalid_argument(
"Empty url passed CcdbApi, cannot initialize. Aborting.");
243 constexpr const char* SNAPSHOTPREFIX =
"file://";
246 if (host.substr(0, 7).compare(SNAPSHOTPREFIX) == 0) {
247 auto path = host.substr(7);
248 initInSnapshotMode(
path);
269 std::string snapshotReport{};
270 const char* cachedir = getenv(
"ALICEO2_CCDB_LOCALCACHE");
271 namespace fs = std::filesystem;
273 if (cachedir[0] == 0) {
274 mSnapshotCachePath = fs::weakly_canonical(fs::absolute(
"."));
276 mSnapshotCachePath = fs::weakly_canonical(fs::absolute(cachedir));
278 snapshotReport = fmt::format(
"(cache snapshots to dir={}", mSnapshotCachePath);
281 mPreferSnapshotCache =
true;
282 if (mSnapshotCachePath.empty()) {
283 LOGP(fatal,
"IGNORE_VALIDITYCHECK_OF_CCDB_LOCALCACHE is defined but the ALICEO2_CCDB_LOCALCACHE is not");
285 snapshotReport +=
", prefer if available";
287 if (!snapshotReport.empty()) {
288 snapshotReport +=
')';
291 mNeedAlienToken = (host.find(
"https://") != std::string::npos) || (host.find(
"alice-ccdb.cern.ch") != std::string::npos) || (host.find(
"ccdb-test.cern.ch") != std::string::npos);
293 if (getenv(
"ALICEO2_CCDB_CURL_TIMEOUT_DOWNLOAD")) {
294 auto timeout = atoi(getenv(
"ALICEO2_CCDB_CURL_TIMEOUT_DOWNLOAD"));
296 mCurlTimeoutDownload =
timeout;
303 mCurlTimeoutDownload = 15;
306 mCurlTimeoutDownload = 15;
308 mCurlTimeoutDownload = 5;
312 if (getenv(
"ALICEO2_CCDB_CURL_TIMEOUT_UPLOAD")) {
313 auto timeout = atoi(getenv(
"ALICEO2_CCDB_CURL_TIMEOUT_UPLOAD"));
322 mCurlTimeoutUpload = 3;
325 mCurlTimeoutUpload = 20;
327 mCurlTimeoutUpload = 20;
334 LOGP(
debug,
"Curl timeouts are set to: download={:2}, upload={:2} seconds", mCurlTimeoutDownload, mCurlTimeoutUpload);
336 LOGP(info,
"Init CcdApi with UserAgentID: {}, Host: {}{}, Curl timeouts: upload:{} download:{}", mUniqueAgentID, host,
337 mInSnapshotMode ?
"(snapshot readonly mode)" : snapshotReport.c_str(), mCurlTimeoutUpload, mCurlTimeoutDownload);
346void CcdbApi::updateMetaInformationInLocalFile(std::string
const&
filename, std::map<std::string, std::string>
const* headers,
CCDBQuery const* querysummary)
348 std::lock_guard<std::mutex> guard(
gIOMutex);
349 auto oldlevel = gErrorIgnoreLevel;
350 gErrorIgnoreLevel = 6001;
351 TFile snapshotfile(
filename.c_str(),
"UPDATE");
353 if (!snapshotfile.IsZombie()) {
355 snapshotfile.WriteObjectAny(querysummary, TClass::GetClass(
typeid(*querysummary)),
CCDBQUERY_ENTRY);
358 snapshotfile.WriteObjectAny(headers, TClass::GetClass(
typeid(*headers)),
CCDBMETA_ENTRY);
360 snapshotfile.Write();
361 snapshotfile.Close();
363 gErrorIgnoreLevel = oldlevel;
373 std::string tmpObjectName = objectName;
374 tmpObjectName.erase(std::remove_if(tmpObjectName.begin(), tmpObjectName.end(),
375 [](
auto const&
c) ->
bool { return (!std::isalnum(c) && c !=
'_' && c !=
'/' && c !=
'.'); }),
376 tmpObjectName.end());
377 return tmpObjectName;
384 std::lock_guard<std::mutex> guard(
gIOMutex);
388 info->setFileName(tmpFileName);
389 info->setObjectType(className);
398 std::string className = rootObject->GetName();
401 info->setFileName(tmpFileName);
402 info->setObjectType(
"TObject");
404 std::lock_guard<std::mutex> guard(
gIOMutex);
409 std::map<std::string, std::string>
const& metadata,
410 long startValidityTimestamp,
long endValidityTimestamp,
411 std::vector<char>::size_type
maxSize)
const
415 LOGP(error,
"nullptr is provided for object {}/{}/{}",
path, startValidityTimestamp, endValidityTimestamp);
421 path, metadata, startValidityTimestamp, endValidityTimestamp,
maxSize);
425 const std::string&
path,
const std::map<std::string, std::string>& metadata,
426 long startValidityTimestamp,
long endValidityTimestamp, std::vector<char>::size_type
maxSize)
const
429 LOGP(alarm,
"Object will not be uploaded to {} since its size {} exceeds max allowed {}",
path,
size,
maxSize);
435 long sanitizedStartValidityTimestamp = startValidityTimestamp;
436 if (startValidityTimestamp == -1) {
437 LOGP(info,
"Start of Validity not set, current timestamp used.");
440 long sanitizedEndValidityTimestamp = endValidityTimestamp;
441 if (endValidityTimestamp == -1) {
442 LOGP(info,
"End of Validity not set, start of validity plus 1 day used.");
445 if (mInSnapshotMode) {
447 LOGP(alarm,
"Snapshot mode does not support headers-only upload");
450 auto pthLoc = getSnapshotDir(mSnapshotTopPath,
path);
452 auto flLoc = getSnapshotFile(mSnapshotTopPath,
path,
filename);
454 auto pent = flLoc.find_last_of(
'.');
455 if (pent == std::string::npos) {
458 flLoc.insert(pent, fmt::format(
"_{}_{}", startValidityTimestamp, endValidityTimestamp));
459 ofstream outf(flLoc.c_str(), ios::out | ios::binary);
463 throw std::runtime_error(fmt::format(
"Failed to write local CCDB file {}", flLoc));
465 std::map<std::string, std::string> metaheader(metadata);
467 metaheader[
"Valid-From"] =
std::to_string(startValidityTimestamp);
469 updateMetaInformationInLocalFile(flLoc.c_str(), &metaheader);
470 std::string metaStr{};
471 for (
const auto& mentry : metadata) {
472 metaStr += fmt::format(
"{}={};", mentry.first, mentry.second);
474 metaStr +=
"$USER_META;";
475 LOGP(info,
"Created local snapshot {}", flLoc);
476 LOGP(info, R
"(Upload with: o2-ccdb-upload --host "$ccdbhost" -p {} -f {} -k {} --starttimestamp {} --endtimestamp {} -m "{}")",
483 CURL* curl =
nullptr;
484 curl = curl_easy_init();
487 checkMetadataKeys(metadata);
489 if (curl !=
nullptr) {
490 auto mime = curl_mime_init(curl);
491 auto field = curl_mime_addpart(mime);
492 curl_mime_name(field,
"send");
494 curl_mime_filedata(field,
filename.c_str());
499 curl_mime_data(field,
"", 0);
504 curl_easy_setopt(curl, CURLOPT_MIMEPOST, mime);
505 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
506 curl_easy_setopt(curl, CURLOPT_USERAGENT, mUniqueAgentID.c_str());
507 curl_easy_setopt(curl, CURLOPT_TIMEOUT, mCurlTimeoutUpload);
509 CURLcode
res = CURL_LAST;
511 for (
size_t hostIndex = 0; hostIndex < hostsPool.size() &&
res > 0; hostIndex++) {
512 std::string fullUrl = getFullUrlForStorage(curl,
path, objectType, metadata, sanitizedStartValidityTimestamp, sanitizedEndValidityTimestamp, hostIndex);
513 LOG(debug3) <<
"Full URL Encoded: " << fullUrl;
515 curl_easy_setopt(curl, CURLOPT_URL, fullUrl.c_str());
518 struct curl_slist* headerlist = curl_slist_append(
nullptr,
"Expect:");
519 headerlist = appendGateToken(headerlist, fullUrl);
520 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist);
523 res = CURL_perform(curl);
525 if (
res != CURLE_OK) {
526 if (
res == CURLE_OPERATION_TIMEDOUT) {
527 LOGP(alarm,
"curl_easy_perform() timed out. Consider increasing the timeout using the env var `ALICEO2_CCDB_CURL_TIMEOUT_UPLOAD` (seconds), current one is {}", mCurlTimeoutUpload);
529 LOGP(alarm,
"curl_easy_perform() failed: {}", curl_easy_strerror(
res));
533 curl_slist_free_all(headerlist);
537 curl_easy_cleanup(curl);
540 curl_mime_free(mime);
542 LOGP(alarm,
"curl initialization failure");
549 long startValidityTimestamp,
long endValidityTimestamp, std::vector<char>::size_type
maxSize)
const
553 LOGP(error,
"nullptr is provided for object {}/{}/{}",
path, startValidityTimestamp, endValidityTimestamp);
561std::string CcdbApi::getFullUrlForStorage(CURL* curl,
const std::string&
path,
const std::string& objtype,
562 const std::map<std::string, std::string>& metadata,
563 long startValidityTimestamp,
long endValidityTimestamp,
int hostIndex)
const
566 std::string startValidityString = getTimestampString(startValidityTimestamp < 0 ?
getCurrentTimestamp() : startValidityTimestamp);
567 std::string endValidityString = getTimestampString(endValidityTimestamp < 0 ?
getFutureTimestamp(60 * 60 * 24 * 1) : endValidityTimestamp);
569 std::string
url = getHostUrl(hostIndex);
571 std::string fullUrl =
url +
"/" +
path +
"/" + startValidityString +
"/" + endValidityString +
"/";
574 char* objtypeEncoded = curl_easy_escape(curl, objtype.c_str(), objtype.size());
575 fullUrl +=
"ObjectType=" + std::string(objtypeEncoded) +
"/";
576 curl_free(objtypeEncoded);
578 for (
auto& kv : metadata) {
579 std::string mfirst = kv.first;
580 std::string msecond = kv.second;
582 char* mfirstEncoded = curl_easy_escape(curl, mfirst.c_str(), mfirst.size());
583 char* msecondEncoded = curl_easy_escape(curl, msecond.c_str(), msecond.size());
584 fullUrl += std::string(mfirstEncoded) +
"=" + std::string(msecondEncoded) +
"/";
585 curl_free(mfirstEncoded);
586 curl_free(msecondEncoded);
592std::string CcdbApi::getFullUrlForRetrieval(CURL* curl,
const std::string&
path,
const std::map<std::string, std::string>& metadata,
long timestamp,
int hostIndex)
const
594 if (mInSnapshotMode) {
595 return getSnapshotFile(mSnapshotTopPath,
path);
601 std::string hostUrl = getHostUrl(hostIndex);
603 std::string fullUrl = hostUrl +
"/" +
path +
"/" + validityString +
"/";
605 for (
auto& kv : metadata) {
606 std::string mfirst = kv.first;
607 std::string msecond = kv.second;
609 char* mfirstEncoded = curl_easy_escape(curl, mfirst.c_str(), mfirst.size());
610 char* msecondEncoded = curl_easy_escape(curl, msecond.c_str(), msecond.size());
611 fullUrl += std::string(mfirstEncoded) +
"=" + std::string(msecondEncoded) +
"/";
612 curl_free(mfirstEncoded);
613 curl_free(msecondEncoded);
635static size_t WriteMemoryCallback(
void* contents,
size_t size,
size_t nmemb,
void* userp)
637 size_t realsize =
size * nmemb;
640 mem->memory = (
char*)realloc(mem->memory, mem->size + realsize + 1);
641 if (mem->memory ==
nullptr) {
642 printf(
"not enough memory (realloc returned NULL)\n");
646 memcpy(&(mem->memory[mem->size]), contents, realsize);
647 mem->size += realsize;
648 mem->memory[mem->size] = 0;
664static size_t WriteToFileCallback(
void*
ptr,
size_t size,
size_t nmemb, FILE*
stream)
677static CURLcode ssl_ctx_callback(CURL*,
void*,
void* parm)
679 std::string
msg((
const char*)parm);
682 if (
msg.length() > 0 &&
end == -1) {
684 }
else if (
end > 0) {
696 CredentialsKind cmk = mJAlienCredentials->getPreferedCredentials();
699 if (cmk == cNOT_FOUND) {
703 TJAlienCredentialsObject cmo = mJAlienCredentials->get(cmk);
705 char* CAPath = getenv(
"X509_CERT_DIR");
707 curl_easy_setopt(curl_handle, CURLOPT_CAPATH, CAPath);
709 curl_easy_setopt(curl_handle, CURLOPT_CAINFO,
nullptr);
710 curl_easy_setopt(curl_handle, CURLOPT_SSLCERT, cmo.certpath.c_str());
711 curl_easy_setopt(curl_handle, CURLOPT_SSLKEY, cmo.keypath.c_str());
714 curl_easy_setopt(curl_handle, CURLOPT_SSL_CTX_FUNCTION, ssl_ctx_callback);
715 curl_easy_setopt(curl_handle, CURLOPT_SSL_CTX_DATA, mJAlienCredentials->getMessages().c_str());
722void CcdbApi::initCurlOptionsForRetrieve(CURL* curlHandle,
void* chunk,
CurlWriteCallback writeCallback,
bool followRedirect)
const
724 curl_easy_setopt(curlHandle, CURLOPT_WRITEFUNCTION, writeCallback);
725 curl_easy_setopt(curlHandle, CURLOPT_WRITEDATA, chunk);
726 curl_easy_setopt(curlHandle, CURLOPT_FOLLOWLOCATION, followRedirect ? 1L : 0L);
731template <
typename MapType = std::map<std::
string, std::
string>>
732size_t header_map_callback(
char*
buffer,
size_t size,
size_t nitems,
void* userdata)
734 auto* headers =
static_cast<MapType*
>(userdata);
735 auto header = std::string(
buffer,
size * nitems);
736 std::string::size_type
index = header.find(
':', 0);
737 if (
index != std::string::npos) {
738 const auto key = boost::algorithm::trim_copy(header.substr(0,
index));
739 const auto value = boost::algorithm::trim_copy(header.substr(
index + 1));
740 LOGP(
debug,
"Adding #{} {} -> {}", headers->size(),
key,
value);
742 if (
key ==
"Content-Length") {
743 auto cl = headers->find(
"Content-Length");
744 if (cl != headers->end()) {
745 if (std::stol(cl->second) < stol(
value)) {
755 auto cl = headers->find(
"ETag");
756 if (cl != headers->end()) {
762 if (
key ==
"Content-Type") {
763 auto cl = headers->find(
"Content-Type");
764 if (cl != headers->end()) {
770 headers->insert(std::make_pair(
key,
value));
773 return size * nitems;
777void CcdbApi::initCurlHTTPHeaderOptionsForRetrieve(CURL* curlHandle, curl_slist*& option_list,
long timestamp, std::map<std::string, std::string>* headers, std::string
const&
etag,
782 option_list = curl_slist_append(option_list, (
"If-None-Match: " +
etag).c_str());
786 option_list = curl_slist_append(option_list, (
"If-Not-After: " +
createdNotAfter).c_str());
790 option_list = curl_slist_append(option_list, (
"If-Not-Before: " +
createdNotBefore).c_str());
793 if (headers !=
nullptr) {
794 option_list = curl_slist_append(option_list, (
"If-None-Match: " +
to_string(timestamp)).c_str());
795 curl_easy_setopt(curlHandle, CURLOPT_HEADERFUNCTION, header_map_callback<>);
796 curl_easy_setopt(curlHandle, CURLOPT_HEADERDATA, headers);
799 option_list = appendGateToken(option_list,
url);
803 curl_easy_setopt(curlHandle, CURLOPT_HTTPHEADER, option_list);
805 curl_easy_setopt(curlHandle, CURLOPT_USERAGENT, mUniqueAgentID.c_str());
808bool CcdbApi::receiveToFile(FILE* fileHandle, std::string
const&
path, std::map<std::string, std::string>
const& metadata,
809 long timestamp, std::map<std::string, std::string>* headers, std::string
const&
etag,
815bool CcdbApi::receiveToMemory(
void* chunk, std::string
const&
path, std::map<std::string, std::string>
const& metadata,
816 long timestamp, std::map<std::string, std::string>* headers, std::string
const&
etag,
822bool CcdbApi::receiveObject(
void* dataHolder, std::string
const&
path, std::map<std::string, std::string>
const& metadata,
823 long timestamp, std::map<std::string, std::string>* headers, std::string
const&
etag,
828 curlHandle = curl_easy_init();
829 curl_easy_setopt(curlHandle, CURLOPT_USERAGENT, mUniqueAgentID.c_str());
831 if (curlHandle !=
nullptr) {
834 initCurlOptionsForRetrieve(curlHandle, dataHolder, writeCallback, followRedirect);
835 long responseCode = 0;
836 CURLcode curlResultCode = CURL_LAST;
838 for (
size_t hostIndex = 0; hostIndex < hostsPool.size() && (responseCode >= 400 || curlResultCode > 0); hostIndex++) {
839 std::string fullUrl = getFullUrlForRetrieval(curlHandle,
path, metadata, timestamp, hostIndex);
840 curl_easy_setopt(curlHandle, CURLOPT_URL, fullUrl.c_str());
843 curl_slist* option_list =
nullptr;
846 curlResultCode = CURL_perform(curlHandle);
848 if (curlResultCode != CURLE_OK) {
849 LOGP(alarm,
"curl_easy_perform() failed: {}", curl_easy_strerror(curlResultCode));
851 curlResultCode = curl_easy_getinfo(curlHandle, CURLINFO_RESPONSE_CODE, &responseCode);
852 if ((curlResultCode == CURLE_OK) && (responseCode < 300)) {
853 curl_slist_free_all(option_list);
854 curl_easy_cleanup(curlHandle);
857 if (curlResultCode != CURLE_OK) {
858 LOGP(alarm,
"invalid URL {}", fullUrl);
860 LOGP(alarm,
"not found under link {}", fullUrl);
864 curl_slist_free_all(option_list);
867 curl_easy_cleanup(curlHandle);
873 long timestamp)
const
881 bool res = receiveToMemory((
void*)&chunk,
path, metadata, timestamp);
884 std::lock_guard<std::mutex> guard(
gIOMutex);
886 mess.SetBuffer(chunk.
memory, chunk.
size, kFALSE);
891 LOGP(info,
"couldn't retrieve the object {}",
path);
903 std::string
str = inp;
904 str.erase(std::remove_if(
str.begin(),
str.end(), ::isspace),
str.end());
905 str = std::regex_replace(
str, std::regex(
"::"),
"-");
911 long timestamp, std::map<std::string, std::string>* headers, std::string
const&
etag,
918 long timestamp,
bool preservePath, std::string
const& localFileName, std::string
const&
createdNotAfter, std::string
const&
createdNotBefore, std::map<std::string, std::string>* outHeaders)
const
922 std::string fulltargetdir = targetdir + (preservePath ? (
'/' +
path) :
"");
926 }
catch (std::exception e) {
927 LOGP(error,
"Could not create local snapshot cache directory {}, reason: {}", fulltargetdir, e.what());
932 std::map<std::string, std::string> headers;
935 if ((headers.count(
"Error") != 0) || (buff.empty())) {
936 LOGP(error,
"Unable to find object {}/{}, Aborting",
path, timestamp);
940 auto getFileName = [&headers]() {
941 auto& s = headers[
"Content-Disposition"];
943 std::regex re(
"(.*;)filename=\"(.*)\"");
945 if (std::regex_match(s.c_str(),
m, re)) {
949 std::string backupname(
"ccdb-blob.bin");
950 LOG(error) <<
"Cannot determine original filename from Content-Disposition ... falling back to " << backupname;
953 auto filename = localFileName.size() > 0 ? localFileName : getFileName();
954 std::string targetpath = fulltargetdir +
"/" +
filename;
956 std::ofstream objFile(targetpath, std::ios::out | std::ofstream::binary);
957 std::copy(buff.begin(), buff.end(), std::ostreambuf_iterator<char>(objFile));
958 if (!objFile.good()) {
959 LOGP(error,
"Unable to open local file {}, Aborting", targetpath);
965 updateMetaInformationInLocalFile(targetpath.c_str(), &headers, &querysummary);
967 *outHeaders = std::move(headers);
972void CcdbApi::snapshot(std::string
const& ccdbrootpath, std::string
const& localDir,
long timestamp)
const
976 std::map<std::string, std::string> metadata;
977 for (
auto& folder : allfolders) {
987 auto object = file.GetObjectChecked(what, cl);
991 std::string objectName(cl->GetName());
993 object = file.GetObjectChecked(objectName.c_str(), cl);
994 LOG(warn) <<
"Did not find object under expected name " << what;
998 LOG(warn) <<
"Found object under deprecated name " << cl->GetName();
1003 if (cl->InheritsFrom(
"TObject")) {
1006 auto tree =
dynamic_cast<TTree*
>((
TObject*)
object);
1008 tree->LoadBaskets(0x1L << 32);
1009 tree->SetDirectory(
nullptr);
1012 auto h =
dynamic_cast<TH1*
>((
TObject*)
object);
1014 h->SetDirectory(
nullptr);
1022void* CcdbApi::extractFromLocalFile(std::string
const&
filename, std::type_info
const& tinfo, std::map<std::string, std::string>* headers)
const
1024 if (!std::filesystem::exists(
filename)) {
1025 LOG(error) <<
"Local snapshot " <<
filename <<
" not found \n";
1028 std::lock_guard<std::mutex> guard(
gIOMutex);
1029 auto tcl = tinfo2TClass(tinfo);
1034 *headers = *storedmeta;
1037 if ((
isSnapshotMode() || mPreferSnapshotCache) && headers->find(
"ETag") == headers->end()) {
1040 if (headers->find(
"fileSize") == headers->end()) {
1041 (*headers)[
"fileSize"] = fmt::format(
"{}",
f.GetEND());
1047bool CcdbApi::initTGrid()
const
1049 if (mNeedAlienToken && !gGrid) {
1050 static bool allowNoToken = getenv(
"ALICEO2_CCDB_NOTOKENCHECK") && atoi(getenv(
"ALICEO2_CCDB_NOTOKENCHECK"));
1052 LOG(fatal) <<
"Alien Token Check failed - Please get an alien token before running with https CCDB endpoint, or alice-ccdb.cern.ch!";
1054 TGrid::Connect(
"alien");
1055 static bool errorShown =
false;
1056 if (!gGrid && errorShown ==
false) {
1058 LOG(error) <<
"TGrid::Connect returned nullptr. May be due to missing alien token";
1060 LOG(fatal) <<
"TGrid::Connect returned nullptr. May be due to missing alien token";
1065 return gGrid !=
nullptr;
1068void* CcdbApi::downloadFilesystemContent(std::string
const&
url, std::type_info
const& tinfo, std::map<std::string, std::string>* headers)
const
1070 if ((
url.find(
"alien:/", 0) != std::string::npos) && !initTGrid()) {
1073 std::lock_guard<std::mutex> guard(
gIOMutex);
1074 auto memfile = TMemFile::Open(
url.c_str(),
"OPEN");
1076 auto cl = tinfo2TClass(tinfo);
1078 if (headers && headers->find(
"fileSize") == headers->end()) {
1079 (*headers)[
"fileSize"] = fmt::format(
"{}", memfile->GetEND());
1087void* CcdbApi::interpretAsTMemFileAndExtract(
char* contentptr,
size_t contentsize, std::type_info
const& tinfo)
1090 Int_t previousErrorLevel = gErrorIgnoreLevel;
1091 gErrorIgnoreLevel = kFatal;
1092 std::lock_guard<std::mutex> guard(
gIOMutex);
1093 TMemFile memFile(
"name", contentptr, contentsize,
"READ");
1094 gErrorIgnoreLevel = previousErrorLevel;
1095 if (!memFile.IsZombie()) {
1096 auto tcl = tinfo2TClass(tinfo);
1107void* CcdbApi::navigateURLsAndRetrieveContent(CURL* curl_handle, std::string
const&
url, std::type_info
const& tinfo, std::map<std::string, std::string>* headers)
const
1112 static thread_local std::multimap<std::string, std::string> headerData;
1115 if ((
url.find(
"alien:/", 0) != std::string::npos) || (
url.find(
"file:/", 0) != std::string::npos)) {
1116 return downloadFilesystemContent(
url, tinfo, headers);
1123 curl_easy_setopt(curl_handle, CURLOPT_URL,
url.c_str());
1125 MemoryStruct chunk{(
char*)malloc(1), 0};
1126 initCurlOptionsForRetrieve(curl_handle, (
void*)&chunk, WriteMemoryCallback,
false);
1128 curl_easy_setopt(curl_handle, CURLOPT_HEADERFUNCTION, header_map_callback<
decltype(headerData)>);
1130 curl_easy_setopt(curl_handle, CURLOPT_HEADERDATA, (
void*)&headerData);
1134 auto res = CURL_perform(curl_handle);
1135 long response_code = -1;
1136 void* content =
nullptr;
1138 if (
res == CURLE_OK && curl_easy_getinfo(curl_handle, CURLINFO_RESPONSE_CODE, &response_code) == CURLE_OK) {
1140 for (
auto& p : headerData) {
1141 (*headers)[
p.first] =
p.second;
1144 if (200 <= response_code && response_code < 300) {
1146 content = interpretAsTMemFileAndExtract(chunk.memory, chunk.size, tinfo);
1147 if (headers && headers->find(
"fileSize") == headers->end()) {
1148 (*headers)[
"fileSize"] = fmt::format(
"{}", chunk.size);
1150 }
else if (response_code == 304) {
1155 LOGP(
debug,
"Object exists but I am not serving it since it's already in your possession");
1158 else if (300 <= response_code && response_code < 400) {
1164 auto complement_Location = [
this](std::string
const& loc) {
1165 if (loc[0] ==
'/') {
1172 std::vector<std::string> locs;
1173 auto iter = headerData.find(
"Location");
1174 if (iter != headerData.end()) {
1175 locs.push_back(complement_Location(iter->second));
1178 auto iter2 = headerData.find(
"Content-Location");
1179 if (iter2 != headerData.end()) {
1180 auto range = headerData.equal_range(
"Content-Location");
1181 for (
auto it =
range.first; it !=
range.second; ++it) {
1182 if (std::find(locs.begin(), locs.end(), it->second) == locs.end()) {
1183 locs.push_back(complement_Location(it->second));
1187 for (
auto& l : locs) {
1189 LOG(
debug) <<
"Trying content location " << l;
1190 content = navigateURLsAndRetrieveContent(curl_handle, l, tinfo, headers);
1196 }
else if (response_code == 404) {
1197 LOG(error) <<
"Requested resource does not exist: " <<
url;
1200 LOG(error) <<
"Error in fetching object " <<
url <<
", curl response code:" << response_code;
1204 if (chunk.memory !=
nullptr) {
1208 LOGP(alarm,
"Curl request to {} failed with result {}, response code: {}",
url,
int(
res), response_code);
1213 (*headers)[
"Error"] =
"An error occurred during retrieval";
1219 std::map<std::string, std::string>
const& metadata,
long timestamp,
1220 std::map<std::string, std::string>* headers, std::string
const&
etag,
1223 if (!mSnapshotCachePath.empty()) {
1225 auto semaphore_barrier = std::make_unique<CCDBSemaphore>(mSnapshotCachePath,
path);
1226 std::string logfile = mSnapshotCachePath +
"/log";
1227 std::fstream out(logfile, ios_base::out | ios_base::app);
1228 if (out.is_open()) {
1229 out <<
"CCDB-access[" << getpid() <<
"] of " << mUniqueAgentID <<
" to " <<
path <<
" timestamp " << timestamp <<
"\n";
1231 auto snapshotfile = getSnapshotFile(mSnapshotCachePath,
path);
1232 bool snapshoting =
false;
1233 if (!std::filesystem::exists(snapshotfile)) {
1235 out <<
"CCDB-access[" << getpid() <<
"] ... " << mUniqueAgentID <<
" downloading to snapshot " << snapshotfile <<
"\n";
1238 out <<
"CCDB-access[" << getpid() <<
"] ... " << mUniqueAgentID <<
" failed to create directory for " << snapshotfile <<
"\n";
1241 out <<
"CCDB-access[" << getpid() <<
"] ... " << mUniqueAgentID <<
"serving from local snapshot " << snapshotfile <<
"\n";
1244 auto res = extractFromLocalFile(snapshotfile, tinfo, headers);
1246 logReading(
path, timestamp, headers,
"retrieve from snapshot");
1253 CURL* curl_handle = curl_easy_init();
1254 curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, mUniqueAgentID.c_str());
1255 std::string fullUrl = getFullUrlForRetrieval(curl_handle,
path, metadata, timestamp);
1257 if (mInSnapshotMode) {
1258 auto res = extractFromLocalFile(fullUrl, tinfo, headers);
1260 logReading(
path, timestamp, headers,
"retrieve from snapshot");
1265 curl_slist* option_list =
nullptr;
1267 auto content = navigateURLsAndRetrieveContent(curl_handle, fullUrl, tinfo, headers);
1269 for (
size_t hostIndex = 1; hostIndex < hostsPool.size() && !(content); hostIndex++) {
1270 fullUrl = getFullUrlForRetrieval(curl_handle,
path, metadata, timestamp, hostIndex);
1272 curl_slist_free_all(option_list);
1273 option_list =
nullptr;
1275 content = navigateURLsAndRetrieveContent(curl_handle, fullUrl, tinfo, headers);
1278 logReading(
path, timestamp, headers,
"retrieve");
1280 curl_slist_free_all(option_list);
1281 curl_easy_cleanup(curl_handle);
1287 size_t newLength =
size * nmemb;
1288 size_t oldLength = s->size();
1290 s->resize(oldLength + newLength);
1291 }
catch (std::bad_alloc& e) {
1292 LOG(error) <<
"memory error when getting data from CCDB";
1296 std::copy((
char*)contents, (
char*)contents + newLength, s->begin() + oldLength);
1297 return size * nmemb;
1303 CURLcode
res = CURL_LAST;
1306 curl = curl_easy_init();
1307 if (curl !=
nullptr) {
1309 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &
result);
1310 curl_easy_setopt(curl, CURLOPT_USERAGENT, mUniqueAgentID.c_str());
1314 std::string fullUrl;
1316 for (
size_t hostIndex = 0; hostIndex < hostsPool.size() &&
res != CURLE_OK; hostIndex++) {
1317 fullUrl = getHostUrl(hostIndex);
1318 fullUrl += latestOnly ?
"/latest/" :
"/browse/";
1320 curl_easy_setopt(curl, CURLOPT_URL, fullUrl.c_str());
1323 struct curl_slist* headers =
nullptr;
1324 headers = curl_slist_append(headers, (std::string(
"Accept: ") + returnFormat).c_str());
1325 headers = curl_slist_append(headers, (std::string(
"Content-Type: ") + returnFormat).c_str());
1332 headers = appendGateToken(headers, fullUrl);
1333 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
1335 res = CURL_perform(curl);
1336 if (
res != CURLE_OK) {
1337 LOGP(alarm,
"CURL_perform() failed: {}", curl_easy_strerror(
res));
1339 curl_slist_free_all(headers);
1341 curl_easy_cleanup(curl);
1347std::string CcdbApi::getTimestampString(
long timestamp)
const
1360 curl = curl_easy_init();
1361 if (curl !=
nullptr) {
1362 curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST,
"DELETE");
1363 curl_easy_setopt(curl, CURLOPT_USERAGENT, mUniqueAgentID.c_str());
1364 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
1367 for (
size_t hostIndex = 0; hostIndex < hostsPool.size(); hostIndex++) {
1370 stringstream fullUrl;
1371 fullUrl << getHostUrl(hostIndex) <<
"/" <<
path <<
"/" << timestampLocal;
1372 curl_easy_setopt(curl, CURLOPT_URL, fullUrl.str().c_str());
1376 struct curl_slist*
list = appendGateToken(
nullptr, fullUrl.str());
1377 curl_easy_setopt(curl, CURLOPT_HTTPHEADER,
list);
1380 res = CURL_perform(curl);
1381 if (
res != CURLE_OK) {
1382 LOGP(alarm,
"CURL_perform() failed: {}", curl_easy_strerror(
res));
1384 curl_slist_free_all(
list);
1388 curl_easy_cleanup(curl);
1396 for (
size_t i = 0;
i < hostsPool.size();
i++) {
1400 stringstream fullUrl;
1401 std::string
url = getHostUrl(
i);
1402 fullUrl <<
url <<
"/truncate/" <<
path;
1404 curl = curl_easy_init();
1405 curl_easy_setopt(curl, CURLOPT_USERAGENT, mUniqueAgentID.c_str());
1406 if (curl !=
nullptr) {
1407 curl_easy_setopt(curl, CURLOPT_URL, fullUrl.str().c_str());
1413 struct curl_slist*
list = appendGateToken(
nullptr, fullUrl.str());
1414 curl_easy_setopt(curl, CURLOPT_HTTPHEADER,
list);
1415 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
1419 res = CURL_perform(curl);
1420 if (
res != CURLE_OK) {
1421 LOGP(alarm,
"CURL_perform() failed: {}", curl_easy_strerror(
res));
1423 curl_easy_cleanup(curl);
1424 curl_slist_free_all(
list);
1431 return size * nmemb;
1437 CURLcode
res = CURL_LAST;
1440 curl = curl_easy_init();
1441 curl_easy_setopt(curl, CURLOPT_USERAGENT, mUniqueAgentID.c_str());
1454 for (
size_t hostIndex = 0; hostIndex < hostsPool.size() &&
res != CURLE_OK; hostIndex++) {
1455 curl_easy_setopt(curl, CURLOPT_URL, mUrl.data());
1456 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
write_data);
1458 res = CURL_perform(curl);
1463 curl_easy_cleanup(curl);
1472 std::stringstream ss(reply.c_str());
1474 std::vector<std::string> folders;
1476 size_t numberoflines = std::count(reply.begin(), reply.end(),
'\n');
1477 bool inSubFolderSection =
false;
1479 for (
size_t linenumber = 0; linenumber < numberoflines; ++linenumber) {
1480 std::getline(ss, line);
1481 if (inSubFolderSection && line.size() > 0) {
1486 if (line.compare(
"Subfolders:") == 0) {
1487 inSubFolderSection =
true;
1495size_t header_callback(
char*
buffer,
size_t size,
size_t nitems,
void* userdata)
1497 auto* headers =
static_cast<std::vector<std::string>*
>(userdata);
1498 auto header = std::string(
buffer,
size * nitems);
1499 headers->emplace_back(std::string(header.data()));
1500 return size * nitems;
1508 auto p = std::filesystem::path(
filename).parent_path();
1509 if (!std::filesystem::exists(p)) {
1510 std::filesystem::create_directories(p);
1513 rapidjson::StringBuffer
buffer;
1514 rapidjson::Writer<rapidjson::StringBuffer> writer(
buffer);
1515 writer.StartObject();
1516 for (
const auto& pair : meta) {
1517 writer.Key(pair.first.c_str());
1518 writer.String(pair.second.c_str());
1524 if (file.is_open()) {
1525 file <<
buffer.GetString();
1537 if (!file.is_open()) {
1538 std::cerr <<
"Failed to open file for reading." << std::endl;
1542 std::string jsonStr((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
1545 rapidjson::Document document;
1546 document.Parse(jsonStr.c_str());
1548 if (document.HasParseError()) {
1549 std::cerr <<
"Error parsing JSON" << std::endl;
1554 for (
auto itr = document.MemberBegin(); itr != document.MemberEnd(); ++itr) {
1555 meta[itr->name.GetString()] = itr->value.GetString();
1560std::map<std::string, std::string>
CcdbApi::retrieveHeaders(std::string
const&
path, std::map<std::string, std::string>
const& metadata,
long timestamp)
const
1563 auto do_remote_header_call = [
this, &
path, &metadata, timestamp]() -> std::map<std::string, std::string> {
1564 CURL* curl = curl_easy_init();
1565 CURLcode
res = CURL_LAST;
1566 std::string fullUrl = getFullUrlForRetrieval(curl,
path, metadata, timestamp);
1567 std::map<std::string, std::string> headers;
1569 if (curl !=
nullptr) {
1570 struct curl_slist*
list =
nullptr;
1572 list = appendGateToken(
list, fullUrl);
1574 curl_easy_setopt(curl, CURLOPT_HTTPHEADER,
list);
1577 curl_easy_setopt(curl, CURLOPT_NOBODY, 1L);
1578 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
1579 curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, header_map_callback<>);
1580 curl_easy_setopt(curl, CURLOPT_HEADERDATA, &headers);
1581 curl_easy_setopt(curl, CURLOPT_USERAGENT, mUniqueAgentID.c_str());
1586 long httpCode = 404;
1587 CURLcode getCodeRes = CURL_LAST;
1588 for (
size_t hostIndex = 0; hostIndex < hostsPool.size() && (httpCode >= 400 ||
res > 0 || getCodeRes > 0); hostIndex++) {
1589 curl_easy_setopt(curl, CURLOPT_URL, fullUrl.c_str());
1590 res = CURL_perform(curl);
1591 if (
res != CURLE_OK &&
res != CURLE_UNSUPPORTED_PROTOCOL) {
1595 LOG(error) <<
"CURL_perform() failed: " << curl_easy_strerror(
res);
1597 getCodeRes = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpCode);
1599 if (httpCode == 404) {
1602 curl_easy_cleanup(curl);
1607 if (!mSnapshotCachePath.empty()) {
1609 auto semaphore_barrier = std::make_unique<CCDBSemaphore>(mSnapshotCachePath + std::string(
"_headers"),
path);
1611 std::string logfile = mSnapshotCachePath +
"/log";
1612 std::fstream out(logfile, ios_base::out | ios_base::app);
1613 if (out.is_open()) {
1614 out <<
"CCDB-header-access[" << getpid() <<
"] of " << mUniqueAgentID <<
" to " <<
path <<
" timestamp " << timestamp <<
"\n";
1616 auto snapshotfile = getSnapshotFile(mSnapshotCachePath,
path +
"/" +
std::to_string(timestamp),
"header.json");
1617 if (!std::filesystem::exists(snapshotfile)) {
1618 out <<
"CCDB-header-access[" << getpid() <<
"] ... " << mUniqueAgentID <<
" storing to snapshot " << snapshotfile <<
"\n";
1621 auto meta = do_remote_header_call();
1625 LOG(warn) <<
"Failed to cache the header information to disc";
1629 out <<
"CCDB-header-access[" << getpid() <<
"] ... " << mUniqueAgentID <<
"serving from local snapshot " << snapshotfile <<
"\n";
1630 std::map<std::string, std::string> meta;
1632 LOG(warn) <<
"Failed to read cached information from disc";
1633 return do_remote_header_call();
1638 return do_remote_header_call();
1643 auto curl = curl_easy_init();
1649 struct curl_slist*
list =
nullptr;
1650 list = curl_slist_append(
list, (
"If-None-Match: " +
etag).c_str());
1653 curl_easy_setopt(curl, CURLOPT_HTTPHEADER,
list);
1655 curl_easy_setopt(curl, CURLOPT_URL,
url.c_str());
1657 curl_easy_setopt(curl, CURLOPT_NOBODY, 1L);
1658 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
1659 curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, header_callback);
1660 curl_easy_setopt(curl, CURLOPT_HEADERDATA, &headers);
1661 if (!agentID.empty()) {
1662 curl_easy_setopt(curl, CURLOPT_USERAGENT, agentID.c_str());
1668 curl_easy_perform(curl);
1669 long http_code = 404;
1670 curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
1671 if (http_code == 304) {
1679 static std::string etagHeader =
"ETag: ";
1680 static std::string locationHeader =
"Content-Location: ";
1683 for (
auto h : headers) {
1684 if (
h.find(etagHeader) == 0) {
1685 etag = trimHeaderValue(std::string_view(
h).substr(etagHeader.size()));
1686 }
else if (
h.find(locationHeader) == 0) {
1687 pfns.emplace_back(trimHeaderValue(std::string_view(
h).substr(locationHeader.size())));
1703 auto object = file.GetObjectChecked(
CCDBMETA_ENTRY, TClass::GetClass(
typeid(std::map<std::string, std::string>)));
1705 return static_cast<std::map<std::string, std::string>*
>(
object);
1712void traverseAndFillFolders(
CcdbApi const& api, std::string
const&
top, std::vector<std::string>& folders)
1716 folders.emplace_back(
top);
1719 if (subfolders.size() > 0) {
1721 for (
auto& sub : subfolders) {
1722 traverseAndFillFolders(api, sub, folders);
1732 std::vector<std::string> folders;
1733 traverseAndFillFolders(*
this,
top, folders);
1737TClass* CcdbApi::tinfo2TClass(std::type_info
const& tinfo)
1739 TClass* cl = TClass::GetClass(tinfo);
1741 throw std::runtime_error(fmt::format(
"Could not retrieve ROOT dictionary for type {}, aborting", tinfo.name()));
1747int CcdbApi::updateMetadata(std::string
const&
path, std::map<std::string, std::string>
const& metadata,
long timestamp, std::string
const&
id,
long newEOV)
1750 CURL* curl = curl_easy_init();
1751 curl_easy_setopt(curl, CURLOPT_USERAGENT, mUniqueAgentID.c_str());
1752 if (curl !=
nullptr) {
1754 for (
size_t hostIndex = 0; hostIndex < hostsPool.size(); hostIndex++) {
1757 stringstream fullUrl;
1758 fullUrl << getHostUrl(hostIndex) <<
"/" <<
path <<
"/" << timestamp;
1760 fullUrl <<
"/" << newEOV;
1763 fullUrl <<
"/" <<
id;
1767 for (
auto& kv : metadata) {
1768 std::string mfirst = kv.first;
1769 std::string msecond = kv.second;
1771 char* mfirstEncoded = curl_easy_escape(curl, mfirst.c_str(), mfirst.size());
1772 char* msecondEncoded = curl_easy_escape(curl, msecond.c_str(), msecond.size());
1773 fullUrl << std::string(mfirstEncoded) +
"=" + std::string(msecondEncoded) +
"&";
1774 curl_free(mfirstEncoded);
1775 curl_free(msecondEncoded);
1778 if (curl !=
nullptr) {
1779 LOG(
debug) <<
"passing to curl: " << fullUrl.str();
1780 curl_easy_setopt(curl, CURLOPT_URL, fullUrl.str().c_str());
1781 curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST,
"PUT");
1782 curl_easy_setopt(curl, CURLOPT_USERAGENT, mUniqueAgentID.c_str());
1783 curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
1786 struct curl_slist*
list = appendGateToken(
nullptr, fullUrl.str());
1787 curl_easy_setopt(curl, CURLOPT_HTTPHEADER,
list);
1791 res = CURL_perform(curl);
1792 if (
res != CURLE_OK) {
1793 LOGP(alarm,
"CURL_perform() failed: {}, code: {}", curl_easy_strerror(
res),
int(
res));
1798 curl_slist_free_all(
list);
1803 curl_easy_cleanup(curl);
1808void CcdbApi::initHostsPool(std::string hosts)
1811 auto splitted = hosts | std::views::transform([](
char c) {
return (
c ==
';') ?
',' :
c; }) | std::views::split(
',');
1812 for (
auto&& part : splitted) {
1813 hostsPool.emplace_back(part.begin(), part.end());
1817std::string CcdbApi::getHostUrl(
int hostIndex)
const
1819 return hostsPool.at(hostIndex);
1825 data->hoPair.object = &requestContext.
dest;
1827 std::function<bool(std::string)> localContentCallback = [
this, &requestContext](std::string
url) {
1831 auto writeCallback = [](
void* contents,
size_t size,
size_t nmemb,
void* chunkptr) {
1833 auto& chunk = *ho.
object;
1834 size_t realsize =
size * nmemb, sz = 0;
1837 if (chunk.capacity() < chunk.size() + realsize) {
1839 const char hannot[] =
"header";
1840 size_t hsize = getFlatHeaderSize(ho.header);
1841 auto cl = ho.header.find(
"Content-Length");
1842 if (cl != ho.header.end()) {
1843 size_t sizeFromHeader = std::stol(cl->second);
1844 sz = hsize + std::max(chunk.size() * (sizeFromHeader ? 1 : 2) + realsize, sizeFromHeader);
1846 sz = hsize + std::max(chunk.size() * 2, chunk.size() + realsize);
1851 char* contC = (
char*)contents;
1852 chunk.insert(chunk.end(), contC, contC + realsize);
1853 }
catch (std::exception e) {
1860 CURL* curl_handle = curl_easy_init();
1861 curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, mUniqueAgentID.c_str());
1862 std::string fullUrl = getFullUrlForRetrieval(curl_handle, requestContext.
path, requestContext.
metadata, requestContext.
timestamp);
1865 data->hosts = hostsPool;
1868 data->localContentCallback = localContentCallback;
1869 data->userAgent = mUniqueAgentID;
1876 data->optionsLists.reserve(hostsPool.size());
1877 for (
size_t hostIndex = 0; hostIndex < hostsPool.size(); hostIndex++) {
1878 curl_slist* hostOptions =
nullptr;
1879 const std::string hostUrl = getFullUrlForRetrieval(curl_handle, requestContext.
path, requestContext.
metadata,
1881 initCurlHTTPHeaderOptionsForRetrieve(curl_handle, hostOptions, requestContext.
timestamp, &requestContext.
headers,
1884 data->optionsLists.push_back(hostOptions);
1889 if (!
data->optionsLists.empty()) {
1890 curl_easy_setopt(curl_handle, CURLOPT_HTTPHEADER,
data->optionsLists.front());
1893 curl_easy_setopt(curl_handle, CURLOPT_URL, fullUrl.c_str());
1894 initCurlOptionsForRetrieve(curl_handle, (
void*)(&
data->hoPair), writeCallback,
false);
1895 curl_easy_setopt(curl_handle, CURLOPT_HEADERFUNCTION, header_map_callback<
decltype(
data->hoPair.header)>);
1896 curl_easy_setopt(curl_handle, CURLOPT_HEADERDATA, (
void*)&(
data->hoPair.header));
1897 curl_easy_setopt(curl_handle, CURLOPT_PRIVATE, (
void*)
data);
1900 asynchPerform(curl_handle, requestCounter);
1905 std::hash<std::string> hasher;
1906 std::string semhashedstring =
"aliceccdb" +
std::to_string(hasher(basedir + ccdbpath)).substr(0, 16);
1907 return semhashedstring;
1915 return new boost::interprocess::named_semaphore(boost::interprocess::open_or_create_t{}, semhashedstring.c_str(), 1);
1916 }
catch (std::exception e) {
1917 LOG(warn) <<
"Exception occurred during CCDB (cache) semaphore setup; Continuing without";
1926 if (sem->try_wait()) {
1937 boost::interprocess::named_semaphore semaphore(boost::interprocess::open_only, semaname.c_str());
1938 std::cout <<
"Found CCDB semaphore: " << semaname <<
"\n";
1940 auto success = boost::interprocess::named_semaphore::remove(semaname.c_str());
1942 std::cout <<
"Removed CCDB semaphore: " << semaname <<
"\n";
1947 }
catch (std::exception
const& e) {
1958 namespace fs = std::filesystem;
1959 std::string fileName{
"snapshot.root"};
1961 auto absolutesnapshotdir = fs::weakly_canonical(fs::absolute(snapshotdir));
1962 for (
const auto&
entry : fs::recursive_directory_iterator(absolutesnapshotdir)) {
1963 if (
entry.is_directory()) {
1964 const fs::path& currentDir = fs::canonical(fs::absolute(
entry.path()));
1965 fs::path filePath = currentDir / fileName;
1966 if (fs::exists(filePath) && fs::is_regular_file(filePath)) {
1967 std::cout <<
"Directory with file '" << fileName <<
"': " << currentDir << std::endl;
1971 auto numtokens = pathtokens.size();
1972 if (numtokens < 3) {
1977 std::string
path = pathtokens[numtokens - 3] +
"/" + pathtokens[numtokens - 2] +
"/" + pathtokens[numtokens - 1];
1983 }
catch (std::exception
const& e) {
1984 LOG(info) <<
"Semaphore search had exception " << e.what();
1989 long timestamp, std::map<std::string, std::string>& headers,
1992 if (createSnapshot) {
1993 std::string logfile = mSnapshotCachePath +
"/log";
1994 std::fstream logStream = std::fstream(logfile, ios_base::out | ios_base::app);
1995 if (logStream.is_open()) {
1996 logStream <<
"CCDB-access[" << getpid() <<
"] of " << mUniqueAgentID <<
" to " <<
path <<
" timestamp " << timestamp <<
" for load to memory\n";
1999 if (mInSnapshotMode) {
2004 }
else if (mPreferSnapshotCache && std::filesystem::exists(snapshotpath)) {
2016 if (!mSnapshotCachePath.empty() && !(mInSnapshotMode && mSnapshotTopPath == mSnapshotCachePath)) {
2017 auto semaphore_barrier = std::make_unique<CCDBSemaphore>(mSnapshotCachePath, requestContext.
path);
2019 auto snapshotdir = getSnapshotDir(mSnapshotCachePath, requestContext.
path);
2020 std::string snapshotpath = getSnapshotFile(mSnapshotCachePath, requestContext.
path);
2022 std::fstream logStream;
2023 if (logStream.is_open()) {
2024 logStream <<
"CCDB-access[" << getpid() <<
"] ... " << mUniqueAgentID <<
" downloading to snapshot " << snapshotpath <<
" from memory\n";
2027 LOGP(
debug,
"creating snapshot {} -> {}", requestContext.
path, snapshotpath);
2030 std::ofstream objFile(snapshotpath, std::ios::out | std::ofstream::binary);
2031 std::copy(requestContext.
dest.begin(), requestContext.
dest.end(), std::ostreambuf_iterator<char>(objFile));
2034 updateMetaInformationInLocalFile(snapshotpath, &requestContext.
headers, &querysummary);
2040 std::map<std::string, std::string>
const& metadata,
long timestamp,
2041 std::map<std::string, std::string>* headers, std::string
const&
etag,
2045 destP.reserve(dest.size());
2048 dest.reserve(destP.size());
2049 for (
const auto c : destP) {
2055 std::map<std::string, std::string>
const& metadata,
long timestamp,
2056 std::map<std::string, std::string>* headers, std::string
const&
etag,
2068 std::vector<RequestContext> contexts = {requestContext};
2074 size_t hsize = getFlatHeaderSize(headers), cnt = dest.size();
2075 dest.resize(cnt + hsize);
2076 auto addString = [&dest, &cnt](
const std::string& s) {
2083 for (
auto&
h : headers) {
2085 addString(
h.second);
2087 *
reinterpret_cast<int*
>(&dest[cnt]) = hsize;
2088 std::memcpy(&dest[cnt +
sizeof(
int)], FlatHeaderAnnot,
sizeof(FlatHeaderAnnot));
2093 LOGP(
debug,
"loadFileToMemory {} ETag=[{}]", requestContext.
path, requestContext.
etag);
2094 bool createSnapshot = requestContext.
considerSnapshot && !mSnapshotCachePath.empty();
2096 std::string snapshotpath;
2097 if (mInSnapshotMode || std::filesystem::exists(snapshotpath = getSnapshotFile(mSnapshotCachePath, requestContext.
path))) {
2098 auto semaphore_barrier = std::make_unique<CCDBSemaphore>(mSnapshotCachePath, requestContext.
path);
2109 std::vector<int> fromSnapshots(requestContexts.size());
2110 size_t requestCounter = 0;
2113 for (
int i = 0;
i < requestContexts.size();
i++) {
2115 auto& requestContext = requestContexts.at(
i);
2120 while (requestCounter > 0) {
2125 for (
int i = 0;
i < requestContexts.size();
i++) {
2126 auto& requestContext = requestContexts.at(
i);
2127 if (!requestContext.dest.empty()) {
2128 logReading(requestContext.path, requestContext.timestamp, &requestContext.headers,
2129 fmt::format(
"{}{}", requestContext.considerSnapshot ?
"load to memory" :
"retrieve", fromSnapshots.at(
i) ?
" from snapshot" :
""));
2130 if (requestContext.considerSnapshot && fromSnapshots.at(
i) != 2) {
2139 if (
url.find(
"alien:/", 0) != std::string::npos) {
2140 std::map<std::string, std::string> localHeaders;
2142 auto it = localHeaders.find(
"Error");
2143 if (it != localHeaders.end() && it->second ==
"An error occurred during retrieval") {
2149 if ((
url.find(
"file:/", 0) != std::string::npos)) {
2150 std::string
path =
url.substr(7);
2151 if (std::filesystem::exists(
path)) {
2152 std::map<std::string, std::string> localHeaders;
2154 auto it = localHeaders.find(
"Error");
2155 if (it != localHeaders.end() && it->second ==
"An error occurred during retrieval") {
2168 constexpr size_t MaxCopySize = 0x1L << 25;
2169 auto signalError = [&dest, localHeaders]() {
2173 (*localHeaders)[
"Error"] =
"An error occurred during retrieval";
2176 if (
path.find(
"alien:/") == 0 && !initTGrid()) {
2180 std::string fname(
path);
2181 if (fname.find(
"?filetype=raw") == std::string::npos) {
2182 fname +=
"?filetype=raw";
2184 std::unique_ptr<TFile> sfile{TFile::Open(fname.c_str())};
2185 if (!sfile || sfile->IsZombie()) {
2186 LOG(error) <<
"Failed to open file " << fname;
2190 size_t totalread = 0, fsize = sfile->GetSize(), b00 = sfile->GetBytesRead();
2192 char* dptr = dest.data();
2196 size_t b0 = sfile->GetBytesRead(), b1 = b0 - b00;
2197 size_t readsize = fsize - b1 > MaxCopySize ? MaxCopySize : fsize - b1;
2198 if (readsize == 0) {
2201 sfile->Seek(totalread, TFile::kBeg);
2202 bool failed = sfile->ReadBuffer(dptr, (Int_t)readsize);
2203 nread = sfile->GetBytesRead() - b0;
2204 if (
failed || nread < 0) {
2205 LOG(error) <<
"failed to copy file " << fname <<
" to memory buffer";
2211 }
while (nread == (
long)MaxCopySize);
2213 if (localHeaders && fetchLocalMetaData) {
2214 TMemFile memFile(
"name",
const_cast<char*
>(dest.data()), dest.size(),
"READ");
2215 auto storedmeta = (std::map<std::string, std::string>*)
extractFromTFile(memFile, TClass::GetClass(
"std::map<std::string, std::string>"),
CCDBMETA_ENTRY);
2217 *localHeaders = *storedmeta;
2220 if ((
isSnapshotMode() || mPreferSnapshotCache) && localHeaders->find(
"ETag") == localHeaders->end()) {
2221 (*localHeaders)[
"ETag"] =
path;
2223 if (localHeaders->find(
"fileSize") == localHeaders->end()) {
2224 (*localHeaders)[
"fileSize"] = fmt::format(
"{}", memFile.GetEND());
2230void CcdbApi::checkMetadataKeys(std::map<std::string, std::string>
const& metadata)
const
2236 const std::regex regexPatternSearch(R
"([ :;.,\\/'?!\(\)\{\}\[\]@<>=+*#$&`|~^%])");
2237 bool isInvalid =
false;
2239 for (
auto& el : metadata) {
2240 auto keyMd = el.first;
2242 std::smatch searchRes;
2243 while (std::regex_search(keyMd, searchRes, regexPatternSearch)) {
2245 LOG(error) <<
"Invalid character found in metadata key '" << tmp <<
"\': '" << searchRes.str() <<
"\'";
2246 keyMd = searchRes.suffix();
2250 LOG(fatal) <<
"Some metadata keys have invalid characters, please fix!";
2255void CcdbApi::logReading(
const std::string&
path,
long ts,
const std::map<std::string, std::string>* headers,
const std::string& comment)
const
2257 std::string upath{
path};
2259 auto ent = headers->find(
"Valid-From");
2260 if (ent != headers->end()) {
2261 upath +=
"/" + ent->second;
2263 ent = headers->find(
"ETag");
2264 if (ent != headers->end()) {
2265 upath +=
"/" + ent->second;
2268 upath.erase(remove(upath.begin(), upath.end(),
'\"'), upath.end());
2269 LOGP(info,
"ccdb reads {}{}{} for {} ({}, agent_id: {}), ", mUrl, mUrl.back() ==
'/' ?
"" :
"/", upath, ts < 0 ?
getCurrentTimestamp() : ts, comment, mUniqueAgentID);
2272void CcdbApi::asynchPerform(CURL* handle,
size_t* requestCounter)
const
2277CURLcode CcdbApi::CURL_perform(CURL* handle)
const
2279 if (mIsCCDBDownloaderPreferred) {
2280 return mDownloader->
perform(handle);
2283 for (
int i = 1;
i <= mCurlRetries && (
result = curl_easy_perform(handle)) != CURLE_OK;
i++) {
2284 usleep(mCurlDelayRetries *
i);
2295 LOG(
debug) <<
"Entering semaphore barrier";
2298 mSem =
new boost::interprocess::named_semaphore(boost::interprocess::open_or_create_t{}, mSemName.c_str(), 1);
2299 }
catch (std::exception e) {
2300 LOG(warn) <<
"Exception occurred during CCDB (cache) semaphore setup; Continuing without";
2305 gSemaRegistry.
add(
this);
2312 LOG(
debug) <<
"Ending semaphore barrier";
2315 if (mSem->try_wait()) {
2317 boost::interprocess::named_semaphore::remove(mSemName.c_str());
2319 gSemaRegistry.
remove(
this);
2325 LOG(
debug) <<
"Cleaning up semaphore registry with count " << mStore.size();
2326 for (
auto& s : mStore) {
std::string createdNotBefore
std::string createdNotAfter
Class for time synchronization of RawReader instances.
void setRequestTimeoutTime(int timeoutMS)
CURLcode perform(CURL *handle)
void asynchSchedule(CURL *handle, size_t *requestCounter)
void setKeepaliveTimeoutTime(int timeoutMS)
void runLoop(bool noWait)
CCDBSemaphore(std::string const &cachepath, std::string const &path)
static void curlSetSSLOptions(CURL *curl)
static std::string generateFileName(const std::string &inp)
std::string list(std::string const &path="", bool latestOnly=false, std::string const &returnFormat="text/plain", long createdNotAfter=-1, long createdNotBefore=-1) const
int storeAsTFile_impl(const void *obj1, std::type_info const &info, std::string const &path, std::map< std::string, std::string > const &metadata, long startValidityTimestamp=-1, long endValidityTimestamp=-1, std::vector< char >::size_type maxSize=0) const
static bool checkAlienToken()
void runDownloaderLoop(bool noWait)
void releaseNamedSemaphore(boost::interprocess::named_semaphore *sem, std::string const &path) const
static std::map< std::string, std::string > * retrieveMetaInfo(TFile &)
void scheduleDownload(RequestContext &requestContext, size_t *requestCounter) const
TObject * retrieve(std::string const &path, std::map< std::string, std::string > const &metadata, long timestamp) const
void init(std::string const &hosts)
TObject * retrieveFromTFile(std::string const &path, std::map< std::string, std::string > const &metadata, long timestamp, std::map< std::string, std::string > *headers, std::string const &etag, const std::string &createdNotAfter, const std::string &createdNotBefore) const
std::string const & getURL() const
void getFromSnapshot(bool createSnapshot, std::string const &path, long timestamp, std::map< std::string, std::string > &headers, std::string &snapshotpath, o2::pmr::vector< char > &dest, int &fromSnapshot, std::string const &etag) const
bool loadLocalContentToMemory(o2::pmr::vector< char > &dest, std::string &url) const
static void removeLeakingSemaphores(std::string const &basedir, bool remove=false)
void saveSnapshot(RequestContext &requestContext) const
static std::unique_ptr< std::vector< char > > createObjectImage(const T *obj, CcdbObjectInfo *info=nullptr)
static void * extractFromTFile(TFile &file, TClass const *cl, const char *what=CCDBOBJECT_ENTRY)
int storeAsTFile(const TObject *rootObject, std::string const &path, std::map< std::string, std::string > const &metadata, long startValidityTimestamp=-1, long endValidityTimestamp=-1, std::vector< char >::size_type maxSize=0) const
void snapshot(std::string const &ccdbrootpath, std::string const &localDir, long timestamp) const
bool isSnapshotMode() const
bool isHostReachable() const
void loadFileToMemory(std::vector< char > &dest, std::string const &path, std::map< std::string, std::string > const &metadata, long timestamp, std::map< std::string, std::string > *headers, std::string const &etag, const std::string &createdNotAfter, const std::string &createdNotBefore, bool considerSnapshot=true) const
static std::string determineSemaphoreName(std::string const &basedir, std::string const &objectpath)
void deleteObject(std::string const &path, long timestamp=-1) const
static void appendFlatHeader(o2::pmr::vector< char > &dest, const std::map< std::string, std::string > &headers)
std::vector< std::string > getAllFolders(std::string const &top) const
void vectoredLoadFileToMemory(std::vector< RequestContext > &requestContext) const
boost::interprocess::named_semaphore * createNamedSemaphore(std::string const &path) const
static bool removeSemaphore(std::string const &name, bool remove=false)
std::map< std::string, std::string > retrieveHeaders(std::string const &path, std::map< std::string, std::string > const &metadata, long timestamp=-1) const
CcdbApi()
Default constructor.
static bool getCCDBEntryHeaders(std::string const &url, std::string const &etag, std::vector< std::string > &headers, const std::string &agentID="")
static CCDBQuery * retrieveQueryInfo(TFile &)
static constexpr const char * CCDBQUERY_ENTRY
void truncate(std::string const &path) const
int storeAsBinaryFile(const char *buffer, size_t size, const std::string &fileName, const std::string &objectType, const std::string &path, const std::map< std::string, std::string > &metadata, long startValidityTimestamp, long endValidityTimestamp, std::vector< char >::size_type maxSize=0) const
static void parseCCDBHeaders(std::vector< std::string > const &headers, std::vector< std::string > &pfns, std::string &etag)
bool retrieveBlob(std::string const &path, std::string const &targetdir, std::map< std::string, std::string > const &metadata, long timestamp, bool preservePathStructure=true, std::string const &localFileName="snapshot.root", std::string const &createdNotAfter="", std::string const &createdNotBefore="", std::map< std::string, std::string > *headers=nullptr) const
int updateMetadata(std::string const &path, std::map< std::string, std::string > const &metadata, long timestamp, std::string const &id="", long newEOV=0)
static constexpr const char * CCDBMETA_ENTRY
static constexpr const char * CCDBOBJECT_ENTRY
void navigateSourcesAndLoadFile(RequestContext &requestContext, int &fromSnapshot, size_t *requestCounter) const
std::vector< std::string > parseSubFolders(std::string const &reply) const
virtual ~CcdbApi()
Default destructor.
void add(CCDBSemaphore const *ptr)
void remove(CCDBSemaphore const *ptr)
SemaphoreRegistry()=default
GLdouble GLdouble GLdouble GLdouble top
GLboolean GLboolean GLboolean b
GLsizei const GLfloat * value
GLsizei const GLchar *const * path
GLboolean GLboolean GLboolean GLboolean a
GLbitfield GLuint64 timeout
information complementary to a CCDB object (path, metadata, startTimeValidity, endTimeValidity etc)
bool stdmap_to_jsonfile(std::map< std::string, std::string > const &meta, std::string const &filename)
size_t write_data(void *, size_t size, size_t nmemb, void *)
long getCurrentTimestamp()
returns the timestamp in long corresponding to "now"
size_t(*)(void *, size_t, size_t, void *) CurlWriteCallback
std::string sanitizeObjectName(const std::string &objectName)
bool jsonfile_to_stdmap(std::map< std::string, std::string > &meta, std::string const &filename)
long getFutureTimestamp(int secondsInFuture)
returns the timestamp in long corresponding to "now + secondsInFuture"
size_t CurlWrite_CallbackFunc_StdString2(void *contents, size_t size, size_t nmemb, std::string *s)
std::string timestamp() noexcept
Defining ITS Vertex explicitly as messageable.
std::vector< T, fair::mq::pmr::polymorphic_allocator< T > > vector
void createDirectoriesIfAbsent(std::string const &path)
std::string to_string(gsl::span< T, Size > span)
std::map< std::string, std::string > const & metadata
std::string createdNotAfter
std::map< std::string, std::string > & headers
o2::pmr::vector< char > & dest
std::string createdNotBefore
static DeploymentMode deploymentMode()
static std::string getClassName(const T &obj)
get the class name of the object
static std::unique_ptr< FileImage > createFileImage(const TObject &obj, const std::string &fileName, const std::string &objName)
static void trim(std::string &s)
static std::vector< std::string > tokenize(const std::string &src, char delim, bool trimToken=true, bool skipEmpty=true)
static std::string concat_string(Ts const &... ts)
static bool endsWith(const std::string &s, const std::string &ending)
LOG(info)<< "Compressed in "<< sw.CpuTime()<< " s"
std::unique_ptr< TTree > tree((TTree *) flIn.Get(std::string(o2::base::NameConf::CTFTREENAME).c_str()))
uint64_t const void const *restrict const msg