CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
cond2xml.py
Go to the documentation of this file.
1 
2 import os
3 import shutil
4 import sys
5 import time
6 import glob
7 import importlib
8 
9 # as we need to load the shared lib from here, make sure it's in our path:
10 if os.path.join( os.environ['CMSSW_BASE'], 'src') not in sys.path:
11  sys.path.append( os.path.join( os.environ['CMSSW_BASE'], 'src') )
12 
13 # -------------------------------------------------------------------------------------------------------
14 
15 payload2xmlCodeTemplate = """
16 
17 #include <iostream>
18 #include <string>
19 #include <memory>
20 
21 #include <boost/python/class.hpp>
22 #include <boost/python/module.hpp>
23 #include <boost/python/init.hpp>
24 #include <boost/python/def.hpp>
25 #include <iostream>
26 #include <string>
27 #include <sstream>
28 
29 #include "boost/archive/xml_oarchive.hpp"
30 #include "CondFormats/Serialization/interface/Serializable.h"
31 #include "CondFormats/Serialization/interface/Archive.h"
32 
33 #include "CondCore/Utilities/src/CondFormats.h"
34 
35 namespace { // Avoid cluttering the global namespace.
36 
37  std::string %(plTypeSan)s2xml( const std::string &payloadData, const std::string &payloadType ) {
38 
39  // now to convert
40  std::unique_ptr< %(plType)s > payload;
41 
42  std::stringbuf sdataBuf;
43  sdataBuf.pubsetbuf( const_cast<char *> ( payloadData.c_str() ), payloadData.size() );
44 
45  std::istream inBuffer( &sdataBuf );
46  eos::portable_iarchive ia( inBuffer );
47  payload.reset( new %(plType)s );
48  ia >> (*payload);
49 
50  // now we have the object in memory, convert it to xml in a string and return it
51 
52  std::ostringstream outBuffer;
53  boost::archive::xml_oarchive xmlResult( outBuffer );
54  xmlResult << boost::serialization::make_nvp( "cmsCondPayload", *payload );
55 
56  return outBuffer.str();
57  }
58 
59 } // end namespace
60 
61 
62 BOOST_PYTHON_MODULE(%(mdName)s)
63 {
64  using namespace boost::python;
65  def ("%(plTypeSan)s2xml", %(plTypeSan)s2xml);
66 }
67 
68 """
69 
70 buildFileTemplate = """
71 <flags CXXFLAGS="-Wno-sign-compare -Wno-unused-variable -Os"/>
72 <use name="boost"/>
73 <use name="boost_python"/>
74 <use name="boost_iostreams"/>
75 <use name="boost_serialization"/>
76 <use name="boost_program_options"/>
77 <use name="CondCore/DBCommon"/>
78 <use name="CondCore/IOVService"/>
79 <use name="CondCore/MetaDataService"/>
80 <use name="CondCore/TagCollection"/>
81 <use name="CondCore/CondDB"/>
82 <use name="CondFormats/HLTObjects"/>
83 <use name="CondFormats/Alignment"/>
84 <use name="CondFormats/BeamSpotObjects"/>
85 <use name="CondFormats/CastorObjects"/>
86 <use name="CondFormats/HIObjects"/>
87 <use name="CondFormats/CSCObjects"/>
88 <use name="CondFormats/DTObjects"/>
89 <use name="CondFormats/ESObjects"/>
90 <use name="CondFormats/EcalObjects"/>
91 <use name="CondFormats/EgammaObjects"/>
92 <use name="CondFormats/Luminosity"/>
93 <use name="CondFormats/HcalObjects"/>
94 <use name="CondFormats/JetMETObjects"/>
95 <use name="CondFormats/L1TObjects"/>
96 <use name="CondFormats/PhysicsToolsObjects"/>
97 <use name="CondFormats/GeometryObjects"/>
98 <use name="CondFormats/RecoMuonObjects"/>
99 <use name="CondFormats/RPCObjects"/>
100 <use name="CondFormats/RunInfo"/>
101 <use name="CondFormats/SiPixelObjects"/>
102 <use name="CondFormats/SiStripObjects"/>
103 <use name="CondFormats/Common"/>
104 <use name="CondFormats/BTauObjects"/>
105 <use name="CondFormats/MFObjects"/>
106 <export>
107  <lib name="1"/>
108 </export>
109 """
110 
111 # helper function
112 def sanitize(typeName):
113  return typeName.replace(' ','').replace('<','_').replace('>','')
114 
116 
117  def __init__(self, condDBIn):
118  self.conddb = condDBIn
119  self._pl2xml_isPrepared = False
120 
121  if not os.path.exists( os.path.join( os.environ['CMSSW_BASE'], 'src') ):
122  raise Exception("Looks like you are not running in a CMSSW developer area, $CMSSW_BASE/src/ does not exist")
123 
124  self.fakePkgName = "fakeSubSys4pl/fakePkg4pl"
125  self._pl2xml_tmpDir = os.path.join( os.environ['CMSSW_BASE'], 'src', self.fakePkgName )
126 
127  self.doCleanup = True
128 
129  def __del__(self):
130 
131  if self.doCleanup:
132  shutil.rmtree( '/'.join( self._pl2xml_tmpDir.split('/')[:-1] ) )
133  os.unlink( os.path.join( os.environ['CMSSW_BASE'], 'src', './pl2xmlComp.so') )
134  return
135 
136  def discover(self, payloadType):
137 
138  # print "discover> checking for plugin of type %s" % payloadType
139 
140  # first search in developer area:
141  libDir = os.path.join( os.environ["CMSSW_BASE"], 'lib', os.environ["SCRAM_ARCH"] )
142  pluginList = glob.glob( libDir + '/plugin%s_toXML.so' % sanitize(payloadType) )
143 
144  # if nothing found there, check release:
145  if not pluginList:
146  libDir = os.path.join( os.environ["CMSSW_RELEASE_BASE"], 'lib', os.environ["SCRAM_ARCH"] )
147  pluginList = glob.glob( libDir + '/plugin%s_toXML.so' % sanitize(payloadType) )
148 
149  # if pluginList:
150  # print "found plugin for %s (in %s) : %s " % (payloadType, libDir, pluginList)
151  # else:
152  # print "no plugin found for type %s" % payloadType
153 
154  xmlConverter = None
155  if len(pluginList) > 0:
156  dirPath, libName = os.path.split( pluginList[0] )
157  sys.path.append(dirPath)
158  # print "going to import %s from %s" % (libName, dirPath)
159  xmlConverter = importlib.import_module( libName.replace('.so', '') )
160  # print "found methods: ", dir(xmlConverter)
161  self.doCleanup = False
162 
163  return xmlConverter
164 
165  def prepPayload2xml(self, session, payload):
166 
167  startTime = time.time()
168 
169  # get payload from DB:
170  result = session.query(self.conddb.Payload.data, self.conddb.Payload.object_type).filter(self.conddb.Payload.hash == payload).one()
171  data, plType = result
172 
173  info = { "mdName" : "pl2xmlComp",
174  'plType' : plType,
175  'plTypeSan' : sanitize(plType),
176  }
177 
178  converter = self.discover(plType)
179  if converter: return converter
180 
181  code = payload2xmlCodeTemplate % info
182 
183  tmpDir = self._pl2xml_tmpDir
184  if ( os.path.exists( tmpDir ) ) :
185  msg = '\nERROR: %s already exists, please remove if you did not create that manually !!' % tmpDir
186  self.doCleanup = False
187  raise Exception(msg)
188 
189  os.makedirs( tmpDir+'/src' )
190 
191  buildFileName = "%s/BuildFile.xml" % (tmpDir,)
192  with open(buildFileName, 'w') as buildFile:
193  buildFile.write( buildFileTemplate )
194  buildFile.close()
195 
196  tmpFileName = "%s/src/%s" % (tmpDir, info['mdName'],)
197  with open(tmpFileName+'.cpp', 'w') as codeFile:
198  codeFile.write(code)
199  codeFile.close()
200 
201  libDir = os.path.join( os.environ["CMSSW_BASE"], 'tmp', os.environ["SCRAM_ARCH"], 'src', self.fakePkgName, 'src', self.fakePkgName.replace('/',''))
202  libName = libDir + '/lib%s.so' % self.fakePkgName.replace('/','')
203  cmd = "source /afs/cern.ch/cms/cmsset_default.sh;"
204  cmd += "(cd %s ; scram b 2>&1 >build.log && cp %s $CMSSW_BASE/src/pl2xmlComp.so )" % (tmpDir, libName)
205  ret = os.system(cmd)
206  if ret != 0 : self.doCleanup = False
207 
208  buildTime = time.time()-startTime
209  print >> sys.stderr, "buillding done in ", buildTime, 'sec., return code from build: ', ret
210 
211  if (ret != 0):
212  return None
213 
214  return importlib.import_module( 'pl2xmlComp' )
215 
216  def payload2xml(self, session, payload):
217 
218  if not self._pl2xml_isPrepared:
219  xmlConverter = self.prepPayload2xml(session, payload)
220  if not xmlConverter:
221  msg = "Error preparing code for "+payload
222  raise Exception(msg)
223  self._pl2xml_isPrepared = True
224 
225 
226  # get payload from DB:
227  result = session.query(self.conddb.Payload.data, self.conddb.Payload.object_type).filter(self.conddb.Payload.hash == payload).one()
228  data, plType = result
229 
230  convFuncName = sanitize(plType)+'2xml'
231  sys.path.append('.')
232  func = getattr(xmlConverter, convFuncName)
233  resultXML = func( str(data), str(plType) )
234 
235  print resultXML
236 
def sanitize
Definition: cond2xml.py:112
static std::string join(char **cmd)
Definition: RemoteFile.cc:18
list object
Definition: dbtoconf.py:77