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  TagAuthorization
 
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, as_admin=False)
 
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 609 of file conddblib.py.

References submitPVResolutionJobs.count, and ALCARECOTkAlBeamHalo_cff.filter.

Referenced by listObject().

609 def _exists(session, primary_key, value):
610  ret = None
611  try:
612  ret = session.query(primary_key).\
613  filter(primary_key == value).\
614  count() != 0
615  except sqlalchemy.exc.OperationalError:
616  pass
617 
618  return ret
619 
def _exists(session, primary_key, value)
Definition: conddblib.py:609

◆ _getCMSFrontierConnectionString()

def conddblib._getCMSFrontierConnectionString (   database)
private

Definition at line 470 of file conddblib.py.

References communicate(), and nano_mu_digi_cff.strip.

Referenced by _getCMSSQLAlchemyConnectionString().

470 def _getCMSFrontierConnectionString(database):
471  import subprocess
472  return subprocess.Popen(['cmsGetFnConnect', 'frontier://%s' % database], stdout = subprocess.PIPE).communicate()[0].strip()
473 
def _getCMSFrontierConnectionString(database)
Definition: conddblib.py:470
static void * communicate(void *obj)
Definition: DQMNet.cc:1057

◆ _getCMSSQLAlchemyConnectionString()

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

Definition at line 474 of file conddblib.py.

References _getCMSFrontierConnectionString().

Referenced by make_url().

474 def _getCMSSQLAlchemyConnectionString(technology,service,schema_name):
475  if technology == 'frontier':
476  import urllib
477  import sys
478  py3k = sys.version_info >= (3, 0)
479  if py3k:
480  return '%s://@%s/%s' % ('oracle+frontier', urllib.parse.quote_plus(_getCMSFrontierConnectionString(service)), schema_name )
481  else:
482  return '%s://@%s/%s' % ('oracle+frontier', urllib.quote_plus(_getCMSFrontierConnectionString(service)), schema_name )
483  elif technology == 'oracle':
484  return '%s://%s@%s' % (technology, schema_name, service)
485 
486 # Entry point
def _getCMSFrontierConnectionString(database)
Definition: conddblib.py:470
def _getCMSSQLAlchemyConnectionString(technology, service, schema_name)
Definition: conddblib.py:474

◆ _inserted_before()

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

Definition at line 620 of file conddblib.py.

References conddb2hdf5._parse_timestamp().

Referenced by listObject().

620 def _inserted_before(timestamp):
621  '''To be used inside filter().
622  '''
623 
624  if timestamp is None:
625  # XXX: Returning None does not get optimized (skipped) by SQLAlchemy,
626  # and returning True does not work in Oracle (generates "and 1"
627  # which breaks Oracle but not SQLite). For the moment just use
628  # this dummy condition.
629  return sqlalchemy.literal(True) == sqlalchemy.literal(True)
630 
631  return conddb.IOV.insertion_time <= _parse_timestamp(timestamp)
632 
def _parse_timestamp(timestamp)
Definition: conddb2hdf5.py:43
def _inserted_before(timestamp)
Definition: conddblib.py:620

◆ connect()

def conddblib.connect (   url,
  authPath = None,
  verbose = 0,
  as_admin = False 
)
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 533 of file conddblib.py.

References oracle_connection_string(), and str.

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

533 def connect(url, authPath=None, verbose=0, as_admin=False):
534  '''Returns a Connection instance to the CMS Condition DB.
535 
536  See database_help for the description of the database parameter.
537 
538  The verbosity level is as follows:
539 
540  0 = No output (default).
541  1 = SQL statements issued, including their parameters.
542  2 = In addition, results of the queries (all rows and the column headers).
543  '''
544 
545  check_admin = as_admin
546  if url.drivername == 'oracle':
547  if url.username is None:
548  logging.error('Could not resolve the username for the connection %s. Please provide a connection in the format oracle://[user]:[pass]@[host]' %url )
549  raise Exception('Connection format error: %s' %url )
550  if url.password is None:
551  if authPath is None:
552  if authPathEnvVar in os.environ:
553  authPath = os.environ[authPathEnvVar]
554  explicit_auth = False
555  if authPath is not None:
556  dbkey_path = os.path.join(authPath,dbkey_folder)
557  if not os.path.exists(dbkey_path):
558  authFile = os.path.join(authPath,'.netrc')
559  if os.path.exists(authFile):
560  entryKey = url.host.lower()+"/"+url.username.lower()
561  logging.debug('Looking up credentials for %s in file %s ' %(entryKey,authFile) )
562  import netrc
563  params = netrc.netrc( authFile ).authenticators(entryKey)
564  if params is not None:
565  (username, account, password) = params
566  url.username = username
567  url.password = password
568  else:
569  msg = 'The entry %s has not been found in the .netrc file.' %entryKey
570  raise TypeError(msg)
571  else:
572  explicit_auth =True
573  else:
574  import libCondDBPyBind11Interface as auth
575  role_code = auth.reader_role
576  if url.username == dbwriter_user_name:
577  role_code = auth.writer_role
578  if check_admin:
579  role_code = auth.admin_role
580  connection_string = oracle_connection_string(url.host.lower(),schema_name)
581  logging.debug('Using db key to get credentials for %s' %connection_string )
582  (dbuser,username,password) = auth.get_credentials_from_db(connection_string,role_code,authPath)
583  if username=='' or password=='':
584  raise Exception('No credentials found to connect on %s with the required access role.'%connection_string)
585  check_admin = False
586  url.username = username
587  url.password = password
588  else:
589  import getpass
590  pwd = getpass.getpass('Password for %s: ' % str(url))
591  if pwd is None or pwd == '':
592  pwd = getpass.getpass('Password for %s: ' % str(url))
593  if pwd is None or pwd == '':
594  raise Exception('Empty password provided, bailing out...')
595  url.password = pwd
596  if check_admin:
597  raise Exception('Admin access has not been granted. Please provide a valid admin db-key.')
598  if check_admin:
599  raise Exception('Admin access is not available for technology "%s".' %url.drivername)
600  if verbose >= 1:
601  logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
602 
603  if verbose >= 2:
604  logging.getLogger('sqlalchemy.engine').setLevel(logging.DEBUG)
605 
606  return Connection(url)
607 
608 
def oracle_connection_string(db_service, db_schema)
Definition: conddblib.py:139
def connect(url, authPath=None, verbose=0, as_admin=False)
Definition: conddblib.py:533
#define str(s)

◆ fq_col()

def conddblib.fq_col (   schema,
  table,
  column 
)

Definition at line 184 of file conddblib.py.

Referenced by make_dbtype().

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 
def fq_col(schema, table, column)
Definition: conddblib.py:184

◆ 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 
def fq_name(schema_name, table_name)
Definition: conddblib.py:166

◆ getPayload()

def conddblib.getPayload (   session,
  hash 
)

Definition at line 672 of file conddblib.py.

References ALCARECOTkAlBeamHalo_cff.filter.

Referenced by TotemT2FramePosition.printXML().

672 def getPayload(session, hash):
673  # get payload from DB:
674  data, payloadType = session.query(Payload.data, Payload.object_type).filter(Payload.hash == hash).one()
675  return data
676 
def getPayload(session, hash)
Definition: conddblib.py:672

◆ getSchema()

def conddblib.getSchema (   tp)

Definition at line 230 of file conddblib.py.

Referenced by conddblib.Connection.is_valid().

230 def getSchema(tp):
231  if tp.__table_args__ is not None:
232  return tp.__table_args__['schema']
233  return None
234 
def getSchema(tp)
Definition: conddblib.py:230

◆ getSessionOnMasterDB()

def conddblib.getSessionOnMasterDB (   session1,
  session2 
)

Definition at line 448 of file conddblib.py.

References make_url().

448 def getSessionOnMasterDB( session1, session2 ):
449  key = '%s/%s'
450  sessiondict = { }
451  sessiondict[key %(session1._url.drivername,session1._url.host)] = session1
452  sessiondict[key %(session2._url.drivername,session2._url.host)] = session2
453  masterkey = key %('oracle',ONLINEORAPRO)
454  if masterkey in sessiondict.keys():
455  return sessiondict[masterkey]
456  adgkey = key %('oracle',ORAPRO)
457  if adgkey in sessiondict.keys():
458  return sessiondict[adgkey]
459  frontierkey = key %('frontier',PRO)
460  if frontierkey in sessiondict.keys():
461  return sessiondict[frontierkey]
462  # default case: frontier on pro
463  conn = Connection(make_url())
464  session = conn.session()
465  # is it required?
466  session._conn = conn
467  return session
468 
469 # Connection helpers
def getSessionOnMasterDB(session1, session2)
Definition: conddblib.py:448
def make_url(database='pro', read_only=True)
Definition: conddblib.py:487

◆ 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
def hash(data)
Definition: conddblib.py:52

◆ listObject()

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

Definition at line 633 of file conddblib.py.

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

633 def listObject(session, name, snapshot=None):
634 
635  is_tag = _exists(session, Tag.name, name)
636  result = {}
637  if is_tag:
638  result['type'] = 'Tag'
639  result['name'] = session.query(Tag).get(name).name
640  result['timeType'] = session.query(Tag.time_type).\
641  filter(Tag.name == name).\
642  scalar()
643 
644  result['iovs'] = session.query(IOV.since, IOV.insertion_time, IOV.payload_hash, Payload.object_type).\
645  join(IOV.payload).\
646  filter(
647  IOV.tag_name == name,
648  _inserted_before(snapshot),
649  ).\
650  order_by(IOV.since.desc(), IOV.insertion_time.desc()).\
651  from_self().\
652  order_by(IOV.since, IOV.insertion_time).\
653  all()
654 
655  try:
656  is_global_tag = _exists(session, GlobalTag.name, name)
657  if is_global_tag:
658  result['type'] = 'GlobalTag'
659  result['name'] = session.query(GlobalTag).get(name)
660  result['tags'] = session.query(GlobalTagMap.record, GlobalTagMap.label, GlobalTagMap.tag_name).\
661  filter(GlobalTagMap.global_tag_name == name).\
662  order_by(GlobalTagMap.record, GlobalTagMap.label).\
663  all()
664  except sqlalchemy.exc.OperationalError:
665  sys.stderr.write("No table for GlobalTags found in DB.\n\n")
666 
667  if not is_tag and not is_global_tag:
668  raise Exception('There is no tag or global tag named %s in the database.' % name)
669 
670  return result
671 
def listObject(session, name, snapshot=None)
Definition: conddblib.py:633
def all(container)
workaround iterator generators for ROOT classes
Definition: cmstools.py:25
static std::string join(char **cmd)
Definition: RemoteFile.cc:19
def _inserted_before(timestamp)
Definition: conddblib.py:620
def _exists(session, primary_key, value)
Definition: conddblib.py:609

◆ make_dbtype()

def conddblib.make_dbtype (   backendName,
  schemaName,
  baseType 
)

Definition at line 190 of file conddblib.py.

References fq_col().

Referenced by conddblib.Connection.get_dbtype().

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  defColVal = None
200  if len(v)==3:
201  defColVal = v[2]
202  if isinstance(v[0],DbRef):
203  refColDbt = v[0].rtype.columns[v[0].rcol][0]
204  pk = (True if v[1]==_Col.pk else False)
205  if v[1]==_Col.pk:
206  members[k] = sqlalchemy.Column(refColDbt,sqlalchemy.ForeignKey(fq_col(schemaName,v[0].rtype.__tablename__,v[0].rcol)),primary_key=True)
207  else:
208  nullable = (False if v[1] == _Col.notNull else True)
209  members[k] = sqlalchemy.Column(refColDbt,sqlalchemy.ForeignKey(fq_col(schemaName,v[0].rtype.__tablename__,v[0].rcol)),nullable=nullable)
210  if v[0].rtype.__name__ not in deps_reg:
211  deps_reg.add(v[0].rtype.__name__)
212  reftype_name = '%s_%s' %(v[0].rtype.__name__,backendName)
213  members[(v[0].rtype.__name__).lower()] = sqlalchemy.orm.relationship(reftype_name)
214  else:
215  if v[1]==_Col.pk:
216  members[k] = sqlalchemy.Column(v[0],primary_key=True)
217  else:
218  nullable = (True if v[1]==_Col.nullable else False)
219  if defColVal is None:
220  members[k] = sqlalchemy.Column(v[0],nullable=nullable)
221  else:
222  members[k] = sqlalchemy.Column(v[0],nullable=nullable, default=defColVal)
223  dbType = type(dbtype_name,(_Base,),members)
224 
225  if backendName not in db_models.keys():
226  db_models[backendName] = {}
227  db_models[backendName][baseType.__name__] = dbType
228  return dbType
229 
def make_dbtype(backendName, schemaName, baseType)
Definition: conddblib.py:190
def fq_col(schema, table, column)
Definition: conddblib.py:184

◆ make_url()

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

Definition at line 487 of file conddblib.py.

References _getCMSSQLAlchemyConnectionString().

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

487 def make_url(database='pro',read_only = True):
488  if database.startswith('sqlite:') or database.startswith('sqlite_file:'):
489  ignore, database = database.split(':',1)
490 
491  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
492  database, schema = database.split(':')
493 
494  officialdbs = {
495  # frontier
496  'pro' : ('frontier','PromptProd', { 'R': schema_name }, ),
497  'arc' : ('frontier','FrontierArc', { 'R': schema_name }, ),
498  'int' : ('frontier','FrontierInt', { 'R': schema_name }, ),
499  'dev' : ('frontier','FrontierPrep', { 'R': schema_name }, ),
500  # oracle adg
501  'orapro': ('oracle', 'cms_orcon_adg', { 'R': dbreader_user_name }, ),
502  'oraarc': ('oracle', 'cmsarc_lb', { 'R': dbreader_user_name }, ),
503  # oracle masters
504  'oraint': ('oracle', 'cms_orcoff_int', { 'R': dbreader_user_name,
505  'W': dbwriter_user_name }, ),
506  'oradev': ('oracle', 'cms_orcoff_prep', { 'R': dbreader_user_name,
507  'W': dbwriter_user_name }, ),
508  'onlineorapro': ('oracle', 'cms_orcon_prod', { 'R': dbreader_user_name,
509  'W': dbwriter_user_name }, ),
510  'onlineoraint': ('oracle', 'cmsintr_lb', { 'R': dbreader_user_name,
511  'W': dbwriter_user_name }, ),
512  }
513 
514  if database in officialdbs.keys():
515  key = ('R' if read_only else 'W')
516  mapping = officialdbs[database]
517  tech = mapping[0]
518  service = mapping[1]
519  schema_dict = mapping[2]
520  if key in schema_dict.keys():
521  database = _getCMSSQLAlchemyConnectionString(tech,service,schema_dict[key])
522  else:
523  raise Exception("Read-only database %s://%s cannot be accessed in update mode." %(tech,service))
524 
525  logging.debug('connection string set to "%s"' % database)
526 
527  try:
528  url = sqlalchemy.engine.url.make_url(database)
529  except sqlalchemy.exc.ArgumentError:
530  url = sqlalchemy.engine.url.make_url('sqlite:///%s' % database)
531  return url
532 
def make_url(database='pro', read_only=True)
Definition: conddblib.py:487
def _getCMSSQLAlchemyConnectionString(technology, service, schema_name)
Definition: conddblib.py:474

◆ oracle_connection_string()

def conddblib.oracle_connection_string (   db_service,
  db_schema 
)

Definition at line 139 of file conddblib.py.

Referenced by connect().

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