Line Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
#!/usr/bin/env python3

import os
import sys
import configparser as ConfigParser
import optparse
import datetime

scriptTemplate = """
#!/bin/bash
#init
export STAGE_SVCCLASS=cmscaf
source /afs/cern.ch/cms/sw/cmsset_default.sh
cd %(CMSSW_BASE)s
eval `scramv1 ru -sh`
rfmkdir -p %(workDir)s
rm -f %(workDir)s/*
cd %(workDir)s

#run
pwd
df -h .
#run configfile and post-proccess it
%(commandLine)s &> cmsRunOut.%(name)s.log

echo "----"
echo "List of files in $(pwd):"
ls -ltr
echo "----"
echo ""

#retrive
rfmkdir %(outDir)s
rfmkdir %(outDir)s/%(name)s
gzip cmsRunOut.%(name)s.log
rfmkdir %(logDir)s
rfcp cmsRunOut.%(name)s%(isn)s.log.gz %(logDir)s
for i in *.root
do
   rfcp $i %(outDir)s/%(name)s/${i/.root}%(isn)s.root
done
   
#cleanup
#rm -rf %(workDir)s
echo "done."
"""

extractDQMtemplate = """
import FWCore.ParameterSet.Config as cms

process = cms.Process("EDMtoMEConvert")
process.load("DQMServices.Examples.test.MessageLogger_cfi")

process.load("DQMServices.Components.EDMtoMEConverter_cff")

process.maxEvents = cms.untracked.PSet(
    input = cms.untracked.int32(-1)
)
process.source = cms.Source("PoolSource",
    fileNames = cms.untracked.vstring(%(AlCARecos)s)
)

process.p1 = cms.Path(process.EDMtoMEConverter*process.dqmSaver)
process.dqmSaver.convention = 'Offline'
process.dqmSaver.workflow = '/ConverterTester/Test/RECO'
"""

####################--- Classes ---############################
class BetterConfigParser(ConfigParser.ConfigParser):
    def optionxform(self, optionstr):
        return optionstr
    
    def exists( self, section, option):
        try:
            items = self.items(section) 
        except ConfigParser.NoSectionError:
            return False
        for item in items:
            if item[0] == option:
                return True
        return False

class Sample:
   def __init__(self, name, config):
      self.name = name
      self.files = config.get("sample:%s"%name, "files").split("\n")
      self.globalTag = config.get("sample:%s"%name, "globalTag")
      self.maxEvents = config.get("sample:%s"%name, "maxEvents")
      self.AlCaRecos = config.get("sample:%s"%name, "AlCaRecos")
      self.AlcaRecoScripts = None
      self.DQMScript = None
      self.DQMConfig = None
      self.__config = config
   
   def createScript(self, path, style, commandLine, isn = None):
      repMap = {
                   "name": self.name,
                   "workDir": self.__config.get("general", "workDir"),
                   "outDir": self.__config.get("general", "outDir"),
                   "logDir": self.__config.get("general", "logDir"),
                   "CMSSW_BASE": os.environ["CMSSW_BASE"],
                   "commandLine":commandLine
                   }
      fileName = "%s_%s"%(style,self.name)
      if not isn == None:
         repMap["isn"] = "_%03i"%isn
         fileName += repMap["isn"]
      else:
         repMap["isn"] = ""
         
      fileName += ".sh"
      scriptPath = os.path.join(path, fileName)
      scriptFile = open( scriptPath, "w" )
      scriptFile.write( scriptTemplate%repMap )
      scriptFile.close()
      os.chmod(scriptPath, 0o755)
      return scriptPath
   
   def createDQMExtract(self, path):
      filePrefix = "ALCARECO%s"%self.AlCaRecos.split("+")[0]

      alcaFiles = []
      for i in range( 0,len(self.files) ):
         alcaFilePath = os.path.join( self.__config.get("general","outDir"), self.name,"%s_%03i.root"%(filePrefix,i+1) )
         alcaFilePath = os.path.expandvars(alcaFilePath)
         alcaFilePath = os.path.abspath(alcaFilePath)   
         if alcaFilePath.startswith("/castor"):
            alcaFilePath = "'rfio:"+alcaFilePath+"'"
         else:
            alcaFilePath = "'file:"+alcaFilePath+"'"
         alcaFiles.append(alcaFilePath)
      repMap = { "AlCARecos":", ".join(alcaFiles)}   
      fileName = "extractDQM_%s_cfg.py"%self.name
      cfgPath = os.path.join(path, fileName)
      cfgFile = open( cfgPath, "w" )
      cfgFile.write( extractDQMtemplate%repMap )
      cfgFile.close()
      return cfgPath
   
   def createScripts(self, path):
      result = []
      repMap = {"maxEvents":self.maxEvents,
                "globalTag":self.globalTag,
                "AlCaRecos":self.AlCaRecos,
                "sampleFile":"" }
      i = 1
      for sampleFile in self.files:
         repMap["sampleFile"] = sampleFile
         result.append(self.createScript(path, "AlCaReco", """
cmsDriver.py step3 -s ALCA:%(AlCaRecos)s+DQM \\
    -n %(maxEvents)s \\
    --filein %(sampleFile)s\\
    --conditions FrontierConditions_GlobalTag,%(globalTag)s \\
    --eventcontent RECO\\
    --mc"""%repMap, i))
         i += 1
      self.AlcaRecoScripts = result
      self.DQMConfig = self.createDQMExtract(path)
      self.DQMScript = self.createScript(path, "extractDQM", "cmsRun %s"%self.DQMConfig)
      return result

######################### Helpers ####################
#excute [command] and return output
def getCommandOutput2(command):
    child = os.popen(command)
    data = child.read()
    err = child.close()
    if err:
        raise RuntimeError('%s failed w/ exit code %d' % (command, err))
    return data
 
def runJob(jobName, script, config):
   jobMode = config.get("general","jobMode")
   print("> Testing "+jobName)
   if jobMode == "interactive":
       getCommandOutput2( script )
   if jobMode.split(",")[0] == "lxBatch":
       commands = jobMode.split(",")[1]
       getCommandOutput2("bsub "+commands+" -J "+jobName+" "+ script)     

def readSamples( config):
   result = []
   for section in config.sections():
      if "sample:" in section:
         name = section.split("sample:")[1]
         result.append( Sample(name, config) )
   return result

def main(argv = None):
    if argv == None:
       argv = sys.argv[1:]
    optParser = optparse.OptionParser()
    optParser.description = "test the tracker AlCaReco production and DQM"
    optParser.add_option("-n", "--dryRun", dest="dryRun", action="store_true", default=False,
                         help="create all scripts and cfg File but do not start jobs (default=False)")
    optParser.add_option("-c", "--config", dest="config",
                         help="configuration to use (default testConfig.ini) this can be a comma-seperated list of all .ini file you want to merge", metavar="CONFIG")
    optParser.add_option("-N", "--Name", dest="Name",
                         help="Name of this test (default: test_DATE_TIME)", metavar="NAME")

    (options, args) = optParser.parse_args(argv)

    if options.config == None:
        options.config = "testConfig.ini"
    else:
        options.config = options.config.split(",")
        result = []
        for iniFile in options.config:
            result.append( os.path.abspath(iniFile) )
        options.config = result
    
    config = BetterConfigParser()
    config.read( options.config )

    if options.Name == None:
        options.Name = "test_%s"%(datetime.datetime.now().strftime("%y%m%d_%H%M%S"))

    outPath = os.path.abspath( options.Name )
    for dir in [ "workDir","dataDir","logDir" ]:
       if not config.has_option("general", dir):
          config.set("general", dir, os.path.join( os.getcwd(), options.Name ))
       else:
          config.set("general", dir, os.path.join( config.get("general",dir), options.Name ))

    if not os.path.exists( outPath ):
        os.makedirs( outPath )
    elif not os.path.isdir( outPath ):
        raise "the file %s is in the way rename the Job or move it away"%outPath
     
    samples = readSamples( config )
    for sample in samples:
       sample.createScripts( outPath )
       for scriptPath in sample.AlcaRecoScripts:
          if not options.dryRun:
             runJob( sample.name, scriptPath, config )
     
if __name__ == "__main__":        
    main()