CMS 3D CMS Logo

cond2xml.py
Go to the documentation of this file.
1 from __future__ import print_function
2 
3 import os
4 import shutil
5 import sys
6 import time
7 import glob
8 import importlib
9 import logging
10 import subprocess
11 
12 # as we need to load the shared lib from here, make sure it's in our path:
13 if os.path.join( os.environ['CMSSW_BASE'], 'src') not in sys.path:
14  sys.path.append( os.path.join( os.environ['CMSSW_BASE'], 'src') )
15 
16 # -------------------------------------------------------------------------------------------------------
17 
18 payload2xmlCodeTemplate = """
19 
20 #include "CondCore/Utilities/interface/Payload2XMLModule.h"
21 #include "CondCore/Utilities/src/CondFormats.h"
22 
23 PAYLOAD_2XML_MODULE( %s ){
24  PAYLOAD_2XML_CLASS( %s );
25 }
26 
27 """
28 
29 buildFileTemplate = """
30 <flags CXXFLAGS="-Wno-sign-compare -Wno-unused-variable -Os"/>
31 <library file="%s" name="%s">
32  <use name="CondCore/Utilities"/>
33  <use name="py3-pybind11"/>
34  <use name="python3"/>
35 </library>
36 <export>
37  <lib name="1"/>
38 </export>
39 """
40 
41 # helper function
42 def sanitize(typeName):
43  return typeName.replace(' ','').replace('<','_').replace('>','')
44 
45 def localLibName( payloadType ):
46  # required to avoid ( unlikely ) clashes between lib names from templates and lib names from classes
47  prefix = ''
48  if '<' in payloadType and '>' in payloadType:
49  prefix = 't'
50  ptype = payloadType
51  if '::' in payloadType:
52  ptype = payloadType.replace('::','_')
53  return "%s_%spayload2xml" %(sanitize(ptype),prefix)
54 
56 
57  def __init__(self, condDBIn):
58  self.conddb = condDBIn
59 
60  if not os.path.exists( os.path.join( os.environ['CMSSW_BASE'], 'src') ):
61  raise Exception("Looks like you are not running in a CMSSW developer area, $CMSSW_BASE/src/ does not exist")
62 
63  self.fakePkgName = "fakeSubSys4pl/fakePkg4pl"
64  self._pl2xml_tmpDir = os.path.join( os.environ['CMSSW_BASE'], 'src', self.fakePkgName )
65 
66  self.doCleanup = False
67 
68  def __del__(self):
69 
70  if self.doCleanup:
71  shutil.rmtree( '/'.join( self._pl2xml_tmpDir.split('/')[:-1] ) )
72  return
73 
74  def discover(self, payloadType):
75 
76  libName = 'pluginUtilities_payload2xml.so'
77  # first search: developer area or main release
78  libDir = os.path.join( os.environ["CMSSW_BASE"], 'lib', os.environ["SCRAM_ARCH"] )
79  devLibDir = libDir
80  libPath = os.path.join( devLibDir, libName )
81  releaseBase = os.environ["CMSSW_RELEASE_BASE"]
82  devCheckout = (releaseBase != '')
83  if not devCheckout:
84  logging.debug('Looks like the current working environment is a read-only release')
85  if not os.path.exists( libPath ) and devCheckout:
86  # main release ( for dev checkouts )
87  libDir = os.path.join( releaseBase, 'lib', os.environ["SCRAM_ARCH"] )
88  libPath = os.path.join( libDir, libName )
89  if not os.path.exists( libPath ):
90  if "CMSSW_FULL_RELEASE_BASE" in os.environ:
91  libDir = os.path.join( os.environ["CMSSW_FULL_RELEASE_BASE"], 'lib', os.environ["SCRAM_ARCH"] )
92  libPath = os.path.join( libDir, libName )
93  if not os.path.exists( libPath ):
94  # it should never happen!
95  raise Exception('No built-in library %s found with XML converters.' %libPath)
96  logging.debug("Importing built-in library %s" %libPath)
97  module = importlib.import_module( libName.replace('.so', '') )
98  functors = dir(module)
99  funcName = payloadType+'2xml'
100  if funcName in functors:
101  logging.info('XML converter for payload class %s found in the built-in library.' %payloadType)
102  return getattr( module, funcName)
103  if not devCheckout:
104  # give-up if it is a read-only release...
105  raise Exception('No XML converter suitable for payload class %s has been found in the built-in library.')
106  libName = 'plugin%s.so' %localLibName( payloadType )
107  libPath = os.path.join( devLibDir, libName )
108  if os.path.exists( libPath ):
109  logging.info('Found local library with XML converter for class %s' %payloadType )
110  module = importlib.import_module( libName.replace('.so', '') )
111  return getattr( module, funcName)
112  logging.warning('No XML converter for payload class %s found in the built-in library.' %payloadType)
113  return None
114 
115  def prepPayload2xml(self, payloadType):
116 
117  converter = self.discover(payloadType)
118  if converter: return converter
119 
120  #otherwise, go for the code generation in the local checkout area.
121  startTime = time.time()
122 
123  libName = localLibName( payloadType )
124  pluginName = 'plugin%s' % libName
125  tmpLibName = "Tmp_payload2xml"
126  tmpPluginName = 'plugin%s' %tmpLibName
127 
128  libDir = os.path.join( os.environ["CMSSW_BASE"], 'lib', os.environ["SCRAM_ARCH"] )
129  tmpLibFile = os.path.join( libDir,tmpPluginName+'.so' )
130  code = payload2xmlCodeTemplate %(pluginName,payloadType)
131 
132  tmpSrcFileName = 'Local_2XML.cpp'
133  tmpDir = self._pl2xml_tmpDir
134  if ( os.path.exists( tmpDir ) ) :
135  msg = '\nERROR: %s already exists, please remove if you did not create that manually !!' % tmpDir
136  raise Exception(msg)
137 
138  logging.debug('Creating temporary package %s' %self._pl2xml_tmpDir)
139  os.makedirs( tmpDir+'/plugins' )
140 
141  buildFileName = "%s/plugins/BuildFile.xml" % (tmpDir,)
142  with open(buildFileName, 'w') as buildFile:
143  buildFile.write( buildFileTemplate %(tmpSrcFileName,tmpLibName) )
144  buildFile.close()
145 
146  tmpSrcFilePath = "%s/plugins/%s" % (tmpDir, tmpSrcFileName,)
147  with open(tmpSrcFilePath, 'w') as codeFile:
148  codeFile.write(code)
149  codeFile.close()
150 
151  cmd = "source $CMS_PATH/cmsset_default.sh;"
152  cmd += "(cd %s ; scram b 2>&1 >build.log)" %tmpDir
153  pipe = subprocess.Popen( cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT )
154  out, err = pipe.communicate()
155  ret = pipe.returncode
156 
157  buildTime = time.time()-startTime
158  logging.info("Building done in %s sec., return code from build: %s" %(buildTime,ret) )
159 
160  if (ret != 0):
161  logging.error("Local build for xml dump failed.")
162  return None
163 
164  libFile = os.path.join(libDir,pluginName + '.so')
165  shutil.copyfile(tmpLibFile,libFile)
166 
167  module = importlib.import_module( pluginName )
168  funcName = payloadType+'2xml'
169  functor = getattr( module, funcName )
170  self.doCleanup = True
171  return functor
172 
173  def payload2xml(self, session, payloadHash, destFile):
174 
175  Payload = session.get_dbtype(self.conddb.Payload)
176  # get payload from DB:
177  result = session.query(Payload.data, Payload.object_type).filter(Payload.hash == payloadHash).one()
178  data, plType = result
179  logging.info('Found payload of type %s' %plType)
180 
181  convFuncName = sanitize(plType)+'2xml'
182  xmlConverter = self.prepPayload2xml(plType)
183 
184  if xmlConverter is not None:
185  obj = xmlConverter()
186  resultXML = obj.write( data )
187  if destFile is None:
188  print(resultXML)
189  else:
190  with open(destFile, 'w') as outFile:
191  outFile.write(resultXML)
192  outFile.close()
cond2xml.CondXmlProcessor.prepPayload2xml
def prepPayload2xml(self, payloadType)
Definition: cond2xml.py:115
cond2xml.CondXmlProcessor.doCleanup
doCleanup
Definition: cond2xml.py:66
resolutioncreator_cfi.object
object
Definition: resolutioncreator_cfi.py:4
SiPixelPI::one
Definition: SiPixelPayloadInspectorHelper.h:39
cond2xml.localLibName
def localLibName(payloadType)
Definition: cond2xml.py:45
join
static std::string join(char **cmd)
Definition: RemoteFile.cc:17
cond2xml.sanitize
def sanitize(typeName)
Definition: cond2xml.py:42
cond2xml.CondXmlProcessor.conddb
conddb
Definition: cond2xml.py:58
cond2xml.CondXmlProcessor.payload2xml
def payload2xml(self, session, payloadHash, destFile)
Definition: cond2xml.py:173
cond2xml.CondXmlProcessor.__init__
def __init__(self, condDBIn)
Definition: cond2xml.py:57
submitPVValidationJobs.split
def split(sequence, size)
Definition: submitPVValidationJobs.py:352
ALCARECOTkAlBeamHalo_cff.filter
filter
Definition: ALCARECOTkAlBeamHalo_cff.py:27
cond2xml.CondXmlProcessor
Definition: cond2xml.py:55
print
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:46
Exception
cond2xml.CondXmlProcessor.discover
def discover(self, payloadType)
Definition: cond2xml.py:74
cond2xml.CondXmlProcessor.__del__
def __del__(self)
Definition: cond2xml.py:68
cond2xml.CondXmlProcessor.fakePkgName
fakePkgName
Definition: cond2xml.py:63
cond2xml.CondXmlProcessor._pl2xml_tmpDir
_pl2xml_tmpDir
Definition: cond2xml.py:64
DeadROC_duringRun.dir
dir
Definition: DeadROC_duringRun.py:23
python.rootplot.root2matplotlib.replace
def replace(string, replacements)
Definition: root2matplotlib.py:444