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)
 
def oracle_connection_string (db_service, db_schema)
 

Detailed Description

CMS Conditions DB Python library.

Function Documentation

◆ _exists()

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

Definition at line 581 of file conddblib.py.

581 def _exists(session, primary_key, value):
582  ret = None
583  try:
584  ret = session.query(primary_key).\
585  filter(primary_key == value).\
586  count() != 0
587  except sqlalchemy.exc.OperationalError:
588  pass
589 
590  return ret
591 

References submitPVResolutionJobs.count, and ALCARECOTkAlBeamHalo_cff.filter.

Referenced by listObject().

◆ _getCMSFrontierConnectionString()

def conddblib._getCMSFrontierConnectionString (   database)
private

Definition at line 453 of file conddblib.py.

453 def _getCMSFrontierConnectionString(database):
454  import subprocess
455  return subprocess.Popen(['cmsGetFnConnect', 'frontier://%s' % database], stdout = subprocess.PIPE).communicate()[0].strip()
456 

References communicate(), and digitizers_cfi.strip.

Referenced by _getCMSSQLAlchemyConnectionString().

◆ _getCMSSQLAlchemyConnectionString()

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

Definition at line 457 of file conddblib.py.

457 def _getCMSSQLAlchemyConnectionString(technology,service,schema_name):
458  if technology == 'frontier':
459  import urllib
460  import sys
461  py3k = sys.version_info >= (3, 0)
462  if py3k:
463  return '%s://@%s/%s' % ('oracle+frontier', urllib.parse.quote_plus(_getCMSFrontierConnectionString(service)), schema_name )
464  else:
465  return '%s://@%s/%s' % ('oracle+frontier', urllib.quote_plus(_getCMSFrontierConnectionString(service)), schema_name )
466  elif technology == 'oracle':
467  return '%s://%s@%s' % (technology, schema_name, service)
468 
469 # Entry point

References _getCMSFrontierConnectionString().

Referenced by make_url().

◆ _inserted_before()

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

Definition at line 592 of file conddblib.py.

592 def _inserted_before(timestamp):
593  '''To be used inside filter().
594  '''
595 
596  if timestamp is None:
597  # XXX: Returning None does not get optimized (skipped) by SQLAlchemy,
598  # and returning True does not work in Oracle (generates "and 1"
599  # which breaks Oracle but not SQLite). For the moment just use
600  # this dummy condition.
601  return sqlalchemy.literal(True) == sqlalchemy.literal(True)
602 
603  return conddb.IOV.insertion_time <= _parse_timestamp(timestamp)
604 

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 516 of file conddblib.py.

516 def connect(url, authPath=None, verbose=0):
517  '''Returns a Connection instance to the CMS Condition DB.
518 
519  See database_help for the description of the database parameter.
520 
521  The verbosity level is as follows:
522 
523  0 = No output (default).
524  1 = SQL statements issued, including their parameters.
525  2 = In addition, results of the queries (all rows and the column headers).
526  '''
527 
528  if url.drivername == 'oracle':
529  if url.username is None:
530  logging.error('Could not resolve the username for the connection %s. Please provide a connection in the format oracle://[user]:[pass]@[host]' %url )
531  raise Exception('Connection format error: %s' %url )
532  if url.password is None:
533  if authPath is None:
534  if authPathEnvVar in os.environ:
535  authPath = os.environ[authPathEnvVar]
536  explicit_auth = False
537  if authPath is not None:
538  dbkey_path = os.path.join(authPath,dbkey_folder)
539  if not os.path.exists(dbkey_path):
540  authFile = os.path.join(authPath,'.netrc')
541  if os.path.exists(authFile):
542  entryKey = url.host.lower()+"/"+url.username.lower()
543  logging.debug('Looking up credentials for %s in file %s ' %(entryKey,authFile) )
544  import netrc
545  params = netrc.netrc( authFile ).authenticators(entryKey)
546  if params is not None:
547  (username, account, password) = params
548  url.username = username
549  url.password = password
550  else:
551  msg = 'The entry %s has not been found in the .netrc file.' %entryKey
552  raise TypeError(msg)
553  else:
554  explicit_auth =True
555  else:
556  import pluginCondDBPyBind11Interface as credential_store
557  connect_for_update = ( url.username == dbwriter_user_name )
558  connection_string = oracle_connection_string(url.host.lower(),schema_name)
559  logging.debug('Using db key to get credentials for %s' %connection_string )
560  (username,password) = credential_store.get_db_credentials(connection_string,connect_for_update,authPath)
561  url.username = username
562  url.password = password
563  else:
564  import getpass
565  pwd = getpass.getpass('Password for %s: ' % str(url))
566  if pwd is None or pwd == '':
567  pwd = getpass.getpass('Password for %s: ' % str(url))
568  if pwd is None or pwd == '':
569  raise Exception('Empty password provided, bailing out...')
570  url.password = pwd
571 
572  if verbose >= 1:
573  logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
574 
575  if verbose >= 2:
576  logging.getLogger('sqlalchemy.engine').setLevel(logging.DEBUG)
577 
578  return Connection(url)
579 
580 

References oracle_connection_string(), and str.

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

◆ fq_col()

def conddblib.fq_col (   schema,
  table,
  column 
)

Definition at line 182 of file conddblib.py.

182 def fq_col( schema, table, column ):
183  fqn = '%s.%s' %(table, column)
184  if schema is not None:
185  fqn = '%s.%s' %(schema,fqn)
186  return fqn
187 

Referenced by make_dbtype().

◆ fq_name()

def conddblib.fq_name (   schema_name,
  table_name 
)

Definition at line 164 of file conddblib.py.

164 def fq_name( schema_name, table_name ):
165  name = table_name
166  if schema_name is not None:
167  name = '%s.%s' %(schema_name, table_name)
168  return name
169 

◆ getPayload()

def conddblib.getPayload (   session,
  hash 
)

Definition at line 644 of file conddblib.py.

644 def getPayload(session, hash):
645  # get payload from DB:
646  data, payloadType = session.query(Payload.data, Payload.object_type).filter(Payload.hash == hash).one()
647  return data

References ALCARECOTkAlBeamHalo_cff.filter, and SiPixelPI.one.

◆ getSchema()

def conddblib.getSchema (   tp)

Definition at line 222 of file conddblib.py.

222 def getSchema(tp):
223  if tp.__table_args__ is not None:
224  return tp.__table_args__['schema']
225  return None
226 

Referenced by conddblib.Connection.is_valid().

◆ getSessionOnMasterDB()

def conddblib.getSessionOnMasterDB (   session1,
  session2 
)

Definition at line 431 of file conddblib.py.

431 def getSessionOnMasterDB( session1, session2 ):
432  key = '%s/%s'
433  sessiondict = { }
434  sessiondict[key %(session1._url.drivername,session1._url.host)] = session1
435  sessiondict[key %(session2._url.drivername,session2._url.host)] = session2
436  masterkey = key %('oracle',ONLINEORAPRO)
437  if masterkey in sessiondict.keys():
438  return sessiondict[masterkey]
439  adgkey = key %('oracle',ORAPRO)
440  if adgkey in sessiondict.keys():
441  return sessiondict[adgkey]
442  frontierkey = key %('frontier',PRO)
443  if frontierkey in sessiondict.keys():
444  return sessiondict[frontierkey]
445  # default case: frontier on pro
446  conn = Connection(make_url())
447  session = conn.session()
448  # is it required?
449  session._conn = conn
450  return session
451 
452 # Connection helpers

References make_url().

◆ hash()

def conddblib.hash (   data)

Definition at line 52 of file conddblib.py.

52 def hash(data):
53  return hashlib.sha1(data.encode('ascii')).hexdigest()
54 
55 
56 # Constants

◆ listObject()

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

Definition at line 605 of file conddblib.py.

605 def listObject(session, name, snapshot=None):
606 
607  is_tag = _exists(session, Tag.name, name)
608  result = {}
609  if is_tag:
610  result['type'] = 'Tag'
611  result['name'] = session.query(Tag).get(name).name
612  result['timeType'] = session.query(Tag.time_type).\
613  filter(Tag.name == name).\
614  scalar()
615 
616  result['iovs'] = session.query(IOV.since, IOV.insertion_time, IOV.payload_hash, Payload.object_type).\
617  join(IOV.payload).\
618  filter(
619  IOV.tag_name == name,
620  _inserted_before(snapshot),
621  ).\
622  order_by(IOV.since.desc(), IOV.insertion_time.desc()).\
623  from_self().\
624  order_by(IOV.since, IOV.insertion_time).\
625  all()
626 
627  try:
628  is_global_tag = _exists(session, GlobalTag.name, name)
629  if is_global_tag:
630  result['type'] = 'GlobalTag'
631  result['name'] = session.query(GlobalTag).get(name)
632  result['tags'] = session.query(GlobalTagMap.record, GlobalTagMap.label, GlobalTagMap.tag_name).\
633  filter(GlobalTagMap.global_tag_name == name).\
634  order_by(GlobalTagMap.record, GlobalTagMap.label).\
635  all()
636  except sqlalchemy.exc.OperationalError:
637  sys.stderr.write("No table for GlobalTags found in DB.\n\n")
638 
639  if not is_tag and not is_global_tag:
640  raise Exception('There is no tag or global tag named %s in the database.' % name)
641 
642  return result
643 

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 188 of file conddblib.py.

188 def make_dbtype( backendName, schemaName, baseType ):
189  members = {}
190  deps_reg = set()
191  dbtype_name = '%s_%s' %(baseType.__name__,backendName)
192  members['__tablename__'] = baseType.__tablename__
193  members['__table_args__'] = None
194  if schemaName is not None:
195  members['__table_args__'] = {'schema': schemaName }
196  for k,v in baseType.columns.items():
197  if isinstance(v[0],DbRef):
198  refColDbt = v[0].rtype.columns[v[0].rcol][0]
199  pk = (True if v[1]==_Col.pk else False)
200  if v[1]==_Col.pk:
201  members[k] = sqlalchemy.Column(refColDbt,sqlalchemy.ForeignKey(fq_col(schemaName,v[0].rtype.__tablename__,v[0].rcol)),primary_key=True)
202  else:
203  nullable = (False if v[1] == _Col.notNull else True)
204  members[k] = sqlalchemy.Column(refColDbt,sqlalchemy.ForeignKey(fq_col(schemaName,v[0].rtype.__tablename__,v[0].rcol)),nullable=nullable)
205  if v[0].rtype.__name__ not in deps_reg:
206  deps_reg.add(v[0].rtype.__name__)
207  reftype_name = '%s_%s' %(v[0].rtype.__name__,backendName)
208  members[(v[0].rtype.__name__).lower()] = sqlalchemy.orm.relationship(reftype_name)
209  else:
210  if v[1]==_Col.pk:
211  members[k] = sqlalchemy.Column(v[0],primary_key=True)
212  else:
213  nullable = (True if v[1]==_Col.nullable else False)
214  members[k] = sqlalchemy.Column(v[0],nullable=nullable)
215  dbType = type(dbtype_name,(_Base,),members)
216 
217  if backendName not in db_models.keys():
218  db_models[backendName] = {}
219  db_models[backendName][baseType.__name__] = dbType
220  return dbType
221 

References fq_col().

Referenced by conddblib.Connection.get_dbtype().

◆ make_url()

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

Definition at line 470 of file conddblib.py.

470 def make_url(database='pro',read_only = True):
471  if database.startswith('sqlite:') or database.startswith('sqlite_file:'):
472  ignore, database = database.split(':',1)
473 
474  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
475  database, schema = database.split(':')
476 
477  officialdbs = {
478  # frontier
479  'pro' : ('frontier','PromptProd', { 'R': schema_name }, ),
480  'arc' : ('frontier','FrontierArc', { 'R': schema_name }, ),
481  'int' : ('frontier','FrontierInt', { 'R': schema_name }, ),
482  'dev' : ('frontier','FrontierPrep', { 'R': schema_name }, ),
483  # oracle adg
484  'orapro': ('oracle', 'cms_orcon_adg', { 'R': dbreader_user_name }, ),
485  'oraarc': ('oracle', 'cmsarc_lb', { 'R': dbreader_user_name }, ),
486  # oracle masters
487  'oraint': ('oracle', 'cms_orcoff_int', { 'R': dbreader_user_name,
488  'W': dbwriter_user_name }, ),
489  'oradev': ('oracle', 'cms_orcoff_prep', { 'R': dbreader_user_name,
490  'W': dbwriter_user_name }, ),
491  'onlineorapro': ('oracle', 'cms_orcon_prod', { 'R': dbreader_user_name,
492  'W': dbwriter_user_name }, ),
493  'onlineoraint': ('oracle', 'cmsintr_lb', { 'R': dbreader_user_name,
494  'W': dbwriter_user_name }, ),
495  }
496 
497  if database in officialdbs.keys():
498  key = ('R' if read_only else 'W')
499  mapping = officialdbs[database]
500  tech = mapping[0]
501  service = mapping[1]
502  schema_dict = mapping[2]
503  if key in schema_dict.keys():
504  database = _getCMSSQLAlchemyConnectionString(tech,service,schema_dict[key])
505  else:
506  raise Exception("Read-only database %s://%s cannot be accessed in update mode." %(tech,service))
507 
508  logging.debug('connection string set to "%s"' % database)
509 
510  try:
511  url = sqlalchemy.engine.url.make_url(database)
512  except sqlalchemy.exc.ArgumentError:
513  url = sqlalchemy.engine.url.make_url('sqlite:///%s' % database)
514  return url
515 

References _getCMSSQLAlchemyConnectionString().

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

◆ oracle_connection_string()

def conddblib.oracle_connection_string (   db_service,
  db_schema 
)

Definition at line 139 of file conddblib.py.

139 def oracle_connection_string(db_service, db_schema ):
140  return 'oracle://%s/%s'%(db_service,db_schema)
141 

Referenced by connect().

conddblib.make_dbtype
def make_dbtype(backendName, schemaName, baseType)
Definition: conddblib.py:188
SiPixelPI::one
Definition: SiPixelPayloadInspectorHelper.h:39
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:182
conddblib.fq_name
def fq_name(schema_name, table_name)
Definition: conddblib.py:164
conddblib.getPayload
def getPayload(session, hash)
Definition: conddblib.py:644
conddblib._inserted_before
def _inserted_before(timestamp)
Definition: conddblib.py:592
conddblib._getCMSSQLAlchemyConnectionString
def _getCMSSQLAlchemyConnectionString(technology, service, schema_name)
Definition: conddblib.py:457
conddblib.hash
def hash(data)
Definition: conddblib.py:52
str
#define str(s)
Definition: TestProcessor.cc:51
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.getSessionOnMasterDB
def getSessionOnMasterDB(session1, session2)
Definition: conddblib.py:431
Exception
conddblib.getSchema
def getSchema(tp)
Definition: conddblib.py:222
conddblib.connect
def connect(url, authPath=None, verbose=0)
Definition: conddblib.py:516
conddblib.listObject
def listObject(session, name, snapshot=None)
Definition: conddblib.py:605
conddblib._exists
def _exists(session, primary_key, value)
Definition: conddblib.py:581
conddblib._getCMSFrontierConnectionString
def _getCMSFrontierConnectionString(database)
Definition: conddblib.py:453
conddblib.make_url
def make_url(database='pro', read_only=True)
Definition: conddblib.py:470