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