CMS 3D CMS Logo

Classes | Functions
conddblib Namespace Reference

Classes

class  _Col
 
class  BoostRunMap
 
class  Connection
 
class  DbRef
 
class  Enum
 
class  EnumMetaclass
 
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

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

Definition at line 590 of file conddblib.py.

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

Referenced by listObject().

590 def _exists(session, primary_key, value):
591  ret = None
592  try:
593  ret = session.query(primary_key).\
594  filter(primary_key == value).\
595  count() != 0
596  except sqlalchemy.exc.OperationalError:
597  pass
598 
599  return ret
600 
def _exists(session, primary_key, value)
Definition: conddblib.py:590
def conddblib._getCMSFrontierConnectionString (   database)
private

Definition at line 480 of file conddblib.py.

References communicate(), and digi_MixPreMix_cfi.strip.

Referenced by _getCMSSQLAlchemyConnectionString().

481  import subprocess
482  return subprocess.Popen(['cmsGetFnConnect', 'frontier://%s' % database], stdout = subprocess.PIPE).communicate()[0].strip()
483 
def _getCMSFrontierConnectionString(database)
Definition: conddblib.py:480
static void * communicate(void *obj)
Definition: DQMNet.cc:1251
def conddblib._getCMSSQLAlchemyConnectionString (   technology,
  service,
  schema_name 
)
private

Definition at line 484 of file conddblib.py.

References _getCMSFrontierConnectionString().

Referenced by make_url().

484 def _getCMSSQLAlchemyConnectionString(technology,service,schema_name):
485  if technology == 'frontier':
486  import urllib
487  return '%s://@%s/%s' % ('oracle+frontier', urllib.quote_plus(_getCMSFrontierConnectionString(service)), schema_name )
488  elif technology == 'oracle':
489  return '%s://%s@%s' % (technology, schema_name, service)
490 
491 # Entry point
def _getCMSFrontierConnectionString(database)
Definition: conddblib.py:480
def _getCMSSQLAlchemyConnectionString(technology, service, schema_name)
Definition: conddblib.py:484
def conddblib._inserted_before (   timestamp)
private
To be used inside filter().

Definition at line 601 of file conddblib.py.

Referenced by listObject().

601 def _inserted_before(timestamp):
602  '''To be used inside filter().
603  '''
604 
605  if timestamp is None:
606  # XXX: Returning None does not get optimized (skipped) by SQLAlchemy,
607  # and returning True does not work in Oracle (generates "and 1"
608  # which breaks Oracle but not SQLite). For the moment just use
609  # this dummy condition.
610  return sqlalchemy.literal(True) == sqlalchemy.literal(True)
611 
612  return conddb.IOV.insertion_time <= _parse_timestamp(timestamp)
613 
def _inserted_before(timestamp)
Definition: conddblib.py:601
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 538 of file conddblib.py.

References harvestTrackValidationPlots.str.

538 def connect(url, authPath=None, verbose=0):
539  '''Returns a Connection instance to the CMS Condition DB.
540 
541  See database_help for the description of the database parameter.
542 
543  The verbosity level is as follows:
544 
545  0 = No output (default).
546  1 = SQL statements issued, including their parameters.
547  2 = In addition, results of the queries (all rows and the column headers).
548  '''
549 
550  if url.drivername == 'oracle':
551  if url.username is None:
552  logging.error('Could not resolve the username for the connection %s. Please provide a connection in the format oracle://[user]:[pass]@[host]' %url )
553  raise Exception('Connection format error: %s' %url )
554  if url.password is None:
555  if authPath is None:
556  if authPathEnvVar in os.environ:
557  authPath = os.environ[authPathEnvVar]
558  authFile = None
559  if authPath is not None:
560  authFile = os.path.join(authPath,'.netrc')
561  if authFile is not None:
562  entryKey = url.host.lower()+"/"+url.username.lower()
563  logging.debug('Looking up credentials for %s in file %s ' %(entryKey,authFile) )
564  import netrc
565  params = netrc.netrc( authFile ).authenticators(entryKey)
566  if params is not None:
567  (username, account, password) = params
568  url.password = password
569  else:
570  msg = 'The entry %s has not been found in the .netrc file.' %entryKey
571  raise TypeError(msg)
572  else:
573  import getpass
574  pwd = getpass.getpass('Password for %s: ' % str(url))
575  if pwd is None or pwd == '':
576  pwd = getpass.getpass('Password for %s: ' % str(url))
577  if pwd is None or pwd == '':
578  raise Exception('Empty password provided, bailing out...')
579  url.password = pwd
580 
581  if verbose >= 1:
582  logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
583 
584  if verbose >= 2:
585  logging.getLogger('sqlalchemy.engine').setLevel(logging.DEBUG)
586 
587  return Connection(url)
588 
589 
def connect(url, authPath=None, verbose=0)
Definition: conddblib.py:538
def conddblib.fq_col (   schema,
  table,
  column 
)

Definition at line 209 of file conddblib.py.

Referenced by make_dbtype().

209 def fq_col( schema, table, column ):
210  fqn = '%s.%s' %(table, column)
211  if schema is not None:
212  fqn = '%s.%s' %(schema,fqn)
213  return fqn
214 
def fq_col(schema, table, column)
Definition: conddblib.py:209
def conddblib.fq_name (   schema_name,
  table_name 
)

Definition at line 191 of file conddblib.py.

191 def fq_name( schema_name, table_name ):
192  name = table_name
193  if schema_name is not None:
194  name = '%s.%s' %(schema_name, table_name)
195  return name
196 
def fq_name(schema_name, table_name)
Definition: conddblib.py:191
def conddblib.getPayload (   session,
  hash 
)

Definition at line 653 of file conddblib.py.

References ALCARECOTkAlBeamHalo_cff.filter.

653 def getPayload(session, hash):
654  # get payload from DB:
655  data, payloadType = session.query(Payload.data, Payload.object_type).filter(Payload.hash == hash).one()
656  return data
657 
def getPayload(session, hash)
Definition: conddblib.py:653
def conddblib.getSchema (   tp)

Definition at line 249 of file conddblib.py.

Referenced by conddblib.Connection.is_valid().

249 def getSchema(tp):
250  if tp.__table_args__ is not None:
251  return tp.__table_args__['schema']
252  return None
253 
def getSchema(tp)
Definition: conddblib.py:249
def conddblib.getSessionOnMasterDB (   session1,
  session2 
)

Definition at line 458 of file conddblib.py.

References make_url().

458 def getSessionOnMasterDB( session1, session2 ):
459  key = '%s/%s'
460  sessiondict = { }
461  sessiondict[key %(session1._url.drivername,session1._url.host)] = session1
462  sessiondict[key %(session2._url.drivername,session2._url.host)] = session2
463  masterkey = key %('oracle',ONLINEORAPRO)
464  if masterkey in sessiondict.keys():
465  return sessiondict[masterkey]
466  adgkey = key %('oracle',ORAPRO)
467  if adgkey in sessiondict.keys():
468  return sessiondict[adgkey]
469  frontierkey = key %('frontier',PRO)
470  if frontierkey in sessiondict.keys():
471  return sessiondict[frontierkey]
472  # default case: frontier on pro
473  conn = Connection(make_url())
474  session = conn.session()
475  # is it required?
476  session._conn = conn
477  return session
478 
479 # Connection helpers
def getSessionOnMasterDB(session1, session2)
Definition: conddblib.py:458
def make_url(database='pro', read_only=True)
Definition: conddblib.py:492
def conddblib.hash (   data)

Definition at line 82 of file conddblib.py.

82 def hash(data):
83  return hashlib.sha1(data).hexdigest()
84 
85 
86 # Constants
def hash(data)
Definition: conddblib.py:82
def conddblib.listObject (   session,
  name,
  snapshot = None 
)

Definition at line 614 of file conddblib.py.

References _exists(), _inserted_before(), Vispa.Plugins.EdmBrowser.EdmDataAccessor.all(), ALCARECOTkAlBeamHalo_cff.filter, reco.get(), join(), and hitfit.scalar().

614 def listObject(session, name, snapshot=None):
615 
616  is_tag = _exists(session, Tag.name, name)
617  result = {}
618  if is_tag:
619  result['type'] = 'Tag'
620  result['name'] = session.query(Tag).get(name).name
621  result['timeType'] = session.query(Tag.time_type).\
622  filter(Tag.name == name).\
623  scalar()
624 
625  result['iovs'] = session.query(IOV.since, IOV.insertion_time, IOV.payload_hash, Payload.object_type).\
626  join(IOV.payload).\
627  filter(
628  IOV.tag_name == name,
629  _inserted_before(snapshot),
630  ).\
631  order_by(IOV.since.desc(), IOV.insertion_time.desc()).\
632  from_self().\
633  order_by(IOV.since, IOV.insertion_time).\
634  all()
635 
636  try:
637  is_global_tag = _exists(session, GlobalTag.name, name)
638  if is_global_tag:
639  result['type'] = 'GlobalTag'
640  result['name'] = session.query(GlobalTag).get(name)
641  result['tags'] = session.query(GlobalTagMap.record, GlobalTagMap.label, GlobalTagMap.tag_name).\
642  filter(GlobalTagMap.global_tag_name == name).\
643  order_by(GlobalTagMap.record, GlobalTagMap.label).\
644  all()
645  except sqlalchemy.exc.OperationalError:
646  sys.stderr.write("No table for GlobalTags found in DB.\n\n")
647 
648  if not is_tag and not is_global_tag:
649  raise Exception('There is no tag or global tag named %s in the database.' % name)
650 
651  return result
652 
def listObject(session, name, snapshot=None)
Definition: conddblib.py:614
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
def _inserted_before(timestamp)
Definition: conddblib.py:601
T get(const Candidate &c)
Definition: component.h:55
def _exists(session, primary_key, value)
Definition: conddblib.py:590
double scalar(const CLHEP::HepGenMatrix &m)
Return the matrix as a scalar. Raise an assertion if the matris is not .
Definition: matutil.cc:183
def conddblib.make_dbtype (   backendName,
  schemaName,
  baseType 
)

Definition at line 215 of file conddblib.py.

References fq_col().

Referenced by conddblib.Connection.get_dbtype().

215 def make_dbtype( backendName, schemaName, baseType ):
216  members = {}
217  deps_reg = set()
218  dbtype_name = '%s_%s' %(baseType.__name__,backendName)
219  members['__tablename__'] = baseType.__tablename__
220  members['__table_args__'] = None
221  if schemaName is not None:
222  members['__table_args__'] = {'schema': schemaName }
223  for k,v in baseType.columns.items():
224  if isinstance(v[0],DbRef):
225  refColDbt = v[0].rtype.columns[v[0].rcol][0]
226  pk = (True if v[1]==_Col.pk else False)
227  if v[1]==_Col.pk:
228  members[k] = sqlalchemy.Column(refColDbt,sqlalchemy.ForeignKey(fq_col(schemaName,v[0].rtype.__tablename__,v[0].rcol)),primary_key=True)
229  else:
230  nullable = (False if v[1] == _Col.notNull else True)
231  members[k] = sqlalchemy.Column(refColDbt,sqlalchemy.ForeignKey(fq_col(schemaName,v[0].rtype.__tablename__,v[0].rcol)),nullable=nullable)
232  if v[0].rtype.__name__ not in deps_reg:
233  deps_reg.add(v[0].rtype.__name__)
234  reftype_name = '%s_%s' %(v[0].rtype.__name__,backendName)
235  members[(v[0].rtype.__name__).lower()] = sqlalchemy.orm.relationship(reftype_name)
236  else:
237  if v[1]==_Col.pk:
238  members[k] = sqlalchemy.Column(v[0],primary_key=True)
239  else:
240  nullable = (True if v[1]==_Col.nullable else False)
241  members[k] = sqlalchemy.Column(v[0],nullable=nullable)
242  dbType = type(dbtype_name,(_Base,),members)
243 
244  if backendName not in db_models.keys():
245  db_models[backendName] = {}
246  db_models[backendName][baseType.__name__] = dbType
247  return dbType
248 
def make_dbtype(backendName, schemaName, baseType)
Definition: conddblib.py:215
def fq_col(schema, table, column)
Definition: conddblib.py:209
def conddblib.make_url (   database = 'pro',
  read_only = True 
)

Definition at line 492 of file conddblib.py.

References _getCMSSQLAlchemyConnectionString().

Referenced by getSessionOnMasterDB().

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