BmnRoot 26.10.0-233-gb9bbe585
Software framework of the BM@N experiment
Loading...
Searching...
No Matches
GeoSetup.cxx
Go to the documentation of this file.
1#include "GeoSetup.h"
2
3#include "BmnNewFieldMap.h"
4#include "FairModule.h"
5#include "FairRunAna.h"
6#include "TClass.h"
7#include "TGeoBBox.h"
8#include "TGeoBoolNode.h"
10#include "TGeoCone.h"
11#include "TGeoManager.h"
12#include "TGeoMatrix.h"
13#include "TGeoTrd2.h"
14#include "TGeoTube.h"
15#include "TInterpreter.h"
16#include "TKey.h"
17#include "TObjArray.h"
18#include "TObjString.h"
19#include "TSQLResult.h"
20#include "TSQLRow.h"
21#include "TSQLiteServer.h"
22#include "TSystem.h"
23#include "TXMLEngine.h"
24
25#include <cctype>
26#include <cstdlib>
27#include <cstring>
28#include <filesystem>
29#include <iostream>
30#include <sys/stat.h> /* stat */
31#include <time.h> /* time */
32#include <unistd.h> /* access, getpid */
33
34bool GeoSetup::exists_file(const char* name)
35{
36 return (access(name, F_OK) != -1);
37}
38
39static bool ichar_equals(char a, char b)
40{
41 return std::tolower(static_cast<unsigned char>(a)) == std::tolower(static_cast<unsigned char>(b));
42}
43
44// TSQLRow::GetField() returns nullptr for a NULL field and the server answers are not trusted,
45// so all conversions below tolerate a missing or malformed value instead of crashing or throwing
46static int FieldToInt(const char* field, int defaultValue = 0)
47{
48 if (field == nullptr)
49 return defaultValue;
50 char* end = nullptr;
51 long value = strtol(field, &end, 10);
52 return (end == field) ? defaultValue : static_cast<int>(value);
53}
54
55static uint64_t FieldToUInt64(const char* field, uint64_t defaultValue = 0)
56{
57 if (field == nullptr)
58 return defaultValue;
59 char* end = nullptr;
60 unsigned long long value = strtoull(field, &end, 10);
61 return (end == field) ? defaultValue : static_cast<uint64_t>(value);
62}
63
64static double FieldToDouble(const char* field, double defaultValue = 0.)
65{
66 if (field == nullptr)
67 return defaultValue;
68 char* end = nullptr;
69 double value = strtod(field, &end);
70 return (end == field) ? defaultValue : value;
71}
72
73// setup tags are put into shell command lines, so only the characters used in tag names are allowed
74static bool IsSafeTag(const string& tag)
75{
76 if (tag.empty())
77 return false;
78 for (char c : tag)
79 if (!std::isalnum(static_cast<unsigned char>(c)) && c != '_' && c != '.' && c != '-')
80 return false;
81
82 return true;
83}
84
85// double the single quotes to safely put the value into an SQL string literal
86static string SqlEscape(string_view value)
87{
88 string escaped;
89 escaped.reserve(value.size());
90 for (char c : value) {
91 escaped += c;
92 if (c == '\'')
93 escaped += c;
94 }
95
96 return escaped;
97}
98
99// get the value of a boolean attribute of the local settings: true, yes, 1 or false, no, 0 (case is ignored)
100// return value: false, if the value is wrong (the result is not changed then)
101static bool AttrToBool(const TString& name, TString value, bool& result)
102{
103 value = value.Strip(TString::kBoth);
104 value.ToLower();
105 if (value == "true" || value == "yes" || value == "1") {
106 result = true;
107 return true;
108 }
109 if (value == "false" || value == "no" || value == "0") {
110 result = false;
111 return true;
112 }
113
114 LOG(error) << "Wrong value of the '" << name << "' attribute: '" << value
115 << "', the allowed values are true, yes, 1, false, no, 0";
116 return false;
117}
118
119// get the value of a numeric attribute of the local settings
120// return value: false, if the value is not a number (the result is not changed then)
121static bool AttrToDouble(const TString& name, TString value, double& result)
122{
123 value = value.Strip(TString::kBoth);
124 char* end = nullptr;
125 double number = strtod(value.Data(), &end);
126 if (value.IsNull() || *end != '\0') {
127 LOG(error) << "Wrong value of the '" << name << "' attribute: '" << value << "', a number is expected";
128 return false;
129 }
130
131 result = number;
132 return true;
133}
134
135// put the local settings of a setup module to the map; the latest settings of the same module are used
136static void PutModuleEdit(map<TString, setup_module_ptr>& edits, const TString& key, setup_module_ptr sNode)
137{
138 map<TString, setup_module_ptr>::iterator it = edits.find(key);
139 if (it == edits.end()) {
140 edits.insert(make_pair(key, sNode));
141 return;
142 }
143
144 LOG(warning) << "The setup module '" << key << "' is customized more than once, the latest settings are used";
145 delete it->second;
146 it->second = sNode;
147}
148
149// temporary geometry files of the modules with changed positions, which are written by this process and are read by
150// FairRoot during the initialization of the simulation, and the process owning the files
151static vector<string> gTmpGeometryFiles;
152static pid_t gTmpGeometryPid = 0;
153
154// remove the temporary geometry files at the process exit
156{
157 // a forked child process must not remove the files, which are still used by the parent process
158 if (getpid() != gTmpGeometryPid)
159 return;
160
161 error_code ec;
162 for (const string& fileName : gTmpGeometryFiles)
163 filesystem::remove(fileName, ec);
164}
165
166// options of wget for the requests to the Geometry Web Service: the number of attempts and the timeouts are limited, so
167// that the loading of a setup does not hang for a long time, if the server is not reachable (as in installLocalDB.C)
168static const char* const kWgetOptions = "--tries=1 --dns-timeout=10 --connect-timeout=10";
169
170// unique name of a temporary file in the /tmp/$USER/ folder
172{
173 return GetTmpPath() + TString::Format("%s_%d", baseName, gSystem->GetPid());
174}
175
176unsigned long int GeoSetup::GetServerRevision(const char* url)
177{
178 unsigned long int serverRev = 0;
179 // a unique file name in the temporary folder: several jobs can run in the same working directory
180 TString fileName = GetTmpFileName("server_revision.txt");
181 gSystem->Exec(TString::Format("wget -O %s \"%s/get_cur_timestamp.php\" > /dev/null 2>&1", fileName.Data(), url));
182 std::ifstream myFile_Handler;
183 std::string myLine;
184 myFile_Handler.open(fileName.Data());
185 if (myFile_Handler.is_open()) {
186 char* ptr;
187 while (getline(myFile_Handler, myLine)) {
188 serverRev = strtoul(myLine.c_str(), &ptr, 10);
189 break;
190 }
191 myFile_Handler.close();
192 std::remove(fileName.Data());
193 }
194 return serverRev;
195}
196string GeoSetup::GetLastApprovedSetupTag(string_view pattern)
197{
198 std::pair<int, string> res = GetTagName4PatternServer(pattern);
199 if (res.first == 1)
200 return res.second;
201 // the local database is searched by its own connection, so the loaded setup is kept
202 TString localDbPath = GetLocalDbPath().c_str();
203 res = GetTagName4PatternLocal(pattern, localDbPath);
204 if (res.first == 1)
205 return res.second;
206
207 LOG(error) << "No approved geometry setup found for the tag prefix: " << pattern;
208 return "";
209}
210std::pair<int, string> GeoSetup::GetTagName4PatternServer(string_view pattern_tag, const char* url)
211{
212 std::pair<int, string> res = std::make_pair<int, string>(0, "");
213 // the pattern is put into a shell command line, so it has to be checked; a string_view is not
214 // necessarily null-terminated, hence the copy
215 std::string pattern(pattern_tag);
216 if (!IsSafeTag(pattern)) {
217 LOG(error) << "ERROR: the setup tag pattern contains forbidden characters: `" << pattern << "`";
218 return res;
219 }
220 // a unique file name in the temporary folder: several jobs can run in the same working directory
221 TString fileName = GetTmpFileName("setup_name.txt");
222 std::remove(fileName.Data());
223 TString command = TString::Format("wget %s -O %s \"%s/get_setup_name.php?tag=%s\" > /dev/null 2>&1", kWgetOptions,
224 fileName.Data(), url, pattern.c_str());
225 gSystem->Exec(command);
226 std::ifstream myFile_Handler;
227 std::string myLine;
228 myFile_Handler.open(fileName.Data());
229 if (myFile_Handler.is_open()) {
230 getline(myFile_Handler, myLine);
231 myFile_Handler.close();
232 // the server answer is read, the downloaded file is not needed any more
233 std::remove(fileName.Data());
234 std::size_t found = myLine.find(";");
235 if (found == std::string::npos) {
236 return res;
237 }
238 vector<string> results;
239 istringstream f(myLine);
240 std::string token;
241 while (getline(f, token, ':')) {
242 results.push_back(token);
243 }
244 if (results.size() != 3)
245 return res;
246 res = std::make_pair<int, string>(1, results[0].c_str());
247 }
248 return res;
249}
250
251std::pair<int, uint64_t> GeoSetup::CheckTagOnServer(string_view setup_tag, const char* url)
252{
253 int retval = -1;
254 // a unique file name in the temporary folder: several jobs can run in the same working directory
255 TString fileName = GetTmpFileName("server_setup_list.txt");
256 gSystem->Exec(TString::Format("wget %s -O %s \"%s/get_setup_list.php\" > /dev/null 2>&1", kWgetOptions,
257 fileName.Data(), url));
258 std::ifstream myFile_Handler;
259 std::string myLine;
260 std::string sTag(setup_tag);
261 myFile_Handler.open(fileName.Data());
262 if (myFile_Handler.is_open()) {
263 while (getline(myFile_Handler, myLine)) {
264 istringstream f(myLine);
265 string s;
266 while (getline(f, s, ';')) {
267 vector<string> results;
268 std::string token;
269 std::istringstream input;
270 input.str(s);
271 while (getline(input, token, ':')) { // Specify the delimiter
272 results.push_back(token);
273 }
274 if (results.size() < 2)
275 continue; // wrong format
276 std::string tag = results[0];
277 std::string status = results[1];
278 uint64_t upTime = 0;
279 if (results.size() > 2) {
280 // the server answer is not trusted: a non-numeric value must not throw
281 upTime = FieldToUInt64(results[2].c_str());
282 }
283 bool bb = std::equal(tag.begin(), tag.end(), sTag.begin(), sTag.end(), ichar_equals);
284 if (tag.size() == sTag.size() && bb) {
285 myFile_Handler.close();
286 std::remove(fileName.Data());
287 return std::make_pair(FieldToInt(status.c_str(), -1), upTime);
288 }
289 }
290 break;
291 }
292 myFile_Handler.close();
293 std::remove(fileName.Data());
294 }
295 return std::make_pair(retval, 0);
296}
297
298std::pair<int, string> GeoSetup::GetTagName4PatternLocal(string_view pattern_tag, TString& localDbPath)
299{
300 std::pair<int, string> res = std::make_pair<int, string>(0, "");
301 if (exists_file(localDbPath)) {
302 std::ostringstream stringStream;
303 stringStream << "sqlite://" << localDbPath;
304 TSQLiteServer db(stringStream.str().c_str());
305 stringStream.str("");
306 if (db.IsConnected()) {
307 stringStream << "SELECT setup_tag, status, creation_date FROM setup where status=1 and setup_tag like '"
308 << SqlEscape(pattern_tag) << "%' order by creation_date DESC limit 1;";
309 TSQLResult* resQ = db.Query(stringStream.str().c_str());
310 if (resQ != 0) {
311 TSQLRow* row = resQ->Next();
312 if (row != NULL) {
313 const char* name = row->GetField(0);
314 if (name != NULL)
315 res = std::make_pair<int, string>(1, name);
316 delete row;
317 }
318 delete resQ;
319 }
320 }
321 }
322 return res;
323}
324unsigned long int GeoSetup::GetLocalRevision(TString& localDbPath)
325{
326 unsigned long int localRev = 0;
327 // char type;
328 if (exists_file(localDbPath)) {
329 std::ostringstream stringStream;
330 stringStream << "sqlite://" << localDbPath;
331 TSQLiteServer db(stringStream.str().c_str());
332 stringStream.str("");
333 if (db.IsConnected()) {
334 stringStream << "select value_field from config where key_field='config_time';";
335 // cout << stringStream.str().c_str() << std::endl;
336 TSQLResult* resQ = db.Query(stringStream.str().c_str());
337 if (resQ != 0) {
338 TSQLRow* row = resQ->Next();
339 if (row != NULL) {
340 const char* ch_time = row->GetField(0);
341 char* ptr;
342 if (ch_time != NULL)
343 localRev = strtoul(ch_time, &ptr, 10);
344 }
345 }
346 }
347 }
348 return localRev;
349}
350
351// check that the directory can be modified to install the Local Geometry DB (e.g. in case of CVMFS)
352bool GeoSetup::IsWritableDir(const char* path)
353{
354 return (access(path, W_OK | X_OK) == 0);
355}
356
357// the unique folder, where the Local Geometry Database is installed by this process
358// instead of the read-only directory, and the process owning the folder
359static string gWritableDbDir;
360static pid_t gWritableDbPid = 0;
361
362// remove the unique folder of the installed database at the process exit
364{
365 // a forked child process must not remove the folder, which is still used by the parent process
366 if (gWritableDbDir.empty() || getpid() != gWritableDbPid)
367 return;
368
369 error_code ec;
370 filesystem::remove_all(gWritableDbDir, ec);
371}
372
373// prepare a writable directory to install the Local Geometry Database to, when the directory of the
374// database (the parent of GEOMPATH) is read-only. A unique folder is created in the DBL_CACHE_PATH directory, if it is
375// set, otherwise in $TMPDIR or in /tmp/$USER
377{
378 TString baseDir;
379 const char* env_p = getenv("DBL_CACHE_PATH");
380 if (env_p != nullptr) {
381 baseDir = env_p;
382 if (gSystem->ExpandPathName(baseDir)) {
383 LOG(error) << "Cannot expand the DBL_CACHE_PATH value: " << env_p;
384 return "";
385 }
386 } else {
387 const char* tmp_p = getenv("TMPDIR");
388 baseDir = (tmp_p != nullptr && IsWritableDir(tmp_p)) ? TString(tmp_p) : GetTmpPath();
389 }
390 // the folder is unique for the process: jobs installing the database at the same time must not overwrite
391 // the files of each other, also the jobs on different nodes sharing the same directory, e.g. DBL_CACHE_PATH
392 TString dirName = TString::Format("geo_db_%s_%d", gSystem->HostName(), gSystem->GetPid());
393 gSystem->PrependPathName(baseDir.Data(), dirName);
394
395 if (!exists_file(dirName.Data()) && gSystem->mkdir(dirName, true) != 0) {
396 LOG(error) << "ERROR: cannot create the folder for the geometry database: " << dirName;
397 return "";
398 }
399 if (!IsWritableDir(dirName.Data())) {
400 LOG(error) << "ERROR: the folder for the geometry database is not writable: " << dirName;
401 return "";
402 }
403
404 return dirName;
405}
406
407int GeoSetup::installLocalDB(string_view setup_tag, const char* url)
408{
409 CloseDB();
410 TString localDbPath = GetLocalDbPath().c_str();
411 if (localDbPath == "") {
412 LOG(error) << "GEOMPATH is not set. Please, set GEOMPATH as a path to the storage of the Local Geometry "
413 "Database, the database file (local.db) is located in its parent directory"
414 << endl;
415 return -1;
416 }
417
418 TString dirName(gSystem->DirName(localDbPath.Data()));
419 // the database is installed to a writable directory instead of the read-only one given by GEOMPATH
420 bool isMovedDb = false;
421 if (!exists_file(dirName.Data())) {
422 if (gSystem->mkdir(dirName, true) != 0) {
423 LOG(error) << "ERROR: cannot create folder: " << dirName << endl;
424 return -3;
425 }
426 } else if (!IsWritableDir(dirName.Data())) {
427 // the database directory is read-only (on CVMFS, for example), so the database
428 // is installed to a writable directory, which is used by this process from now on
429 LOG(info) << "The directory of the Local Geometry Database is read-only: " << dirName
430 << ". The database will be installed to a writable directory";
431 TString writableDir = PrepareWritableDbDir();
432 if (writableDir.Length() == 0)
433 return -3;
434 // the folder is removed at the process exit, also if the installation fails below
435 if (gWritableDbPid != getpid()) {
436 gWritableDbDir = writableDir.Data();
437 gWritableDbPid = getpid();
438 atexit(RemoveWritableDbDir);
439 }
440 dirName = writableDir;
441 localDbPath = dirName + "/local.db";
442 isMovedDb = true;
443 }
444 // a unique file name in the temporary folder: several jobs can run in the same working directory
445 TString tarName = GetTmpFileName("geo_db.tar");
446 TString command;
447 if (setup_tag.size() == 0)
448 command = TString::Format("wget %s -O %s \"%s/download_file.php?type=all&tag=all\" > /dev/null 2>&1",
449 kWgetOptions, tarName.Data(), url);
450 else {
451 std::string tag(setup_tag);
452 if (!IsSafeTag(tag)) {
453 LOG(error) << "ERROR: the setup tag contains forbidden characters: `" << tag << "`";
454 return -7;
455 }
456 command = TString::Format("wget %s -O %s \"%s/download_file.php?type=s&tag=%s&rev=1\" > /dev/null 2>&1",
457 kWgetOptions, tarName.Data(), url, tag.c_str());
458 }
459 // Exec returns the raw status of system(), the wget exit code is its high byte
460 int wgetStatus = gSystem->Exec(command);
461 if (wgetStatus != 0 || !exists_file(tarName.Data())) {
462 LOG(error) << "ERROR: downloading the geometry database file failed (wget exit code " << wgetStatus / 256
463 << "), please, check url: " << url << endl;
464 gSystem->Unlink(tarName.Data());
465 return -4;
466 }
467 FileStat_t file_stat;
468 gSystem->GetPathInfo(tarName.Data(), file_stat);
469 if (file_stat.fSize == 0) {
470 LOG(error) << "ERROR: downloaded geometry database file has 0 size, please, check url: " << url << endl;
471 gSystem->Unlink(tarName.Data());
472 return -5;
473 }
474 // an incomplete download or an error page of the server is not unpacked, otherwise a part of the files of the
475 // local database would be overwritten before tar fails
476 if (gSystem->Exec(TString::Format("tar -tf %s > /dev/null 2>&1", tarName.Data())) != 0) {
477 LOG(error) << "ERROR: the downloaded geometry database file is not a valid archive (an incomplete download or "
478 "an error page of the server), please, check url: "
479 << url << endl;
480 gSystem->Unlink(tarName.Data());
481 return -8;
482 }
483 // untar archive with the database file
484 int tarResult =
485 gSystem->Exec(TString::Format("tar -xf %s -C \"%s/\" > /dev/null 2>&1", tarName.Data(), dirName.Data()));
486 // remove temporary archive
487 gSystem->Unlink(tarName.Data());
488 if (tarResult != 0) {
489 LOG(error) << "ERROR: cannot unpack the geometry database archive to the directory: " << dirName << endl;
490 return -8;
491 }
492 // the archive is unpacked, but the database file itself can be absent in it
493 if (!exists_file(localDbPath.Data())) {
494 LOG(error) << "ERROR: no database file found after unpacking the archive: " << localDbPath << endl;
495 return -9;
496 }
497 // the installed database is used by GetLocalDbPath(), GetRootPath(), by FairRoot (the media file of the setup) and
498 // by the magnetic field map; GEOMPATH is changed only now, so that the read-only database is still used if the
499 // installation failed
500 TString previousGeomPath;
501 if (isMovedDb) {
502 previousGeomPath = getenv("GEOMPATH");
503 gSystem->Setenv("GEOMPATH", (dirName + "/storage/").Data());
504 }
505 if (!OpenLocalGeoDatabase()) {
506 if (isMovedDb)
507 gSystem->Setenv("GEOMPATH", previousGeomPath.Data());
508 return -6;
509 }
510 if (isMovedDb)
511 LOG(info) << "GEOMPATH is changed to the storage of the installed database: " << GetRootPath();
512 LOG(info) << "The Local Geometry Database was successfully installed to the directory: " << dirName << endl;
513 return 0;
514}
515
517{
518 m_modules_table.clear();
519 m_modules_active.clear();
520 for (auto& item : m_modules_revision_table)
521 delete item.second;
523 if (m_db != nullptr) {
524 m_db->Close();
525 delete m_db;
526 m_db = nullptr;
527 }
528}
529
530// GeoSetup destructor
536
537// create connection to the Local Geometry Database and fill the tables with modules and their revisions
539{
540 string fPath = GetLocalDbPath();
541 if (fPath.size() == 0) {
542 LOG(error) << "Please, set GEOMPATH environment variable (the storage of the Local Geometry Database) before "
543 "using the Geometry Database";
544 return false;
545 }
546 if (!exists_file(fPath.c_str())) {
547 LOG(error) << "No Database found in " << fPath;
548 return false;
549 }
550 ostringstream stringStream;
551 stringStream << "sqlite://" << fPath;
552
553 LOG(debug1) << "Connecting the Local Geometry Database at path: " << stringStream.str().c_str();
554 // std::cerr<<"Connecting the Local Geometry Database at path: "<<stringStream.str().c_str()<<std::endl;
555 // the connection and the tables of a previous call (e.g. for another setup) are replaced
556 CloseDB();
557 m_db = new TSQLiteServer(stringStream.str().c_str());
558 if (PutModules() != 0) {
559 LOG(error) << "Cannot load detector geometry, please, check GEOMPATH environment variable";
560 return false;
561 }
562 if (PutModuleRevisions() != 0) {
563 LOG(error) << "Cannot load detector geometry, please, check GEOMPATH environment variable";
564 return false;
565 }
566
567 return true;
568}
569
570// the shape of an assembly volume is owned by the volume itself, but setups built with FairRoot keep these
571// shapes in the list of shapes as well, where they are deleted the second time, when the geometry is deleted
572static void RemoveAssemblyShapes(TGeoManager* geoManager)
573{
574 TObjArray* shapes = geoManager->GetListOfShapes();
575 TIter nextVolume(geoManager->GetListOfVolumes());
576 int removedCount = 0;
577 while (TGeoVolume* volume = (TGeoVolume*)nextVolume())
578 if (volume->IsAssembly() && shapes->Remove(volume->GetShape()) != nullptr)
579 removedCount++;
580
581 // the setup files built with the fixed FairRoot have no assembly shapes in the list
582 if (removedCount > 0) {
583 shapes->Compress();
584 LOG(info) << removedCount << " assembly shapes were removed from the list of shapes of the geometry";
585 }
586}
587
588//-1 problem to load DB. Require to check GEOMPATH environment variable.
589//-2 No geometry setup found for the given tag
590//-3 Setup is damaged.
591// load selected geometry setup from the Local Geometry Database and create gGeoManager instance
592int GeoSetup::LoadSetupToGeoManager(string_view setup_tag)
593{
594 // e.g. GetLastApprovedSetupTag found no setup
595 if (setup_tag.empty()) {
596 LOG(error) << "The tag of the geometry setup is not set";
597 return -2;
598 }
599 // the local settings are applied only for the simulation, so the settings of a previous LoadSetupToFairRunSim call
600 // (e.g. the replaced field map) must not be used for this setup
602 if (GetLocalDbPath().empty()) {
603 LOG(error) << "Please, set GEOMPATH environment variable (the storage of the Local Geometry Database) before "
604 "using the Geometry Database";
605 return -1;
606 }
607 bool isOpen = false;
609 isOpen = true;
610 TSQLResult* resQ = nullptr;
611 TSQLRow* row = nullptr;
612 ostringstream stringStream;
613 string tag = SqlEscape(setup_tag);
614 // if (revision == nullptr)
615 stringStream << "select setup_id,status,material_id,field_id,file_name,modified_date from setup where "
616 "lower(setup_tag)=lower('"
617 << tag << "') order by creation_date desc;";
618 int sStatus = 0;
619 uint64_t sUpTime = 0;
620 std::pair<int, uint64_t> status;
621 // else
622 // stringStream<<"select idsd,status,idma,idfi,rfile from setup where lower(stag)=lower('"<<setupTag<<"') and
623 // TRIM(revision)=TRIM('"<<revision<<"') order by sdate desc;";
624 if (isOpen) {
625 resQ = m_db->Query(stringStream.str().c_str());
626 if (resQ == nullptr) {
627 // temporary, for support of old database versions without the modified_date column
628 stringStream.str("");
629 stringStream << "select setup_id,status,material_id,field_id,file_name, creation_date from setup where "
630 "lower(setup_tag)=lower('"
631 << tag << "') order by creation_date desc;";
632 resQ = m_db->Query(stringStream.str().c_str());
633 if (resQ == nullptr)
634 LOG(error) << "SQL query was failed while searching the given tag: `" << setup_tag
635 << "`. Setup will download from server.";
636 else
637 row = resQ->Next();
638 } else
639 row = resQ->Next();
640 }
641 if (row != nullptr) {
642 sStatus = FieldToInt(row->GetField(1));
643 sUpTime = FieldToUInt64(row->GetField(5));
644 }
645 if (sStatus == 0) {
646 status = CheckTagOnServer(setup_tag);
647 }
648 if (row == nullptr || (sStatus == 0 && status.second > sUpTime)) {
649 if (row == nullptr)
650 LOG(info) << "No geometry setup found in the local database for `" << setup_tag << "` tag";
651 else
652 LOG(info) << "A newer version of the not approved geometry setup `" << setup_tag
653 << "` is on the geometry server";
654 delete resQ;
655 resQ = nullptr;
656 if (row != nullptr) {
657 delete row;
658 row = nullptr;
659 }
660 if (status.first >= 0) {
661 int isUpload = -1;
662 if (status.first == 1) {
663 LOG(info) << "Approved geometry setup found on the geometry server:`" << GEO_SERVER_HOST
664 << "`. Downloading...";
665 isUpload = installLocalDB("");
666 } else {
667 LOG(info) << "Not approved geometry setup found on the geometry server:`" << GEO_SERVER_HOST
668 << "`. Downloading";
669 isUpload = installLocalDB(setup_tag);
670 }
671 if (isUpload >= 0) {
672 // In this case do not set modified time for support old DB
673 stringStream.str("");
674 stringStream
675 << "select setup_id,status,material_id,field_id,file_name from setup where lower(setup_tag)=lower('"
676 << tag << "') order by creation_date desc;";
677 resQ = m_db->Query(stringStream.str().c_str());
678 if (resQ == nullptr)
679 LOG(error) << "SQL query was failed while searching the given tag: `" << setup_tag << "`";
680 else
681 row = resQ->Next();
682 } else {
683 LOG(error) << "Cannot download the geometry setup from the server:`" << GEO_SERVER_HOST << "`.";
684 return -2;
685 }
686 } else
687 LOG(error) << "No geometry setup found on the geometry server:`" << GEO_SERVER_HOST << "`.";
688 if (row == nullptr) {
689 LOG(error) << "The geometry setup `" << setup_tag << "` is absent in the Geometry Database";
690 delete resQ;
691 return -2;
692 }
693 }
694
695 m_sid = FieldToInt(row->GetField(0));
696 // int idma = FieldToInt(row->GetField(2));
697 m_fid = FieldToInt(row->GetField(3), -1);
698 // the field and the material file of a previously loaded setup are not valid anymore (the field object is owned
699 // by the run it was given to)
700 m_field = nullptr;
701 m_refVoltage = -1;
702 m_materialFile = "";
703 TString geoFileField = row->GetField(4) != nullptr ? row->GetField(4) : "";
704 geoFileField = geoFileField.Strip(TString::kBoth);
705 delete row;
706 delete resQ;
707
708 // the setup can be defined only by separate modules (for simulation) without a file with the full geometry
709 if (geoFileField.IsNull()) {
710 LOG(error) << "The geometry setup `" << setup_tag
711 << "` has no ROOT file with the full geometry in the Geometry Database";
712 return -3;
713 }
714 TString geoFileName = GetRootPath() + geoFileField;
715
716 TFile* geoFile = new TFile(geoFileName, "READ");
717 if (geoFile->IsZombie() || !geoFile->IsOpen()) {
718 LOG(error) << "ERROR: could not open ROOT file with geometry: " + geoFileName;
719 delete geoFile;
720 return -3;
721 }
722 TList* keyList = geoFile->GetListOfKeys();
723 TIter next(keyList);
724 TKey* key = (TKey*)next();
725 if (key == nullptr || !TString(key->GetClassName()).BeginsWith("TGeoManager")) {
726 LOG(error) << "ERROR: TGeoManager is not top element in geometry file " + geoFileName;
727 delete geoFile;
728 return -3;
729 }
730 // the read geometry registers itself as gGeoManager, so the file can be closed (as TGeoManager::Import does)
731 key->ReadObj();
732 delete geoFile;
733 if (gGeoManager != nullptr)
735
736 m_setupTag = string(setup_tag);
737 return 0;
738}
739
740// parse the geometry tag, which can contain the path to an XML file with a local customization of the setup
741// geometry after the ';' separator, e.g. "run9_26.09.0;$VMCWORKDIR/my_setup.xml"
742int GeoSetup::ParseGeometryTag(TString& geometry_tag, TString& local_settings)
743{
744 local_settings = "";
745 if (!geometry_tag.Contains(';'))
746 return 0;
747
748 TString setup_tag = "", unexpected_part = "";
749 TObjArray* tag_tokens = geometry_tag.Tokenize(";");
750 for (Int_t i = 0; i < tag_tokens->GetEntriesFast(); i++) {
751 TString token = ((TObjString*)tag_tokens->At(i))->GetString().Strip(TString::kBoth);
752 if (token.IsNull())
753 continue;
754
755 bool is_xml_file = token.EndsWith(".xml", TString::kIgnoreCase);
756 if (is_xml_file && local_settings.IsNull())
757 local_settings = token;
758 else if (!is_xml_file && setup_tag.IsNull())
759 setup_tag = token;
760 else if (unexpected_part.IsNull()) // e.g. a second XML file or a second setup tag
761 unexpected_part = token;
762 }
763 delete tag_tokens;
764
765 // the separator without an XML file after it is considered as a part of the setup tag itself
766 if (local_settings.IsNull()) {
767 LOG(warning) << "No XML file with a geometry customization was found after ';', the whole value is used as "
768 "the setup tag: "
769 << geometry_tag;
770 return 0;
771 }
772 if (!unexpected_part.IsNull()) {
773 LOG(error) << "Unexpected part '" << unexpected_part << "' in the geometry tag: " << geometry_tag;
774 local_settings = "";
775 return -1;
776 }
777
778 geometry_tag = setup_tag;
779 // the check expands a copy of the path, so the file can be given as, e.g., "$VMCWORKDIR/my_setup.xml",
780 // while the path is returned as given to be valid on another computer
781 TString local_settings_path = local_settings;
782 gSystem->ExpandPathName(local_settings_path);
783 if (gSystem->AccessPathName(local_settings_path, kReadPermission)) {
784 LOG(error) << "No XML file with a geometry customization: " << local_settings_path;
785 local_settings = "";
786 return -2;
787 }
788
789 return 0;
790}
791
792// load selected geometry for simulation application from the Geometry Database.
793int GeoSetup::LoadSetupToFairRunSim(string_view setup_tag, const char* localSettings)
794{
795 // e.g. GetLastApprovedSetupTag found no setup
796 if (setup_tag.empty()) {
797 LOG(error) << "The tag of the geometry setup is not set";
798 return -2;
799 }
800 // the local settings and the loaded modules of a previous call must not be applied to this setup
802 m_loadedModule.clear();
803 if (localSettings != nullptr) {
804 // the path can contain environment variables, e.g. "$VMCWORKDIR/my_setup.xml"
805 TString localSettingsPath(localSettings);
806 gSystem->ExpandPathName(localSettingsPath);
807 // the setup is not loaded partly customized, because a simulation with the wrong geometry is useless
808 if (!LoadLocalSettings(localSettingsPath.Data())) {
809 LOG(error) << "The local settings of the geometry from '" << localSettingsPath
810 << "' cannot be applied, the setup is not loaded";
812 return -4;
813 }
814 }
815
816 bool isOpen = false;
818 isOpen = true;
819 TSQLResult* resQ = nullptr;
820 TSQLRow* row = nullptr;
821
822 ostringstream stringStream;
823 string tag = SqlEscape(setup_tag);
824 // if (revision == nullptr)
825 stringStream
826 << "select setup_id,status,material_id,field_id,modified_date from setup where lower(setup_tag)=lower('" << tag
827 << "') order by creation_date desc;"; // KG если я правильно понял, то нужно брать по-умолчанию,
828 // самый новый релиз?
829 // else
830 // stringStream<<"select idsd,status,idma,idfi from setup where stag='"<<setupTag<<"' and
831 // TRIM(revision)=TRIM('"<<revision<<"') order by sdate desc;";
832 LOG(debug1) << stringStream.str().c_str();
833 int sStatus = 0;
834 uint64_t sUpTime = 0;
835 std::pair<int, uint64_t> status;
836 if (isOpen) {
837 resQ = m_db->Query(stringStream.str().c_str());
838 if (resQ == nullptr) {
839 // temprorary for support old versions
840 stringStream.str("");
841 stringStream
842 << "select setup_id,status,material_id,field_id,creation_date from setup where lower(setup_tag)=lower('"
843 << tag << "') order by creation_date desc;";
844 resQ = m_db->Query(stringStream.str().c_str());
845 if (resQ == nullptr)
846 LOG(error) << "SQL query was failed while searching the given tag: `" << setup_tag
847 << "`. Setup will download from server.";
848 else
849 row = resQ->Next();
850 // return -2;
851 } else
852 row = resQ->Next();
853 }
854 if (row != nullptr) {
855 sStatus = FieldToInt(row->GetField(1));
856 sUpTime = FieldToUInt64(row->GetField(4));
857 }
858 if (sStatus == 0) {
859 status = CheckTagOnServer(setup_tag);
860 }
861 if (row == nullptr || (sStatus == 0 && status.second > sUpTime)) {
862 if (row == nullptr)
863 LOG(info) << "No geometry setup found in the local database for `" << setup_tag << "` tag";
864 else
865 LOG(info) << "A newer version of the not approved geometry setup `" << setup_tag
866 << "` is on the geometry server";
867 delete resQ;
868 resQ = nullptr;
869 if (status.first >= 0) {
870 int isUpload = -1;
871 if (status.first == 1) {
872 LOG(info) << "Approved geometry setup found on the geometry server:`" << GEO_SERVER_HOST
873 << "`. Downloading...";
874 isUpload = installLocalDB("");
875 } else {
876 LOG(info) << "Not approved geometry setup found on the geometry server:`" << GEO_SERVER_HOST
877 << "`. Downloading...";
878 isUpload = installLocalDB(setup_tag);
879 }
880 if (isUpload >= 0) {
881 // AE added for support old version
882 stringStream.str("");
883 stringStream
884 << "select setup_id,status,material_id,field_id,file_name from setup where lower(setup_tag)=lower('"
885 << tag << "') order by creation_date desc;";
886
887 // the row of the outdated version is replaced by the row of the installed one
888 delete row;
889 row = nullptr;
890 resQ = m_db->Query(stringStream.str().c_str());
891 if (resQ == nullptr)
892 LOG(error) << "SQL query was failed while searching the given tag: `" << setup_tag << "`";
893 else
894 row = resQ->Next();
895 } else {
896 LOG(error) << "Cannot download the geometry setup from the server:`" << GEO_SERVER_HOST << "`.";
897 delete row;
898 return -2;
899 }
900 } else
901 LOG(error) << "No geometry setup found on the geometry server:`" << GEO_SERVER_HOST << "`.";
902 if (row == nullptr) {
903 LOG(error) << "The geometry setup `" << setup_tag << "` is absent in the Geometry Database";
904 delete resQ;
905 return -2;
906 }
907 }
908
909 FairRunSim* fRun = FairRunSim::Instance();
910 if (fRun == nullptr) {
911 fRun = new FairRunSim();
912 LOG(info) << "New FairRunSim instance has been created";
913 }
914
915 m_sid = FieldToInt(row->GetField(0));
916 int idma = FieldToInt(row->GetField(2));
917 m_fid = FieldToInt(row->GetField(3), -1);
918 // the field and the material file of a previously loaded setup are not valid anymore (the field object is owned
919 // by the run it was given to)
920 m_field = nullptr;
921 m_refVoltage = -1;
922 m_materialFile = "";
923 if (idma > 0) {
924 delete row;
925 delete resQ;
926
927 stringStream.str("");
928 stringStream << "select matag,file_name from material where material_id=" << idma << ";";
929 resQ = m_db->Query(stringStream.str().c_str());
930
931 // an empty result is detected by the first row, because SQLite does not provide the row count (-1)
932 if (resQ == nullptr) {
933 LOG(info) << "Materials were not found";
934 } else {
935 row = resQ->Next();
936 /* const char* media_path = row->GetField(1);
937
938 TString Mat = getenv("GEOMPATH");
939 if (Mat.IsNull()) {
940 Mat = ((TString)getenv("VMCWORKDIR")) + "/geometry/";
941 Mat.ReplaceAll("//", "/");
942 } else {
943 Mat.ReplaceAll("//", "/");
944 if (!Mat.EndsWith("/"))
945 Mat += "/";
946 }
947
948 string workP(Mat.Data());
949 LOG(debug1) << "Working geometry directory: " << workP;
950
951 size_t found = workP.find('/');
952 TString in("");
953 if (found != string::npos) {
954 while ((found = workP.find('/', found + 1)) != string::npos) {
955 LOG(debug1) << "found:" << found;
956 in += "../";
957 }
958 }
959 in += GetRootPath() + media_path;
960 */
961 if (row == nullptr)
962 LOG(info) << "Materials were not found";
963 else {
964 const char* materialFile = row->GetField(1);
965 TString in = (materialFile != nullptr ? materialFile : "");
966 fRun->SetMaterials(in.Data());
967 m_materialFile = in.Data();
968
969 delete row;
970 }
971 delete resQ;
972 }
973 } else {
974 delete row;
975 delete resQ;
976 }
977 LOG(info) << "Load geometry with tag=" << setup_tag << " from database";
978 LOG(debug1) << "setup_id = " << m_sid << "; material_id = " << idma << "; filed_id = " << m_fid << endl;
979 stringStream.str("");
980 stringStream << "select setup_module_id from sms where setup_id=" << m_sid << ";";
981 resQ = m_db->Query(stringStream.str().c_str());
982 if (resQ == nullptr) {
983 LOG(error) << "ERROR: SQL query was failed while searching the modules of the setup";
984 return -3;
985 }
986 // the empty setup is detected by the number of the rows, because SQLite does not provide the row count (-1)
987 int moduleCount = 0;
988 while ((row = resQ->Next()) != nullptr) {
989 moduleCount++;
990 stringStream.str("");
991 const char* idsm = row->GetField(0);
992 int idsmI = FieldToInt(idsm);
993 LOG(debug1) << "module=" << idsmI << std::endl;
994 // if (subSetup < 0 || subSetup == idsmI){ //check subset
995 int res = LoadModuleToFairRunSim(idsmI, fRun);
996 delete row;
997 // the error is reported by LoadModuleToFairRunSim: wrong local settings for the module or a damaged setup
998 if (res < 0) {
999 delete resQ;
1000 return (res == -3) ? -4 : -3;
1001 }
1002 }
1003 delete resQ;
1004 if (moduleCount == 0) {
1005 LOG(error) << "ERROR: no modules found for the setup `" << setup_tag << "`";
1006 return -3;
1007 }
1008 // the modules from the local settings are added after the modules of the setup, when the cave already exists
1009 for (const auto& item : m_moduleAdd)
1010 if (!AddModuleToFairRunSim(item, fRun))
1011 return -4;
1012
1013 m_setupTag = string(setup_tag);
1014 return 0;
1015}
1016
1017// get field map of selected geometry: the map is created once for the loaded setup and is returned as it was measured,
1018// i.e. with the unit scale, because the scale of the run is defined by the caller
1020{
1021 // return magnetic field if exists
1022 if (m_field != nullptr)
1023 return m_field;
1024
1025 if (m_db == nullptr) {
1026 LOG(error) << "Geometry Database is not loaded";
1027 return nullptr;
1028 }
1029 if (m_fid == -1 && m_ExternalField.IsNull()) {
1030 LOG(debug1) << "Selected Geometry Database has no magnetic field";
1031 return nullptr;
1032 }
1033
1034 // the field map from the local settings ('editFieldMap') replaces the map of the setup, but the reference voltage
1035 // of the setup field is used for it
1036 TString mapFile = m_ExternalField;
1037 double refVoltage = 0;
1038 if (m_fid != -1) {
1039 // get field map for the current id from the Geometry Database
1040 ostringstream stringStream;
1041 stringStream << "select file_name,reference_voltage from field where field_id=" << m_fid << ";";
1042 TSQLResult* resQ = m_db->Query(stringStream.str().c_str());
1043 bool isRefVoltageProvided = (resQ != nullptr);
1044 if (!isRefVoltageProvided) {
1045 // temporary, for support of old database versions without the 'reference_voltage' column
1046 LOG(warning) << "The Geometry Database does not provide the reference voltage of the magnetic field. "
1047 "Please, update the Geometry Database";
1048 stringStream.str("");
1049 stringStream << "select file_name from field where field_id=" << m_fid << ";";
1050 resQ = m_db->Query(stringStream.str().c_str());
1051 }
1052 if (resQ == nullptr) {
1053 LOG(error) << "SQL query was failed while searching magnetic field for id: `" << m_fid << "`";
1054 return nullptr;
1055 }
1056
1057 TSQLRow* row = resQ->Next();
1058 if (row == nullptr) {
1059 LOG(error) << "ERROR: no selected magnetic field in the Geometry Database for id=" << m_fid;
1060 delete resQ;
1061 return nullptr;
1062 }
1063 if (mapFile.IsNull())
1064 mapFile = (row->GetField(0) != nullptr ? row->GetField(0) : "");
1065 if (isRefVoltageProvided)
1066 refVoltage = FieldToDouble(row->GetField(1));
1067 delete row;
1068 delete resQ;
1069 }
1070 if (mapFile.IsNull()) {
1071 LOG(error) << "ERROR: no file of the magnetic field map in the Geometry Database for id=" << m_fid;
1072 return nullptr;
1073 }
1074 if (!m_ExternalField.IsNull())
1075 LOG(info) << "\033[38;2;255;165;0mThe magnetic field map is replaced by the local settings\033[0m";
1076
1077 BmnNewFieldMap* pBmnNewFieldMap = new BmnNewFieldMap();
1078 pBmnNewFieldMap->SetFileName(mapFile);
1079 LOG(info) << "field path=" << pBmnNewFieldMap->GetFileName();
1080 m_field = pBmnNewFieldMap;
1081 m_refVoltage = refVoltage;
1082
1083 return m_field;
1084}
1085
1086// get parameter file by given detector name
1087string GeoSetup::GetParameterFile(string_view name)
1088{
1089 if (name == "") {
1090 LOG(error) << "Detector name for the parameter file is not set";
1091 return "";
1092 }
1093 if (m_sid == -1) {
1094 LOG(error) << "The geometry setup is not loaded";
1095 return "";
1096 }
1097 if (m_db == nullptr) {
1098 LOG(error) << "The Geometry Database is not connected";
1099 return "";
1100 }
1101
1102 TString sname(name);
1103 int index = GetModuleIndex(sname);
1104 if (index < 0) {
1105 LOG(error) << "The detector name \'" << sname << "\'does not exist in the Geometry Database";
1106 return "";
1107 }
1108 LOG(debug1) << "The detector name \'" << sname << "\'exists in the Geometry Database";
1109
1110 // the parameter file is set for the setup module, whose geometry file belongs to a class of the detector module
1111 ostringstream stringStream;
1112 stringStream
1113 << "select sm.parfile_name from sms s INNER JOIN setup_module sm on s.setup_module_id=sm.setup_module_id "
1114 "INNER JOIN geometry_file f on sm.file_id=f.file_id INNER JOIN module_class mc on "
1115 "f.module_id=mc.module_class_id where s.setup_id="
1116 << m_sid << " and mc.module_id=" << index << ";";
1117 LOG(debug1) << "Request \'" << stringStream.str().c_str() << "\'.";
1118 TSQLResult* resQ = m_db->Query(stringStream.str().c_str());
1119 if (resQ == nullptr) {
1120 LOG(error) << "SQL query was failed while searching parameter file for detector `" << sname << "`";
1121 return "";
1122 }
1123 TSQLRow* row = resQ->Next();
1124 if (row == nullptr) {
1125 LOG(info) << "Parameter file for detector `" << sname << "` not found";
1126 delete resQ;
1127 return "";
1128 }
1129
1130 // the field points to the memory owned by the row, so it has to be copied before the row is deleted
1131 const char* file = row->GetField(0);
1132 string parameterFile = (file != nullptr ? file : "");
1133 delete row;
1134 delete resQ;
1135
1136 if (parameterFile.empty()) {
1137 LOG(info) << "Parameter file for detector `" << sname << "` does not exist in the Geometry Database";
1138 return "";
1139 }
1140
1141 // the parameter files are located in the storage of the Local Geometry Database
1142 return GetRootPath() + parameterFile;
1143}
1144
1145// get the material file of the current setup
1147{
1148 // the file name is read by LoadSetupToFairRunSim(), it is requested here only if the setup geometry
1149 // was loaded by another way, e.g. by LoadSetupToGeoManager()
1150 if (!m_materialFile.empty())
1151 return m_materialFile;
1152
1153 if (m_sid == -1) {
1154 LOG(error) << "The geometry setup is not loaded";
1155 return "";
1156 }
1157 if (m_db == nullptr) {
1158 LOG(error) << "The Geometry Database is not connected";
1159 return "";
1160 }
1161
1162 ostringstream stringStream;
1163 stringStream << "select m.file_name from setup s INNER JOIN material m on m.material_id=s.material_id where "
1164 "s.setup_id="
1165 << m_sid << ";";
1166 TSQLResult* resQ = m_db->Query(stringStream.str().c_str());
1167 if (resQ == nullptr) {
1168 LOG(info) << "SQL query was failed while searching the material file of the setup";
1169 return "";
1170 }
1171 TSQLRow* row = resQ->Next();
1172 if (row == nullptr) {
1173 LOG(info) << "Material file of the setup was not found in the Geometry Database";
1174 delete resQ;
1175 return "";
1176 }
1177
1178 // the field points to the memory owned by the row, so it has to be copied before the row is deleted
1179 const char* file = row->GetField(0);
1180 m_materialFile = (file != nullptr ? file : "");
1181 delete row;
1182 delete resQ;
1183
1184 return m_materialFile;
1185}
1186
1187// expanded value of the GEOMPATH environment variable (the storage of the Local Geometry Database) without the
1188// trailing slashes; "" if it is not set or cannot be expanded
1190{
1191 const char* env_p = getenv("GEOMPATH");
1192 if (env_p == nullptr || env_p[0] == '\0') {
1193 LOG(debug1) << "GEOMPATH environment variable is not set";
1194 return "";
1195 }
1196 // the TString overload reports an error by the return value and, unlike the char* one,
1197 // does not allocate a buffer that has to be deleted by the caller
1198 TString path(env_p);
1199 if (gSystem->ExpandPathName(path)) {
1200 LOG(error) << "Cannot expand the GEOMPATH value: " << env_p;
1201 return "";
1202 }
1203 while (path.Length() > 1 && path.EndsWith("/"))
1204 path.Chop();
1205
1206 return string(path.Data());
1207}
1208
1209// get path to the storage of the Local Geometry Database (GEOMPATH) with the trailing slash
1211{
1212 string storagePath = ExpandGeomPath();
1213 if (storagePath.empty())
1214 return "";
1215
1216 return storagePath + "/";
1217}
1218
1219// get path to the file of the Local Geometry Database, which is located in the parent directory of its storage. The
1220// parent directory is taken from the path string instead of "storage/..", so that the storage linked to another place
1221// (e.g. to a shared disk) does not move the database file there
1223{
1224 string storagePath = ExpandGeomPath();
1225 if (storagePath.empty())
1226 return "";
1227
1228 return string(gSystem->GetDirName(storagePath.c_str()).Data()) + "/local.db";
1229}
1230
1231// get path to a temporary directory (/tmp/$USER/), and create if absent
1233{
1234 if (m_tmpFolder.Length() != 0)
1235 return m_tmpFolder;
1236
1237 UserGroup_t* user = gSystem->GetUserInfo();
1238 string login(user->fUser.Data());
1239 delete user;
1240 m_tmpFolder = "/tmp/" + login + "/";
1241 system("mkdir -p " + m_tmpFolder);
1242
1243 return m_tmpFolder;
1244}
1245
1246// load local settings from the file for all setup modules
1247bool GeoSetup::LoadLocalSettings(const char* fileName)
1248{
1249 LOG(info) << "Load local settings of geometry DB from '" << fileName << "'";
1250 TXMLEngine xml;
1251 XMLDocPointer_t xmldoc = xml.ParseFile(fileName);
1252 if (xmldoc == nullptr) {
1253 LOG(error) << "Selected file has not XML format: " << fileName;
1254 return false;
1255 }
1256
1257 XMLNodePointer_t mainnode = xml.DocGetRootElement(xmldoc);
1258 if (TString(xml.GetNodeName(mainnode)) != "setup")
1259 LOG(warning) << "The root element of the local settings is <" << xml.GetNodeName(mainnode)
1260 << "> instead of <setup>";
1261
1262 // all the elements are parsed to report all the errors at once; a misspelled element or attribute is an error
1263 // as well, because otherwise the requested change is silently not applied
1264 bool isCorrect = true;
1265 for (XMLNodePointer_t child = xml.GetChild(mainnode); child != nullptr; child = xml.GetNext(child)) {
1266 TString chName = xml.GetNodeName(child);
1267 bool isParsed = false;
1268 if (chName == "editSetupModule")
1269 isParsed = ParseEditSetupModule(xml, child);
1270 else if (chName == "addSetupModule")
1271 isParsed = ParseAddSetupModule(xml, child);
1272 else if (chName == "editFieldMap")
1273 isParsed = ParseEditFieldMap(xml, child);
1274 else
1275 LOG(error) << "Unknown element of the local settings: <" << chName
1276 << ">, the allowed ones are <editSetupModule>, <addSetupModule>, <editFieldMap>";
1277 if (!isParsed)
1278 isCorrect = false;
1279 }
1280
1281 xml.FreeDoc(xmldoc);
1282 return isCorrect;
1283}
1284
1285// parse the 'editSetupModule' element of the local settings: change or disable a module of the setup
1287{
1288 setup_module_ptr sNode = new setup_module();
1289 sNode->xMove = 0;
1290 sNode->yMove = 0;
1291 sNode->zMove = 0;
1292 sNode->enable = true;
1293 sNode->type = TString("");
1294 TString module_name = "";
1295
1296 bool isCorrect = true;
1297 for (XMLAttrPointer_t attr = xml.GetFirstAttr(node); attr != nullptr; attr = xml.GetNextAttr(attr)) {
1298 TString aName = xml.GetAttrName(attr);
1299 TString aValue = xml.GetAttrValue(attr);
1300 LOG(debug1) << "attr: " << aName << " value: " << aValue;
1301 if (aName == "tag") {
1302 aValue.ToUpper();
1303 sNode->type = aValue.Strip(TString::kBoth);
1304 } else if (aName == "module") {
1305 aValue.ToUpper();
1306 module_name = aValue.Strip(TString::kBoth);
1307 } else if (aName == "enable")
1308 isCorrect &= AttrToBool(aName, aValue, sNode->enable);
1309 else if (aName == "file_path") {
1310 gSystem->ExpandPathName(aValue);
1311 sNode->file_path = aValue;
1312 } else if (aName == "moveX")
1313 isCorrect &= AttrToDouble(aName, aValue, sNode->xMove);
1314 else if (aName == "moveY")
1315 isCorrect &= AttrToDouble(aName, aValue, sNode->yMove);
1316 else if (aName == "moveZ")
1317 isCorrect &= AttrToDouble(aName, aValue, sNode->zMove);
1318 else {
1319 LOG(error) << "Unknown attribute '" << aName << "' of the <editSetupModule> element, the allowed ones are "
1320 << "tag, module, enable, file_path, moveX, moveY, moveZ";
1321 isCorrect = false;
1322 }
1323 }
1324 if (sNode->type.IsNull() && module_name.IsNull()) {
1325 LOG(error) << "Neither 'tag' nor 'module' attribute is set for the <editSetupModule> element";
1326 isCorrect = false;
1327 }
1328 // the geometry file is not needed for a disabled module
1329 if (sNode->enable && !sNode->file_path.IsNull() && !FindModuleGeometryFile(sNode->file_path))
1330 isCorrect = false;
1331 if (!isCorrect) {
1332 delete sNode;
1333 return false;
1334 }
1335
1336 // the setup module can be selected by its tag ('tag') or by the name of its module ('module'), the
1337 // 'module="*"' value selects all the detector modules of the setup
1338 if (!sNode->type.IsNull()) {
1339 if (!module_name.IsNull())
1340 LOG(warning) << "Both 'tag' and 'module' attributes are set for the setup module, the tag is used: "
1341 << sNode->type;
1342 PutModuleEdit(m_moduleEdit, sNode->type, sNode);
1343 } else if (module_name == "*") {
1344 if (m_moduleEditAll != nullptr) {
1345 LOG(warning) << "All the detector modules (module=\"*\") are customized more than once, "
1346 "the latest settings are used";
1347 delete m_moduleEditAll;
1348 }
1349 m_moduleEditAll = sNode;
1350 } else
1351 PutModuleEdit(m_moduleEditByName, module_name, sNode);
1352
1353 return true;
1354}
1355
1356// parse the 'addSetupModule' element of the local settings: add a new module to the setup
1358{
1359 module_r_ptr module = new module_r();
1360 bool isCorrect = true;
1361 for (XMLAttrPointer_t attr = xml.GetFirstAttr(node); attr != nullptr; attr = xml.GetNextAttr(attr)) {
1362 TString aName = xml.GetAttrName(attr);
1363 TString aValue = xml.GetAttrValue(attr);
1364 LOG(debug1) << "attr: " << aName << " value: " << aValue;
1365 if (aName == "class_name")
1366 module->class_name = aValue.Strip(TString::kBoth);
1367 else if (aName == "object_name")
1368 module->object_name = aValue.Strip(TString::kBoth);
1369 else if (aName == "active")
1370 isCorrect &= AttrToBool(aName, aValue, module->active);
1371 else if (aName == "file_path") {
1372 gSystem->ExpandPathName(aValue);
1373 module->file_path = aValue;
1374 } else if (aName == "moveX")
1375 isCorrect &= AttrToDouble(aName, aValue, module->xMove);
1376 else if (aName == "moveY")
1377 isCorrect &= AttrToDouble(aName, aValue, module->yMove);
1378 else if (aName == "moveZ")
1379 isCorrect &= AttrToDouble(aName, aValue, module->zMove);
1380 else {
1381 LOG(error) << "Unknown attribute '" << aName << "' of the <addSetupModule> element, the allowed ones are "
1382 << "class_name, object_name, active, file_path, moveX, moveY, moveZ";
1383 isCorrect = false;
1384 }
1385 }
1386 if (module->class_name.IsNull() || module->object_name.IsNull() || module->file_path.IsNull()) {
1387 LOG(error) << "The 'class_name', 'object_name' and 'file_path' attributes are required for the "
1388 "<addSetupModule> element";
1389 isCorrect = false;
1390 } else {
1391 // the class and the name are checked here to report the errors before the setup is loaded
1392 TClass* module_class = TClass::GetClass(module->class_name);
1393 if (module_class == nullptr || !module_class->InheritsFrom(FairModule::Class())) {
1394 LOG(error) << "No '" << module->class_name << "' class inherited from FairModule is found for the '"
1395 << module->object_name << "' module";
1396 isCorrect = false;
1397 }
1398 if (!IsSafeTag(module->object_name.Data())) {
1399 LOG(error) << "Wrong object name of the module: '" << module->object_name
1400 << "', only letters, digits, '_', '.' and '-' are allowed";
1401 isCorrect = false;
1402 }
1403 if (!FindModuleGeometryFile(module->file_path))
1404 isCorrect = false;
1405 }
1406 if (!isCorrect) {
1407 delete module;
1408 return false;
1409 }
1410
1411 m_moduleAdd.push_back(module);
1412 return true;
1413}
1414
1415// parse the 'editFieldMap' element of the local settings: replace the field map of the setup
1417{
1418 TString file_path = "";
1419 bool isCorrect = true;
1420 for (XMLAttrPointer_t attr = xml.GetFirstAttr(node); attr != nullptr; attr = xml.GetNextAttr(attr)) {
1421 TString aName = xml.GetAttrName(attr);
1422 TString aValue = xml.GetAttrValue(attr);
1423 if (aName == "file_path") {
1424 gSystem->ExpandPathName(aValue);
1425 file_path = aValue;
1426 } else {
1427 LOG(error) << "Unknown attribute '" << aName << "' of the <editFieldMap> element, the allowed one is "
1428 << "file_path";
1429 isCorrect = false;
1430 }
1431 }
1432 if (file_path.IsNull()) {
1433 LOG(error) << "The 'file_path' attribute is required for the <editFieldMap> element";
1434 return false;
1435 }
1436 // the map file is searched for in the same way as the field map does it
1437 TString mapFilePath = BmnFieldMap::GetMapFilePath(file_path);
1438 if (gSystem->AccessPathName(mapFilePath, kReadPermission)) {
1439 LOG(error) << "No file of the magnetic field map is found: " << mapFilePath;
1440 return false;
1441 }
1442 if (!isCorrect)
1443 return false;
1444
1445 if (!m_ExternalField.IsNull())
1446 LOG(warning) << "The magnetic field map is changed more than once, the latest one is used";
1447 m_ExternalField = file_path;
1448 return true;
1449}
1450
1451// delete the loaded local settings of the geometry
1453{
1454 for (auto& item : m_moduleEdit)
1455 delete item.second;
1456 m_moduleEdit.clear();
1457 for (auto& item : m_moduleEditByName)
1458 delete item.second;
1459 m_moduleEditByName.clear();
1460 delete m_moduleEditAll;
1461 m_moduleEditAll = nullptr;
1462 for (module_r_ptr module : m_moduleAdd)
1463 delete module;
1464 m_moduleAdd.clear();
1465 m_ExternalField = "";
1466}
1467
1468// find the geometry file of a module set by the local settings and check that it contains a geometry
1470{
1471 // a relative path is searched for as FairRoot does it: in $GEOMPATH, i.e. in the storage of the Local Geometry
1472 // Database, and then in $VMCWORKDIR/geometry
1473 vector<TString> candidates;
1474 if (gSystem->IsAbsoluteFileName(file_path))
1475 candidates.push_back(file_path);
1476 else {
1477 string storagePath = GetRootPath();
1478 if (!storagePath.empty())
1479 candidates.push_back(TString(storagePath) + file_path);
1480 const char* workDir = getenv("VMCWORKDIR");
1481 if (workDir != nullptr && workDir[0] != '\0')
1482 candidates.push_back(TString(workDir) + "/geometry/" + file_path);
1483 }
1484
1485 TString foundPath = "";
1486 for (TString& candidate : candidates) {
1487 gSystem->ExpandPathName(candidate);
1488 candidate.ReplaceAll("//", "/");
1489 FileStat_t file_stat;
1490 if (gSystem->GetPathInfo(candidate, file_stat) == 0 && !R_ISDIR(file_stat.fMode)
1491 && !gSystem->AccessPathName(candidate, kReadPermission))
1492 {
1493 foundPath = candidate;
1494 break;
1495 }
1496 }
1497 if (foundPath.IsNull()) {
1498 LOG(error) << "No geometry file '" << file_path << "' is found"
1499 << (gSystem->IsAbsoluteFileName(file_path) ? ""
1500 : " in $GEOMPATH (the storage of the Local Geometry "
1501 "Database) and $VMCWORKDIR/geometry");
1502 return false;
1503 }
1504
1505 // the geometry in the ASCII format (.geo) is read by FairRoot itself, the ROOT file is checked by the same rule as
1506 // FairRoot reads it: a geometry manager under any key, otherwise a volume under the first key; FairRoot crashes on
1507 // another file during the initialization
1508 if (foundPath.EndsWith(".root")) {
1509 bool hasGeometry = false;
1510 TFile* f = TFile::Open(foundPath, "READ");
1511 if (f != nullptr && !f->IsZombie()) {
1512 bool isFirstKey = true;
1513 TIter nextKey(f->GetListOfKeys());
1514 while (TKey* key = (TKey*)nextKey()) {
1515 TClass* keyClass = TClass::GetClass(key->GetClassName());
1516 if (keyClass != nullptr
1517 && (keyClass->InheritsFrom(TGeoManager::Class())
1518 || (isFirstKey && keyClass->InheritsFrom(TGeoVolume::Class()))))
1519 {
1520 hasGeometry = true;
1521 break;
1522 }
1523 isFirstKey = false;
1524 }
1525 }
1526 delete f;
1527 if (!hasGeometry) {
1528 LOG(error) << "The geometry file is damaged or contains no geometry (a geometry manager or a volume as the "
1529 "first object): "
1530 << foundPath;
1531 return false;
1532 }
1533 }
1534
1535 file_path = foundPath;
1536 return true;
1537}
1538
1539// write the geometry of the module to a temporary ROOT file with a new position of the module
1541 const TString& module_name,
1542 const TGeoMatrix* placement,
1543 double xMove,
1544 double yMove,
1545 double zMove)
1546{
1547 if (!file_path.EndsWith(".root")) {
1548 LOG(error) << "ERROR: the position of the module can be changed only for the geometry in a ROOT file: "
1549 << file_path;
1550 return "";
1551 }
1552
1553 TGeoManager* geom = new TGeoManager(module_name, TString::Format("Geometry of the %s module", module_name.Data()));
1554 LOG(debug1) << "import file" << file_path << endl;
1555 TFile* f = new TFile(file_path);
1556 if (f->IsZombie() || !f->IsOpen()) {
1557 LOG(error) << "ERROR: could not open ROOT file with the module geometry: " << file_path;
1558 delete f;
1559 delete geom;
1560 return "";
1561 }
1562 TGeoVolume* root_volume = GetRootVolume(f);
1563 TGeoNodeMatrix* node = (root_volume == nullptr) ? nullptr : dynamic_cast<TGeoNodeMatrix*>(root_volume->GetNode(0));
1564 if (node == nullptr) {
1565 LOG(error) << "ERROR: no geometry volume with a position matrix found in the file: " << file_path;
1566 f->Close();
1567 delete f;
1568 delete geom;
1569 return "";
1570 }
1571
1572 // the whole matrix is copied, so the rotation of the module is kept, only the translation is shifted
1573 TGeoHMatrix* matrix = new TGeoHMatrix((placement != nullptr) ? *placement : *node->GetMatrix());
1574 const Double_t* translation = matrix->GetTranslation();
1575 matrix->SetDx(translation[0] + xMove);
1576 matrix->SetDy(translation[1] + yMove);
1577 matrix->SetDz(translation[2] + zMove);
1578 node->SetMatrix(matrix);
1579
1580 // the file name is unique for the process and the module, so parallel jobs and several modules with the same name,
1581 // e.g. the sections of the beam pipe, do not overwrite the files of each other
1582 static int exportCount = 0;
1583 TString out = GetTmpFileName(TString::Format("%s_%d", module_name.Data(), ++exportCount).Data()) + ".root";
1584 root_volume->Export(out.Data());
1585 LOG(debug1) << "Exporting geometry to ROOT file: " << out;
1586 if (gTmpGeometryPid == 0) {
1587 gTmpGeometryPid = getpid();
1588 atexit(RemoveTmpGeometryFiles);
1589 }
1590 gTmpGeometryFiles.push_back(out.Data());
1591
1592 delete geom;
1593 f->Close();
1594 delete f;
1595 return out;
1596}
1597
1598// create the module object of the given class with the given module name
1599FairModule* GeoSetup::CreateModule(const TString& class_name, const TString& module_name, bool isActive)
1600{
1601 TClass* module_class = TClass::GetClass(class_name);
1602 if (module_class == nullptr || !module_class->InheritsFrom(FairModule::Class())) {
1603 LOG(error) << "ERROR: no '" << class_name << "' class inherited from FairModule is found for the '"
1604 << module_name << "' module";
1605 return nullptr;
1606 }
1607 // the names are put into the interpreted code, so the canonical name of the found class is used and the name of
1608 // the module can contain only the characters of the names
1609 if (!IsSafeTag(module_name.Data())) {
1610 LOG(error) << "ERROR: wrong name of the module: '" << module_name
1611 << "', only letters, digits, '_', '.' and '-' are allowed";
1612 return nullptr;
1613 }
1614
1615 // the constructor is a method with the class name without the namespace
1616 TString constructor_name = module_class->GetName();
1617 Ssiz_t namespaceEnd = constructor_name.Last(':');
1618 if (namespaceEnd != kNPOS)
1619 constructor_name.Remove(0, namespaceEnd + 1);
1620
1621 TString command = TString::Format("new %s(\"%s\"", module_class->GetName(), module_name.Data());
1622 if (module_class->GetMethodWithPrototype(constructor_name, "const char*,Bool_t") != nullptr)
1623 command += isActive ? ",kTRUE)" : ",kFALSE)";
1624 else {
1625 if (isActive)
1626 LOG(info) << "The " << module_class->GetName() << " class has no active flag, so the '" << module_name
1627 << "' module is added as a passive one";
1628 command += ")";
1629 }
1630 LOG(debug1) << "command:" << command;
1631
1632 FairModule* obj = (FairModule*)gInterpreter->Calc(command);
1633 if (obj == nullptr)
1634 LOG(error) << "ERROR: cannot create the module by the command: " << command;
1635
1636 return obj;
1637}
1638
1639// get local settings for the setup module: by the tag of the setup module, then by the name of its module, then by the
1640// settings for all the detector modules ('module="*"')
1641setup_module_ptr GeoSetup::FindModuleEdit(TString setup_module_tag, TString module_name, int dbModuleRev)
1642{
1643 setup_module_tag.ToUpper();
1644 map<TString, setup_module_ptr>::iterator itr = m_moduleEdit.find(setup_module_tag);
1645 if (itr != m_moduleEdit.end())
1646 return itr->second;
1647
1648 module_name.ToUpper();
1649 itr = m_moduleEditByName.find(module_name);
1650 if (itr != m_moduleEditByName.end())
1651 return itr->second;
1652
1653 // the settings for all the modules are applied to the detectors only, so the passive elements of the setup (the
1654 // cave, the magnet, the target and the beam pipe) are always kept
1655 if (m_moduleEditAll != nullptr) {
1656 map<int, bool>::iterator it_active = m_modules_active.find(GetModuleId(dbModuleRev));
1657 if (it_active != m_modules_active.end() && it_active->second)
1658 return m_moduleEditAll;
1659 }
1660
1661 return nullptr;
1662}
1663
1664// get module name by index; return "Unknown" if not found
1666{
1667 map<int, TString>::iterator it = m_modules_table.find(dbModuleUndex);
1668 if (it != m_modules_table.end())
1669 return it->second;
1670 else {
1671 LOG(error) << "Unknown module type with id=" << dbModuleUndex;
1672 return TString("Unknown");
1673 }
1674}
1675
1676// get module index by name; return -1 if not found
1678{
1679 map<int, TString>::iterator it;
1680 for (it = m_modules_table.begin(); it != m_modules_table.end(); ++it)
1681 if ((it->second).CompareTo(name, TString::ECaseCompare::kIgnoreCase) == 0)
1682 return it->first;
1683
1684 return -1;
1685}
1686
1687// get module_r_ptr (pointer to the module revision) by revision number
1689{
1690 map<int, module_r_ptr>::iterator it = m_modules_revision_table.find(dbModuleRev);
1691 if (it != m_modules_revision_table.end())
1692 return it->second; //.class_name;
1693
1694 module_r_ptr mr = nullptr;
1695 return mr;
1696}
1697
1698// get module ID by revision number; return -1 if not found
1699int GeoSetup::GetModuleId(int dbModuleRev)
1700{
1701 map<int, module_r_ptr>::iterator it = m_modules_revision_table.find(dbModuleRev);
1702 if (it != m_modules_revision_table.end())
1703 return it->second->idm;
1704
1705 return -1;
1706}
1707
1708// get module type by revision number
1710{
1711 return GetModuleName(GetModuleId(dbModuleRev));
1712}
1713
1714// get root volume in the TFile object (first search for TGeoManager)
1716{
1717 TKey* key;
1718 TGeoManager* geoManager = nullptr;
1719 TList* l = f->GetListOfKeys();
1720 TIter next(l);
1721 while ((key = (TKey*)next())) {
1722 if (strcmp(key->GetClassName(), "TGeoManager") != 0)
1723 continue;
1724 geoManager = (TGeoManager*)key->ReadObj();
1725 geoManager->cd();
1726 TGeoNode* top = geoManager->GetNode(0);
1727 if (top == nullptr || top->GetNdaughters() == 0) {
1728 LOG(error) << "ERROR: geometry in the file " << f->GetName() << " has no daughter volume";
1729 return nullptr;
1730 }
1731 return (TGeoVolume*)top->GetDaughter(0)->GetVolume();
1732 }
1733
1734 // if TGeoManager was not found in the file
1735 key = (TKey*)l->At(0); // Get the first key in the list
1736 if (key == nullptr) {
1737 LOG(error) << "ERROR: no keys found in the geometry file " << f->GetName();
1738 return nullptr;
1739 }
1740 TGeoVolume* volume = dynamic_cast<TGeoVolume*>(key->ReadObj());
1741
1742 return volume;
1743}
1744
1745// add FairModule defined by revision number and geometry file path to the FairRunSim instance
1746bool GeoSetup::AddModuleToFairRunSim(int dbModuleRev, const char* path, FairRunSim* fRun)
1747{
1748 module_r_ptr mr = GetModuleRevision(dbModuleRev);
1749 if (mr == nullptr) {
1750 LOG(error) << "ERROR: no module revision with id=" << dbModuleRev << " in the Geometry Database";
1751 return false;
1752 }
1753
1754 // TClass* cl = TClass::GetClass(mr->class_name);
1755 // FairModule* f_cl = (FairModule*) cl->New();
1756 // cout<<"TClass:"<<cl<<endl; f_cl->Dump();
1757
1758 TString type_name;
1759 if (mr->object_name.Length() > 0) {
1760 type_name = mr->object_name;
1761 // f_cl->SetName(mr.object_name);
1762 } else {
1763 type_name = GetModuleType(dbModuleRev);
1764 // f_cl->SetName(getModuleType(dbModuleRev));
1765 }
1766
1767 FairModule* obj = CreateModule(mr->class_name, type_name, mr->active);
1768 if (obj == nullptr)
1769 return false;
1770 obj->SetGeometryFileName(path);
1771 fRun->AddModule(obj);
1772
1773 // cerr<<"dbModuleRev="<<dbModuleRev<<" idmr="<<mr.idmr<<" idm="<<mr.idm<<" class_name="<<typeid(f_cl).name()<<endl;
1774 return true;
1775}
1776
1777// add the module from the local settings ('addSetupModule' element) to the FairRunSim instance
1779{
1780 if (module == nullptr)
1781 return false;
1782
1783 // a module with the same name overlaps the geometry and renames the branches of the MC points of both modules
1784 // (e.g. VSPPoint_1 and VSPPoint_2), and the second cave replaces the top volume of the setup
1785 TClass* module_class = TClass::GetClass(module->class_name);
1786 bool isCave = (module_class != nullptr && module_class->InheritsFrom("FairCave"));
1787 TIter nextModule(fRun->GetListOfModules());
1788 while (FairModule* runModule = (FairModule*)nextModule()) {
1789 if (module->object_name == runModule->GetName() || (isCave && runModule->InheritsFrom("FairCave"))) {
1790 LOG(error) << "ERROR: the '" << module->object_name
1791 << "' module is not added, because the setup already has the '" << runModule->GetName()
1792 << "' module (" << runModule->ClassName()
1793 << "). Use the <editSetupModule> element with the 'file_path' attribute to replace the "
1794 "geometry of a setup module";
1795 return false;
1796 }
1797 }
1798
1799 TString geo_file = module->file_path;
1800 bool isMoved = (module->xMove != 0 || module->yMove != 0 || module->zMove != 0);
1801 if (isMoved) {
1802 geo_file = ExportModuleGeometry(module->file_path, module->object_name, nullptr, module->xMove, module->yMove,
1803 module->zMove);
1804 if (geo_file.IsNull())
1805 return false;
1806 }
1807
1808 FairModule* obj = CreateModule(module->class_name, module->object_name, module->active);
1809 if (obj == nullptr)
1810 return false;
1811 obj->SetGeometryFileName(geo_file);
1812 fRun->AddModule(obj);
1813 LOG(info) << "\033[0;32mAdded external detector: name=" << module->object_name << " file_path=" << module->file_path
1814 << " class_name=" << module->class_name << " isActive=" << module->active << "\033[0m";
1815 if (isMoved)
1816 LOG(info) << "\033[0;32mThe position of the '" << module->object_name << "' module was shifted by ("
1817 << module->xMove << ", " << module->yMove << ", " << module->zMove << ") cm\033[0m";
1818 return true;
1819}
1820
1822{
1823 TFile* f = new TFile(fileName);
1824 if (f->IsZombie() || !f->IsOpen()) {
1825 LOG(error) << "ERROR: could not open ROOT file with geometry: " << fileName;
1826 delete f;
1827 return nullptr;
1828 }
1829 // the node of the module is the same as the one, whose position is changed by ExportModuleGeometry, also for the
1830 // file with the whole geometry manager, where it is placed in the first volume of the top one (not the top node)
1831 TGeoVolume* root_volume = GetRootVolume(f);
1832 TGeoNode* node = (root_volume == nullptr) ? nullptr : root_volume->GetNode(0);
1833 f->Close();
1834 delete f;
1835 return node;
1836}
1837
1838bool GeoSetup::IsEqlMatrix(const char* fileName, TSQLRow* row)
1839{
1840 if (row == NULL || fileName == NULL)
1841 return false;
1842 bool res = true;
1843 try {
1844 // cerr<<"Start compare fileName:"<<fileName<<endl;
1845 TGeoNode* node = ConstructRootGeometry(fileName);
1846 if (node == NULL)
1847 return false;
1848 const Double_t* tran = node->GetMatrix()->GetTranslation(); // 3
1849 // const Double_t * sc = node->GetMatrix()->GetScale();//3
1850 const Double_t* rot = node->GetMatrix()->GetRotationMatrix(); // 9
1851 unsigned int i;
1852 for (i = 0; i < 3; i++) {
1853 double t = FieldToDouble(row->GetField(3 + i));
1854 if (tran[i] != t) {
1855 LOG(debug1) << " for i=" << i << " tran[i]=" << tran[i] << " t=" << t << endl;
1856 res = false;
1857 }
1858 }
1859 for (i = 0; i < 9; i++) {
1860 double t = FieldToDouble(row->GetField(6 + i));
1861 if (rot[i] != t) {
1862 LOG(debug1) << " for i=" << i << " rot[i]=" << rot[i] << " t=" << t << endl;
1863 res = false;
1864 }
1865 }
1866 } catch (...) {
1867 return false;
1868 }
1869 return res;
1870}
1871// load one module from the Geometry Database and add to the FairRunSim instance
1873{
1874 map<int, TString>::iterator it = m_loadedModule.find(idsm);
1875 if (it != m_loadedModule.end())
1876 return 0;
1877 // mark the module as being loaded to break possible parent_id loops in the database
1878 m_loadedModule.insert(pair<int, TString>(idsm, ""));
1879
1880 LOG(debug1) << "Start load setup_module_id=" << idsm;
1881 ostringstream stringStream;
1882 stringStream << "select "
1883 "f.module_id,f.file_name,sm.parent_id,sm.tx,sm.ty,sm.tz,r11,r12,r13,r21,r22,r23,r31,r32,r33,sm."
1884 "setup_module_tag "
1885 "from setup_module sm INNER JOIN geometry_file f ON f.file_id=sm.file_id where sm.setup_module_id="
1886 << idsm << ";";
1887
1888 TSQLResult* resQ = m_db->Query(stringStream.str().c_str());
1889 // an empty result is detected by the first row, because SQLite does not provide the row count (-1)
1890 TSQLRow* row = (resQ == nullptr) ? nullptr : resQ->Next();
1891 if (row == nullptr) {
1892 LOG(error) << "ERROR: no file for the setup module (" << idsm << ") was found";
1893 delete resQ;
1894 return -1;
1895 }
1896 int dbModuleIndex = FieldToInt(row->GetField(0));
1897 int idP = FieldToInt(row->GetField(2), -1);
1898 LOG(debug1) << "idP=" << idP;
1899 if (idP != -1) {
1900 int res = LoadModuleToFairRunSim(idP, fRun);
1901 if (res < 0) {
1902 delete row;
1903 delete resQ;
1904 return res;
1905 }
1906 }
1907
1908 stringStream.str("");
1909 LOG(debug1) << row->GetField(1);
1910 stringStream << GetRootPath().c_str() << (row->GetField(1) != nullptr ? row->GetField(1) : "");
1911
1912 TString mName = GetModuleType(dbModuleIndex), out = "";
1913 mName.ToUpper();
1914 bool isEnable = true;
1915 TString smTag = row->GetField(15);
1916 TString file_path = stringStream.str().c_str();
1917 smTag.ToUpper();
1918
1919 // the module of the setup, which cannot be created (e.g. its class is not found), is an error of the setup
1920 bool isAdded = true;
1921 if (mName == TString("CAVE") || ((TString)stringStream.str()).EndsWith(".geo")) {
1922 bool isFind = false;
1923 setup_module_ptr moduleEdit = FindModuleEdit(smTag, mName, dbModuleIndex);
1924 if (moduleEdit != nullptr) {
1925 LOG(debug1) << "detector was found";
1926 isEnable = moduleEdit->enable;
1927 if (isEnable) {
1928 // the position of the cave and of the modules in the ASCII format is defined by the file itself
1929 if (moduleEdit->xMove != 0 || moduleEdit->yMove != 0 || moduleEdit->zMove != 0) {
1930 LOG(error) << "ERROR: the position of the module with tag=" << smTag
1931 << " cannot be changed by the local settings, because it is the cave or its geometry "
1932 "is in the ASCII format (.geo)";
1933 delete row;
1934 delete resQ;
1935 return -3;
1936 }
1937 if (moduleEdit->file_path.Length() > 0) {
1938 file_path = moduleEdit->file_path;
1939 isFind = true;
1940 }
1941 }
1942 }
1943 if (isEnable) {
1944 // a second cave replaces the top volume, so all the detectors are left outside the setup geometry
1945 bool isDuplicateCave = false;
1946 if (mName == TString("CAVE")) {
1947 TIter nextModule(fRun->GetListOfModules());
1948 while (TObject* module = nextModule())
1949 if (module->InheritsFrom("FairCave")) {
1950 isDuplicateCave = true;
1951 break;
1952 }
1953 }
1954 if (isDuplicateCave)
1955 LOG(warning) << "The cave has been already added, so the duplicate cave module with tag=" << smTag
1956 << " is skipped. Please, remove it from the setup in the Geometry Database";
1957 else {
1958 if (isFind)
1959 LOG(info) << "\033[38;2;255;165;0mEdit module with tag=" << smTag
1960 << " use local settings. New path: " << file_path << "\033[0m";
1961 else
1962 LOG(info) << "Loading module with tag=" << smTag;
1963 isAdded = AddModuleToFairRunSim(dbModuleIndex, file_path, fRun);
1964 }
1965 } else
1966 LOG(info) << "\033[0;31mDisable module with tag=" << smTag << " use local settings.\033[0m";
1967 } else {
1968 double mx = 0, my = 0, mz = 0;
1969 bool isFind = false;
1970 setup_module_ptr moduleEdit = FindModuleEdit(smTag, mName, dbModuleIndex);
1971 LOG(debug1) << "detector " << dbModuleIndex;
1972 if (moduleEdit != nullptr) {
1973 isFind = true;
1974 LOG(debug1) << "detector was found";
1975 isEnable = moduleEdit->enable;
1976 if (isEnable) {
1977 mx = moduleEdit->xMove;
1978 my = moduleEdit->yMove;
1979 mz = moduleEdit->zMove;
1980 if (moduleEdit->file_path.Length() > 0)
1981 file_path = moduleEdit->file_path;
1982 LOG(debug1) << "Move detector " << dbModuleIndex << " to x:" << mx << " to y:" << my << " to z:" << mz;
1983 }
1984 }
1985 // the geometry in the ASCII format (.geo), e.g. the one replacing the module by the local settings, has no
1986 // matrix of the module, so it is used as it is, and its position cannot be changed
1987 bool isAscii = file_path.EndsWith(".geo");
1988 if (isEnable && isAscii && (mx != 0 || my != 0 || mz != 0)) {
1989 LOG(error) << "ERROR: the position of the module with tag=" << smTag
1990 << " cannot be changed by the local settings, because its geometry is in the ASCII format";
1991 delete row;
1992 delete resQ;
1993 return -3;
1994 }
1995 // the file used for the module (also the one replaced by the local settings) is taken as it is only if the
1996 // module is placed in it at the position of the setup module, otherwise it is moved to this position
1997 if (isEnable && mx == 0 && my == 0 && mz == 0 && (isAscii || IsEqlMatrix(file_path, row))) {
1998 LOG(debug1) << "The same matrix for file=" << file_path << endl;
1999 if (isFind)
2000 LOG(info) << "\033[38;2;255;165;0mEdit module with tag=" << smTag
2001 << " use local settings. New path: " << file_path << "\033[0m";
2002 else
2003 LOG(info) << "Loading module with tag=" << smTag;
2004 isAdded = AddModuleToFairRunSim(dbModuleIndex, file_path, fRun);
2005 } else if (isEnable) {
2006 // the module is placed at the position of the setup module in the Geometry Database (with its rotation)
2007 // shifted by the local settings
2008 TGeoHMatrix placement;
2009 Double_t translation[3], rotation[9];
2010 for (int i = 0; i < 3; i++)
2011 translation[i] = FieldToDouble(row->GetField(3 + i));
2012 for (int i = 0; i < 9; i++)
2013 rotation[i] = FieldToDouble(row->GetField(6 + i));
2014 placement.SetTranslation(translation);
2015 placement.SetRotation(rotation);
2016 out = ExportModuleGeometry(file_path, mName, &placement, mx, my, mz);
2017 if (out.IsNull()) {
2018 delete row;
2019 delete resQ;
2020 return -1;
2021 }
2022 if (isFind)
2023 LOG(info) << "\033[38;2;255;165;0mEdit module with tag=" << smTag
2024 << " use local settings. New path: " << file_path << ". The position was changed.\033[0m";
2025 else
2026 LOG(info) << "Loading module with tag=" << smTag;
2027 isAdded = AddModuleToFairRunSim(dbModuleIndex, out.Data(), fRun);
2028 } else
2029 LOG(info) << "\033[0;31mDisable module with tag=" << smTag << " use local settings.\033[0m";
2030 }
2031 m_loadedModule[idsm] = out;
2032
2033 delete row;
2034 delete resQ;
2035 return isAdded ? 0 : -2;
2036}
2037
2038// fill table with modules (m_modules_table) from the Geometry Database
2040{
2041 bool isActiveKnown = true;
2042 TSQLResult* resQ = m_db->Query("select module_id,module_name,active from module;");
2043 if (resQ == nullptr) {
2044 // temporary, for support of old database versions without the 'active' column
2045 isActiveKnown = false;
2046 LOG(warning)
2047 << "The Geometry Database does not provide the 'active' flag of the modules, so the 'module=\"*\"' "
2048 "local setting of the geometry will be ignored. Please, update the Geometry Database";
2049 resQ = m_db->Query("select module_id,module_name from module;");
2050 }
2051 if (resQ == nullptr) {
2052 LOG(error) << "ERROR: SQL query was failed. Please, check connection to the Geometry Database and "
2053 "GEOMPATH variable is correct";
2054 return -1;
2055 }
2056 // the empty table is detected by the number of the rows, because SQLite does not provide the row count (-1)
2057 int rowCount = 0;
2058 TSQLRow* row;
2059 while ((row = resQ->Next()) != 0) {
2060 rowCount++;
2061 int id = FieldToInt(row->GetField(0));
2062 TString name(row->GetField(1));
2063 m_modules_table.insert(make_pair(id, name));
2064 // the module is considered as a passive element of the setup if the flag is not defined
2065 if (isActiveKnown)
2066 m_modules_active.insert(make_pair(id, FieldToInt(row->GetField(2)) != 0));
2067 delete row;
2068 }
2069
2070 delete resQ;
2071 if (rowCount == 0) {
2072 LOG(error) << "ERROR: no modules in the Geometry Database";
2073 return -2;
2074 }
2075 return 0;
2076}
2077
2078// fill table with module revisions (m_modules_revision_table) from the Geometry Database
2080{
2081 TSQLResult* resQ = m_db->Query("select module_class_id,mc.module_id,class_name,revision,active,object_name from "
2082 "module_class as mc INNER JOIN module as m ON mc.module_id=m.module_id;");
2083 if (resQ == nullptr) {
2084 LOG(error) << "ERROR: SQL query was failed. Please, check connection to the Geometry Database and "
2085 "GEOMPATH variable is correct";
2086 return -1;
2087 }
2088 // the empty table is detected by the number of the rows, because SQLite does not provide the row count (-1)
2089 int rowCount = 0;
2090 TSQLRow* row;
2091 while ((row = resQ->Next()) != 0) {
2092 rowCount++;
2093 module_r_ptr mr = new module_r();
2094 mr->idmr = FieldToInt(row->GetField(0));
2095 mr->idm = FieldToInt(row->GetField(1));
2096 mr->class_name = row->GetField(2);
2097 mr->rev = FieldToInt(row->GetField(3));
2098 if (FieldToInt(row->GetField(4)) == 0)
2099 mr->active = false;
2100 else
2101 mr->active = true;
2102 mr->object_name = row->GetField(5);
2103
2104 m_modules_revision_table.insert(make_pair(mr->idmr, mr));
2105 delete row;
2106 }
2107
2108 delete resQ;
2109 if (rowCount == 0) {
2110 LOG(error) << "ERROR: no module revisions in the geometry database";
2111 return -2;
2112 }
2113 return 0;
2114}
static pid_t gWritableDbPid
Definition GeoSetup.cxx:360
static vector< string > gTmpGeometryFiles
Definition GeoSetup.cxx:151
static const char *const kWgetOptions
Definition GeoSetup.cxx:168
static bool AttrToBool(const TString &name, TString value, bool &result)
Definition GeoSetup.cxx:101
static int FieldToInt(const char *field, int defaultValue=0)
Definition GeoSetup.cxx:46
static void RemoveTmpGeometryFiles()
Definition GeoSetup.cxx:155
static void RemoveWritableDbDir()
Definition GeoSetup.cxx:363
static pid_t gTmpGeometryPid
Definition GeoSetup.cxx:152
static bool ichar_equals(char a, char b)
Definition GeoSetup.cxx:39
static bool AttrToDouble(const TString &name, TString value, double &result)
Definition GeoSetup.cxx:121
static uint64_t FieldToUInt64(const char *field, uint64_t defaultValue=0)
Definition GeoSetup.cxx:55
static string SqlEscape(string_view value)
Definition GeoSetup.cxx:86
static void RemoveAssemblyShapes(TGeoManager *geoManager)
Definition GeoSetup.cxx:572
static void PutModuleEdit(map< TString, setup_module_ptr > &edits, const TString &key, setup_module_ptr sNode)
Definition GeoSetup.cxx:136
static double FieldToDouble(const char *field, double defaultValue=0.)
Definition GeoSetup.cxx:64
static string gWritableDbDir
Definition GeoSetup.cxx:359
static bool IsSafeTag(const string &tag)
Definition GeoSetup.cxx:74
struct SETUPMODULE setup_module
struct SETUPMODULE * setup_module_ptr
struct MODULEREVISION module_r
struct MODULEREVISION * module_r_ptr
int i
Definition P4_F32vec4.h:22
int Int_t
int Ssiz_t
double Double_t
constexpr Ssiz_t kNPOS
R__EXTERN TGeoManager * gGeoManager
#define gInterpreter
kReadPermission
Bool_t R_ISDIR(Int_t mode)
R__EXTERN TSystem * gSystem
void * XMLNodePointer_t
void * XMLDocPointer_t
void * XMLAttrPointer_t
static TString GetMapFilePath(TString mapName)
Get the expanded path to the field map file in the current installation.
const char * GetFileName()
Accessor to field map file.
void SetFileName(const char *map_file_name)
Set field map file path.
Definition BmnFieldMap.h:65
Field Map does not have any symmetries w.r.t coordinate axises.
map< TString, setup_module_ptr > m_moduleEditByName
Definition GeoSetup.h:149
map< TString, setup_module_ptr > m_moduleEdit
Definition GeoSetup.h:147
map< int, module_r_ptr > m_modules_revision_table
Definition GeoSetup.h:144
FairField * GetMagneticField()
Get magnetic field of the current setup geometry.
TString & GetTmpPath()
int GetModuleId(int dbModuleRev)
TGeoNode * ConstructRootGeometry(const char *fileName)
string GetParameterFile(string_view detector_name)
Get path to parameter file for the given detector name of the current setup.
void ClearLocalSettings()
string m_setupTag
Definition GeoSetup.h:169
bool OpenLocalGeoDatabase()
Definition GeoSetup.cxx:538
double m_refVoltage
Definition GeoSetup.h:161
int m_sid
Definition GeoSetup.h:165
TString GetModuleName(int dbModuleUndex)
FairModule * CreateModule(const TString &class_name, const TString &module_name, bool isActive)
TString m_ExternalField
Definition GeoSetup.h:155
int LoadModuleToFairRunSim(int idsm, FairRunSim *fRun)
TSQLServer * m_db
Definition GeoSetup.h:157
int PutModules()
TString GetTmpFileName(const char *baseName)
Definition GeoSetup.cxx:171
int LoadSetupToGeoManager(string_view setup_tag)
Load selected geometry setup from the Local Geometry Database and create gGeoManager instance.
Definition GeoSetup.cxx:592
string GetLocalDbPath()
bool FindModuleGeometryFile(TString &file_path)
bool ParseEditFieldMap(TXMLEngine &xml, XMLNodePointer_t node)
bool LoadLocalSettings(const char *fileName)
string GetMaterialFile()
Get the material file of the current setup, which defines the media of the setup geometry.
map< int, TString > m_loadedModule
Definition GeoSetup.h:145
map< int, TString > m_modules_table
Definition GeoSetup.h:140
TString ExportModuleGeometry(const TString &file_path, const TString &module_name, const TGeoMatrix *placement, double xMove, double yMove, double zMove)
string GetRootPath()
bool ParseEditSetupModule(TXMLEngine &xml, XMLNodePointer_t node)
std::pair< int, uint64_t > CheckTagOnServer(string_view setup_tag, const char *url=GEO_SERVER_HOST)
Definition GeoSetup.cxx:251
TGeoVolume * GetRootVolume(TFile *f)
int installLocalDB(string_view setup_tag, const char *url=GEO_SERVER_HOST)
Definition GeoSetup.cxx:407
unsigned long int GetServerRevision(const char *url=GEO_SERVER_HOST)
Definition GeoSetup.cxx:176
TString GetModuleType(int dbModuleRev)
void CloseDB()
Definition GeoSetup.cxx:516
int PutModuleRevisions()
TString PrepareWritableDbDir()
Definition GeoSetup.cxx:376
setup_module_ptr FindModuleEdit(TString setup_module_tag, TString module_name, int dbModuleRev)
int m_fid
Definition GeoSetup.h:163
module_r_ptr GetModuleRevision(int dbModuleRev)
static bool exists_file(const char *name)
Definition GeoSetup.cxx:34
static int ParseGeometryTag(TString &geometry_tag, TString &local_settings)
Parse the geometry tag, which can contain the path to an XML file with a local customization of the s...
Definition GeoSetup.cxx:742
static bool IsWritableDir(const char *path)
Definition GeoSetup.cxx:352
int GetModuleIndex(TString &name)
TString m_tmpFolder
Definition GeoSetup.h:167
bool ParseAddSetupModule(TXMLEngine &xml, XMLNodePointer_t node)
bool IsEqlMatrix(const char *fileName, TSQLRow *row)
~GeoSetup()
Destructor method.
Definition GeoSetup.cxx:531
unsigned long int GetLocalRevision(TString &localDbPath)
Definition GeoSetup.cxx:324
FairField * m_field
Definition GeoSetup.h:159
std::pair< int, string > GetTagName4PatternLocal(string_view pattern_tag, TString &localDbPath)
Definition GeoSetup.cxx:298
bool AddModuleToFairRunSim(module_r_ptr module, FairRunSim *fRun)
std::pair< int, string > GetTagName4PatternServer(string_view pattern_tag, const char *url=GEO_SERVER_HOST)
Definition GeoSetup.cxx:210
string ExpandGeomPath()
string GetLastApprovedSetupTag(string_view tag_prefix)
Get tag for the last approved setup corresponding to the pattern.
Definition GeoSetup.cxx:196
setup_module_ptr m_moduleEditAll
Definition GeoSetup.h:151
vector< module_r_ptr > m_moduleAdd
Definition GeoSetup.h:152
string m_materialFile
Definition GeoSetup.h:171
map< int, bool > m_modules_active
Definition GeoSetup.h:143
int LoadSetupToFairRunSim(string_view setupTag, const char *localSettings=nullptr)
Load selected geometry setup from the Local or Central (defined by url) Geometry Database and add it ...
Definition GeoSetup.cxx:793
TMethod * GetMethodWithPrototype(const char *method, const char *proto, Bool_t objectIsConst=kFALSE, ROOT::EFunctionMatchMode mode=ROOT::kConversionMatch)
static TClass * GetClass(Bool_t load=kTRUE, Bool_t silent=kFALSE)
Bool_t InheritsFrom(const char *cl) const override
TList * GetListOfKeys() const override
virtual Bool_t IsOpen() const
static TFile * Open(const char *name, Option_t *option="", const char *ftitle="", Int_t compress=ROOT::RCompressionSetting::EDefaults::kUseCompiledDefault, Int_t netopt=0)
void SetRotation(const Double_t *matrix)
void SetDz(Double_t dz) override
void SetDy(Double_t dy) override
void SetDx(Double_t dx) override
virtual Double_t * GetTranslation()
void SetTranslation(const Double_t *vect)
static TClass * Class()
TObjArray * GetListOfVolumes() const
virtual Bool_t cd(const char *path="")
TGeoNode * GetNode(Int_t level) const
TObjArray * GetListOfShapes() const
virtual const Double_t * GetTranslation() const=0
virtual const Double_t * GetRotationMatrix() const=0
void SetMatrix(const TGeoMatrix *matrix)
TGeoMatrix * GetMatrix() const override
TGeoVolume * GetVolume() const
Int_t GetNdaughters() const
TGeoNode * GetDaughter(Int_t ind) const
virtual TGeoMatrix * GetMatrix() const=0
static TClass * Class()
TGeoNode * GetNode(const char *name) const
Int_t Export(const char *filename, const char *name="", Option_t *option="")
virtual const char * GetClassName() const
virtual TObject * ReadObj()
TObject * At(Int_t idx) const override
const char * GetName() const override
Int_t GetEntriesFast() const
virtual void Compress()
TObject * At(Int_t idx) const override
TObject * Remove(TObject *obj) override
R__ALWAYS_INLINE Bool_t IsZombie() const
virtual TSQLRow * Next()=0
virtual const char * GetField(Int_t field)=0
virtual Bool_t IsConnected() const
TSQLResult * Query(const char *sql) final
Ssiz_t Length() const
void ToLower()
Bool_t EndsWith(const char *pat, ECaseCompare cmp=kExact) const
TSubString Strip(EStripType s=kTrailing, char c=' ') const
const char * Data() const
TString & Chop()
Ssiz_t Last(char c) const
void ToUpper()
TObjArray * Tokenize(const TString &delim) const
Bool_t BeginsWith(const char *s, ECaseCompare cmp=kExact) const
Bool_t IsNull() const
static TString Format(const char *fmt,...)
TString & Remove(EStripType s, char c)
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
XMLNodePointer_t GetChild(XMLNodePointer_t xmlnode, Bool_t realnode=kTRUE)
void FreeDoc(XMLDocPointer_t xmldoc)
XMLNodePointer_t DocGetRootElement(XMLDocPointer_t xmldoc)
XMLAttrPointer_t GetNextAttr(XMLAttrPointer_t xmlattr)
const char * GetAttrName(XMLAttrPointer_t xmlattr)
XMLAttrPointer_t GetFirstAttr(XMLNodePointer_t xmlnode)
const char * GetNodeName(XMLNodePointer_t xmlnode)
XMLDocPointer_t ParseFile(const char *filename, Int_t maxbuf=100000)
const char * GetAttrValue(XMLAttrPointer_t xmlattr)
XMLNodePointer_t GetNext(XMLNodePointer_t xmlnode, Bool_t realnode=kTRUE)
const char *const GEO_SERVER_HOST
Long64_t fSize
TString class_name
Definition GeoSetup.h:32
double yMove
Definition GeoSetup.h:40
double zMove
Definition GeoSetup.h:40
double xMove
Definition GeoSetup.h:40
TString object_name
Definition GeoSetup.h:36
TString file_path
Definition GeoSetup.h:37
TString type
Definition GeoSetup.h:24
double zMove
Definition GeoSetup.h:25
TString file_path
Definition GeoSetup.h:27
double xMove
Definition GeoSetup.h:25
double yMove
Definition GeoSetup.h:25
bool enable
Definition GeoSetup.h:26
TString fUser