-
Notifications
You must be signed in to change notification settings - Fork 494
Expand file tree
/
Copy pathCcdbApi.cxx
More file actions
2193 lines (1966 loc) · 81.8 KB
/
CcdbApi.cxx
File metadata and controls
2193 lines (1966 loc) · 81.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019-2020 CERN and copyright holders of ALICE O2.
// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders.
// All rights not expressly granted are reserved.
//
// This software is distributed under the terms of the GNU General Public
// License v3 (GPL Version 3), copied verbatim in the file "COPYING".
//
// In applying this license CERN does not waive the privileges and immunities
// granted to it by virtue of its status as an Intergovernmental Organization
// or submit itself to any jurisdiction.
///
/// \file CcdbApi.cxx
/// \author Barthelemy von Haller, Sandro Wenzel
///
#include "CCDB/CcdbApi.h"
#include "CCDB/CCDBQuery.h"
#include "CommonUtils/StringUtils.h"
#include "CommonUtils/FileSystemUtils.h"
#include "CommonUtils/MemFileHelper.h"
#include "Framework/DefaultsHelpers.h"
#include "Framework/DataTakingContext.h"
#include <chrono>
#include <memory>
#include <sstream>
#include <TFile.h>
#include <TGrid.h>
#include <TSystem.h>
#include <TStreamerInfo.h>
#include <TMemFile.h>
#include <TH1F.h>
#include <TTree.h>
#include <fairlogger/Logger.h>
#include <TError.h>
#include <TClass.h>
#include <CCDB/CCDBTimeStampUtils.h>
#include <algorithm>
#include <filesystem>
#include <boost/algorithm/string.hpp>
#include <boost/asio/ip/host_name.hpp>
#include <iostream>
#include <mutex>
#include <boost/interprocess/sync/named_semaphore.hpp>
#include <regex>
#include <cstdio>
#include <string>
#include <unordered_set>
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
namespace o2::ccdb
{
using namespace std;
std::mutex gIOMutex; // to protect TMemFile IO operations
unique_ptr<TJAlienCredentials> CcdbApi::mJAlienCredentials = nullptr;
/**
* Object, encapsulating a semaphore, regulating
* concurrent (multi-process) access to CCDB snapshot files.
* Intended to be used with smart pointers to achieve automatic resource
* cleanup after the smart pointer goes out of scope.
*/
class CCDBSemaphore
{
public:
CCDBSemaphore(std::string const& cachepath, std::string const& path);
~CCDBSemaphore();
private:
boost::interprocess::named_semaphore* mSem = nullptr;
std::string mSemName{}; // name under which semaphore is kept by the OS kernel
};
// Small registry class with the purpose that a static object
// ensures cleanup of registered semaphores even when programs
// "crash".
class SemaphoreRegistry
{
public:
SemaphoreRegistry() = default;
~SemaphoreRegistry();
void add(CCDBSemaphore const* ptr);
void remove(CCDBSemaphore const* ptr);
private:
std::unordered_set<CCDBSemaphore const*> mStore;
};
static SemaphoreRegistry gSemaRegistry;
CcdbApi::CcdbApi()
{
using namespace o2::framework;
setUniqueAgentID();
DeploymentMode deploymentMode = DefaultsHelpers::deploymentMode();
mIsCCDBDownloaderPreferred = 0;
if (deploymentMode == DeploymentMode::OnlineDDS && deploymentMode == DeploymentMode::OnlineECS && deploymentMode == DeploymentMode::OnlineAUX && deploymentMode == DeploymentMode::FST) {
mIsCCDBDownloaderPreferred = 1;
}
if (getenv("ALICEO2_ENABLE_MULTIHANDLE_CCDBAPI")) { // todo rename ALICEO2_ENABLE_MULTIHANDLE_CCDBAPI to ALICEO2_PREFER_MULTIHANDLE_CCDBAPI
mIsCCDBDownloaderPreferred = atoi(getenv("ALICEO2_ENABLE_MULTIHANDLE_CCDBAPI"));
}
mDownloader = new CCDBDownloader();
}
CcdbApi::~CcdbApi()
{
curl_global_cleanup();
delete mDownloader;
}
void CcdbApi::setUniqueAgentID()
{
std::string host = boost::asio::ip::host_name();
char const* jobID = getenv("ALIEN_PROC_ID");
if (jobID) {
mUniqueAgentID = fmt::format("{}-{}-{}-{}", host, getCurrentTimestamp() / 1000, o2::utils::Str::getRandomString(6), jobID);
} else {
mUniqueAgentID = fmt::format("{}-{}-{}", host, getCurrentTimestamp() / 1000, o2::utils::Str::getRandomString(6));
}
}
bool CcdbApi::checkAlienToken()
{
#ifdef __APPLE__
LOG(debug) << "On macOS we simply rely on TGrid::Connect(\"alien\").";
return true;
#endif
if (getenv("ALICEO2_CCDB_NOTOKENCHECK") && atoi(getenv("ALICEO2_CCDB_NOTOKENCHECK"))) {
return true;
}
if (getenv("JALIEN_TOKEN_CERT")) {
return true;
}
auto returncode = system("LD_PRELOAD= alien-token-info &> /dev/null");
if (returncode == -1) {
LOG(error) << "...";
}
return returncode == 0;
}
void CcdbApi::curlInit()
{
// todo : are there other things to initialize globally for curl ?
curl_global_init(CURL_GLOBAL_DEFAULT);
CcdbApi::mJAlienCredentials = std::make_unique<TJAlienCredentials>();
CcdbApi::mJAlienCredentials->loadCredentials();
CcdbApi::mJAlienCredentials->selectPreferedCredentials();
// allow to configure the socket timeout of CCDBDownloader (for some tuning studies)
if (getenv("ALICEO2_CCDB_SOCKET_TIMEOUT")) {
auto timeoutMS = atoi(getenv("ALICEO2_CCDB_SOCKET_TIMEOUT"));
if (timeoutMS >= 0) {
LOG(info) << "Setting socket timeout to " << timeoutMS << " milliseconds";
mDownloader->setKeepaliveTimeoutTime(timeoutMS);
}
}
}
void CcdbApi::init(std::string const& host)
{
// if host is prefixed with "file://" this is a local snapshot
// in this case we init the API in snapshot (readonly) mode
constexpr const char* SNAPSHOTPREFIX = "file://";
mUrl = host;
if (host.substr(0, 7).compare(SNAPSHOTPREFIX) == 0) {
auto path = host.substr(7);
initInSnapshotMode(path);
} else {
initHostsPool(host);
curlInit();
}
// The environment option ALICEO2_CCDB_LOCALCACHE allows
// to reduce the number of queries to the server, by collecting the objects in a local
// cache folder, and serving from this folder for repeated queries.
// This is useful for instance for MC GRID productions in which we spawn
// many isolated processes, all querying the CCDB (for potentially the same objects and same timestamp).
// In addition, we can monitor exactly which objects are fetched and what is their content.
// One can also distribute so obtained caches to sites without network access.
//
// THE INFORMATION BELOW IS TEMPORARILY WRONG: the functionality of checking the validity if IGNORE_VALIDITYCHECK_OF_CCDB_LOCALCACHE
// is NOT set is broken. At the moment the code is modified to behave as if the IGNORE_VALIDITYCHECK_OF_CCDB_LOCALCACHE is always set
// whenever the ALICEO2_CCDB_LOCALCACHE is defined.
//
// When used with the DPL CCDB fetcher (i.e. loadFileToMemory is called), in order to prefer the available snapshot w/o its validity
// check an extra variable IGNORE_VALIDITYCHECK_OF_CCDB_LOCALCACHE must be defined, otherwhise the object will be fetched from the
// server after the validity check and new snapshot will be created if needed
std::string snapshotReport{};
const char* cachedir = getenv("ALICEO2_CCDB_LOCALCACHE");
namespace fs = std::filesystem;
if (cachedir) {
if (cachedir[0] == 0) {
mSnapshotCachePath = fs::weakly_canonical(fs::absolute("."));
} else {
mSnapshotCachePath = fs::weakly_canonical(fs::absolute(cachedir));
}
snapshotReport = fmt::format("(cache snapshots to dir={}", mSnapshotCachePath);
}
if (cachedir) { // || getenv("IGNORE_VALIDITYCHECK_OF_CCDB_LOCALCACHE")) {
mPreferSnapshotCache = true;
if (mSnapshotCachePath.empty()) {
LOGP(fatal, "IGNORE_VALIDITYCHECK_OF_CCDB_LOCALCACHE is defined but the ALICEO2_CCDB_LOCALCACHE is not");
}
snapshotReport += ", prefer if available";
}
if (!snapshotReport.empty()) {
snapshotReport += ')';
}
mNeedAlienToken = (host.find("https://") != std::string::npos) || (host.find("alice-ccdb.cern.ch") != std::string::npos);
// Set the curl timeout. It can be forced with an env var or it has different defaults based on the deployment mode.
if (getenv("ALICEO2_CCDB_CURL_TIMEOUT_DOWNLOAD")) {
auto timeout = atoi(getenv("ALICEO2_CCDB_CURL_TIMEOUT_DOWNLOAD"));
if (timeout >= 0) { // if valid int
mCurlTimeoutDownload = timeout;
}
} else { // set a default depending on the deployment mode
o2::framework::DeploymentMode deploymentMode = o2::framework::DefaultsHelpers::deploymentMode();
if (deploymentMode == o2::framework::DeploymentMode::OnlineDDS ||
deploymentMode == o2::framework::DeploymentMode::OnlineAUX ||
deploymentMode == o2::framework::DeploymentMode::OnlineECS) {
mCurlTimeoutDownload = 15;
} else if (deploymentMode == o2::framework::DeploymentMode::Grid ||
deploymentMode == o2::framework::DeploymentMode::FST) {
mCurlTimeoutDownload = 15;
} else if (deploymentMode == o2::framework::DeploymentMode::Local) {
mCurlTimeoutDownload = 5;
}
}
if (getenv("ALICEO2_CCDB_CURL_TIMEOUT_UPLOAD")) {
auto timeout = atoi(getenv("ALICEO2_CCDB_CURL_TIMEOUT_UPLOAD"));
if (timeout >= 0) { // if valid int
mCurlTimeoutUpload = timeout;
}
} else { // set a default depending on the deployment mode
o2::framework::DeploymentMode deploymentMode = o2::framework::DefaultsHelpers::deploymentMode();
if (deploymentMode == o2::framework::DeploymentMode::OnlineDDS ||
deploymentMode == o2::framework::DeploymentMode::OnlineAUX ||
deploymentMode == o2::framework::DeploymentMode::OnlineECS) {
mCurlTimeoutUpload = 3;
} else if (deploymentMode == o2::framework::DeploymentMode::Grid ||
deploymentMode == o2::framework::DeploymentMode::FST) {
mCurlTimeoutUpload = 20;
} else if (deploymentMode == o2::framework::DeploymentMode::Local) {
mCurlTimeoutUpload = 20;
}
}
if (mDownloader) {
mDownloader->setRequestTimeoutTime(mCurlTimeoutDownload * 1000L);
}
LOGP(debug, "Curl timeouts are set to: download={:2}, upload={:2} seconds", mCurlTimeoutDownload, mCurlTimeoutUpload);
LOGP(info, "Init CcdApi with UserAgentID: {}, Host: {}{}, Curl timeouts: upload:{} download:{}", mUniqueAgentID, host,
mInSnapshotMode ? "(snapshot readonly mode)" : snapshotReport.c_str(), mCurlTimeoutUpload, mCurlTimeoutDownload);
}
void CcdbApi::runDownloaderLoop(bool noWait)
{
mDownloader->runLoop(noWait);
}
// A helper function used in a few places. Updates a ROOT file with meta/header information.
void CcdbApi::updateMetaInformationInLocalFile(std::string const& filename, std::map<std::string, std::string> const* headers, CCDBQuery const* querysummary)
{
std::lock_guard<std::mutex> guard(gIOMutex);
auto oldlevel = gErrorIgnoreLevel;
gErrorIgnoreLevel = 6001; // ignoring error messages here (since we catch with IsZombie)
TFile snapshotfile(filename.c_str(), "UPDATE");
// The assumption is that the blob is a ROOT file
if (!snapshotfile.IsZombie()) {
if (querysummary && !snapshotfile.Get(CCDBQUERY_ENTRY)) {
snapshotfile.WriteObjectAny(querysummary, TClass::GetClass(typeid(*querysummary)), CCDBQUERY_ENTRY);
}
if (headers && !snapshotfile.Get(CCDBMETA_ENTRY)) {
snapshotfile.WriteObjectAny(headers, TClass::GetClass(typeid(*headers)), CCDBMETA_ENTRY);
}
snapshotfile.Write();
snapshotfile.Close();
}
gErrorIgnoreLevel = oldlevel;
}
/**
* Keep only the alphanumeric characters plus '_' plus '/' plus '.' from the string passed in argument.
* @param objectName
* @return a new string following the rule enounced above.
*/
std::string sanitizeObjectName(const std::string& objectName)
{
string tmpObjectName = objectName;
tmpObjectName.erase(std::remove_if(tmpObjectName.begin(), tmpObjectName.end(),
[](auto const& c) -> bool { return (!std::isalnum(c) && c != '_' && c != '/' && c != '.'); }),
tmpObjectName.end());
return tmpObjectName;
}
std::unique_ptr<std::vector<char>> CcdbApi::createObjectImage(const void* obj, std::type_info const& tinfo, CcdbObjectInfo* info)
{
// Create a binary image of the object, if CcdbObjectInfo pointer is provided, register there
// the assigned object class name and the filename
std::lock_guard<std::mutex> guard(gIOMutex);
std::string className = o2::utils::MemFileHelper::getClassName(tinfo);
std::string tmpFileName = generateFileName(className);
if (info) {
info->setFileName(tmpFileName);
info->setObjectType(className);
}
return o2::utils::MemFileHelper::createFileImage(obj, tinfo, tmpFileName, CCDBOBJECT_ENTRY);
}
std::unique_ptr<std::vector<char>> CcdbApi::createObjectImage(const TObject* rootObject, CcdbObjectInfo* info)
{
// Create a binary image of the object, if CcdbObjectInfo pointer is provided, register there
// the assigned object class name and the filename
std::string className = rootObject->GetName();
std::string tmpFileName = generateFileName(className);
if (info) {
info->setFileName(tmpFileName);
info->setObjectType("TObject"); // why TObject and not the actual name?
}
std::lock_guard<std::mutex> guard(gIOMutex);
return o2::utils::MemFileHelper::createFileImage(*rootObject, tmpFileName, CCDBOBJECT_ENTRY);
}
int CcdbApi::storeAsTFile_impl(const void* obj, std::type_info const& tinfo, std::string const& path,
std::map<std::string, std::string> const& metadata,
long startValidityTimestamp, long endValidityTimestamp,
std::vector<char>::size_type maxSize) const
{
// We need the TClass for this type; will verify if dictionary exists
if (!obj) {
LOGP(error, "nullptr is provided for object {}/{}/{}", path, startValidityTimestamp, endValidityTimestamp);
return -1;
}
CcdbObjectInfo info;
auto img = createObjectImage(obj, tinfo, &info);
return storeAsBinaryFile(img->data(), img->size(), info.getFileName(), info.getObjectType(),
path, metadata, startValidityTimestamp, endValidityTimestamp, maxSize);
}
int CcdbApi::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) const
{
if (maxSize > 0 && size > maxSize) {
LOGP(alarm, "Object will not be uploaded to {} since its size {} exceeds max allowed {}", path, size, maxSize);
return -1;
}
int returnValue = 0;
// Prepare URL
long sanitizedStartValidityTimestamp = startValidityTimestamp;
if (startValidityTimestamp == -1) {
LOGP(info, "Start of Validity not set, current timestamp used.");
sanitizedStartValidityTimestamp = getCurrentTimestamp();
}
long sanitizedEndValidityTimestamp = endValidityTimestamp;
if (endValidityTimestamp == -1) {
LOGP(info, "End of Validity not set, start of validity plus 1 day used.");
sanitizedEndValidityTimestamp = getFutureTimestamp(60 * 60 * 24 * 1);
}
if (mInSnapshotMode) { // write local file
auto pthLoc = getSnapshotDir(mSnapshotTopPath, path);
o2::utils::createDirectoriesIfAbsent(pthLoc);
auto flLoc = getSnapshotFile(mSnapshotTopPath, path, filename);
// add the timestamps to the end
auto pent = flLoc.find_last_of('.');
if (pent == std::string::npos) {
pent = flLoc.size();
}
flLoc.insert(pent, fmt::format("_{}_{}", startValidityTimestamp, endValidityTimestamp));
ofstream outf(flLoc.c_str(), ios::out | ios::binary);
outf.write(buffer, size);
outf.close();
if (!outf.good()) {
throw std::runtime_error(fmt::format("Failed to write local CCDB file {}", flLoc));
} else {
std::map<std::string, std::string> metaheader(metadata);
// add time validity information
metaheader["Valid-From"] = std::to_string(startValidityTimestamp);
metaheader["Valid-Until"] = std::to_string(endValidityTimestamp);
updateMetaInformationInLocalFile(flLoc.c_str(), &metaheader);
std::string metaStr{};
for (const auto& mentry : metadata) {
metaStr += fmt::format("{}={};", mentry.first, mentry.second);
}
metaStr += "$USER_META;";
LOGP(info, "Created local snapshot {}", flLoc);
LOGP(info, R"(Upload with: o2-ccdb-upload --host "$ccdbhost" -p {} -f {} -k {} --starttimestamp {} --endtimestamp {} -m "{}")",
path, flLoc, CCDBOBJECT_ENTRY, startValidityTimestamp, endValidityTimestamp, metaStr);
}
return returnValue;
}
// Curl preparation
CURL* curl = nullptr;
curl = curl_easy_init();
// checking that all metadata keys do not contain invalid characters
checkMetadataKeys(metadata);
if (curl != nullptr) {
auto mime = curl_mime_init(curl);
auto field = curl_mime_addpart(mime);
curl_mime_name(field, "send");
curl_mime_filedata(field, filename.c_str());
curl_mime_data(field, buffer, size);
struct curl_slist* headerlist = nullptr;
static const char buf[] = "Expect:";
headerlist = curl_slist_append(headerlist, buf);
curlSetSSLOptions(curl);
curl_easy_setopt(curl, CURLOPT_MIMEPOST, mime);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_USERAGENT, mUniqueAgentID.c_str());
curl_easy_setopt(curl, CURLOPT_TIMEOUT, mCurlTimeoutUpload);
CURLcode res = CURL_LAST;
for (size_t hostIndex = 0; hostIndex < hostsPool.size() && res > 0; hostIndex++) {
string fullUrl = getFullUrlForStorage(curl, path, objectType, metadata, sanitizedStartValidityTimestamp, sanitizedEndValidityTimestamp, hostIndex);
LOG(debug3) << "Full URL Encoded: " << fullUrl;
/* what URL that receives this POST */
curl_easy_setopt(curl, CURLOPT_URL, fullUrl.c_str());
/* Perform the request, res will get the return code */
res = CURL_perform(curl);
/* Check for errors */
if (res != CURLE_OK) {
if (res == CURLE_OPERATION_TIMEDOUT) {
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);
} else { // generic message
LOGP(alarm, "curl_easy_perform() failed: {}", curl_easy_strerror(res));
}
returnValue = res;
}
}
/* always cleanup */
curl_easy_cleanup(curl);
/* free slist */
curl_slist_free_all(headerlist);
/* free mime */
curl_mime_free(mime);
} else {
LOGP(alarm, "curl initialization failure");
returnValue = -2;
}
return returnValue;
}
int CcdbApi::storeAsTFile(const TObject* rootObject, std::string const& path, std::map<std::string, std::string> const& metadata,
long startValidityTimestamp, long endValidityTimestamp, std::vector<char>::size_type maxSize) const
{
// Prepare file
if (!rootObject) {
LOGP(error, "nullptr is provided for object {}/{}/{}", path, startValidityTimestamp, endValidityTimestamp);
return -1;
}
CcdbObjectInfo info;
auto img = createObjectImage(rootObject, &info);
return storeAsBinaryFile(img->data(), img->size(), info.getFileName(), info.getObjectType(), path, metadata, startValidityTimestamp, endValidityTimestamp, maxSize);
}
string CcdbApi::getFullUrlForStorage(CURL* curl, const string& path, const string& objtype,
const map<string, string>& metadata,
long startValidityTimestamp, long endValidityTimestamp, int hostIndex) const
{
// Prepare timestamps
string startValidityString = getTimestampString(startValidityTimestamp < 0 ? getCurrentTimestamp() : startValidityTimestamp);
string endValidityString = getTimestampString(endValidityTimestamp < 0 ? getFutureTimestamp(60 * 60 * 24 * 1) : endValidityTimestamp);
// Get url
string url = getHostUrl(hostIndex);
// Build URL
string fullUrl = url + "/" + path + "/" + startValidityString + "/" + endValidityString + "/";
// Add type as part of metadata
// we need to URL encode the object type, since in case it has special characters (like the "<", ">" for templated classes) it won't work otherwise
char* objtypeEncoded = curl_easy_escape(curl, objtype.c_str(), objtype.size());
fullUrl += "ObjectType=" + string(objtypeEncoded) + "/";
curl_free(objtypeEncoded);
// Add general metadata
for (auto& kv : metadata) {
string mfirst = kv.first;
string msecond = kv.second;
// same trick for the metadata as for the object type
char* mfirstEncoded = curl_easy_escape(curl, mfirst.c_str(), mfirst.size());
char* msecondEncoded = curl_easy_escape(curl, msecond.c_str(), msecond.size());
fullUrl += string(mfirstEncoded) + "=" + string(msecondEncoded) + "/";
curl_free(mfirstEncoded);
curl_free(msecondEncoded);
}
return fullUrl;
}
// todo make a single method of the one above and below
string CcdbApi::getFullUrlForRetrieval(CURL* curl, const string& path, const map<string, string>& metadata, long timestamp, int hostIndex) const
{
if (mInSnapshotMode) {
return getSnapshotFile(mSnapshotTopPath, path);
}
// Prepare timestamps
string validityString = getTimestampString(timestamp < 0 ? getCurrentTimestamp() : timestamp);
// Get host url
string hostUrl = getHostUrl(hostIndex);
// Build URL
string fullUrl = hostUrl + "/" + path + "/" + validityString + "/";
// Add metadata
for (auto& kv : metadata) {
string mfirst = kv.first;
string msecond = kv.second;
// trick for the metadata in case it contains special characters
char* mfirstEncoded = curl_easy_escape(curl, mfirst.c_str(), mfirst.size());
char* msecondEncoded = curl_easy_escape(curl, msecond.c_str(), msecond.size());
fullUrl += string(mfirstEncoded) + "=" + string(msecondEncoded) + "/";
curl_free(mfirstEncoded);
curl_free(msecondEncoded);
}
return fullUrl;
}
/**
* Struct to store the data we will receive from the CCDB with CURL.
*/
struct MemoryStruct {
char* memory;
unsigned int size;
};
/**
* Callback used by CURL to store the data received from the CCDB.
* See https://curl.haxx.se/libcurl/c/getinmemory.html
* @param contents
* @param size
* @param nmemb
* @param userp a MemoryStruct where data is stored.
* @return the size of the data we received and stored at userp.
*/
static size_t WriteMemoryCallback(void* contents, size_t size, size_t nmemb, void* userp)
{
size_t realsize = size * nmemb;
auto* mem = (struct MemoryStruct*)userp;
mem->memory = (char*)realloc(mem->memory, mem->size + realsize + 1);
if (mem->memory == nullptr) {
printf("not enough memory (realloc returned NULL)\n");
return 0;
}
memcpy(&(mem->memory[mem->size]), contents, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
return realsize;
}
/**
* Callback used by CURL to store the data received from the CCDB
* directly into a binary file
* @param contents
* @param size
* @param nmemb
* @param userp a MemoryStruct where data is stored.
* @return the size of the data we received and stored at userp.
* If an error is returned no attempt to establish a connection is made
* and the perform operation will return the callback's error code
*/
static size_t WriteToFileCallback(void* ptr, size_t size, size_t nmemb, FILE* stream)
{
size_t written = fwrite(ptr, size, nmemb, stream);
return written;
}
/**
* Callback to load credentials and CA's
* @param curl curl handler
* @param ssl_ctx SSL context that will be modified
* @param parm
* @return
*/
static CURLcode ssl_ctx_callback(CURL*, void*, void* parm)
{
std::string msg((const char*)parm);
int start = 0, end = msg.find('\n');
if (msg.length() > 0 && end == -1) {
LOG(warn) << msg;
} else if (end > 0) {
while (end > 0) {
LOG(warn) << msg.substr(start, end - start);
start = end + 1;
end = msg.find('\n', start);
}
}
return CURLE_OK;
}
void CcdbApi::curlSetSSLOptions(CURL* curl_handle)
{
CredentialsKind cmk = mJAlienCredentials->getPreferedCredentials();
/* NOTE: return early, the warning should be printed on SSL callback if needed */
if (cmk == cNOT_FOUND) {
return;
}
TJAlienCredentialsObject cmo = mJAlienCredentials->get(cmk);
char* CAPath = getenv("X509_CERT_DIR");
if (CAPath) {
curl_easy_setopt(curl_handle, CURLOPT_CAPATH, CAPath);
}
curl_easy_setopt(curl_handle, CURLOPT_CAINFO, nullptr);
curl_easy_setopt(curl_handle, CURLOPT_SSLCERT, cmo.certpath.c_str());
curl_easy_setopt(curl_handle, CURLOPT_SSLKEY, cmo.keypath.c_str());
// NOTE: for lazy logging only
curl_easy_setopt(curl_handle, CURLOPT_SSL_CTX_FUNCTION, ssl_ctx_callback);
curl_easy_setopt(curl_handle, CURLOPT_SSL_CTX_DATA, mJAlienCredentials->getMessages().c_str());
// CURLcode ret = curl_easy_setopt(curl_handle, CURLOPT_SSL_CTX_FUNCTION, *ssl_ctx_callback);
}
using CurlWriteCallback = size_t (*)(void*, size_t, size_t, void*);
void CcdbApi::initCurlOptionsForRetrieve(CURL* curlHandle, void* chunk, CurlWriteCallback writeCallback, bool followRedirect) const
{
curl_easy_setopt(curlHandle, CURLOPT_WRITEFUNCTION, writeCallback);
curl_easy_setopt(curlHandle, CURLOPT_WRITEDATA, chunk);
curl_easy_setopt(curlHandle, CURLOPT_FOLLOWLOCATION, followRedirect ? 1L : 0L);
}
namespace
{
template <typename MapType = std::map<std::string, std::string>>
size_t header_map_callback(char* buffer, size_t size, size_t nitems, void* userdata)
{
auto* headers = static_cast<MapType*>(userdata);
auto header = std::string(buffer, size * nitems);
std::string::size_type index = header.find(':', 0);
if (index != std::string::npos) {
const auto key = boost::algorithm::trim_copy(header.substr(0, index));
const auto value = boost::algorithm::trim_copy(header.substr(index + 1));
LOGP(debug, "Adding #{} {} -> {}", headers->size(), key, value);
bool insert = true;
if (key == "Content-Length") {
auto cl = headers->find("Content-Length");
if (cl != headers->end()) {
if (std::stol(cl->second) < stol(value)) {
headers->erase(key);
} else {
insert = false;
}
}
}
// Keep only the first ETag encountered
if (key == "ETag") {
auto cl = headers->find("ETag");
if (cl != headers->end()) {
insert = false;
}
}
// Keep only the first Content-Type encountered
if (key == "Content-Type") {
auto cl = headers->find("Content-Type");
if (cl != headers->end()) {
insert = false;
}
}
if (insert) {
headers->insert(std::make_pair(key, value));
}
}
return size * nitems;
}
} // namespace
void CcdbApi::initCurlHTTPHeaderOptionsForRetrieve(CURL* curlHandle, curl_slist*& option_list, long timestamp, std::map<std::string, std::string>* headers, std::string const& etag,
const std::string& createdNotAfter, const std::string& createdNotBefore) const
{
// struct curl_slist* list = nullptr;
if (!etag.empty()) {
option_list = curl_slist_append(option_list, ("If-None-Match: " + etag).c_str());
}
if (!createdNotAfter.empty()) {
option_list = curl_slist_append(option_list, ("If-Not-After: " + createdNotAfter).c_str());
}
if (!createdNotBefore.empty()) {
option_list = curl_slist_append(option_list, ("If-Not-Before: " + createdNotBefore).c_str());
}
if (headers != nullptr) {
option_list = curl_slist_append(option_list, ("If-None-Match: " + to_string(timestamp)).c_str());
curl_easy_setopt(curlHandle, CURLOPT_HEADERFUNCTION, header_map_callback<>);
curl_easy_setopt(curlHandle, CURLOPT_HEADERDATA, headers);
}
if (option_list) {
curl_easy_setopt(curlHandle, CURLOPT_HTTPHEADER, option_list);
}
curl_easy_setopt(curlHandle, CURLOPT_USERAGENT, mUniqueAgentID.c_str());
}
bool CcdbApi::receiveToFile(FILE* fileHandle, 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 followRedirect) const
{
return receiveObject((void*)fileHandle, path, metadata, timestamp, headers, etag, createdNotAfter, createdNotBefore, followRedirect, (CurlWriteCallback)&WriteToFileCallback);
}
bool CcdbApi::receiveToMemory(void* chunk, 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 followRedirect) const
{
return receiveObject((void*)chunk, path, metadata, timestamp, headers, etag, createdNotAfter, createdNotBefore, followRedirect, (CurlWriteCallback)&WriteMemoryCallback);
}
bool CcdbApi::receiveObject(void* dataHolder, 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 followRedirect, CurlWriteCallback writeCallback) const
{
CURL* curlHandle;
curlHandle = curl_easy_init();
curl_easy_setopt(curlHandle, CURLOPT_USERAGENT, mUniqueAgentID.c_str());
if (curlHandle != nullptr) {
curlSetSSLOptions(curlHandle);
initCurlOptionsForRetrieve(curlHandle, dataHolder, writeCallback, followRedirect);
curl_slist* option_list = nullptr;
initCurlHTTPHeaderOptionsForRetrieve(curlHandle, option_list, timestamp, headers, etag, createdNotAfter, createdNotBefore);
long responseCode = 0;
CURLcode curlResultCode = CURL_LAST;
for (size_t hostIndex = 0; hostIndex < hostsPool.size() && (responseCode >= 400 || curlResultCode > 0); hostIndex++) {
string fullUrl = getFullUrlForRetrieval(curlHandle, path, metadata, timestamp, hostIndex);
curl_easy_setopt(curlHandle, CURLOPT_URL, fullUrl.c_str());
curlResultCode = CURL_perform(curlHandle);
if (curlResultCode != CURLE_OK) {
LOGP(alarm, "curl_easy_perform() failed: {}", curl_easy_strerror(curlResultCode));
} else {
curlResultCode = curl_easy_getinfo(curlHandle, CURLINFO_RESPONSE_CODE, &responseCode);
if ((curlResultCode == CURLE_OK) && (responseCode < 300)) {
curl_slist_free_all(option_list);
curl_easy_cleanup(curlHandle);
return true;
} else {
if (curlResultCode != CURLE_OK) {
LOGP(alarm, "invalid URL {}", fullUrl);
} else {
LOGP(alarm, "not found under link {}", fullUrl);
}
}
}
}
curl_slist_free_all(option_list);
curl_easy_cleanup(curlHandle);
}
return false;
}
TObject* CcdbApi::retrieve(std::string const& path, std::map<std::string, std::string> const& metadata,
long timestamp) const
{
struct MemoryStruct chunk {
(char*)malloc(1) /*memory*/, 0 /*size*/
};
TObject* result = nullptr;
bool res = receiveToMemory((void*)&chunk, path, metadata, timestamp);
if (res) {
std::lock_guard<std::mutex> guard(gIOMutex);
TMessage mess(kMESS_OBJECT);
mess.SetBuffer(chunk.memory, chunk.size, kFALSE);
mess.SetReadMode();
mess.Reset();
result = (TObject*)(mess.ReadObjectAny(mess.GetClass()));
if (result == nullptr) {
LOGP(info, "couldn't retrieve the object {}", path);
}
}
free(chunk.memory);
return result;
}
std::string CcdbApi::generateFileName(const std::string& inp)
{
// generate file name for the CCDB object (for now augment the input string by the timestamp)
std::string str = inp;
str.erase(std::remove_if(str.begin(), str.end(), ::isspace), str.end());
str = std::regex_replace(str, std::regex("::"), "-");
str += "_" + std::to_string(o2::ccdb::getCurrentTimestamp()) + ".root";
return str;
}
TObject* CcdbApi::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
{
return (TObject*)retrieveFromTFile(typeid(TObject), path, metadata, timestamp, headers, etag, createdNotAfter, createdNotBefore);
}
bool CcdbApi::retrieveBlob(std::string const& path, std::string const& targetdir, std::map<std::string, std::string> const& metadata,
long timestamp, bool preservePath, std::string const& localFileName, std::string const& createdNotAfter, std::string const& createdNotBefore) const
{
// we setup the target path for this blob
std::string fulltargetdir = targetdir + (preservePath ? ('/' + path) : "");
try {
o2::utils::createDirectoriesIfAbsent(fulltargetdir);
} catch (std::exception e) {
LOGP(error, "Could not create local snapshot cache directory {}, reason: {}", fulltargetdir, e.what());
return false;
}
o2::pmr::vector<char> buff;
std::map<std::string, std::string> headers;
// avoid creating snapshot via loadFileToMemory itself
loadFileToMemory(buff, path, metadata, timestamp, &headers, "", createdNotAfter, createdNotBefore, false);
if ((headers.count("Error") != 0) || (buff.empty())) {
LOGP(error, "Unable to find object {}/{}, Aborting", path, timestamp);
return false;
}
// determine local filename --> use user given one / default -- or if empty string determine from content
auto getFileName = [&headers]() {
auto& s = headers["Content-Disposition"];
if (s != "") {
std::regex re("(.*;)filename=\"(.*)\"");
std::cmatch m;
if (std::regex_match(s.c_str(), m, re)) {
return m[2].str();
}
}
std::string backupname("ccdb-blob.bin");
LOG(error) << "Cannot determine original filename from Content-Disposition ... falling back to " << backupname;
return backupname;
};
auto filename = localFileName.size() > 0 ? localFileName : getFileName();
std::string targetpath = fulltargetdir + "/" + filename;
{
std::ofstream objFile(targetpath, std::ios::out | std::ofstream::binary);
std::copy(buff.begin(), buff.end(), std::ostreambuf_iterator<char>(objFile));
if (!objFile.good()) {
LOGP(error, "Unable to open local file {}, Aborting", targetpath);
return false;
}
}
CCDBQuery querysummary(path, metadata, timestamp);
updateMetaInformationInLocalFile(targetpath.c_str(), &headers, &querysummary);
return true;
}
void CcdbApi::snapshot(std::string const& ccdbrootpath, std::string const& localDir, long timestamp) const
{
// query all subpaths to ccdbrootpath
const auto allfolders = getAllFolders(ccdbrootpath);
std::map<string, string> metadata;
for (auto& folder : allfolders) {
retrieveBlob(folder, localDir, metadata, timestamp);
}
}
void* CcdbApi::extractFromTFile(TFile& file, TClass const* cl, const char* what)
{
if (!cl) {
return nullptr;
}
auto object = file.GetObjectChecked(what, cl);
if (!object) {
// it could be that object was stored with previous convention
// where the classname was taken as key
std::string objectName(cl->GetName());
o2::utils::Str::trim(objectName);
object = file.GetObjectChecked(objectName.c_str(), cl);
LOG(warn) << "Did not find object under expected name " << what;
if (!object) {
return nullptr;
}
LOG(warn) << "Found object under deprecated name " << cl->GetName();
}
auto result = object;
// We need to handle some specific cases as ROOT ties them deeply
// to the file they are contained in
if (cl->InheritsFrom("TObject")) {
// make a clone
// detach from the file
auto tree = dynamic_cast<TTree*>((TObject*)object);
if (tree) {
tree->LoadBaskets(0x1L << 32); // make tree memory based
tree->SetDirectory(nullptr);
result = tree;
} else {
auto h = dynamic_cast<TH1*>((TObject*)object);
if (h) {
h->SetDirectory(nullptr);
result = h;
}
}
}
return result;
}
void* CcdbApi::extractFromLocalFile(std::string const& filename, std::type_info const& tinfo, std::map<std::string, std::string>* headers) const
{
if (!std::filesystem::exists(filename)) {
LOG(error) << "Local snapshot " << filename << " not found \n";
return nullptr;
}
std::lock_guard<std::mutex> guard(gIOMutex);
auto tcl = tinfo2TClass(tinfo);
TFile f(filename.c_str(), "READ");
if (headers) {
auto storedmeta = retrieveMetaInfo(f);
if (storedmeta) {
*headers = *storedmeta; // do a simple deep copy
delete storedmeta;
}
if ((isSnapshotMode() || mPreferSnapshotCache) && headers->find("ETag") == headers->end()) { // generate dummy ETag to profit from the caching
(*headers)["ETag"] = filename;
}
if (headers->find("fileSize") == headers->end()) {
(*headers)["fileSize"] = fmt::format("{}", f.GetEND());
}
}
return extractFromTFile(f, tcl);
}
bool CcdbApi::initTGrid() const
{
if (mNeedAlienToken && !gGrid) {
static bool allowNoToken = getenv("ALICEO2_CCDB_NOTOKENCHECK") && atoi(getenv("ALICEO2_CCDB_NOTOKENCHECK"));
if (!allowNoToken && !checkAlienToken()) {
LOG(fatal) << "Alien Token Check failed - Please get an alien token before running with https CCDB endpoint, or alice-ccdb.cern.ch!";
}
TGrid::Connect("alien");
static bool errorShown = false;
if (!gGrid && errorShown == false) {
if (allowNoToken) {
LOG(error) << "TGrid::Connect returned nullptr. May be due to missing alien token";
} else {
LOG(fatal) << "TGrid::Connect returned nullptr. May be due to missing alien token";
}
errorShown = true;
}
}
return gGrid != nullptr;
}
void* CcdbApi::downloadFilesystemContent(std::string const& url, std::type_info const& tinfo, std::map<string, string>* headers) const
{
if ((url.find("alien:/", 0) != std::string::npos) && !initTGrid()) {
return nullptr;
}
std::lock_guard<std::mutex> guard(gIOMutex);
auto memfile = TMemFile::Open(url.c_str(), "OPEN");
if (memfile) {
auto cl = tinfo2TClass(tinfo);
auto content = extractFromTFile(*memfile, cl);
if (headers && headers->find("fileSize") == headers->end()) {
(*headers)["fileSize"] = fmt::format("{}", memfile->GetEND());
}
delete memfile;
return content;
}
return nullptr;
}
void* CcdbApi::interpretAsTMemFileAndExtract(char* contentptr, size_t contentsize, std::type_info const& tinfo)
{