CMS 3D CMS Logo

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  {
54  boost::archive::xml_oarchive xmlResult( outBuffer );
55  xmlResult << boost::serialization::make_nvp( "cmsCondPayload", *payload );
56  }
57  return outBuffer.str();
58  }
59 
60 } // end namespace
61 
62 
63 BOOST_PYTHON_MODULE(%(mdName)s)
64 {
65  using namespace boost::python;
66  def ("%(plTypeSan)s2xml", %(plTypeSan)s2xml);
67 }
68 
69 """
70 
71 buildFileTemplate = """
72 <flags CXXFLAGS="-Wno-sign-compare -Wno-unused-variable -Os"/>
73 <use name="CondCore/Utilities"/>
74 <use name="boost_python"/>
75 <use name="boost_iostreams"/>
76 <use name="boost_serialization"/>
77 <export>
78  <lib name="1"/>
79 </export>
80 """
81 
82 # helper function
83 def sanitize(typeName):
84  return typeName.replace(' ','').replace('<','_').replace('>','')
85 
87 
88  def __init__(self, condDBIn):
89  self.conddb = condDBIn
90  self._pl2xml_isPrepared = False
91 
92  if not os.path.exists( os.path.join( os.environ['CMSSW_BASE'], 'src') ):
93  raise Exception("Looks like you are not running in a CMSSW developer area, $CMSSW_BASE/src/ does not exist")
94 
95  self.fakePkgName = "fakeSubSys4pl/fakePkg4pl"
96  self._pl2xml_tmpDir = os.path.join( os.environ['CMSSW_BASE'], 'src', self.fakePkgName )
97 
98  self.doCleanup = True
99 
100  def __del__(self):
101 
102  if self.doCleanup:
103  shutil.rmtree( '/'.join( self._pl2xml_tmpDir.split('/')[:-1] ) )
104  os.unlink( os.path.join( os.environ['CMSSW_BASE'], 'src', './pl2xmlComp.so') )
105  return
106 
107  def discover(self, payloadType):
108 
109  # print "discover> checking for plugin of type %s" % payloadType
110 
111  # first search in developer area:
112  libDir = os.path.join( os.environ["CMSSW_BASE"], 'lib', os.environ["SCRAM_ARCH"] )
113  pluginList = glob.glob( libDir + '/plugin%s_toXML.so' % sanitize(payloadType) )
114 
115  # if nothing found there, check release:
116  if not pluginList:
117  libDir = os.path.join( os.environ["CMSSW_RELEASE_BASE"], 'lib', os.environ["SCRAM_ARCH"] )
118  pluginList = glob.glob( libDir + '/plugin%s_toXML.so' % sanitize(payloadType) )
119 
120  # if pluginList:
121  # print "found plugin for %s (in %s) : %s " % (payloadType, libDir, pluginList)
122  # else:
123  # print "no plugin found for type %s" % payloadType
124 
125  xmlConverter = None
126  if len(pluginList) > 0:
127  dirPath, libName = os.path.split( pluginList[0] )
128  sys.path.append(dirPath)
129  # print "going to import %s from %s" % (libName, dirPath)
130  xmlConverter = importlib.import_module( libName.replace('.so', '') )
131  # print "found methods: ", dir(xmlConverter)
132  self.doCleanup = False
133 
134  return xmlConverter
135 
136  def prepPayload2xml(self, session, payload):
137 
138  startTime = time.time()
139 
140  Payload = session.get_dbtype(self.conddb.Payload)
141  # get payload from DB:
142  result = session.query(Payload.data, Payload.object_type).filter(Payload.hash == payload).one()
143  data, plType = result
144 
145  info = { "mdName" : "pl2xmlComp",
146  'plType' : plType,
147  'plTypeSan' : sanitize(plType),
148  }
149 
150  converter = self.discover(plType)
151  if converter: return converter
152 
153  code = payload2xmlCodeTemplate % info
154 
155  tmpDir = self._pl2xml_tmpDir
156  if ( os.path.exists( tmpDir ) ) :
157  msg = '\nERROR: %s already exists, please remove if you did not create that manually !!' % tmpDir
158  self.doCleanup = False
159  raise Exception(msg)
160 
161  os.makedirs( tmpDir+'/src' )
162 
163  buildFileName = "%s/BuildFile.xml" % (tmpDir,)
164  with open(buildFileName, 'w') as buildFile:
165  buildFile.write( buildFileTemplate )
166  buildFile.close()
167 
168  tmpFileName = "%s/src/%s" % (tmpDir, info['mdName'],)
169  with open(tmpFileName+'.cpp', 'w') as codeFile:
170  codeFile.write(code)
171  codeFile.close()
172 
173  libDir = os.path.join( os.environ["CMSSW_BASE"], 'tmp', os.environ["SCRAM_ARCH"], 'src', self.fakePkgName, 'src', self.fakePkgName.replace('/',''))
174  libName = libDir + '/lib%s.so' % self.fakePkgName.replace('/','')
175  cmd = "source /afs/cern.ch/cms/cmsset_default.sh;"
176  cmd += "(cd %s ; scram b 2>&1 >build.log && cp %s $CMSSW_BASE/src/pl2xmlComp.so )" % (tmpDir, libName)
177  ret = os.system(cmd)
178  if ret != 0 : self.doCleanup = False
179 
180  buildTime = time.time()-startTime
181  print >> sys.stderr, "buillding done in ", buildTime, 'sec., return code from build: ', ret
182 
183  if (ret != 0):
184  return None
185 
186  return importlib.import_module( 'pl2xmlComp' )
187 
188  def payload2xml(self, session, payload):
189 
190  if not self._pl2xml_isPrepared:
191  xmlConverter = self.prepPayload2xml(session, payload)
192  if not xmlConverter:
193  msg = "Error preparing code for "+payload
194  raise Exception(msg)
195  self._pl2xml_isPrepared = True
196 
197 
198  Payload = session.get_dbtype(self.conddb.Payload)
199  # get payload from DB:
200  result = session.query(Payload.data, Payload.object_type).filter(Payload.hash == payload).one()
201  data, plType = result
202 
203  convFuncName = sanitize(plType)+'2xml'
204  sys.path.append('.')
205  func = getattr(xmlConverter, convFuncName)
206  resultXML = func( str(data), str(plType) )
207 
208  print resultXML
209 
def __init__(self, condDBIn)
Definition: cond2xml.py:88
def replace(string, replacements)
def sanitize(typeName)
Definition: cond2xml.py:83
def discover(self, payloadType)
Definition: cond2xml.py:107
def prepPayload2xml(self, session, payload)
Definition: cond2xml.py:136
def payload2xml(self, session, payload)
Definition: cond2xml.py:188
static std::string join(char **cmd)
Definition: RemoteFile.cc:18