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

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 

References submitPVResolutionJobs.count, and ALCARECOTkAlBeamHalo_cff.filter.

Referenced by listObject().

◆ _getCMSFrontierConnectionString()

def conddblib._getCMSFrontierConnectionString (   database)
private

Definition at line 455 of file conddblib.py.

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

References communicate(), and digitizers_cfi.strip.

Referenced by _getCMSSQLAlchemyConnectionString().

◆ _getCMSSQLAlchemyConnectionString()

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

Definition at line 459 of file conddblib.py.

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

References _getCMSFrontierConnectionString().

Referenced by make_url().

◆ _inserted_before()

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

Definition at line 594 of file conddblib.py.

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 

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

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 

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

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 

Referenced by make_dbtype().

◆ fq_name()

def conddblib.fq_name (   schema_name,
  table_name 
)

Definition at line 166 of file conddblib.py.

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 

◆ getPayload()

def conddblib.getPayload (   session,
  hash 
)

Definition at line 646 of file conddblib.py.

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

References ALCARECOTkAlBeamHalo_cff.filter, and SiPixelPI.one.

◆ getSchema()

def conddblib.getSchema (   tp)

Definition at line 224 of file conddblib.py.

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

Referenced by conddblib.Connection.is_valid().

◆ getSessionOnMasterDB()

def conddblib.getSessionOnMasterDB (   session1,
  session2 
)

Definition at line 433 of file conddblib.py.

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

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

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 

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

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 

References fq_col().

Referenced by conddblib.Connection.get_dbtype().

◆ make_url()

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

Definition at line 472 of file conddblib.py.

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 

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:190
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:184
conddblib.fq_name
def fq_name(schema_name, table_name)
Definition: conddblib.py:166
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.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.getSessionOnMasterDB
def getSessionOnMasterDB(session1, session2)
Definition: conddblib.py:433
Exception
conddblib.getSchema
def getSchema(tp)
Definition: conddblib.py:224
conddblib.connect
def connect(url, authPath=None, verbose=0)
Definition: conddblib.py:518
conddblib.listObject
def listObject(session, name, snapshot=None)
Definition: conddblib.py:607
conddblib._exists
def _exists(session, primary_key, value)
Definition: conddblib.py:583
conddblib._getCMSFrontierConnectionString
def _getCMSFrontierConnectionString(database)
Definition: conddblib.py:455
conddblib.make_url
def make_url(database='pro', read_only=True)
Definition: conddblib.py:472