CMS 3D CMS Logo

CondDBESSource.cc
Go to the documentation of this file.
1 //
2 // Package: CondCore/ESSources
3 // Module: CondDBESSource
4 //
5 // Description: <one line class summary>
6 //
7 // Implementation:
8 // <Notes on implementation>
9 //
10 // Author: Zhen Xie
11 // Fixes and other changes: Giacomo Govi
12 //
13 #include "CondDBESSource.h"
14 
15 #include <boost/algorithm/string.hpp>
20 
23 
29 #include <exception>
30 
31 #include <iomanip>
32 
33 #include <nlohmann/json.hpp>
34 
36 
37 namespace {
38  /* utility ot build the name of the plugin corresponding to a given record
39  se ESSources
40  */
41  std::string buildName(std::string const& iRecordName) { return iRecordName + std::string("@NewProxy"); }
42 
43  std::string joinRecordAndLabel(std::string const& iRecordName, std::string const& iLabelName) {
44  return iRecordName + std::string("@") + iLabelName;
45  }
46 
47  /* utility class to return a IOVs associated to a given "name"
48  This implementation return the IOV associated to a record...
49  It is essentialy a workaround to get the full IOV out of the tag colector
50  that is not accessible as hidden in the ESSource
51  FIXME: need to support label??
52  */
53  class CondGetterFromESSource : public cond::persistency::CondGetter {
54  public:
55  CondGetterFromESSource(CondDBESSource::ResolverMap const& ip) : m_resolvers(ip) {}
56  ~CondGetterFromESSource() override {}
57 
58  cond::persistency::IOVProxy get(std::string name) const override {
59  CondDBESSource::ResolverMap::const_iterator p = m_resolvers.find(name);
60  if (p != m_resolvers.end())
61  return (*p).second->iovProxy();
63  }
64 
65  CondDBESSource::ResolverMap const& m_resolvers;
66  };
67 
68  // This needs to be re-design and implemented...
69  // dump the state of a ProductResolver
70  void dumpInfo(std::ostream& out, std::string const& recName, cond::ProductResolverWrapperBase const& proxy) {
71  //cond::SequenceState state(proxy.proxy()->iov().state());
72  out << recName << " / " << proxy.label() << ": " << proxy.connString() << ", " << proxy.tag()
73  << "\n "
74  // << state.size() << ", " << state.revision() << ", "
75  // << cond::time::to_boost(state.timestamp()) << "\n "
76  // << state.comment()
77  << "\n "
78  // << "refresh " << proxy.proxy()->stats.nRefresh
79  // << "/" << proxy.proxy()->stats.nArefresh
80  // << ", reconnect " << proxy.proxy()->stats.nReconnect
81  // << "/" << proxy.proxy()->stats.nAreconnect
82  // << ", make " << proxy.proxy()->stats.nMake
83  // << ", load " << proxy.proxy()->stats.nLoad
84  ;
85  //if ( proxy.proxy()->stats.nLoad>0) {
86  out << "Time look up, payloadIds:" << std::endl;
87  const auto& pids = *proxy.requests();
88  for (const auto& id : pids)
89  out << " " << id.since << " - " << id.till << " : " << id.payloadId << std::endl;
90  }
91 
92  void dumpInfoJson(json& jsonData, const std::string& recName, cond::ProductResolverWrapperBase const& proxy) {
93  json recordData;
94  recordData["label"] = proxy.label();
95  recordData["connectionString"] = proxy.connString();
96  recordData["tag"] = proxy.tag();
97 
98  // Code to fill the JSON structure
99 
100  recordData["timeLookupPayloadIds"] = json::array();
101  const auto& pids = *proxy.requests();
102  for (const auto& id : pids) {
103  json payloadIdData;
104  payloadIdData["since"] = id.since;
105  payloadIdData["till"] = id.till;
106  payloadIdData["payloadId"] = id.payloadId;
107  recordData["timeLookupPayloadIds"].push_back(payloadIdData);
108  }
109 
110  jsonData[recName].push_back(recordData);
111  }
112 
113 } // namespace
114 
115 /*
116  * config Param
117  * RefreshEachRun: if true will refresh the IOV at each new run (or lumiSection)
118  * DumpStat: if true dump the statistics of all ProductResolver (currently on cout)
119  * DBParameters: configuration set of the connection
120  * globaltag: The GlobalTag
121  * toGet: list of record label tag connection-string to add/overwrite the content of the global-tag
122  */
124  : m_jsonDumpFilename(iConfig.getUntrackedParameter<std::string>("JsonDumpFileName", "")),
125  m_connection(),
126  m_connectionString(""),
127  m_frontierKey(""),
128  m_lastRun(0), // for the stat
129  m_lastLumi(0), // for the stat
130  m_policy(NOREFRESH),
131  m_doDump(iConfig.getUntrackedParameter<bool>("DumpStat", false)) {
132  if (iConfig.getUntrackedParameter<bool>("RefreshAlways", false)) {
134  }
135  if (iConfig.getUntrackedParameter<bool>("RefreshOpenIOVs", false)) {
137  }
138  if (iConfig.getUntrackedParameter<bool>("RefreshEachRun", false)) {
140  }
141  if (iConfig.getUntrackedParameter<bool>("ReconnectEachRun", false)) {
143  }
144 
145  Stats s = {0, 0, 0, 0, 0, 0, 0, 0};
146  m_stats = s;
147 
148  /*parameter set parsing
149  */
151  if (iConfig.exists("globaltag")) {
152  globaltag = iConfig.getParameter<std::string>("globaltag");
153  // the global tag _requires_ a connection string
154  m_connectionString = iConfig.getParameter<std::string>("connect");
155 
156  if (!globaltag.empty()) {
158  if (siteLocalConfig.isAvailable()) {
159  if (siteLocalConfig->useLocalConnectString()) {
160  std::string const& localConnectPrefix = siteLocalConfig->localConnectPrefix();
161  std::string const& localConnectSuffix = siteLocalConfig->localConnectSuffix();
162  m_connectionString = localConnectPrefix + globaltag + localConnectSuffix;
163  }
164  }
165  }
166  } else if (iConfig.exists("connect")) // default connection string
167  m_connectionString = iConfig.getParameter<std::string>("connect");
168 
169  // frontier key
170  m_frontierKey = iConfig.getUntrackedParameter<std::string>("frontierKey", "");
171 
172  // snapshot
173  boost::posix_time::ptime snapshotTime;
174  if (iConfig.exists("snapshotTime")) {
175  std::string snapshotTimeString = iConfig.getParameter<std::string>("snapshotTime");
176  if (!snapshotTimeString.empty())
177  snapshotTime = boost::posix_time::time_from_string(snapshotTimeString);
178  }
179 
180  // connection configuration
181  if (iConfig.exists("DBParameters")) {
182  edm::ParameterSet connectionPset = iConfig.getParameter<edm::ParameterSet>("DBParameters");
183  m_connection.setParameters(connectionPset);
184  }
186 
187  // load specific record/tag info - it will overwrite the global tag ( if any )
188  std::map<std::string, cond::GTEntry_t> replacements;
189  std::map<std::string, boost::posix_time::ptime> specialSnapshots;
190  if (iConfig.exists("toGet")) {
191  typedef std::vector<edm::ParameterSet> Parameters;
192  Parameters toGet = iConfig.getParameter<Parameters>("toGet");
193  for (Parameters::iterator itToGet = toGet.begin(); itToGet != toGet.end(); ++itToGet) {
194  std::string recordname = itToGet->getParameter<std::string>("record");
195  if (recordname.empty())
196  throw cond::Exception("ESSource: The record name has not been provided in a \"toGet\" entry.");
197  std::string labelname = itToGet->getUntrackedParameter<std::string>("label", "");
198  std::string pfn("");
199  if (m_connectionString.empty() || itToGet->exists("connect"))
200  pfn = itToGet->getParameter<std::string>("connect");
201  std::string tag("");
202  std::string fqTag("");
203  if (itToGet->exists("tag")) {
204  tag = itToGet->getParameter<std::string>("tag");
206  }
207  boost::posix_time::ptime tagSnapshotTime =
208  boost::posix_time::time_from_string(std::string(cond::time::MAX_TIMESTAMP));
209  if (itToGet->exists("snapshotTime"))
210  tagSnapshotTime = boost::posix_time::time_from_string(itToGet->getParameter<std::string>("snapshotTime"));
211  if (itToGet->exists("refreshTime")) {
212  cond::Time_t refreshTime = itToGet->getParameter<unsigned long long>("refreshTime");
213  m_refreshTimeForRecord.insert(std::make_pair(recordname, std::make_pair(refreshTime, true)));
214  }
215 
216  std::string recordLabelKey = joinRecordAndLabel(recordname, labelname);
217  replacements.insert(
218  std::make_pair(recordLabelKey, cond::GTEntry_t(std::make_tuple(recordname, labelname, fqTag))));
219  specialSnapshots.insert(std::make_pair(recordLabelKey, tagSnapshotTime));
220  }
221  }
222 
223  // get the global tag, merge with "replacement" store in "tagCollection"
224  std::vector<std::string> globaltagList;
225  std::vector<std::string> connectList;
226  std::vector<std::string> pfnPrefixList;
227  std::vector<std::string> pfnPostfixList;
228  if (!globaltag.empty()) {
229  std::string pfnPrefix(iConfig.getUntrackedParameter<std::string>("pfnPrefix", ""));
230  std::string pfnPostfix(iConfig.getUntrackedParameter<std::string>("pfnPostfix", ""));
231  boost::split(globaltagList, globaltag, boost::is_any_of("|"), boost::token_compress_off);
232  fillList(m_connectionString, connectList, globaltagList.size(), "connection");
233  fillList(pfnPrefix, pfnPrefixList, globaltagList.size(), "pfnPrefix");
234  fillList(pfnPostfix, pfnPostfixList, globaltagList.size(), "pfnPostfix");
235  }
236 
237  cond::GTMetadata_t gtMetadata;
238  fillTagCollectionFromDB(connectList, pfnPrefixList, pfnPostfixList, globaltagList, replacements, gtMetadata);
239  // if no job specific setting has been found, use the GT timestamp
240  if (snapshotTime.is_not_a_date_time())
241  snapshotTime = gtMetadata.snapshotTime;
242 
243  TagCollection::iterator it;
244  TagCollection::iterator itBeg = m_tagCollection.begin();
245  TagCollection::iterator itEnd = m_tagCollection.end();
246 
247  std::map<std::string, cond::persistency::Session> sessions;
248 
249  /* load ProductResolver Plugin (it is strongly typed due to EventSetup ideosyncrasis)
250  * construct proxy
251  * contrary to EventSetup the "object-name" is not used as identifier: multiple entries in a record are
252  * dinstinguished only by their label...
253  * done in two step: first create ResolverWrapper loading ALL required dictionaries
254  * this will allow to initialize POOL in one go for each "database"
255  * The real initialization of the Data-Resolvers is done in the second loop
256  */
257  std::vector<std::unique_ptr<cond::ProductResolverWrapperBase>> resolverWrappers(m_tagCollection.size());
258  size_t ipb = 0;
259  for (it = itBeg; it != itEnd; ++it) {
260  size_t ind = ipb++;
261  resolverWrappers[ind] = std::unique_ptr<cond::ProductResolverWrapperBase>{
262  cond::ProductResolverFactory::get()->tryToCreate(buildName(it->second.recordName()))};
263  if (!resolverWrappers[ind].get()) {
264  edm::LogWarning("CondDBESSource") << "Plugin for Record " << it->second.recordName() << " has not been found.";
265  }
266  }
267 
268  // now all required libraries have been loaded
269  // init sessions and DataResolvers
270  ipb = 0;
271  for (it = itBeg; it != itEnd; ++it) {
273  std::string tag = it->second.tagName();
274  std::pair<std::string, std::string> tagParams = cond::persistency::parseTag(it->second.tagName());
275  if (!tagParams.second.empty()) {
276  connStr = tagParams.second;
277  tag = tagParams.first;
278  }
279  std::map<std::string, cond::persistency::Session>::iterator p = sessions.find(connStr);
281  if (p == sessions.end()) {
283  std::tuple<std::string, std::string, std::string> connPars =
285  std::string dbService = std::get<1>(connPars);
286  std::string dbAccount = std::get<2>(connPars);
287  if ((dbService == "cms_orcon_prod" || dbService == "cms_orcon_adg") && dbAccount != "CMS_CONDITIONS")
288  edm::LogWarning("CondDBESSource")
289  << "[WARNING] You are reading tag \"" << tag << "\" from V1 account \"" << connStr
290  << "\". The concerned Conditions might be out of date." << std::endl;
291  //open db get tag info (i.e. the IOV token...)
292  nsess = m_connection.createReadOnlySession(connStr, "");
293  sessions.insert(std::make_pair(connStr, nsess));
294  } else
295  nsess = (*p).second;
296 
297  // ownership...
298  ResolverP resolver(std::move(resolverWrappers[ipb++]));
299  // instert in the map
300  if (resolver.get()) {
301  m_resolvers.insert(std::make_pair(it->second.recordName(), resolver));
302  // initialize
303  boost::posix_time::ptime tagSnapshotTime = snapshotTime;
304  auto tagSnapshotIter = specialSnapshots.find(it->first);
305  if (tagSnapshotIter != specialSnapshots.end())
306  tagSnapshotTime = tagSnapshotIter->second;
307  // finally, if the snapshot is set to infinity, reset the snapshot to null, to take the full iov set...
308  if (tagSnapshotTime == boost::posix_time::time_from_string(std::string(cond::time::MAX_TIMESTAMP)))
309  tagSnapshotTime = boost::posix_time::ptime();
310 
311  resolver->lateInit(nsess, tag, tagSnapshotTime, it->second.recordLabel(), connStr, &m_queue, &m_mutex);
312  }
313  }
314 
315  // one loaded expose all other tags to the Proxy!
316  CondGetterFromESSource visitor(m_resolvers);
317  ResolverMap::iterator b = m_resolvers.begin();
318  ResolverMap::iterator e = m_resolvers.end();
319  for (; b != e; b++) {
320  (*b).second->proxy(0)->loadMore(visitor);
321 
323  EventSetupRecordKey recordKey = b->second->recordKey();
324  if (recordKey.type() != EventSetupRecordKey::TypeTag()) {
325  findingRecordWithKey(recordKey);
326  usingRecordWithKey(recordKey);
327  } else {
328  edm::LogWarning("CondDBESSource") << "Failed to load key for record " << b->first
329  << ". No data from this record will be available.";
330  }
331  }
332 
333  m_stats.nData = m_resolvers.size();
334 }
335 
336 void CondDBESSource::fillList(const std::string& stringList,
337  std::vector<std::string>& listToFill,
338  const unsigned int listSize,
339  const std::string& type) {
340  boost::split(listToFill, stringList, boost::is_any_of("|"), boost::token_compress_off);
341  // If it is one clone it for each GT
342  if (listToFill.size() == 1) {
343  for (unsigned int i = 1; i < listSize; ++i) {
344  listToFill.push_back(stringList);
345  }
346  }
347  // else if they don't match the number of GTs throw an exception
348  else if (listSize != listToFill.size()) {
349  throw cond::Exception(
350  std::string("ESSource: number of global tag components does not match number of " + type + " strings"));
351  }
352 }
353 
355  std::cout << "CondDBESSource Statistics\n"
356  << "DataProxy " << stats.nData << " setInterval " << stats.nSet << " Runs " << stats.nRun << " Lumis "
357  << stats.nLumi << " Refresh " << stats.nRefresh << " Actual Refresh " << stats.nActualRefresh
358  << " Reconnect " << stats.nReconnect << " Actual Reconnect " << stats.nActualReconnect << std::endl;
359 }
360 
361 void saveJsonToFile(const json& jsonData, const std::string& filename) {
362  std::ofstream outputFile(filename);
363  if (outputFile.is_open()) {
364  outputFile << jsonData.dump(2) << std::endl;
365  std::cout << "JSON data saved in file '" << filename << "'" << std::endl;
366  } else {
367  std::cerr << "Error opening file to write JSON data." << std::endl;
368  }
369 }
370 
372  //dump info FIXME: find a more suitable place...
373  if (m_doDump) {
374  //Output CondDBESSource Statistics to the console
376 
377  ResolverMap::iterator b = m_resolvers.begin();
378  ResolverMap::iterator e = m_resolvers.end();
379  for (; b != e; b++) {
380  dumpInfo(std::cout, (*b).first, *(*b).second);
381  std::cout << "\n" << std::endl;
382  }
383  }
384  //if filename was provided for iConfig by process.GlobalTag.JsonDumpFileName =cms.untracked.string("CondDBESSource.json")
385  if (!m_jsonDumpFilename.empty()) {
386  json jsonData;
387 
388  for (const auto& entry : m_resolvers) {
389  std::string recName = entry.first;
390  const auto& proxy = *entry.second;
391  dumpInfoJson(jsonData, recName, proxy);
392  }
393  //Save the dump data to a file in JSON format
395  }
396  // FIXME
397  // We shall eventually close transaction and session...
398 }
399 
400 //
401 // invoked by EventSetUp: for a given record return the smallest IOV for which iTime is valid
402 // limit to next run/lumisection of Refresh is required
403 //
405  const edm::IOVSyncValue& iTime,
406  edm::ValidityInterval& oInterval) {
407  std::string recordname = iKey.name();
408 
409  edm::LogInfo("CondDBESSource") << "Getting data for record \"" << recordname
410  << "\" to be consumed on Run: " << iTime.eventID().run()
411  << " - Lumiblock:" << iTime.luminosityBlockNumber()
412  << " - Timestamp: " << iTime.time().value() << "; from CondDBESSource::setIntervalFor";
413 
414  std::lock_guard<std::mutex> guard(m_mutex);
415  m_stats.nSet++;
416 
417  if (iTime.eventID().run() != m_lastRun) {
418  m_lastRun = iTime.eventID().run();
419  m_stats.nRun++;
420  }
421  if (iTime.luminosityBlockNumber() != m_lastLumi) {
423  m_stats.nLumi++;
424  }
425 
426  bool doRefresh = false;
427  cond::Time_t defaultIovSize = cond::time::MAX_VAL;
428  bool refreshThisRecord = false;
429  bool reconnectThisRecord = false;
430 
431  auto iR = m_refreshTimeForRecord.find(recordname);
432  refreshThisRecord = iR != m_refreshTimeForRecord.end();
433  if (refreshThisRecord) {
434  defaultIovSize = iR->second.first;
435  reconnectThisRecord = iR->second.second;
436  iR->second.second = false;
437  }
438 
440  // find out the last run number for the proxy of the specified record
441  std::map<std::string, unsigned int>::iterator iRec = m_lastRecordRuns.find(recordname);
442  if (iRec != m_lastRecordRuns.end()) {
443  cond::Time_t lastRecordRun = iRec->second;
444  if (lastRecordRun != m_lastRun) {
445  // a refresh is required!
446  doRefresh = true;
447  iRec->second = m_lastRun;
448  edm::LogInfo("CondDBESSource") << "Preparing refresh for record \"" << recordname
449  << "\" since there has been a transition from run/lumi " << lastRecordRun
450  << " to run/lumi " << m_lastRun << "; from CondDBESSource::setIntervalFor";
451  }
452  } else {
453  doRefresh = true;
454  m_lastRecordRuns.insert(std::make_pair(recordname, m_lastRun));
455  edm::LogInfo("CondDBESSource") << "Preparing refresh for record \"" << recordname << "\" for " << iTime.eventID()
456  << ", timestamp: " << iTime.time().value()
457  << "; from CondDBESSource::setIntervalFor";
458  }
459  if (!doRefresh)
460  edm::LogInfo("CondDBESSource") << "Though enabled, refresh not needed for record \"" << recordname << "\" for "
461  << iTime.eventID() << ", timestamp: " << iTime.time().value()
462  << "; from CondDBESSource::setIntervalFor";
463  } else if (m_policy == REFRESH_ALWAYS || m_policy == REFRESH_OPEN_IOVS) {
464  doRefresh = true;
465  edm::LogInfo("CondDBESSource") << "Forcing refresh for record \"" << recordname << "\" for " << iTime.eventID()
466  << ", timestamp: " << iTime.time().value()
467  << "; from CondDBESSource::setIntervalFor";
468  }
469 
471 
472  // compute the smallest interval (assume all objects have the same timetype....)
473  cond::ValidityInterval recordValidity(1, cond::TIMELIMIT);
474  cond::TimeType timetype = cond::TimeType::invalid;
475  bool userTime = true;
476 
477  //FIXME use equal_range
478  ResolverMap::const_iterator pmBegin = m_resolvers.lower_bound(recordname);
479  ResolverMap::const_iterator pmEnd = m_resolvers.upper_bound(recordname);
480  if (pmBegin == pmEnd) {
481  edm::LogInfo("CondDBESSource") << "No ProductResolver (Pluging) found for record \"" << recordname
482  << "\"; from CondDBESSource::setIntervalFor";
483  return;
484  }
485 
486  for (ResolverMap::const_iterator pmIter = pmBegin; pmIter != pmEnd; ++pmIter) {
487  edm::LogInfo("CondDBESSource") << "Processing record \"" << recordname << "\" and label \""
488  << pmIter->second->label() << "\" for " << iTime.eventID()
489  << ", timestamp: " << iTime.time().value()
490  << "; from CondDBESSource::setIntervalFor";
491 
492  timetype = (*pmIter).second->timeType();
493 
495  userTime = (0 == abtime);
496 
497  if (userTime)
498  return; // oInterval invalid to avoid that make is called...
499 
500  if (doRefresh || refreshThisRecord) {
501  std::string recKey = joinRecordAndLabel(recordname, pmIter->second->label());
502  TagCollection::const_iterator tcIter = m_tagCollection.find(recKey);
503  if (tcIter == m_tagCollection.end()) {
504  edm::LogInfo("CondDBESSource") << "No Tag found for record \"" << recordname << "\" and label \""
505  << pmIter->second->label() << "\"; from CondDBESSource::setIntervalFor";
506  return;
507  }
508 
509  // first reconnect if required
510  if (m_policy == RECONNECT_EACH_RUN || reconnectThisRecord) {
511  edm::LogInfo("CondDBESSource")
512  << "Checking if the session must be closed and re-opened for getting correct conditions"
513  << "; from CondDBESSource::setIntervalFor";
514  std::string transId;
515  if (!reconnectThisRecord) {
516  transId = std::to_string(abtime);
517  } else {
518  transId = cond::time::transactionIdForLumiTime(abtime, defaultIovSize, m_frontierKey);
519  }
521  std::pair<std::string, std::string> tagParams = cond::persistency::parseTag(tcIter->second.tagName());
522  if (!tagParams.second.empty())
523  connStr = tagParams.second;
524  std::map<std::string, std::pair<cond::persistency::Session, std::string>>* sessionPool = &m_sessionPool;
525  if (refreshThisRecord) {
526  sessionPool = &m_sessionPoolForLumiConditions;
527  }
528  auto iSess = sessionPool->find(connStr);
529  bool reopen = false;
530  if (iSess != sessionPool->end()) {
531  if (iSess->second.second != transId) {
532  // the available session is open for a different run: reopen
533  reopen = true;
534  iSess->second.second = transId;
535  }
536  } else {
537  // no available session: probably first run analysed...
538  iSess =
539  sessionPool->insert(std::make_pair(connStr, std::make_pair(cond::persistency::Session(), transId))).first;
540  reopen = true;
541  }
542  if (reopen) {
543  iSess->second.first = m_connection.createReadOnlySession(connStr, transId);
544  edm::LogInfo("CondDBESSource") << "Re-opening the session with connection string " << connStr
545  << " and new transaction Id " << transId
546  << "; from CondDBESSource::setIntervalFor";
547  }
548 
549  edm::LogInfo("CondDBESSource") << "Reconnecting to \"" << connStr << "\" for getting new payload for record \""
550  << recordname << "\" and label \"" << pmIter->second->label()
551  << "\" from IOV tag \"" << tcIter->second.tagName() << "\" to be consumed by "
552  << iTime.eventID() << ", timestamp: " << iTime.time().value()
553  << "; from CondDBESSource::setIntervalFor";
554  pmIter->second->session() = iSess->second.first;
555  pmIter->second->reload();
557  } else {
558  edm::LogInfo("CondDBESSource") << "Refreshing IOV sequence labeled by tag \"" << tcIter->second.tagName()
559  << "\" for getting new payload for record \"" << recordname << "\" and label \""
560  << pmIter->second->label() << "\" to be consumed by " << iTime.eventID()
561  << ", timestamp: " << iTime.time().value()
562  << "; from CondDBESSource::setIntervalFor";
563  pmIter->second->reload();
564  m_stats.nRefresh++;
565  }
566  }
567 
568  //query the IOVSequence
569  cond::ValidityInterval validity = (*pmIter).second->setIntervalFor(abtime);
570 
571  edm::LogInfo("CondDBESSource") << "Validity coming from IOV sequence for record \"" << recordname
572  << "\" and label \"" << pmIter->second->label() << "\": (" << validity.first << ", "
573  << validity.second << ") for time (type: " << cond::timeTypeNames(timetype) << ") "
574  << abtime << "; from CondDBESSource::setIntervalFor";
575 
576  recordValidity.first = std::max(recordValidity.first, validity.first);
577  recordValidity.second = std::min(recordValidity.second, validity.second);
578  if (refreshThisRecord && recordValidity.second == cond::TIMELIMIT) {
579  iR->second.second = true;
580  if (defaultIovSize)
581  recordValidity.second = cond::time::tillTimeForIOV(abtime, defaultIovSize, timetype);
582  else {
583  recordValidity.second = 0;
584  }
585  }
586  }
587 
588  if (m_policy == REFRESH_OPEN_IOVS) {
589  doRefresh = (recordValidity.second == cond::timeTypeSpecs[timetype].endValue);
590  edm::LogInfo("CondDBESSource") << "Validity for record \"" << recordname
591  << "\" and the corresponding label(s) coming from Condition DB: ("
592  << recordValidity.first << ", " << recordValidity.first
593  << ") as the last IOV element in the IOV sequence is infinity"
594  << "; from CondDBESSource::setIntervalFor";
595  }
596 
597  // to force refresh we set end-value to the minimum such an IOV can extend to: current run or lumiblock
598  if ((!userTime) && recordValidity.second != 0) {
599  edm::IOVSyncValue start = cond::time::toIOVSyncValue(recordValidity.first, timetype, true);
601  : cond::time::toIOVSyncValue(recordValidity.second, timetype, false);
602 
605  }
606  oInterval = edm::ValidityInterval(start, stop);
607  }
608 
609  edm::LogInfo("CondDBESSource") << "Setting validity for record \"" << recordname
610  << "\" and corresponding label(s): starting at " << oInterval.first().eventID()
611  << ", timestamp: " << oInterval.first().time().value() << ", ending at "
612  << oInterval.last().eventID() << ", timestamp: " << oInterval.last().time().value()
613  << ", for " << iTime.eventID() << ", timestamp: " << iTime.time().value()
614  << "; from CondDBESSource::setIntervalFor";
615 }
616 
617 //required by EventSetup System
619  const EventSetupRecordKey& iRecordKey, unsigned int iovIndex) {
620  KeyedResolversVector keyedResolversVector;
621 
622  std::string recordname = iRecordKey.name();
623 
624  ResolverMap::const_iterator b = m_resolvers.lower_bound(recordname);
625  ResolverMap::const_iterator e = m_resolvers.upper_bound(recordname);
626  if (b == e) {
627  edm::LogInfo("CondDBESSource") << "No ProductResolver (Pluging) found for record \"" << recordname
628  << "\"; from CondDBESSource::registerResolvers";
629  return keyedResolversVector;
630  }
631 
632  for (ResolverMap::const_iterator p = b; p != e; ++p) {
633  if (nullptr != (*p).second.get()) {
634  edm::eventsetup::TypeTag type = (*p).second->type();
635  DataKey key(type, edm::eventsetup::IdTags((*p).second->label().c_str()));
636  keyedResolversVector.emplace_back(key, (*p).second->esResolver(iovIndex));
637  }
638  }
639  return keyedResolversVector;
640 }
641 
643  std::string recordname = key.name();
644  ResolverMap::const_iterator b = m_resolvers.lower_bound(recordname);
645  ResolverMap::const_iterator e = m_resolvers.upper_bound(recordname);
646  for (ResolverMap::const_iterator p = b; p != e; ++p) {
647  if (p->second) {
648  p->second->initConcurrentIOVs(nConcurrentIOVs);
649  }
650  }
651 }
652 
653 // Fills tag collection from the given globaltag
655  const std::string& prefix,
656  const std::string& postfix,
657  const std::string& roottag,
658  std::set<cond::GTEntry_t>& tagcoll,
659  cond::GTMetadata_t& gtMetadata) {
660  if (!roottag.empty()) {
661  if (connectionString.empty())
662  throw cond::Exception(std::string("ESSource: requested global tag ") + roottag +
663  std::string(" but not connection string given"));
664  std::tuple<std::string, std::string, std::string> connPars =
666  if (std::get<2>(connPars) == "CMS_COND_31X_GLOBALTAG") {
667  edm::LogWarning("CondDBESSource")
668  << "[WARNING] You are reading Global Tag \"" << roottag
669  << "\" from V1 account \"CMS_COND_31X_GLOBALTAG\". The concerned Conditions might be out of date."
670  << std::endl;
671  } else if (roottag.rfind("::All") != std::string::npos && std::get<2>(connPars) == "CMS_CONDITIONS") {
672  edm::LogWarning("CondDBESSource") << "[WARNING] You are trying to read Global Tag \"" << roottag
673  << "\" - postfix \"::All\" should not be used for V2." << std::endl;
674  }
676  session.transaction().start(true);
677  cond::persistency::GTProxy gtp = session.readGlobalTag(roottag, prefix, postfix);
678  gtMetadata.snapshotTime = gtp.snapshotTime();
679  for (const auto& gte : gtp) {
680  tagcoll.insert(gte);
681  }
682  session.transaction().commit();
683  }
684 }
685 
686 // fills tagcollection merging with replacement
687 // Note: it assumem the coraldbList and roottagList have the same length. This checked in the constructor that prepares the two lists before calling this method.
688 void CondDBESSource::fillTagCollectionFromDB(const std::vector<std::string>& connectionStringList,
689  const std::vector<std::string>& prefixList,
690  const std::vector<std::string>& postfixList,
691  const std::vector<std::string>& roottagList,
692  std::map<std::string, cond::GTEntry_t>& replacement,
693  cond::GTMetadata_t& gtMetadata) {
694  std::set<cond::GTEntry_t> tagcoll;
695 
696  auto connectionString = connectionStringList.begin();
697  auto prefix = prefixList.begin();
698  auto postfix = postfixList.begin();
699  for (auto roottag = roottagList.begin(); roottag != roottagList.end();
700  ++roottag, ++connectionString, ++prefix, ++postfix) {
701  fillTagCollectionFromGT(*connectionString, *prefix, *postfix, *roottag, tagcoll, gtMetadata);
702  }
703 
704  std::set<cond::GTEntry_t>::iterator tagCollIter;
705  std::set<cond::GTEntry_t>::iterator tagCollBegin = tagcoll.begin();
706  std::set<cond::GTEntry_t>::iterator tagCollEnd = tagcoll.end();
707 
708  // FIXME the logic is a bit perverse: can be surely linearized (at least simplified!) ....
709  for (tagCollIter = tagCollBegin; tagCollIter != tagCollEnd; ++tagCollIter) {
710  std::string recordLabelKey = joinRecordAndLabel(tagCollIter->recordName(), tagCollIter->recordLabel());
711  std::map<std::string, cond::GTEntry_t>::iterator fid = replacement.find(recordLabelKey);
712  if (fid != replacement.end()) {
713  if (!fid->second.tagName().empty()) {
714  cond::GTEntry_t tagMetadata(
715  std::make_tuple(tagCollIter->recordName(), tagCollIter->recordLabel(), fid->second.tagName()));
716  m_tagCollection.insert(std::make_pair(recordLabelKey, tagMetadata));
717  edm::LogInfo("CondDBESSource") << "Replacing tag \"" << tagCollIter->tagName() << "\" for record \""
718  << tagMetadata.recordName() << "\" and label \"" << tagMetadata.recordLabel()
719  << "\" with tag " << tagMetadata.tagName()
720  << "\"; from CondDBESSource::fillTagCollectionFromDB";
721  } else {
722  m_tagCollection.insert(std::make_pair(recordLabelKey, *tagCollIter));
723  }
724  replacement.erase(fid);
725  } else {
726  m_tagCollection.insert(std::make_pair(recordLabelKey, *tagCollIter));
727  }
728  }
729  std::map<std::string, cond::GTEntry_t>::iterator replacementIter;
730  std::map<std::string, cond::GTEntry_t>::iterator replacementBegin = replacement.begin();
731  std::map<std::string, cond::GTEntry_t>::iterator replacementEnd = replacement.end();
732  for (replacementIter = replacementBegin; replacementIter != replacementEnd; ++replacementIter) {
733  if (replacementIter->second.tagName().empty()) {
734  std::stringstream msg;
735  msg << "ESSource: no tag provided for record " << replacementIter->second.recordName();
736  if (!replacementIter->second.recordLabel().empty())
737  msg << " and label " << replacementIter->second.recordLabel();
738  throw cond::Exception(msg.str());
739  }
740  m_tagCollection.insert(*replacementIter);
741  }
742 }
743 
744 // backward compatibility for configuration files
746 public:
747  explicit PoolDBESSource(const edm::ParameterSet& ps) : CondDBESSource(ps) {}
748 };
749 
751 //define this as a plug-in
persistency::Exception Exception
Definition: Exception.h:25
const std::string & recordName() const
Definition: Types.h:120
const TimeTypeSpecs timeTypeSpecs[]
Definition: Time.cc:16
Definition: start.py:1
const IOVSyncValue & last() const
std::map< std::string, std::pair< cond::Time_t, bool > > m_refreshTimeForRecord
ResolverMap m_resolvers
std::tuple< std::string, std::string, std::string > parseConnectionString(const std::string &connectionString)
Definition: Utils.h:95
std::mutex m_mutex
LuminosityBlockNumber_t luminosityBlockNumber() const
Definition: IOVSyncValue.h:41
T getParameter(std::string const &) const
Definition: ParameterSet.h:307
const IOVSyncValue & first() const
void saveJsonToFile(const json &jsonData, const std::string &filename)
Base exception class for the object to relational access.
Definition: Exception.h:11
std::multimap< std::string, ResolverP > ResolverMap
std::shared_ptr< cond::ProductResolverWrapperBase > ResolverP
void usingRecordWithKey(const EventSetupRecordKey &key)
bool exists(std::string const &parameterName) const
checks if a parameter exists
void setIntervalFor(const EventSetupRecordKey &, const edm::IOVSyncValue &, edm::ValidityInterval &) override
boost::posix_time::ptime snapshotTime
Definition: Types.h:106
static constexpr const char *const MAX_TIMESTAMP
Definition: Time.h:26
std::pair< Time_t, Time_t > ValidityInterval
Definition: Time.h:17
std::map< std::string, std::pair< cond::persistency::Session, std::string > > m_sessionPool
void printStatistics(const Stats &stats) const
RefreshPolicy m_policy
std::string const & label() const
std::string transactionIdForLumiTime(Time_t time, unsigned int iovSize, const std::string &secretKey)
Definition: Time.cc:150
std::string const & connString() const
static std::string to_string(const XMLCh *ch)
TimeType
Definition: Time.h:19
void setParameters(const edm::ParameterSet &connectionPset)
nlohmann::json json
void fillTagCollectionFromGT(const std::string &connectionString, const std::string &prefix, const std::string &postfix, const std::string &roottag, std::set< cond::GTEntry_t > &tagcoll, cond::GTMetadata_t &gtMetadata)
Time_t tillTimeForIOV(Time_t since, unsigned int iovSize, TimeType timeType)
Definition: Time.cc:54
T getUntrackedParameter(std::string const &, T const &) const
Time_t fromIOVSyncValue(edm::IOVSyncValue const &time, TimeType timetype)
Definition: Time.cc:97
edm::SerialTaskQueue m_queue
std::string const & timeTypeNames(int)
Definition: Time.cc:11
unsigned long long Time_t
Definition: Time.h:14
std::string convertoToOracleConnection(const std::string &input)
Definition: Utils.h:120
std::pair< std::string, std::string > parseTag(const std::string &tag)
Definition: GTProxy.cc:14
static const IOVSyncValue & beginOfTime()
Definition: IOVSyncValue.cc:88
cond::persistency::ConnectionPool m_connection
edm::IOVSyncValue toIOVSyncValue(cond::Time_t time, TimeType timetype, bool startOrStop)
Definition: Time.cc:79
Session createSession(const std::string &connectionString, bool writeCapable=false)
key
prepare the HTCondor submission files and eventually submit them
void initConcurrentIOVs(const EventSetupRecordKey &key, unsigned int nConcurrentIOVs) override
std::string fullyQualifiedTag(const std::string &tag, const std::string &connectionString)
Definition: GTProxy.cc:8
void fillList(const std::string &pfn, std::vector< std::string > &pfnList, const unsigned int listSize, const std::string &type)
def dumpInfo(run)
Definition: getInfo.py:88
boost::posix_time::ptime snapshotTime() const
Definition: GTProxy.cc:135
std::map< std::string, std::pair< cond::persistency::Session, std::string > > m_sessionPoolForLumiConditions
std::shared_ptr< std::vector< Iov_t > > const & requests() const
Log< level::Info, false > LogInfo
RunNumber_t run() const
Definition: EventID.h:38
const std::string & tagName() const
Definition: Types.h:122
#define DEFINE_FWK_EVENTSETUP_SOURCE(type)
Definition: SourceFactory.h:92
PoolDBESSource(const edm::ParameterSet &ps)
TimeValue_t value() const
Definition: Timestamp.h:38
TagCollection m_tagCollection
const Time_t TIMELIMIT(std::numeric_limits< Time_t >::max())
double b
Definition: hdecay.h:120
~CondDBESSource() override
tuple msg
Definition: mps_check.py:286
std::string m_jsonDumpFilename
std::vector< std::pair< DataKey, std::shared_ptr< ESProductResolver > >> KeyedResolversVector
std::string const & tag() const
void fillTagCollectionFromDB(const std::vector< std::string > &connectionStringList, const std::vector< std::string > &prefixList, const std::vector< std::string > &postfixList, const std::vector< std::string > &roottagList, std::map< std::string, cond::GTEntry_t > &replacement, cond::GTMetadata_t &gtMetadata)
const EventID & eventID() const
Definition: IOVSyncValue.h:40
std::vector< AlignmentParameters * > Parameters
Definition: Utilities.h:32
heterocontainer::HCTypeTag TypeTag
std::string m_connectionString
const Timestamp & time() const
Definition: IOVSyncValue.h:42
unsigned int m_lastRun
static const ValidityInterval & invalidInterval()
Session createReadOnlySession(const std::string &connectionString, const std::string &transactionId)
std::string m_frontierKey
edm::IOVSyncValue limitedIOVSyncValue(Time_t time, TimeType timetype)
Definition: Time.cc:113
#define get
Log< level::Warning, false > LogWarning
Time_t endValue
Definition: Time.h:42
CondDBESSource(const edm::ParameterSet &)
siteLocalConfig
FrontierDev/CMS_COND_CSC".
std::map< std::string, unsigned int > m_lastRecordRuns
KeyedResolversVector registerResolvers(const EventSetupRecordKey &, unsigned int iovIndex) override
const std::string & recordLabel() const
Definition: Types.h:121
if(threadIdxLocalY==0 &&threadIdxLocalX==0)
unsigned int m_lastLumi
const Time_t MAX_VAL(std::numeric_limits< Time_t >::max())
def move(src, dest)
Definition: eostools.py:511
void findingRecordWithKey(const eventsetup::EventSetupRecordKey &)
static const IOVSyncValue & invalidIOVSyncValue()
Definition: IOVSyncValue.cc:78