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 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
import configparser as ConfigParser
import argparse
import shelve
import sys
import os
import subprocess
import threading
import shutil
import time
import re
from helpers import *

shelve_name = "dump.shelve" # contains all the measurement objects
history_file = "history.log"
clock_interval = 20 # in seconds
delete_logs_after_finish = False  # if it is not desired to keep the log and submit script files
use_caf = False

def save(name, object):
    # in case of multiple threads running this stops potentially problematic file access
    global lock
    lock.acquire() 
    try:
        sh = shelve.open(shelve_name)
        sh[name] = object
        sh.close()
    finally:
        lock.release()

class Dataset:
    def __init__(self, config, name):
        dsDict = dict(config.items("dataset:{}".format(name)))
        self.name = name
        self.baseDirectory = dsDict["baseDirectory"].replace("$CMSSW_BASE", os.environ['CMSSW_BASE'])
        
        self.fileList = []
        names = dsDict["fileNames"].split(" ")
        for name in names:
            parsedNames = replaceAllRanges(name)
            for fileName in parsedNames:
                self.fileList.append(self.baseDirectory+"/"+fileName)
        self.nFiles = len(self.fileList)
        
        self.maxEvents = -1
        if "maxEvents" in dsDict:
            self.maxEvents = int(dsDict["maxEvents"])
        
        self.sampleType ="data1"
        if "isMC" in dsDict and dsDict["isMC"] == "True":
            self.sampleType = "MC"
        
        self.isCosmics = False
        if "isCosmics" in dsDict:
            self.isCosmics = (dsDict["isCosmics"] == "True")
        
        self.conditions, self.validConditions = loadConditions(dsDict)      
        
        # check if any of the sources used for conditions is invalid
        if not self.validConditions:
            print("Invalid conditions defined for dataset {}".format(self.name))
        
        # check if all files specified exist
        self.existingFiles, missingFiles = allFilesExist(self)
        
        if not self.existingFiles:
            for fileName in missingFiles:
                print("Invalid file name {} defined for dataset {}".format(fileName, self.name))
    
class Alignment:        
    def __init__(self, config, name):
        alDict = dict(config.items("alignment:{}".format(name)))
        self.name = name
        
        self.globalTag = "None"
        if "globalTag" in alDict:
            self.globalTag = alDict["globalTag"]
        self.baselineDir = "Design"
        if "baselineDir" in alDict:
            self.baselineDir= alDict["baselineDir"]
        self.isDesign = False
        if "isDesign" in alDict:
            self.isDesign= (alDict["isDesign"] == "True")
        
        # If self.hasAlignmentCondition is true, no other Alignment-Object is loaded in apeEstimator_cfg.py using the 
        self.conditions, self.validConditions = loadConditions(alDict) 
        
        # check if any of the sources used for conditions is invalid
        if not self.validConditions:
            print("Invalid conditions defined for alignment {}".format(self.name))
        

class ApeMeasurement:
    name = "workingArea"
    curIteration = 0
    firstIteration = 0
    maxIterations = 15
    maxEvents = None
    dataset = None
    alignment = None
    runningJobs  = None
    failedJobs      = None
    startTime = ""
    finishTime = ""
    
    def __init__(self, name, config, settings):
        self.name = name        
        self.status_ = STATE_ITERATION_START
        self.runningJobs = []
        self.failedJobs = []
        self.startTime = subprocess.check_output(["date"]).decode().strip()
        
        # load conditions from dictionary, overwrite defaults if defined
        for key, value in settings.items():
            if not key.startswith("condition "):
                setattr(self, key, value)
        
        # Replace names with actual Dataset and Alignment objects
        self.dataset = Dataset(config, settings["dataset"])
        self.alignment = Alignment(config, settings["alignment"])
        
        # If not defined here, replace by setting from Dataset
        if not "maxEvents" in settings:
            self.maxEvents = self.dataset.maxEvents
            
        self.firstIteration=int(self.firstIteration)
        self.maxIterations=int(self.maxIterations)
        self.curIteration = self.firstIteration
        self.maxEvents = int(self.maxEvents)
        if self.alignment.isDesign:
            self.maxIterations = 0
        
        self.conditions, self.validConditions = loadConditions(settings) 
        
        # see if sanity checks passed
        if not self.alignment.validConditions or not self.dataset.validConditions or not self.dataset.existingFiles or not self.validConditions:
            self.setStatus(STATE_INVALID_CONDITIONS, True)
            return
        
        if unitTest:
            return
        
        if self.alignment.isDesign and self.dataset.sampleType != "MC":
            # For now, this won't immediately shut down the program
            print("APE Measurement {} is scheduled to to an APE baseline measurement with a dataset that is not marked as isMC=True. Is this intended?".format(self.name))
        ensurePathExists('{}/hists/{}'.format(base, self.name))
        if not self.alignment.isDesign:
            ensurePathExists('{}/hists/{}/apeObjects'.format(base, self.name))
        
    def status(self):
        return status_map[self.status_]
    
    def printStatus(self):
        print("APE Measurement {} in iteration {} is now in status {}".format(self.name, self.curIteration, self.status()))
    
    def setStatus(self, status, terminal=False):
        if self.status_ != status:
            self.status_ = status
            self.printStatus()
        if terminal:
            self.finishTime = subprocess.check_output(["date"]).decode().strip()
    
    # submit jobs for track refit and hit categorization
    def submitJobs(self):
        toSubmit = []
        
        allConditions = self.alignment.conditions+self.dataset.conditions+self.conditions
        allConditions = list({v['record']:v for v in allConditions}.values()) # Removes double definitions of Records
        
        ensurePathExists("{}/test/autoSubmitter/workingArea".format(base))
        
        # If conditions are made, create file to load them from
        rawFileName = "None"
        conditionsFileName = "None"
        if len(allConditions) > 0:
            conditionsFileName = "{base}/python/conditions/conditions_{name}_iter{iterNo}_cff.py".format(base=base,name=self.name, iterNo=self.curIteration)
            rawFileName = "conditions_{name}_iter{iterNo}_cff".format(name=self.name, iterNo=self.curIteration)
            with open(conditionsFileName, "w") as fi:
                from autoSubmitterTemplates import conditionsFileHeader
                fi.write(conditionsFileHeader)
                from autoSubmitterTemplates import conditionsTemplate
                for condition in allConditions:
                    fi.write(conditionsTemplate.format(record=condition["record"], connect=condition["connect"], tag=condition["tag"]))
                
        alignmentNameToUse = "fromConditions"
        
        lastIter = (self.curIteration==self.maxIterations) and not self.alignment.isDesign
        
        inputCommands = "sample={sample} fileNumber={fileNo} iterNumber={iterNo} lastIter={lastIter} alignRcd={alignRcd} maxEvents={maxEvents} globalTag={globalTag} measurementName={name} conditions={conditions} cosmics={cosmics}".format(sample=self.dataset.sampleType,fileNo="$1",iterNo=self.curIteration,lastIter=lastIter,alignRcd=alignmentNameToUse, maxEvents=self.maxEvents, globalTag=self.alignment.globalTag, name=self.name, conditions=rawFileName,cosmics=self.dataset.isCosmics)
        
        from autoSubmitterTemplates import condorJobTemplate
        jobFileContent = condorJobTemplate.format(base=base, inputFile="$2", inputCommands=inputCommands)
        jobFileName = "{}/test/autoSubmitter/workingArea/batchscript_{}_iter{}.tcsh".format(base, self.name,self.curIteration)
        with open(jobFileName, "w") as jobFile:
            jobFile.write(jobFileContent)
        
        # create a batch job file for each input file
        arguments = ""
        from autoSubmitterTemplates import condorArgumentTemplate
        for i in range(self.dataset.nFiles):
            inputFile = self.dataset.fileList[i]
            fileNumber = i+1
            arguments += condorArgumentTemplate.format(fileNumber=fileNumber, inputFile=inputFile)
            
        # build condor submit script
        date = subprocess.check_output(["date", "+%m_%d_%H_%M_%S"]).decode().strip()
        sub = "{}/test/autoSubmitter/workingArea/job_{}_iter{}".format(base, self.name, self.curIteration)
        
        errorFileTemp  = sub+"_error_{}.txt"
        errorFile  = errorFileTemp.format("$(ProcId)")
        outputFile = sub+"_output_$(ProcId).txt"
        logFileTemp= sub+"_condor_{}.log"
        logFile    = logFileTemp.format("$(ProcId)")
        jobFile    = sub+".tcsh"   
        jobName    = "{}_{}".format(self.name, self.curIteration)
        for i in range(self.dataset.nFiles):
            # make file empty if it existed before
            with open(logFileTemp.format(i), "w") as fi:
                pass
        
        # create submit file
        from autoSubmitterTemplates import condorSubTemplate
        from autoSubmitterTemplates import condorSubTemplateCAF
        if use_caf:
            submitFileContent = condorSubTemplateCAF.format(jobFile=jobFileName, outputFile=outputFile, errorFile=errorFile, logFile=logFile, arguments=arguments, jobName=jobName)
        else:
            submitFileContent = condorSubTemplate.format(jobFile=jobFileName, outputFile=outputFile, errorFile=errorFile, logFile=logFile, arguments=arguments, jobName=jobName)
        submitFileName = "{}/test/autoSubmitter/workingArea/submit_{}_jobs_iter{}.sub".format(base, self.name, self.curIteration)
        with open(submitFileName, "w") as submitFile:
            submitFile.write(submitFileContent)
        
        # submit batch
        from autoSubmitterTemplates import submitCondorTemplate
        subOut = subprocess.check_output(submitCondorTemplate.format(subFile=submitFileName), shell=True).decode().strip()
    
        if len(subOut) == 0:
                print("Running on environment that does not know bsub command or ssh session is timed out (ongoing for longer than 24h?), exiting")
                sys.exit()
                
        cluster = subOut.split(" ")[-1][:-1]
        for i in range(self.dataset.nFiles):
            # list contains condor log files from which to read when job is terminated to detect errors
            self.runningJobs.append((logFileTemp.format(i), errorFileTemp.format(i), "{}.{}".format(cluster, i)))
        
        self.setStatus(STATE_BJOBS_WAITING)
    
    def checkJobs(self):
        stillRunningJobs = []
        # check all still running jobs
        for logName, errName, jobId in self.runningJobs:
            # read condor logs instead of doing condor_q or similar, as it is much faster
            if not os.path.isfile(logName):
                print("{} does not exist even though it should, marking job as failed".format(logName))
                self.failedJobs.append( (logName, errName) ) 
                break
            with open(logName, "r") as logFile:
                log = logFile.read()
            if not "submitted" in log:
                print("{} was apparently not submitted, did you empty the log file or is condor not working?".format(jobId))
                self.failedJobs.append( (logName, errName) ) 
                
            if "Job was aborted" in log:
                print("Job {} of measurement {} in iteration {} was aborted".format(jobId, self.name, self.curIteration))
                self.failedJobs.append( (logName, errName) ) 
            elif "Job terminated" in log:
                if "Normal termination (return value 0)" in log:
                    foundErr = False
                    with open(errName, "r") as err:
                        for line in err:
                            if "Fatal Exception" in line.strip():
                                foundErr = True
                                break
                    if not foundErr:
                        print("Job {} of measurement {} in iteration {} finished successfully".format(jobId, self.name, self.curIteration))
                    else:
                        # Fatal error in stderr
                        print("Job {} of measurement {} in iteration {} has a fatal error, check stderr".format(jobId, self.name, self.curIteration))
                        self.failedJobs.append( (logName, errName) ) 
                else:
                    # nonzero return value
                    print("Job {} of measurement {} in iteration {} failed, check stderr".format(jobId, self.name, self.curIteration))
                    self.failedJobs.append( (logName, errName) ) 
            else:
                stillRunningJobs.append( (logName, errName, jobId) )
        self.runningJobs = stillRunningJobs
        
        # at least one job failed
        if len(self.failedJobs) > 0:
            self.setStatus(STATE_BJOBS_FAILED, True)
        elif len(self.runningJobs) == 0:
            self.setStatus(STATE_BJOBS_DONE)
            print("All condor jobs of APE measurement {} in iteration {} are done".format(self.name, self.curIteration))
            
            # remove files
            if delete_logs_after_finish:
                submitFile = "{}/test/autoSubmitter/workingArea/submit_{}_jobs_iter{}.sub".format(base, self.name, self.curIteration)
                jobFile = "{}/test/autoSubmitter/workingArea/batchscript_{}_iter{}.tcsh".format(base, self.name,self.curIteration)
                os.remove(submitFile)
                os.remove(jobFile)
            
                for i in range(self.dataset.nFiles):
                    sub = "{}/test/autoSubmitter/workingArea/job_{}_iter{}".format(base, self.name, self.curIteration)
                    errorFile  = sub+"_error_{}.txt".format(i)
                    outputFile = sub+"_output_{}.txt".format(i)
                    logFile    = sub+"_condor_{}.log".format(i) 
                    os.remove(errorFile)
                    os.remove(outputFile)
                    os.remove(logFile)
    
    # merges files from jobs
    def mergeFiles(self):
        self.setStatus(STATE_MERGE_WAITING)
        if self.alignment.isDesign:
            folderName = '{}/hists/{}/baseline'.format(base, self.name)
        else:
            folderName = '{}/hists/{}/iter{}'.format(base, self.name, self.curIteration)
        
        # (re)move results from previous measurements before creating folder
        if os.path.isdir(folderName):
            if os.path.isdir(folderName+"_old"):
                shutil.rmtree("{}_old".format(folderName))
            os.rename(folderName, folderName+"_old")
        os.makedirs(folderName)
        
        # This is so that the structure of the tree can be retrieved by ApeEstimatorSummary.cc and the tree does not have to be rebuilt
        if self.curIteration > 0 and not self.alignment.isDesign: # don't have to check for isDesign here because it always ends after iteration 0...
            shutil.copyfile('{}/hists/{}/iter{}/allData_iterationApe.root'.format(base, self.name, self.curIteration-1),folderName+"/allData_iterationApe.root")
        fileNames = ['{}/hists/{}/{}{}.root'.format(base, self.name, self.dataset.sampleType, str(i)) for i in range(1, self.dataset.nFiles+1)]
        fileString = " ".join(fileNames)
        
        from autoSubmitterTemplates import mergeTemplate
        merge_result = subprocess.call(mergeTemplate.format(path=folderName, inputFiles=fileString), shell=True) # returns exit code (0 if no error occured)
        for name in fileNames:
            os.remove(name)
            
        if rootFileValid("{}/allData.root".format(folderName)) and merge_result == 0:
            self.setStatus(STATE_MERGE_DONE)
        else:
            self.setStatus(STATE_MERGE_FAILED, True)
    
    # calculates APE
    def calculateApe(self):
        self.status_ = STATE_SUMMARY_WAITING        
        from autoSubmitterTemplates import summaryTemplate
        if self.alignment.isDesign:
            #use measurement name as baseline folder name in this case
            inputCommands = "iterNumber={} setBaseline={} measurementName={} baselineName={}".format(self.curIteration,self.alignment.isDesign,self.name, self.name)
        else:
            inputCommands = "iterNumber={} setBaseline={} measurementName={} baselineName={}".format(self.curIteration,self.alignment.isDesign,self.name, self.alignment.baselineDir)
        
        summary_result = subprocess.call(summaryTemplate.format(inputCommands=inputCommands), shell=True) # returns exit code (0 if no error occured)
        if summary_result == 0:
            self.setStatus(STATE_SUMMARY_DONE)
        else:
            self.setStatus(STATE_SUMMARY_FAILED, True)
    
    # saves APE to .db file so it can be read out next iteration
    def writeApeToDb(self):
        self.setStatus(STATE_LOCAL_WAITING)      
        from autoSubmitterTemplates import localSettingTemplate
        inputCommands = "iterNumber={} setBaseline={} measurementName={}".format(self.curIteration,self.alignment.isDesign,self.name)

        local_setting_result = subprocess.call(localSettingTemplate.format(inputCommands=inputCommands), shell=True) # returns exit code (0 if no error occured)
        if local_setting_result == 0:
            self.setStatus(STATE_LOCAL_DONE)
        else:
            self.setStatus(STATE_LOCAL_FAILED, True)
        
    def finishIteration(self):
        print("APE Measurement {} just finished iteration {}".format(self.name, self.curIteration))
        if self.curIteration < self.maxIterations:
            self.curIteration += 1
            self.setStatus(STATE_ITERATION_START)
        else:
            self.setStatus(STATE_FINISHED, True)
            print("APE Measurement {}, which was started at {} was finished after {} iterations, at {}".format(self.name, self.startTime, self.curIteration, self.finishTime))
            
    def kill(self):
        from autoSubmitterTemplates import killJobTemplate
        for log, err, jobId in self.runningJobs:
            subprocess.call(killJobTemplate.format(jobId=jobId), shell=True)
        self.runningJobs = []
        self.setStatus(STATE_NONE)
        
    def purge(self):
        self.kill()
        folderName = '{}/hists/{}'.format(base, self.name)
        shutil.rmtree(folderName)
        # remove log-files as well?
        
    def runIteration(self):
        global threadcounter
        global measurements
        threadcounter.acquire()
        try:
            if self.status_ == STATE_ITERATION_START:
                # start bjobs
                print("APE Measurement {} just started iteration {}".format(self.name, self.curIteration))

                try:
                    self.submitJobs()
                    save("measurements", measurements)
                except Exception as e:
                    # this is needed in case the scheduler goes down
                    print("Error submitting jobs for APE measurement {}".format(self.name))
                    print(e)
                    return
                    
            if self.status_ == STATE_BJOBS_WAITING:
                # check if bjobs are finished
                self.checkJobs()
                save("measurements", measurements)
            if self.status_ == STATE_BJOBS_DONE:
                # merge files
                self.mergeFiles()
                save("measurements", measurements)
            if self.status_ == STATE_MERGE_DONE:
                # start summary
                self.calculateApe()
                save("measurements", measurements)
            if self.status_ == STATE_SUMMARY_DONE:
                # start local setting (only if not a baseline measurement)
                if self.alignment.isDesign:
                    self.setStatus(STATE_LOCAL_DONE)
                else:
                    self.writeApeToDb()
                save("measurements", measurements)
            if self.status_ == STATE_LOCAL_DONE:
                self.finishIteration()
                save("measurements", measurements)
                # go to next iteration or finish measurement
            
            if self.status_ == STATE_BJOBS_FAILED or \
                self.status_ == STATE_MERGE_FAILED or \
                self.status_ == STATE_SUMMARY_FAILED or \
                self.status_ == STATE_LOCAL_FAILED or \
                self.status_ == STATE_INVALID_CONDITIONS or \
                self.status_ == STATE_FINISHED:
                    with open(history_file, "a") as fi:
                        fi.write("APE measurement {name} which was started at {start} finished at {end} with state {state} in iteration {iteration}\n".format(name=self.name, start=self.startTime, end=self.finishTime, state=self.status(), iteration=self.curIteration))
                    if self.status_ == STATE_FINISHED:
                        global finished_measurements
                        finished_measurements[self.name] = self
                        save("finished", finished_measurements)
                    else:
                        global failed_measurements
                        failed_measurements[self.name] = self
                        
                        self.setStatus(STATE_NONE)
                        save("failed", failed_measurements)
                    save("measurements", measurements)
            if self.status_ == STATE_ITERATION_START: # this ensures that jobs do not go into idle if many measurements are done simultaneously
                # start bjobs
                print("APE Measurement {} just started iteration {}".format(self.name, self.curIteration))
                self.submitJobs()
                save("measurements", measurements)   
        finally:
            threadcounter.release()

def main():    
    parser = argparse.ArgumentParser(description="Automatically run APE measurements")
    parser.add_argument("-c", "--config", action="append", dest="configs", default=[],
                          help="Config file that has list of measurements")
    parser.add_argument("-k", "--kill", action="append", dest="kill", default=[],
                          help="List of measurement names to kill (=remove from list and kill all bjobs)")
    parser.add_argument("-p", "--purge", action="append", dest="purge", default=[],
                          help="List of measurement names to purge (=kill and remove folder)")
    parser.add_argument("-r", "--resume", action="append", dest="resume", default=[],
                          help="Resume interrupted APE measurements which are stored in shelves (specify shelves)")
    parser.add_argument("-d", "--dump", action="store", dest="dump", default=None,
                          help='Specify in which .shelve file to store the measurements')
    parser.add_argument("-n", "--ncores", action="store", dest="ncores", default=1, type=int,
                          help='Number of threads running in parallel')
    parser.add_argument("-C", "--caf",action="store_true", dest="caf", default=False,
                                              help="Use CAF queue for condor jobs")
    parser.add_argument("-u", "--unitTest", action="store_true", dest="unitTest", default=False,
                          help='If this is used, as soon as a measurement fails, the program will exit and as exit code the status of the measurement, i.e., where it failed')
    args = parser.parse_args()
    
    global base
    global clock_interval
    global shelve_name
    global threadcounter
    global lock
    global use_caf
    global unitTest 
    
    use_caf = args.caf
    unitTest = args.unitTest
    
    threadcounter = threading.BoundedSemaphore(args.ncores)
    lock = threading.Lock()
    
    if args.dump != None: # choose different file than default
        shelve_name = args.dump
    elif args.resume != []:
        shelve_name = args.resume[0]
    try:
        base = os.environ['CMSSW_BASE']+"/src/Alignment/APEEstimation"
    except KeyError:
        print("No CMSSW environment was set, exiting")
        sys.exit(1)

    killTargets = []
    purgeTargets = []
    for toConvert in args.kill:
        killTargets += replaceAllRanges(toConvert)
        
    for toConvert in args.purge:
        purgeTargets += replaceAllRanges(toConvert)
    
    global measurements
    measurements = []
    global finished_measurements
    finished_measurements = {}
    global failed_measurements
    failed_measurements = {}
    
    if args.resume != []:
        for resumeFile in args.resume:
            try:
                sh = shelve.open(resumeFile)
                resumed = sh["measurements"]
                
                resumed_failed = sh["failed"]
                resumed_finished = sh["finished"]
                sh.close()
                
                for res in resumed:
                    measurements.append(res)
                    print("Measurement {} in state {} in iteration {} was resumed".format(res.name, res.status(), res.curIteration))
                    # Killing and purging is done here, because it doesn't make 
                    # sense to kill or purge a measurement that was just started
                    for to_kill in args.kill:
                        if res.name == to_kill:
                            res.kill()
                    for to_purge in args.purge:
                        if res.name == to_purge:
                            res.purge()
                
                failed_measurements.update(resumed_failed)
                finished_measurements.update(resumed_finished)
                
            except IOError:
                print("Could not resume because {} could not be opened, exiting".format(shelve_name))
                sys.exit(2)
            
    # read out from config file
    if args.configs != []:
        config = ConfigParser.RawConfigParser()
        config.optionxform = str 
        config.read(args.configs)
        
        # read measurement names
        meas = [str(x.split("ape:")[1]) for x in list(config.keys()) if x.startswith("ape:")]

        for name in meas:
            if name in [x.name for x in measurements]:
                print("Error: APE Measurement with name {} already exists, skipping".format(name))
                continue
            settings = dict(config.items("ape:{}".format(name)))
            
            measurement = ApeMeasurement(name, config, settings)
            
            if measurement.status_ >= STATE_ITERATION_START:
                measurements.append(measurement)
                print("APE Measurement {} was started".format(measurement.name))
    
    if unitTest:
            # status is 0 if successful, 101 if wrongly configured
            sys.exit(measurement.status_)
    
    initializeModuleLoading()
    enableCAF(use_caf)
    
    
    while True:
        # remove finished and failed measurements
        measurements = [measurement for measurement in measurements if not (measurement.status_==STATE_NONE or measurement.status_ == STATE_FINISHED)]
        save("measurements", measurements)
        save("failed", failed_measurements)
        save("finished", finished_measurements)
        
        list_threads = []
        for measurement in measurements:
            t = threading.Thread(target=measurement.runIteration)
            list_threads.append(t)
            t.start()
        
        # wait for iterations to finish
        for t in list_threads:
            t.join()
     
        if len(measurements) == 0:
            print("No APE measurements are active, exiting")
            sys.exit(0)      
        
        try: # so that interrupting does not give an error message and just ends the program
            time_remaining = clock_interval
            while time_remaining > 0:
                print("Sleeping for {} seconds, you can safely [CTRL+C] now".format(time_remaining))
                time.sleep(1)
                time_remaining -= 1
                sys.stdout.write("\033[F")
                sys.stdout.write("\033[K")
            print("")
            sys.stdout.write("\033[F")
            sys.stdout.write("\033[K")
        except KeyboardInterrupt:
            sys.exit(0)

if __name__ == "__main__":
    main()