CMS 3D CMS Logo

conddblib.py
Go to the documentation of this file.
1 '''CMS Conditions DB Python library.
2 '''
3 
4 __author__ = 'Miguel Ojeda'
5 __copyright__ = 'Copyright 2013, CERN'
6 __credits__ = ['Giacomo Govi', 'Miguel Ojeda', 'Andreas Pfeiffer']
7 __license__ = 'Unknown'
8 __maintainer__ = 'Giacomo Govi'
9 __email__ = 'mojedasa@cern.ch'
10 
11 
12 import os
13 import hashlib
14 import logging
15 
16 import sqlalchemy
17 import sqlalchemy.ext.declarative
18 import enum
19 from sqlalchemy import Enum
20 
21 authPathEnvVar = 'COND_AUTH_PATH'
22 schema_name = 'CMS_CONDITIONS'
23 dbuser_name = 'cms_conditions'
24 dbreader_user_name = 'cms_cond_general_r'
25 dbwriter_user_name = 'cms_cond_general_w'
26 devdbwriter_user_name = 'cms_cond_general_w'
27 logger = logging.getLogger(__name__)
28 
29 # frontier services
30 PRO ='PromptProd'
31 ARC ='FrontierArc'
32 INT ='FrontierInt'
33 DEV ='FrontierPrep'
34 # oracle read only services
35 ORAPRO = 'cms_orcon_adg'
36 ORAARC = 'cmsarc_lb'
37 # oracle masters
38 ORAINT = 'cms_orcoff_int'
39 ORADEV = 'cms_orcoff_prep'
40 ONLINEORAPRO = 'cms_orcon_prod'
41 ONLINEORAINT = 'cmsintr_lb'
42 
43 # Set initial level to WARN. This so that log statements don't occur in
44 # the absense of explicit logging being enabled.
45 if logger.level == logging.NOTSET:
46  logger.setLevel(logging.WARN)
47 
48 # Utility functions
49 def hash(data):
50  return hashlib.sha1(data.encode('ascii')).hexdigest()
51 
52 
53 # Constants
54 empty_label = '-'
55 
56 name_length = 100
57 description_length = 4000
58 hash_length = len(hash(''))
59 
60 web_experts_email = 'cms-cond-dev@cern.ch'
61 offline_db_experts_email = 'cms-offlinedb-exp@cern.ch'
62 offline_db_experts_phone = '+41 22 76 70817, or 70817 from CERN; check https://twiki.cern.ch/twiki/bin/viewauth/CMS/DBShifterHelpPage if it does not work; availability depends on the state of the LHC'
63 
64 contact_help = 'If you need assistance, please write an email to %s and %s. If you need immediate/urgent assistance, you can call the Offline DB expert on call (%s).' % (offline_db_experts_email, web_experts_email, offline_db_experts_phone)
65 database_help = '''
66  The database parameter (--db) refers to the database where the tool
67  will connect to read all the data. By default, the production account
68  (through Frontier) will be used.
69 
70  In subcommands which take a source and a destination, --db always refers to
71  the source, and --destdb to the destination. For both of them the following
72  rules apply.
73 
74  The database parameter can be an official alias, a filename or any
75  valid SQLAlchemy URL.
76 
77  The official aliases are the following strings (first column):
78 
79  Alias Level Database RO/RW Notes
80  ------------ ----------- ------------- ---------- -------------------------------
81 
82  pro Production Frontier (ADG) read-only Default.
83  arc Archive Frontier read-only
84  int Integration Frontier read-only
85  dev Development Frontier read-only
86  boost Production Frontier read-only
87  boostprep Development Frontier read-only
88 
89  orapro Production Oracle (ADG) read-only Password required.
90  oraarc Archive Oracle read-only Password required.
91  oraint Integration Oracle read-write Password required.
92  oradev Development Oracle read-write Password required.
93 
94  onlineorapro Production Oracle read-write Password required. Online only.
95  onlineoraint Online Int Oracle read-write Password required. Online only.
96 
97  Most of the time, if you are a regular user, you will want to read/copy
98  conditions from the Frontier production account. Therefore, you can omit
99  the --db parameter, unless you want to read from somewhere else,
100  e.g. from your local SQLite file.
101 
102  In addition, the parameter may be a filename (path) pointing to a local
103  SQLite file, e.g.
104 
105  file.db
106  relative/path/to/file.db
107  /absolute/path/to/file.db
108 
109  Finally, any valid SQLAlchemy URL can be used. This allows full
110  flexibility in cases where it may be needed, e.g.
111 
112  sqlite:// In-memory, volatile SQLite DB.
113  oracle://user@devdb11 Your private Oracle DB in devdb11 [*]
114 
115  [*] See https://account.cern.ch/ -> Services for more information
116  on personal Oracle accounts.
117 
118  For the official aliases, the password will be asked automatically
119  interactively. The same applies for Oracle URLs where the password
120  was not provided inside it, e.g.:
121 
122  oracle://user@devdb11 The tool will prompt you for the password.
123  oracle://user:pass@devdb11 Password inlined. [+]
124 
125  [+] Caution: Never write passwords in command-line parameters in
126  multi-user machines (e.g. lxplus), since other users can see them
127  in the process table (e.g. ps).
128 
129  This means that both the official aliases and the filenames are shortcuts
130  to the full SQLAlchemy URL equivalents, e.g. the following are the same:
131 
132  relative/path/to/file.db === sqlite:///relative/path/to/file.db
133  /absolute/path/to/file.db === sqlite:////absolute/path/to/file.db
134 '''
135 
136 class Synchronization(enum.Enum):
137  any = 'any'
138  validation = 'validation'
139  mc = 'mc'
140  runmc = 'runmc'
141  hlt = 'hlt'
142  express = 'express'
143  prompt = 'prompt'
144  pcl = 'pcl'
145  offline = 'offline'
146 
147 class TimeType(enum.Enum):
148  Run = 'Run'
149  Time = 'Time'
150  Lumi = 'Lumi'
151  Hash = 'Hash'
152  User = 'User'
153 
154 
155 # Schema definition
156 _Base = sqlalchemy.ext.declarative.declarative_base()
157 
158 def fq_name( schema_name, table_name ):
159  name = table_name
160  if schema_name is not None:
161  name = '%s.%s' %(schema_name, table_name)
162  return name
163 
164 db_models = {}
165 
166 class _Col(Enum):
167  nullable = 0
168  notNull = 1
169  pk = 2
170 
171 class DbRef:
172  def __init__(self,refType, refColumn):
173  self.rtype = refType
174  self.rcol = refColumn
175 
176 def fq_col( schema, table, column ):
177  fqn = '%s.%s' %(table, column)
178  if schema is not None:
179  fqn = '%s.%s' %(schema,fqn)
180  return fqn
181 
182 def make_dbtype( backendName, schemaName, baseType ):
183  members = {}
184  deps_reg = set()
185  dbtype_name = '%s_%s' %(baseType.__name__,backendName)
186  members['__tablename__'] = baseType.__tablename__
187  members['__table_args__'] = None
188  if schemaName is not None:
189  members['__table_args__'] = {'schema': schemaName }
190  for k,v in baseType.columns.items():
191  if isinstance(v[0],DbRef):
192  refColDbt = v[0].rtype.columns[v[0].rcol][0]
193  pk = (True if v[1]==_Col.pk else False)
194  if v[1]==_Col.pk:
195  members[k] = sqlalchemy.Column(refColDbt,sqlalchemy.ForeignKey(fq_col(schemaName,v[0].rtype.__tablename__,v[0].rcol)),primary_key=True)
196  else:
197  nullable = (False if v[1] == _Col.notNull else True)
198  members[k] = sqlalchemy.Column(refColDbt,sqlalchemy.ForeignKey(fq_col(schemaName,v[0].rtype.__tablename__,v[0].rcol)),nullable=nullable)
199  if v[0].rtype.__name__ not in deps_reg:
200  deps_reg.add(v[0].rtype.__name__)
201  reftype_name = '%s_%s' %(v[0].rtype.__name__,backendName)
202  members[(v[0].rtype.__name__).lower()] = sqlalchemy.orm.relationship(reftype_name)
203  else:
204  if v[1]==_Col.pk:
205  members[k] = sqlalchemy.Column(v[0],primary_key=True)
206  else:
207  nullable = (True if v[1]==_Col.nullable else False)
208  members[k] = sqlalchemy.Column(v[0],nullable=nullable)
209  dbType = type(dbtype_name,(_Base,),members)
210 
211  if backendName not in db_models.keys():
212  db_models[backendName] = {}
213  db_models[backendName][baseType.__name__] = dbType
214  return dbType
215 
216 def getSchema(tp):
217  if tp.__table_args__ is not None:
218  return tp.__table_args__['schema']
219  return None
220 
221 class Tag:
222  __tablename__ = 'TAG'
223  columns = { 'name': (sqlalchemy.String(name_length),_Col.pk),
224  'time_type': (sqlalchemy.Enum(*tuple(TimeType.__members__.keys())),_Col.notNull),
225  'object_type': (sqlalchemy.String(name_length),_Col.notNull),
226  'synchronization': (sqlalchemy.Enum(*tuple(Synchronization.__members__.keys())),_Col.notNull),
227  'description': (sqlalchemy.String(description_length),_Col.notNull),
228  'last_validated_time':(sqlalchemy.BIGINT,_Col.notNull),
229  'end_of_validity':(sqlalchemy.BIGINT,_Col.notNull),
230  'insertion_time':(sqlalchemy.TIMESTAMP,_Col.notNull),
231  'modification_time':(sqlalchemy.TIMESTAMP,_Col.notNull) }
232 
234  __tablename__ = 'TAG_METADATA'
235  columns = { 'tag_name': (DbRef(Tag,'name'),_Col.pk),
236  'min_serialization_v': (sqlalchemy.String(20),_Col.notNull),
237  'min_since': (sqlalchemy.BIGINT,_Col.notNull),
238  'modification_time':(sqlalchemy.TIMESTAMP,_Col.notNull) }
239 
240 class Payload:
241  __tablename__ = 'PAYLOAD'
242  columns = { 'hash': (sqlalchemy.CHAR(hash_length),_Col.pk),
243  'object_type': (sqlalchemy.String(name_length),_Col.notNull),
244  'data': (sqlalchemy.BLOB,_Col.notNull),
245  'streamer_info':(sqlalchemy.BLOB,_Col.notNull),
246  'version':(sqlalchemy.String(20),_Col.notNull),
247  'insertion_time':(sqlalchemy.TIMESTAMP,_Col.notNull) }
248 
249 
250 class IOV:
251  __tablename__ = 'IOV'
252  columns = { 'tag_name':(DbRef(Tag,'name'),_Col.pk),
253  'since':(sqlalchemy.BIGINT,_Col.pk),
254  'insertion_time':(sqlalchemy.TIMESTAMP,_Col.pk),
255  'payload_hash':(DbRef(Payload,'hash'),_Col.notNull) }
256 
257 
258 class GlobalTag:
259  __tablename__ = 'GLOBAL_TAG'
260  columns = { 'name':(sqlalchemy.String(name_length),_Col.pk),
261  'validity': (sqlalchemy.BIGINT,_Col.notNull),
262  'description':(sqlalchemy.String(description_length),_Col.notNull),
263  'release':(sqlalchemy.String(name_length),_Col.notNull),
264  'insertion_time':(sqlalchemy.TIMESTAMP,_Col.notNull),
265  'snapshot_time':(sqlalchemy.TIMESTAMP,_Col.notNull) }
266 
268  __tablename__ = 'GLOBAL_TAG_MAP'
269  columns = { 'global_tag_name':(DbRef(GlobalTag,'name'),_Col.pk),
270  'record':(sqlalchemy.String(name_length),_Col.pk),
271  'label':(sqlalchemy.String(name_length),_Col.pk),
272  'tag_name':(DbRef(Tag,'name'),_Col.notNull) }
273 
274 
275 
276 class TagLog:
277  __tablename__ = 'TAG_LOG'
278  columns = { 'tag_name':(DbRef(Tag,'name'),_Col.pk),
279  'event_time':(sqlalchemy.TIMESTAMP,_Col.pk),
280  'action':(sqlalchemy.String(100),_Col.pk),
281  'user_name':(sqlalchemy.String(100),_Col.notNull),
282  'host_name':(sqlalchemy.String(100),_Col.notNull),
283  'command':(sqlalchemy.String(500),_Col.notNull),
284  'user_text':(sqlalchemy.String(4000),_Col.notNull) }
285 
286 class RunInfo:
287  __tablename__ = 'RUN_INFO'
288  columns = { 'run_number':(sqlalchemy.BIGINT,_Col.pk),
289  'start_time':(sqlalchemy.TIMESTAMP,_Col.notNull),
290  'end_time':(sqlalchemy.TIMESTAMP,_Col.notNull) }
291 
293  __tablename__ = 'BOOST_RUN_MAP'
294  columns = { 'run_number':(sqlalchemy.BIGINT,_Col.pk),
295  'run_start_time':(sqlalchemy.TIMESTAMP,_Col.notNull),
296  'boost_version': (sqlalchemy.String(20),_Col.notNull) }
297 
298 # CondDB object
300 
301  def __init__(self, url):
302  # Workaround to avoid creating files if not present.
303  # Python's sqlite3 module does not use sqlite3_open_v2(),
304  # and therefore we cannot disable SQLITE_OPEN_CREATE.
305  # Only in the case of creating a new database we skip the check.
306  if url.drivername == 'sqlite':
307 
308  self.engine = sqlalchemy.create_engine(url)
309 
310  enabled_foreign_keys = self.engine.execute('pragma foreign_keys').scalar()
311  supports_foreign_keys = enabled_foreign_keys is not None
312  if not supports_foreign_keys:
313  logger.warning('Your SQLite database does not support foreign keys, so constraints will not be checked. Please upgrade.')
314  elif not enabled_foreign_keys:
315  self.engine.execute('pragma foreign_keys = on')
316 
317  else:
318  self.engine = sqlalchemy.create_engine(url)
319 
320  self._session = sqlalchemy.orm.scoped_session(sqlalchemy.orm.sessionmaker(bind=self.engine))
321 
322  self._is_frontier = url.drivername == 'oracle+frontier'
323  self._is_oracle = url.drivername == 'oracle'
324  self._is_sqlite = url.drivername == 'sqlite'
325 
326  self._is_read_only = self._is_frontier or url.host in {
327  'cms_orcon_adg',
328  'cmsarc_lb',
329  }
330 
331  self._is_official = self._is_frontier or url.host in {
332  'cms_orcon_adg',
333  'cmsarc_lb',
334  'cms_orcoff_int',
335  'cms_orcoff_prep',
336  'cms_orcon_prod',
337  'cmsintr_lb',
338  }
339  self._url = url
340  self._backendName = ('sqlite' if self._is_sqlite else 'oracle' )
341  self._schemaName = ( None if self._is_sqlite else schema_name )
342  logging.debug(' ... using db "%s", schema "%s"' % (url, self._schemaName) )
343  logging.debug('Loading db types...')
344  self.get_dbtype(Tag).__name__
345  self.get_dbtype(Payload)
346  self.get_dbtype(IOV)
347  self.get_dbtype(TagLog)
348  self.get_dbtype(GlobalTag)
349  self.get_dbtype(GlobalTagMap)
350  self.get_dbtype(RunInfo)
351  if not self._is_sqlite:
352  self.get_dbtype(TagMetadata)
353  self.get_dbtype(BoostRunMap)
354  self._is_valid = self.is_valid()
355 
356  def get_dbtype(self,theType):
357  basename = theType.__name__
358  if self._backendName not in db_models.keys() or basename not in db_models[self._backendName].keys():
359  return make_dbtype( self._backendName, self._schemaName, theType )
360  else:
361  return db_models[self._backendName][basename]
362 
363  def session(self):
364  s = self._session()
365  s.get_dbtype = self.get_dbtype
366  s._is_sqlite = self._is_sqlite
367  s.is_oracle = self.is_oracle
368  s._url = self._url
369  return s
370 
371  @property
372  def metadata(self):
373  return _Base.metadata
374 
375  @property
376  def is_frontier(self):
377  return self._is_frontier
378 
379  @property
380  def is_oracle(self):
381  return self._is_oracle
382 
383  @property
384  def is_sqlite(self):
385  return self._is_sqlite
386 
387  @property
388  def is_read_only(self):
389  return self._is_read_only
390 
391  @property
392  def is_official(self):
393  return self._is_official
394 
395  def is_valid(self):
396  '''Tests whether the current DB looks like a valid CMS Conditions one.
397  '''
398  engine_connection = self.engine.connect()
399  # temporarely avoid the check on the GT tables - there are releases in use where C++ does not create these tables.
400  _Tag = self.get_dbtype(Tag)
401  _IOV = self.get_dbtype(IOV)
402  _Payload = self.get_dbtype(Payload)
403  ret = all([self.engine.dialect.has_table(engine_connection, table.__tablename__,getSchema(table)) for table in [_Tag, _IOV, _Payload]])
404  engine_connection.close()
405  return ret
406 
407  def init(self, drop=False):
408  '''Initializes a database.
409  '''
410  logging.info('Initializing database...')
411  if drop:
412  logging.debug('Dropping tables...')
413  self.metadata.drop_all(self.engine)
414  self._is_valid = False
415  else:
416  if not self._is_valid:
417  logging.debug('Creating tables...')
418  self.get_dbtype(Tag).__table__.create(bind = self.engine)
419  self.get_dbtype(Payload).__table__.create(bind = self.engine)
420  self.get_dbtype(IOV).__table__.create(bind = self.engine)
421  self.get_dbtype(TagLog).__table__.create(bind = self.engine)
422  self.get_dbtype(GlobalTag).__table__.create(bind = self.engine)
423  self.get_dbtype(GlobalTagMap).__table__.create(bind = self.engine)
424  self._is_valid = True
425 
426 def getSessionOnMasterDB( session1, session2 ):
427  key = '%s/%s'
428  sessiondict = { }
429  sessiondict[key %(session1._url.drivername,session1._url.host)] = session1
430  sessiondict[key %(session2._url.drivername,session2._url.host)] = session2
431  masterkey = key %('oracle',ONLINEORAPRO)
432  if masterkey in sessiondict.keys():
433  return sessiondict[masterkey]
434  adgkey = key %('oracle',ORAPRO)
435  if adgkey in sessiondict.keys():
436  return sessiondict[adgkey]
437  frontierkey = key %('frontier',PRO)
438  if frontierkey in sessiondict.keys():
439  return sessiondict[frontierkey]
440  # default case: frontier on pro
441  conn = Connection(make_url())
442  session = conn.session()
443  # is it required?
444  session._conn = conn
445  return session
446 
447 # Connection helpers
449  import subprocess
450  return subprocess.Popen(['cmsGetFnConnect', 'frontier://%s' % database], stdout = subprocess.PIPE).communicate()[0].strip()
451 
452 def _getCMSSQLAlchemyConnectionString(technology,service,schema_name):
453  if technology == 'frontier':
454  import urllib
455  import sys
456  py3k = sys.version_info >= (3, 0)
457  if py3k:
458  return '%s://@%s/%s' % ('oracle+frontier', urllib.parse.quote_plus(_getCMSFrontierConnectionString(service)), schema_name )
459  else:
460  return '%s://@%s/%s' % ('oracle+frontier', urllib.quote_plus(_getCMSFrontierConnectionString(service)), schema_name )
461  elif technology == 'oracle':
462  return '%s://%s@%s' % (technology, schema_name, service)
463 
464 # Entry point
465 def make_url(database='pro',read_only = True):
466  if database.startswith('sqlite:') or database.startswith('sqlite_file:'):
467  ignore, database = database.split(':',1)
468 
469  if ':' in database and '://' not in database: # check if we really got a shortcut like "pro:<schema>" (and not a url like proto://...), if so, disentangle
470  database, schema = database.split(':')
471 
472  officialdbs = {
473  # frontier
474  'pro' : ('frontier','PromptProd', { 'R': schema_name }, ),
475  'arc' : ('frontier','FrontierArc', { 'R': schema_name }, ),
476  'int' : ('frontier','FrontierInt', { 'R': schema_name }, ),
477  'dev' : ('frontier','FrontierPrep', { 'R': schema_name }, ),
478  # oracle adg
479  'orapro': ('oracle', 'cms_orcon_adg', { 'R': dbreader_user_name }, ),
480  'oraarc': ('oracle', 'cmsarc_lb', { 'R': dbreader_user_name }, ),
481  # oracle masters
482  'oraint': ('oracle', 'cms_orcoff_int', { 'R': dbreader_user_name,
483  'W': dbwriter_user_name }, ),
484  'oradev': ('oracle', 'cms_orcoff_prep', { 'R': dbreader_user_name,
485  'W': devdbwriter_user_name }, ),
486  'onlineorapro': ('oracle', 'cms_orcon_prod', { 'R': dbreader_user_name,
487  'W': dbwriter_user_name }, ),
488  'onlineoraint': ('oracle', 'cmsintr_lb', { 'R': dbreader_user_name,
489  'W': dbwriter_user_name }, ),
490  }
491 
492  if database in officialdbs.keys():
493  key = ('R' if read_only else 'W')
494  mapping = officialdbs[database]
495  tech = mapping[0]
496  service = mapping[1]
497  schema_dict = mapping[2]
498  if key in schema_dict.keys():
499  database = _getCMSSQLAlchemyConnectionString(tech,service,schema_dict[key])
500  else:
501  raise Exception("Read-only database %s://%s cannot be accessed in update mode." %(tech,service))
502 
503  logging.debug('connection string set to "%s"' % database)
504 
505  try:
506  url = sqlalchemy.engine.url.make_url(database)
507  except sqlalchemy.exc.ArgumentError:
508  url = sqlalchemy.engine.url.make_url('sqlite:///%s' % database)
509  return url
510 
511 def connect(url, authPath=None, verbose=0):
512  '''Returns a Connection instance to the CMS Condition DB.
513 
514  See database_help for the description of the database parameter.
515 
516  The verbosity level is as follows:
517 
518  0 = No output (default).
519  1 = SQL statements issued, including their parameters.
520  2 = In addition, results of the queries (all rows and the column headers).
521  '''
522 
523  if url.drivername == 'oracle':
524  if url.username is None:
525  logging.error('Could not resolve the username for the connection %s. Please provide a connection in the format oracle://[user]:[pass]@[host]' %url )
526  raise Exception('Connection format error: %s' %url )
527  if url.password is None:
528  if authPath is None:
529  if authPathEnvVar in os.environ:
530  authPath = os.environ[authPathEnvVar]
531  authFile = None
532  if authPath is not None:
533  authFile = os.path.join(authPath,'.netrc')
534  if authFile is not None:
535  entryKey = url.host.lower()+"/"+url.username.lower()
536  logging.debug('Looking up credentials for %s in file %s ' %(entryKey,authFile) )
537  import netrc
538  params = netrc.netrc( authFile ).authenticators(entryKey)
539  if params is not None:
540  (username, account, password) = params
541  url.password = password
542  else:
543  msg = 'The entry %s has not been found in the .netrc file.' %entryKey
544  raise TypeError(msg)
545  else:
546  import getpass
547  pwd = getpass.getpass('Password for %s: ' % str(url))
548  if pwd is None or pwd == '':
549  pwd = getpass.getpass('Password for %s: ' % str(url))
550  if pwd is None or pwd == '':
551  raise Exception('Empty password provided, bailing out...')
552  url.password = pwd
553 
554  if verbose >= 1:
555  logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
556 
557  if verbose >= 2:
558  logging.getLogger('sqlalchemy.engine').setLevel(logging.DEBUG)
559 
560  return Connection(url)
561 
562 
563 def _exists(session, primary_key, value):
564  ret = None
565  try:
566  ret = session.query(primary_key).\
567  filter(primary_key == value).\
568  count() != 0
569  except sqlalchemy.exc.OperationalError:
570  pass
571 
572  return ret
573 
574 def _inserted_before(timestamp):
575  '''To be used inside filter().
576  '''
577 
578  if timestamp is None:
579  # XXX: Returning None does not get optimized (skipped) by SQLAlchemy,
580  # and returning True does not work in Oracle (generates "and 1"
581  # which breaks Oracle but not SQLite). For the moment just use
582  # this dummy condition.
583  return sqlalchemy.literal(True) == sqlalchemy.literal(True)
584 
585  return conddb.IOV.insertion_time <= _parse_timestamp(timestamp)
586 
587 def listObject(session, name, snapshot=None):
588 
589  is_tag = _exists(session, Tag.name, name)
590  result = {}
591  if is_tag:
592  result['type'] = 'Tag'
593  result['name'] = session.query(Tag).get(name).name
594  result['timeType'] = session.query(Tag.time_type).\
595  filter(Tag.name == name).\
596  scalar()
597 
598  result['iovs'] = session.query(IOV.since, IOV.insertion_time, IOV.payload_hash, Payload.object_type).\
599  join(IOV.payload).\
600  filter(
601  IOV.tag_name == name,
602  _inserted_before(snapshot),
603  ).\
604  order_by(IOV.since.desc(), IOV.insertion_time.desc()).\
605  from_self().\
606  order_by(IOV.since, IOV.insertion_time).\
607  all()
608 
609  try:
610  is_global_tag = _exists(session, GlobalTag.name, name)
611  if is_global_tag:
612  result['type'] = 'GlobalTag'
613  result['name'] = session.query(GlobalTag).get(name)
614  result['tags'] = session.query(GlobalTagMap.record, GlobalTagMap.label, GlobalTagMap.tag_name).\
615  filter(GlobalTagMap.global_tag_name == name).\
616  order_by(GlobalTagMap.record, GlobalTagMap.label).\
617  all()
618  except sqlalchemy.exc.OperationalError:
619  sys.stderr.write("No table for GlobalTags found in DB.\n\n")
620 
621  if not is_tag and not is_global_tag:
622  raise Exception('There is no tag or global tag named %s in the database.' % name)
623 
624  return result
625 
626 def getPayload(session, hash):
627  # get payload from DB:
628  data, payloadType = session.query(Payload.data, Payload.object_type).filter(Payload.hash == hash).one()
629  return data
conddblib.Connection._url
_url
Definition: conddblib.py:339
conddblib.TagLog
Definition: conddblib.py:276
conddblib.GlobalTag
Definition: conddblib.py:258
conddblib.make_dbtype
def make_dbtype(backendName, schemaName, baseType)
Definition: conddblib.py:182
conddblib.DbRef
Definition: conddblib.py:171
resolutioncreator_cfi.object
object
Definition: resolutioncreator_cfi.py:4
conddblib.Tag
Definition: conddblib.py:221
digitizers_cfi.strip
strip
Definition: digitizers_cfi.py:19
join
static std::string join(char **cmd)
Definition: RemoteFile.cc:17
conddblib.Connection.__init__
def __init__(self, url)
Definition: conddblib.py:301
relativeConstraints.keys
keys
Definition: relativeConstraints.py:89
conddblib.Connection._backendName
_backendName
Definition: conddblib.py:340
python.cmstools.all
def all(container)
workaround iterator generators for ROOT classes
Definition: cmstools.py:26
conddblib.GlobalTagMap
Definition: conddblib.py:267
conddblib.DbRef.rcol
rcol
Definition: conddblib.py:174
conddblib.fq_col
def fq_col(schema, table, column)
Definition: conddblib.py:176
conddblib.Payload
Definition: conddblib.py:240
conddblib.Connection.get_dbtype
def get_dbtype(self, theType)
Definition: conddblib.py:356
conddblib.fq_name
def fq_name(schema_name, table_name)
Definition: conddblib.py:158
conddblib.Connection._is_official
_is_official
Definition: conddblib.py:331
conddblib.BoostRunMap
Definition: conddblib.py:292
conddblib.getPayload
def getPayload(session, hash)
Definition: conddblib.py:626
conddblib._inserted_before
def _inserted_before(timestamp)
Definition: conddblib.py:574
conddblib._getCMSSQLAlchemyConnectionString
def _getCMSSQLAlchemyConnectionString(technology, service, schema_name)
Definition: conddblib.py:452
conddblib.Connection.is_frontier
def is_frontier(self)
Definition: conddblib.py:376
conddblib.hash
def hash(data)
Definition: conddblib.py:49
str
#define str(s)
Definition: TestProcessor.cc:48
communicate
static void * communicate(void *obj)
Definition: DQMNet.cc:1049
hitfit::scalar
double scalar(const CLHEP::HepGenMatrix &m)
Return the matrix as a scalar. Raise an assertion if the matris is not .
Definition: matutil.cc:166
ALCARECOTkAlBeamHalo_cff.filter
filter
Definition: ALCARECOTkAlBeamHalo_cff.py:27
conddblib.TimeType
Definition: conddblib.py:147
conddblib.Connection._is_read_only
_is_read_only
Definition: conddblib.py:326
conddblib.Synchronization
Definition: conddblib.py:136
conddblib.Connection._session
_session
Definition: conddblib.py:320
conddblib.Connection._is_valid
_is_valid
Definition: conddblib.py:354
conddblib.getSessionOnMasterDB
def getSessionOnMasterDB(session1, session2)
Definition: conddblib.py:426
conddblib.DbRef.__init__
def __init__(self, refType, refColumn)
Definition: conddblib.py:172
KineDebug3::count
void count()
Definition: KinematicConstrainedVertexUpdatorT.h:21
conddblib.Connection.session
def session(self)
Definition: conddblib.py:363
Exception
conddblib.Connection._schemaName
_schemaName
Definition: conddblib.py:341
conddblib.Connection.metadata
def metadata(self)
Definition: conddblib.py:372
conddblib.DbRef.rtype
rtype
Definition: conddblib.py:173
conddblib.TagMetadata
Definition: conddblib.py:233
conddblib.getSchema
def getSchema(tp)
Definition: conddblib.py:216
conddblib.Connection.is_read_only
def is_read_only(self)
Definition: conddblib.py:388
conddblib.connect
def connect(url, authPath=None, verbose=0)
Definition: conddblib.py:511
conddblib.Connection._is_sqlite
_is_sqlite
Definition: conddblib.py:324
conddblib.Connection.is_valid
def is_valid(self)
Definition: conddblib.py:395
conddblib.listObject
def listObject(session, name, snapshot=None)
Definition: conddblib.py:587
conddblib.Connection.is_sqlite
def is_sqlite(self)
Definition: conddblib.py:384
conddblib.Connection._is_oracle
_is_oracle
Definition: conddblib.py:323
conddblib.IOV
Definition: conddblib.py:250
conddblib.Connection.init
def init(self, drop=False)
Definition: conddblib.py:407
conddblib._Col
Definition: conddblib.py:166
conddblib.Connection.engine
engine
Definition: conddblib.py:308
conddblib.Connection
Definition: conddblib.py:299
conddblib.Connection.is_official
def is_official(self)
Definition: conddblib.py:392
conddblib.Connection.is_oracle
def is_oracle(self)
Definition: conddblib.py:380
conddblib._exists
def _exists(session, primary_key, value)
Definition: conddblib.py:563
conddblib.RunInfo
Definition: conddblib.py:286
conddblib._getCMSFrontierConnectionString
def _getCMSFrontierConnectionString(database)
Definition: conddblib.py:448
conddblib.Connection._is_frontier
_is_frontier
Definition: conddblib.py:322
conddblib.make_url
def make_url(database='pro', read_only=True)
Definition: conddblib.py:465