File indexing completed on 2024-04-06 12:01:54
0001 import netrc
0002 import os
0003 import logging
0004
0005 netrcFileName = '.netrc'
0006 defAuthPathEnvVar = 'HOME'
0007 authPathEnvVar = 'COND_AUTH_PATH'
0008
0009 dbkey_filename = 'db.key'
0010 dbkey_folder = os.path.join('.cms_cond',dbkey_filename)
0011
0012 reader_role = 'reader'
0013 writer_role = 'writer'
0014 admin_role = 'admin'
0015
0016 def netrc_machine( service, role ):
0017 return '%s@%s' %(role,service)
0018
0019 def get_credentials_from_file( machine, authPath ):
0020 authFile = netrcFileName
0021 if not authPath is None:
0022 authFile = os.path.join( authPath, authFile )
0023 creds = netrc.netrc( authFile ).authenticators(machine)
0024 return creds
0025
0026 def get_credentials( machine, authPath=None ):
0027 if authPath is None:
0028 if authPathEnvVar in os.environ:
0029 authPath = os.environ[authPathEnvVar]
0030 else:
0031 if defAuthPathEnvVar in os.environ:
0032 authPath = os.environ[defAuthPathEnvVar]
0033 else:
0034 authPath = ''
0035 return get_credentials_from_file( machine, authPath )
0036
0037 def get_credentials_for_schema( service, schema, role, authPath=None ):
0038 if authPath is None:
0039 if authPathEnvVar in os.environ:
0040 authPath = os.environ[authPathEnvVar]
0041 else:
0042 if defAuthPathEnvVar in os.environ:
0043 authPath = os.environ[defAuthPathEnvVar]
0044 else:
0045 authPath = ''
0046 dbkey_path = os.path.join(authPath,dbkey_folder)
0047 if not os.path.exists(dbkey_path):
0048 authFile = os.path.join(authPath,'.netrc')
0049 if not os.path.exists(authFile):
0050 raise Exception("Can't get db credentials, since neither db key nor Netrc file have been found.")
0051 machine = '%s@%s.%s' %(role,schema.lower(),service)
0052 logging.debug('Looking up db credentials %s in file %s ' %(machine,authFile) )
0053 import netrc
0054 params = netrc.netrc( authFile ).authenticators(machine)
0055 if params is None:
0056 msg = 'The required credentials have not been found in the .netrc file.'
0057 raise Exception(msg)
0058 return params
0059 else:
0060 import libCondDBPyBind11Interface as credential_db
0061 roles_map = { reader_role: credential_db.reader_role, writer_role: credential_db.writer_role, admin_role: credential_db.admin_role }
0062 connection_string = 'oracle://%s/%s'%(service.lower(),schema.upper())
0063 logging.debug('Looking up db credentials for %s in credential store' %connection_string )
0064 (dbuser,username,password) = credential_db.get_credentials_from_db(connection_string,roles_map[role],authPath)
0065 if username=='' or password=='':
0066 raise Exception('No credentials found to connect on %s with the required access role.'%connection_string)
0067 return (username,dbuser,password)
0068