transform.py 31.8 KB
Newer Older
Graeme Stewart's avatar
Graeme Stewart committed
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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
# Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration

## @package PyJobTransforms.transform
#
# @brief Main package for new style ATLAS job transforms
# @details Core class for ATLAS job transforms
# @author atlas-comp-transforms-dev@cern.ch
# @version $Id: transform.py 609252 2014-07-29 16:20:33Z wbreaden $
# 

__version__ = '$Revision'
__doc__ = 'Core class for transforms'

import argparse
import os
import os.path
import pprint
import re
import sys
import time
import traceback
import unittest

from xml.etree import ElementTree

import logging
msg = logging.getLogger(__name__)

import PyJobTransforms.trfValidation as trfValidation
import PyJobTransforms.trfExceptions as trfExceptions

from PyJobTransforms.trfSignal import setTrfSignalHandlers, resetTrfSignalHandlers
from PyJobTransforms.trfArgs import addStandardTrfArgs, addFileValidationArguments, addValidationArguments
from PyJobTransforms.trfLogger import setRootLoggerLevel, stdLogLevels
from PyJobTransforms.trfJobOptions import JobOptionsTemplate
from PyJobTransforms.trfArgClasses import trfArgParser, argFile, argHISTFile, argument
from PyJobTransforms.trfExitCodes import trfExit
from PyJobTransforms.trfUtils import shQuoteStrings, listChildren, infanticide, pickledDump, JSONDump, cliToKey, convertToStr
from PyJobTransforms.trfReports import trfJobReport, defaultFileReport
from PyJobTransforms.trfExe import transformExecutor
from PyJobTransforms.trfGraph import executorGraph

## @class transform
#  @brief Core transform class
#  @note Every transform should only have one transform class instantiated
class transform(object):
    
    ## @brief Initialise a job transform
    #  @param standardSignalHandlers Boolean to set signal handlers. Default @True.
    #  @param standardValidationArgs Boolean to set standard validation options. Default @True.
    #  @param trfName Name of the transform. Default is executable name with .py rstripped.
    #  @param executor Executor list
    def __init__(self, standardSignalHandlers = True, standardTrfArgs = True, standardValidationArgs=True, 
                 trfName = os.path.basename(sys.argv[0]).rsplit('.py', 1)[0], 
                 executor = set([transformExecutor(),]), exeArgs = None, description = ''):
        '''Transform class initialiser'''
        msg.debug('Welcome to new transforms')
        
        ## @brief Get starting timestamp as early as possible
        self._transformStart = os.times()

        ## Transform _name
        self._name = trfName        
        
        ## @note Holder for arguments this trf understands
        #  Use @c argparse.SUPPRESS to have non-given arguments unset, rather than None
        #  Support reading arguments from a file using the notation @c @file 
        self.parser = trfArgParser(description='Transform {0}. {1}'.format(trfName, description),
                                   argument_default=argparse.SUPPRESS,
                                   fromfile_prefix_chars='@')

        if standardTrfArgs:
            addStandardTrfArgs(self.parser)

        if standardValidationArgs:
            addValidationArguments(self.parser)
            addFileValidationArguments(self.parser)

        
        ## Argument dictionary for this transform
        self._argdict = dict()
        
        ## Dsta dictionary place holder (this maps data types to their argFile instances)
        self._dataDictionary = dict()
        
        
        # Transform executor list - initalise with an empty set
        self._executors = set()
        self._executorDictionary = {}
        
        # If we were passed executors at construction time then append them to the set:
        if executor is not None:
            self.appendToExecutorSet(executor) 
        
        ## Transform exit code/message holders
        self._exitCode = None
        self._exitMsg = None

        ## Report object for this transform
        self._report = trfJobReport(parentTrf = self)
        
        # Setup standard signal handling if asked
        if standardSignalHandlers:
            setTrfSignalHandlers(self._exitWithReport)
            msg.debug('Standard signal handlers established')

            
    @property
    def name(self):
        return self._name
            
    @property
    def exitCode(self):
        if self._exitCode == None:
            msg.warning('Transform exit code getter: _exitCode is unset, returning "TRF_UNKOWN"')
            return trfExit.nameToCode('TRF_UNKOWN')
        else:
            return self._exitCode
        
    @property
    def exitMsg(self):
        if self._exitMsg == None:
            msg.warning('Transform exit code getter: _exitMsg is unset, returning empty string')
            return ''
        else:
            return self._exitMsg
    
    @property
    def argdict(self):
        return self._argdict
    
    @property
    def dataDictionary(self):
        return self._dataDictionary
    
    @property
    def report(self):
        return self._report
    
    @property
    def transformStart(self):
        return self._transformStart
    
    @property
    def executors(self):
        return self._executors

    def appendToExecutorSet(self, executors):
        # Normalise to something iterable
        if isinstance(executors, transformExecutor):
            executors = [executors,]
        elif not isinstance(executors, (list, tuple, set)):
            raise trfExceptions.TransformInternalException(trfExit.nameToCode('TRF_INTERNAL'), 
                                                           'Transform was initialised with an executor which was not a simple executor or an executor set')
    
        # TRY TO DEPRECATE SETTING trf IN THE EXECUTOR - USE CONF!
        # Executor book keeping: set parent link back to me for all executors
        # Also setup a dictionary, indexed by executor name and check that name is unique
        ## Setting conf here not working - too early to get the dataDictionary
        for executor in executors:
            executor.trf = self
            if executor.name in self._executorDictionary:
                raise trfExceptions.TransformInternalException(trfExit.nameToCode('TRF_INTERNAL'), 
                                                               'Transform has been initialised with two executors with the same name ({0}) - executor names must be unique'.format(value.name))
            self._executors.add(executor)
            self._executorDictionary[executor.name] = executor


    ## @brief Parse command line arguments for a transform
    def parseCmdLineArgs(self, args):
        msg.info('Transform command line was: %s' % ' '.join(shQuoteStrings(sys.argv)))

        try:
            # Use the argparse infrastructure to get the actual command line arguments
            self._argdict=vars(self.parser.parse_args(args))

            # Now look for special arguments, which expand out to other parameters
            # Note that the pickled argdict beats AMIConfig because dict.update() will overwrite
            # (However, we defend the real command line against updates from either source)
            extraParameters = {}
            # AMI configuration?
            if 'AMIConfig' in self._argdict:
                msg.debug('Given AMI tag configuration {0}'.format(self._argdict['AMIConfig']))
                from PyJobTransforms.trfAMI import TagInfo
                tag=TagInfo(self._argdict['AMIConfig'].value)
                updateDict = {}
                for k, v in dict(tag.trfs[0]).iteritems():
                    # Convert to correct internal key form
                    updateDict[cliToKey(k)] = v
                extraParameters.update(updateDict)
            # Pickled arguments?
            if 'argdict' in self._argdict:
                try:
                    import cPickle as pickle
                    msg.debug('Given pickled arguments in {0}'.format(self._argdict['argdict']))
                    argfile = open(self._argdict['argdict'], 'r')
                    extraParameters.update(pickle.load(argfile))
                    argfile.close()
                except Exception, e:
                    raise trfExceptions.TransformArgException(trfExit.nameToCode('TRF_ARG_ERROR'), 'Error when unpickling file {0}'.format(self._argdict['argdict']))
            # JSON arguments?
            if 'argJSON' in self._argdict:
                try:
                    import json
                    msg.debug('Given JSON encoded arguments in {0}'.format(self._argdict['argJSON']))
                    argfile = open(self._argdict['argJSON'], 'r')
                    jsonParams = json.load(argfile)
                    msg.debug('Read: {0}'.format(jsonParams))
                    extraParameters.update(convertToStr(jsonParams))
                    argfile.close()
                except Exception, e:
                    raise trfExceptions.TransformArgException(trfExit.nameToCode('TRF_ARG_ERROR'), 'Error when deserialising JSON file {0} ({1})'.format(self._argdict['argJSON'], e))
            # Process anything we found
            for k,v in extraParameters.iteritems():
                msg.debug('Found this extra argument: {0} with value: {1} ({2})'.format(k, v, type(v)))
                if k not in self.parser._argClass:
                    raise trfExceptions.TransformArgException(trfExit.nameToCode('TRF_ARG_ERROR'), 'Argument "{0}" not known (try "--help")'.format(k))
                if k in self._argdict:
                    msg.debug('Ignored {0}={1} as extra parameter because this argument was given on the command line.'.format(k, v))
                    continue
                # For callable classes we instantiate properly, otherwise we set the value for simple arguments
                if '__call__' in dir(self.parser._argClass[k]):
                    self._argdict[k] = self.parser._argClass[k](v)
                else:
                    self._argdict[k] = v
                msg.debug('Argument {0} set to {1}'.format(k, self._argdict[k]))

            # Set the key name as an argument property - useful to be able to look bask at where this
            # argument came from
            for k, v in self._argdict.iteritems():
                if isinstance(v, argument):
                    v.name = k
                    
            # Now we parsed all arguments, if a pickle/json dump is requested do it here and exit
            if 'dumpPickle' in self._argdict:
                msg.info('Now dumping pickled version of command line to {0}'.format(self._argdict['dumpPickle']))
                pickledDump(self._argdict)
                sys.exit(0)

            # Now we parsed all arguments, if a pickle/json dump is requested do it here and exit
            if 'dumpJSON' in self._argdict:
                msg.info('Now dumping JSON version of command line to {0}'.format(self._argdict['dumpJSON']))
                JSONDump(self._argdict)
                sys.exit(0)

        except trfExceptions.TransformArgException, e:
            msg.critical('Argument parsing failure: {0!s}'.format(e))
            self._exitCode = e.errCode
            self._exitMsg = e.errMsg
            self._report.fast = True
            self.generateReport()
            sys.exit(self._exitCode)

        self.setGlobalLogLevel()
        

    ## @brief Check transform argument dictionary and set the correct root logger option
    def setGlobalLogLevel(self):
        if 'verbose' in self._argdict:
            setRootLoggerLevel(stdLogLevels['DEBUG'])
        elif 'loglevel' in self._argdict:
            if self._argdict['loglevel'] in stdLogLevels:
                msg.info("Loglevel option found - setting root logger level to %s" % 
                         logging.getLevelName(stdLogLevels[self._argdict['loglevel']]))
                setRootLoggerLevel(stdLogLevels[self._argdict['loglevel']])
            else:
                msg.warning('Unrecognised loglevel ({0}) given - ignored'.format(self._argdict['loglevel']))

        
    ## @brief Execute transform
    # @detailed This function calls the actual transform execution class and
    # sets \c self.exitCode and \c self.exitMsg transform data members.
    # TODO: This method should be timed - try a decorator function for that 
    # @return None.
    def execute(self):
        msg.debug('Entering transform execution phase')
  
        try:
            # Intercept a few special options here      
            if 'dumpargs' in self._argdict:
                self.parser.dumpArgs()
                sys.exit(0)
                
            if 'showSteps' in self._argdict:
                for exe in self._executors:
                    print "Executor Step: {0} (alias {1})".format(exe.name, exe.substep)
                sys.exit(0)
                        
            # Graph stuff!
            msg.info('Starting to resolve execution graph')
            self._setupGraph()
            msg.info('Execution graph resolved')
            
            if 'showGraph' in self._argdict:
                print self._executorGraph
                sys.exit(0)
                
            # Graph stuff!
            msg.info('Starting to trace execution path')            
            self._tracePath()
            msg.info('Execution path found with {0} step(s): {1}'.format(len(self._executorPath),
                                                                         ' '.join([exe['name'] for exe in self._executorPath])))

            if 'showPath' in self._argdict:
                msg.debug('Execution path list is: {0}'.format(self._executorPath))
                # Now print it nice
                print 'Executor path is:'
                for node in self._executorPath:
                    print '  {0}: {1} -> {2}'.format(node['name'], list(node['input']), list(node['output']))
                sys.exit(0)

            msg.debug('Execution path is {0}'.format(self._executorPath))
                
            # Prepare files for execution (separate method?)
            for dataType in [ data for data in self._executorGraph.data if 'NULL' not in data ]:
                if dataType in self._dataDictionary:
                    msg.debug('Data type {0} maps to existing argument {1}'.format(dataType, self._dataDictionary[dataType]))
                else:
                    fileName = 'tmp.' + dataType
                    # How to pick the correct argFile class?
                    for (prefix, suffix) in (('tmp', ''), ('output', 'File'), ('input', 'File')):
                        stdArgName = prefix + dataType + suffix
                        if stdArgName in self.parser._argClass:
                            msg.debug('Matched data type {0} to argument {1}'.format(dataType, stdArgName))
                            self._dataDictionary[dataType] = self.parser._argClass[stdArgName](fileName)
                            self._dataDictionary[dataType].io = 'temporary'
                            break
                    if dataType not in self._dataDictionary:
                        if 'HIST' in fileName:
                            self._dataDictionary[dataType] = argHISTFile(fileName, io='temporary', type=dataType.lower())
                            
                        else:
                            self._dataDictionary[dataType] = argFile(fileName, io='temporary', type=dataType.lower())
                            msg.debug('Did not find any argument matching data type {0} - setting to plain argFile: {1}'.format(dataType, self._dataDictionary[dataType]))
                    self._dataDictionary[dataType].name = fileName

            # Now we can set the final executor configuration properly, with the final dataDictionary
            for executor in self._executors:
                executor.conf.setFromTransform(self)


            self.validateInFiles()
            
            for executionStep in self._executorPath:
                msg.debug('Now preparing to execute {0}'.format(executionStep))
                executor = self._executorDictionary[executionStep['name']]
                executor.preExecute(input = executionStep['input'], output = executionStep['output'])
                executor.execute()
                executor.postExecute()
                executor.validate()
                
            self.validateOutFiles()
            
        except trfExceptions.TransformException as e:
            msg.critical('Transform executor raised %s: %s' % (e.__class__.__name__, e.errMsg))
            self._exitCode = e.errCode
            self._exitMsg = e.errMsg
            # Try and write a job report...
            self.generateReport(fast=True)
            sys.exit(self._exitCode)
        
        # As the actual executor function is not part of this class we pass the transform as an argument
        # This means that simple executors do not require explicit subclassing
        msg.debug('Transform executor succeeded')
        self._exitCode = 0
        self._exitMsg = trfExit.codeToName(self._exitCode)
        
        # Just in case any stray processes have been left behind...
        if ('orphanKiller' in self._argdict):
            infanticide(message=True, listOrphans=True)
        else:
            infanticide(message=True)
        
    ## @brief Setup the executor graph
    #  @note This function might need to be called again when the number of 'substeps' is unknown
    #  just based on the input data types - e.g., DigiMReco jobs don't know how many RDOtoESD
    #  steps they need to run until after digitisation.
    def _setupGraph(self):        
        # Get input/output data
        self._inputData = list()
        self._outputData = list()
        
        for key, value in self._argdict.iteritems():
            # Note specifier [A-Za-z0-9_]+? makes this match non-greedy (avoid swallowing the optional 'File' suffix)
            m = re.match(r'(input|output|tmp)([A-Za-z0-9_]+?)(File)?$', key)
            # N.B. Protect against taking argunents which are not type argFile
            if m and isinstance(value, argFile):
                if m.group(1) == 'input':
                    self._inputData.append(m.group(2))
                else:
                    self._outputData.append(m.group(2))
                self._dataDictionary[m.group(2)] = value
                
        ## @note If we have no real data then add the pseudo datatype NULL, which allows us to manage
        #  transforms which can run without data
        if len(self._inputData) is 0:
            self._inputData.append('inNULL')
        if len(self._outputData) is 0:
            self._outputData.append('outNULL')            
        msg.debug('Transform has this input data: {0}; output data {1}'.format(self._inputData, self._outputData))
        
        # Now see if we have any steering - manipulate the substep inputs and outputs before we
        # setup the graph
        if 'steering' in self._argdict.keys():
            msg.debug('Now applying steering to graph: {0}'.format(self._argdict['steering'].value))
            for substep, steeringValues in self._argdict['steering'].value.iteritems():
                foundSubstep = False
                for executor in self._executors:
                    if executor.name == substep or executor.substep == substep:
                        foundSubstep = True
                        msg.debug('Updating {0} with {1}'.format(executor.name, steeringValues))
                        # Steering consists of tuples with (in/out, +/-, datatype) 
                        for steeringValue in steeringValues:
                            if steeringValue[0] == 'in':
                                startSet = executor.inData
                            else:
                                startSet = executor.outData
                            origLen = len(startSet)
                            msg.debug('Data values to be modified are: {0}'.format(startSet))
                            if steeringValue[1] is '+':
                                startSet.add(steeringValue[2])
                                if len(startSet) != origLen + 1:
                                    raise trfExceptions.TransformSetupException(trfExit.nameToCode('TRF_GRAPH_STEERING_ERROR'),
                                                                                'Attempting to add data type {0} from {1} {2} fails (original set of data: {3}). Was this datatype already there?'.format(steeringValue[2], executor.name, steeringValue[1], startSet))
                            else:
                                startSet.discard(steeringValue[2])
                                if len(startSet) != origLen - 1:
                                    raise trfExceptions.TransformSetupException(trfExit.nameToCode('TRF_GRAPH_STEERING_ERROR'),
                                                                                'Attempting to remove data type {0} from {1} {2} fails (original set of data: {3}). Was this datatype even present?'.format(steeringValue[2], executor.name, steeringValue[1], startSet))
                        msg.debug('Updated data values to: {0}'.format(startSet))
                if not foundSubstep:
                    raise trfExceptions.TransformSetupException(trfExit.nameToCode('TRF_GRAPH_STEERING_ERROR'),
                                                                'This transform has no executor/substep {0}'.format(substep))                                
        
        # Setup the graph and topo sort it
        self._executorGraph = executorGraph(self._executors, self._inputData, self._outputData)
        self._executorGraph.doToposort()
    
    
    ## @brief Trace the path through the executor graph
    #  @note This function might need to be called again when the number of 'substeps' is unknown
    #  just based on the input data types - e.g., DigiMReco jobs don't know how many RDOtoESD
    #  steps they need to run until after digitisation.
    def _tracePath(self):
        self._executorGraph.findExecutionPath()
        
        self._executorPath = self._executorGraph.execution
        if len(self._executorPath) is 0:
            raise trfExceptions.TransformSetupException(trfExit.nameToCode('TRF_SETUP'), 
                                                        'Execution path finding resulted in no substeps being executed'
                                                        '(Did you correctly specify input data for this transform?)')
        # Tell the first executor that they are the first
        self._executorDictionary[self._executorPath[0]['name']].conf.firstExecutor = True

    ## @brief Return the last executor which actually executed
    #  @return Last executor which has @c _hasExecuted == @c True, or the very first executor if we didn't even start yet
    @property
    def lastExecuted(self):
        # Just make sure we have the path traced
        if not hasattr(self, '_executorPath') or len(self._executorPath) is 0:
            return None
            
        lastExecutor = self._executorDictionary[self._executorPath[0]['name']]
        for executorStep in self._executorPath[1:]:
            if self._executorDictionary[executorStep['name']].hasExecuted:
                lastExecutor = self._executorDictionary[executorStep['name']]
        return lastExecutor


    ## @brief Transform report generator
    #  @param fast If True ensure that no external calls are made for file metadata (this is 
    #  used to generate reports in a hurry after a crash or a forced exit)
    #  @param fileReport Dictionary giving the type of report to make for each type of file.
    #  This dictionary has to have all io types as keys and valid values are:
    #  @c None - skip this io type; @c 'full' - Provide all details; @c 'name' - only dataset and
    #  filename will be reported on. 
    #  @param reportType Iterable with report types to generate, otherwise a sensible default
    #  is used (~everything, plus the Tier0 report at Tier0)
    def generateReport(self, reportType=None, fast=False, fileReport = defaultFileReport):
        msg.debug('Transform report generator')

        if 'reportType' in self._argdict:
            if reportType is not None:
                msg.info('Transform requested report types {0} overridden by command line to {1}'.format(reportType, self._argdict['reportType'].value))
            reportType = self._argdict['reportType'].value

        if reportType is None:
            reportType = ['text', 'json', 'classic', 'pilotPickle']
            # Only generate the Tier0 report at Tier0 ;-)
            # (It causes spurious warnings for some grid jobs with background files (e.g., digitisation)
            if 'TZHOME' in os.environ:
                reportType.append('gpickle')
            
        if 'reportName' in self._argdict:
            baseName = classicName = self._argdict['reportName'].value
        else:
            baseName = 'jobReport'
            classicName = 'metadata'
        
        try:
            # Text
            if reportType is None or 'text' in reportType: 
                self._report.writeTxtReport(filename='{0}.txt'.format(baseName), fast=fast, fileReport=fileReport)
            # JSON
            if reportType is None or 'json' in reportType:
                self._report.writeJSONReport(filename='{0}.json'.format(baseName), fast=fast, fileReport=fileReport)
            # Classic XML
            if reportType is None or 'classic' in reportType:
                self._report.writeClassicXMLReport(filename='{0}.xml'.format(classicName), fast=fast)
            # Classic gPickle
            if reportType is None or 'gpickle' in reportType:
                self._report.writeGPickleReport(filename='{0}.gpickle'.format(baseName), fast=fast)
            # Pickled version of the JSON report for pilot
            if reportType is None or 'pilotPickle' in reportType:
                self._report.writePilotPickleReport(filename='{0}Extract.pickle'.format(baseName), fast=fast, fileReport=fileReport)

        except trfExceptions.TransformTimeoutException, reportException:
            msg.error('Received timeout when writing report ({0})'.format(reportException))
            msg.error('Report writing is aborted - sorry. Transform will exit with TRF_METADATA_CALL_FAIL status.')
            if ('orphanKiller' in self._argdict):
                infanticide(message=True, listOrphans=True)
            else:
                infanticide(message=True)
            sys.exit(trfExit.nameToCode('TRF_METADATA_CALL_FAIL'))

        except trfExceptions.TransformException, reportException:
            # This is a bad one!
            msg.critical('Attempt to write job report failed with exception {0!s}: {1!s}'.format(reportException.__class__.__name__, reportException))
            msg.critical('Stack trace now follows:\n{0}'.format(traceback.format_exc()))
            msg.critical('Job reports are likely to be missing or incomplete - sorry')
            msg.critical('Please report this as a transforms bug!')
            msg.critical('Before calling the report generator the transform status was: {0}; exit code {1}'.format(self._exitMsg, self._exitCode))
            msg.critical('Now exiting with a transform internal error code')
            if ('orphanKiller' in self._argdict):
                infanticide(message=True, listOrphans=True)
            else:
                infanticide(message=True)
            sys.exit(trfExit.nameToCode('TRF_INTERNAL'))
    

    # Description stolen from old trfs...
    ## @brief Common signal handler.
    #  @details This function is installed in place of the default signal handler and attempts to terminate the 
    #  transform gracefully. When a signal is caught by the transform, the stdout from the running application process 
    #  (i.e. @c athena.py) is allowed to continue uninterrupted and write it's stdout to the log file (to retrieve 
    #  the traceback) before the associated job report records the fact that a signal has been caught and complete 
    #  the report accordingly. 
    #  @param signum Signal number. Not used since this is a common handle assigned to predefined signals using the 
    #  @c _installSignalHandlers(). This param is still required to satisfy the requirements of @c signal.signal().
    #  @param frame Not used. Provided here to satisfy the requirements of @c signal.signal().
    #  @return Does not return. Raises SystemExit exception.
    #  @exception SystemExit()
    def _exitWithReport(self, signum, frame):
        msg.critical('Transform received signal {0}'.format(signum))
        msg.critical('Stack trace now follows:\n{0!s}'.format(''.join(traceback.format_stack(frame))))
        self._exitCode = 128+signum
        self._exitMsg = 'Transform received signal {0}'.format(signum)
        
        # Reset signal handlers now - we don't want to recurse if the same signal arrives again (e.g. multiple ^C)
        resetTrfSignalHandlers()

        msg.critical('Attempting to write reports with known information...')
        self.generateReport(fast=True)
        if ('orphanKiller' in self._argdict):
            infanticide(message=True, listOrphans=True)
        else:
            infanticide(message=True)

        sys.exit(self._exitCode)
    
    ## @brief Setter for transform's validation dictionary
    #  @details This function updates the validation dictionary for the transform,
    #  updating values which are passed in the \c newValidationOptions argument.
    #  @param newValidationOptions Dictionary (or tuples) to update validation 
    #  dictionary with
    #  @return None
    def updateValidationDict(self, newValidationOptions):
        self.validation.update(newValidationOptions)

    ## @brief Getter function for transform validation dictionary
    #  @return Validiation dictionary
    def getValidationDict(self):
        return self.validation
    
    ## @brief Getter for a specific validation option
    #  @param key Validation dictionary key
    #  @return Valdiation key value or @c None if this key is absent
    def getValidationOption(self, key):
        if key in self.validation:
            return self.validation[key]
        else:
            return None

    ## @brief Do transform validation
    def doTrfValidation(self):
        self._validation.runValidation()

    ## @brief Return a list of fileArgs used by the transform
    #  @param \c io Filter files by io attribute
    #  @return List of argFile instances
    def getFiles(self, io = None):
        res = []
        msg.debug('Looking for file arguments matching: io={0}'.format(io))
        for argName, arg in self._argdict.iteritems():
            if isinstance(arg, argFile):
                msg.debug('Argument {0} is argFile type ({1!s})'.format(argName, arg))
                if io != None and arg.io != io:
                    continue
                msg.debug('Argument {0} matches criteria'.format(argName))
                res.append(arg)
        return res


    def validateInFiles(self):
        if (('skipFileValidation' in self._argdict and self._argdict['skipFileValidation'] is True) or
            ('skipInputFileValidation' in self._argdict and self._argdict['skipInputFileValidation'] is True)):
            msg.info('Standard input file validation turned off for transform %s.' % self.name)
        else:
            msg.info('Validating input files')
            if 'parallelFileValidation' in self._argdict:
                trfValidation.performStandardFileValidation(dict=self._dataDictionary, io='input', parallelMode=self._argdict['parallelFileValidation'].value )
            else:
                trfValidation.performStandardFileValidation(dict=self._dataDictionary, io='input')

    def validateOutFiles(self):
        if (('skipFileValidation' in self._argdict and self._argdict['skipFileValidation'] is True) or
            ('skipOutputFileValidation' in self._argdict and self._argdict['skipOutputFileValidation'] is True)):
            msg.info('Standard output file validation turned off for transform %s.' % self.name)
        else:
            msg.info('Validating output files')
            if 'parallelFileValidation' in self._argdict:
                trfValidation.performStandardFileValidation(dict=self._dataDictionary, io='output', parallelMode=self._argdict['parallelFileValidation'].value )
            else:
                trfValidation.performStandardFileValidation(dict=self._dataDictionary, io='output')