CMS 3D CMS Logo

Classes | Functions
conddblib Namespace Reference

Classes

class  _Col
 
class  BoostRunMap
 
class  Connection
 
class  DbRef
 
class  GlobalTag
 
class  GlobalTagMap
 
class  IOV
 
class  Payload
 
class  RunInfo
 
class  Synchronization
 
class  Tag
 
class  TagLog
 
class  TagMetadata
 
class  TimeType
 

Functions

def _exists (session, primary_key, value)
 
def _getCMSFrontierConnectionString (database)
 
def _getCMSSQLAlchemyConnectionString (technology, service, schema_name)
 
def _inserted_before (timestamp)
 
def connect (url, authPath=None, verbose=0)
 
def fq_col (schema, table, column)
 
def fq_name (schema_name, table_name)
 
def getPayload (session, hash)
 
def getSchema (tp)
 
def getSessionOnMasterDB (session1, session2)
 
def hash (data)
 
def listObject (session, name, snapshot=None)
 
def make_dbtype (backendName, schemaName, baseType)
 
def make_url (database='pro', read_only=True)
 

Detailed Description

CMS Conditions DB Python library.

Function Documentation

◆ _exists()

def conddblib._exists (   session,
  primary_key,
  value 
)
private

Definition at line 563 of file conddblib.py.

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 

References KineDebug3.count(), and ALCARECOTkAlBeamHalo_cff.filter.

Referenced by listObject().

◆ _getCMSFrontierConnectionString()

def conddblib._getCMSFrontierConnectionString (   database)
private

Definition at line 448 of file conddblib.py.

448 def _getCMSFrontierConnectionString(database):
449  import subprocess
450  return subprocess.Popen(['cmsGetFnConnect', 'frontier://%s' % database], stdout = subprocess.PIPE).communicate()[0].strip()
451 

References communicate(), and digitizers_cfi.strip.

Referenced by _getCMSSQLAlchemyConnectionString().

◆ _getCMSSQLAlchemyConnectionString()

def conddblib._getCMSSQLAlchemyConnectionString (   technology,
  service,
  schema_name 
)
private

Definition at line 452 of file conddblib.py.

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

References _getCMSFrontierConnectionString().

Referenced by make_url().

◆ _inserted_before()

def conddblib._inserted_before (   timestamp)
private
To be used inside filter().

Definition at line 574 of file conddblib.py.

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 

Referenced by listObject().

◆ connect()

def conddblib.connect (   url,
  authPath = None,
  verbose = 0 
)
Returns a Connection instance to the CMS Condition DB.

See database_help for the description of the database parameter.

The verbosity level is as follows:

    0 = No output (default).
    1 = SQL statements issued, including their parameters.
    2 = In addition, results of the queries (all rows and the column headers).

Definition at line 511 of file conddblib.py.

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 

References str.

Referenced by helperFunctions.getTagsMap(), and conddblib.Connection.is_valid().

◆ fq_col()

def conddblib.fq_col (   schema,
  table,
  column 
)

Definition at line 176 of file conddblib.py.

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 

Referenced by make_dbtype().

◆ fq_name()

def conddblib.fq_name (   schema_name,
  table_name 
)

Definition at line 158 of file conddblib.py.

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 

◆ getPayload()

def conddblib.getPayload (   session,
  hash 
)

Definition at line 626 of file conddblib.py.

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

References ALCARECOTkAlBeamHalo_cff.filter.

◆ getSchema()

def conddblib.getSchema (   tp)

Definition at line 216 of file conddblib.py.

216 def getSchema(tp):
217  if tp.__table_args__ is not None:
218  return tp.__table_args__['schema']
219  return None
220 

Referenced by conddblib.Connection.is_valid().

◆ getSessionOnMasterDB()

def conddblib.getSessionOnMasterDB (   session1,
  session2 
)

Definition at line 426 of file conddblib.py.

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

References make_url().

◆ hash()

def conddblib.hash (   data)

Definition at line 49 of file conddblib.py.

49 def hash(data):
50  return hashlib.sha1(data.encode('ascii')).hexdigest()
51 
52 
53 # Constants

◆ listObject()

def conddblib.listObject (   session,
  name,
  snapshot = None 
)

Definition at line 587 of file conddblib.py.

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 

References _exists(), _inserted_before(), python.cmstools.all(), ALCARECOTkAlBeamHalo_cff.filter, join(), and hitfit.scalar().

◆ make_dbtype()

def conddblib.make_dbtype (   backendName,
  schemaName,
  baseType 
)

Definition at line 182 of file conddblib.py.

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 

References fq_col().

Referenced by conddblib.Connection.get_dbtype().

◆ make_url()

def conddblib.make_url (   database = 'pro',
  read_only = True 
)

Definition at line 465 of file conddblib.py.

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 

References _getCMSSQLAlchemyConnectionString().

Referenced by getSessionOnMasterDB(), and helperFunctions.getTagsMap().

conddblib.make_dbtype
def make_dbtype(backendName, schemaName, baseType)
Definition: conddblib.py:182
digitizers_cfi.strip
strip
Definition: digitizers_cfi.py:19
join
static std::string join(char **cmd)
Definition: RemoteFile.cc:17
python.cmstools.all
def all(container)
workaround iterator generators for ROOT classes
Definition: cmstools.py:26
conddblib.fq_col
def fq_col(schema, table, column)
Definition: conddblib.py:176
conddblib.fq_name
def fq_name(schema_name, table_name)
Definition: conddblib.py:158
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.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.getSessionOnMasterDB
def getSessionOnMasterDB(session1, session2)
Definition: conddblib.py:426
KineDebug3::count
void count()
Definition: KinematicConstrainedVertexUpdatorT.h:21
Exception
conddblib.getSchema
def getSchema(tp)
Definition: conddblib.py:216
conddblib.connect
def connect(url, authPath=None, verbose=0)
Definition: conddblib.py:511
conddblib.listObject
def listObject(session, name, snapshot=None)
Definition: conddblib.py:587
conddblib._exists
def _exists(session, primary_key, value)
Definition: conddblib.py:563
conddblib._getCMSFrontierConnectionString
def _getCMSFrontierConnectionString(database)
Definition: conddblib.py:448
conddblib.make_url
def make_url(database='pro', read_only=True)
Definition: conddblib.py:465