Source

mana-core-testtools / python / iobench.py

Full commit
  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
# @file : iobench.py
# @author: Sebastien Binet <binet@cern.ch>
# @purpose: Measure the I/O performances of an application
#
# @date: July 2006
#

"""
A set of python objects to measure the I/O performances of an application.
"""

__author__  = "$Author: binet $"
__version__ = "$Revision: 1.4 $"

import sys
import resource
import time
import os

###-----------------------------------------------------
def getResources( usageMode = resource.RUSAGE_CHILDREN ):
    """
    A factory method to fetch the used resources at a given 't' time.
    Default mode is 'resource.RUSAGE_CHILDREN'
    """
    return Resource( utime = resource.getrusage( usageMode ).ru_utime,
                     stime = resource.getrusage( usageMode ).ru_stime,
                     rtime = time.time() )

class Resource(object):
    """
    A simple class to hold the resources used by a program:
     - user   time
     - system time
     - real   time
    """
    
    def __init__( self,
                  utime, stime, rtime ):
        object.__init__(self)

        self.utime = utime
        self.stime = stime
        self.rtime = rtime

        return

    def __repr__(self):
        s = os.linesep.join( [ "user : %s" % str( self.user() ),
                               "sys  : %s" % str( self.sys()  ),
                               "real : %s" % str( self.real() ) ] )
        return s

    def __add__(self, rhs):
        return Resource( self.utime + rhs.utime,
                         self.stime + rhs.stime,
                         self.rtime + rhs.rtime )

    def __iadd__(self, rhs):
        self.utime += rhs.utime
        self.stime += rhs.stime
        self.rtime += rhs.rtime
        return self

    def __sub__(self, rhs):
        return Resource( self.utime - rhs.utime,
                         self.stime - rhs.stime,
                         self.rtime - rhs.rtime )

    def __isub__(self, rhs):
        self.utime -= rhs.utime
        self.stime -= rhs.stime
        self.rtime -= rhs.rtime
        return self
    
    def user( self ):
        return self.utime

    def sys( self ):
        return self.stime

    def real( self ):
        return self.rtime

    pass # Resource

class Bench(object):

    def __init__( self,
                  nTimes = 1,
                  stdout = sys.stdout,
                  stderr = sys.stderr ):
        object.__init__(self)

        self.nTimes = nTimes
        self.data = []

    def run( self, fct, *args, **kwargs ):

        self.data = []

        for i in range(self.nTimes):
            iStart = getResources()
            out = fct( *args, **kwargs )
            self.data.append( getResources() - iStart )
            pass

        return

    def stats( self ):
        
        mean = Resource( 0., 0., 0. )
        for d in self.data:
            mean += d
            pass

        print ""
        print "## stats : (nbenchs = %i)" % self.nTimes
        print " time<User> = %8.3f s" % ( mean.user() /  float( self.nTimes ) )
        print " time<Sys > = %8.3f s" % ( mean.sys()  /  float( self.nTimes ) )
        print " time<Real> = %8.3f s" % ( mean.real() /  float( self.nTimes ) )
        
        return

    def save( self, fileName = "iobench.log" ):
        f = open( fileName, "w" )
        for data in self.data:
            f.writelines( "%s %s %s %s" % ( data.user(),
                                            data.sys(),
                                            data.real(),
                                            os.linesep ) )
            pass
        f.close()
        return
    
    pass # Bench

##
## ---- Athena specific part ----
##

import os
import ConfigParser
class ChronoStatsOutputParser( ConfigParser.ConfigParser ):
    """Subclass and specialize ConfigParser to make it case-sensitive
    """
    def optionxform( self, optionStr ):
        return optionStr

class ChronoStat(object):
    """
    A class mirroring the one from the (Gaudi) ChronoStatSvc which models a
    chrono measurement.
    It holds the following informations:
      - total time
      - min
      - mean
      - RMS
      - max
      - number of 'events'
    """
    def __init__( self, nbr, min, max, mean, rms, total ):
        object.__init__(self)
        self.total = total
        self.min   = min
        self.mean  = mean
        self.rms   = rms
        self.max   = max
        self.nbr   = nbr
        pass

    def __repr__(self):
        return os.linesep.join( [
            "min   = %s" % str( self.min   ),
            "max   = %s" % str( self.max   ),
            "mean  = %s" % str( self.mean  ),
            "RMS   = %s" % str( self.RMS   ),
            "total = %s" % str( self.total ),
            "#evts = %s" % str( self.nbr   ),
            ] )
    
class ChronoStatReport(object):

    ReadKeyHdr  = "cObj_"
    WriteKeyHdr = "cRep_"
    KeySep      = "#"
    
    """
    This class stores the report of the ChronoStatSvc dump from Athena/Gaudi.
    """
    def __init__( self, fileName ):
        """
        fileName is supposed to contain the output of the ChronoStatSvc which
        has been configured with 'ChronoStatSvc.ChronoDestinationCout = True'
        """
        object.__init__( self )

        self.logFile = ChronoStatsOutputParser()
        self.logFile.read( fileName )

        self.stats = { }
        self.chronoStats = { }
        self.buildStats()
        pass

    def buildStats( self ):

        for hdr in self.logFile.sections():
            stat = [
                ChronoStat(
                    nbr  = int  (self.logFile.get(hdr, "cpu_%s_nbr"   % item)),
                    min  = float(self.logFile.get(hdr, "cpu_%s_min"   % item)),
                    max  = float(self.logFile.get(hdr, "cpu_%s_max"   % item)),
                    mean = float(self.logFile.get(hdr, "cpu_%s_mean"  % item)),
                    rms  = float(self.logFile.get(hdr, "cpu_%s_RMS"   % item)),
                    total= float(self.logFile.get(hdr, "cpu_%s_total" % item))
                    ) \
                for item in ['user', 'system', 'real']
                ]
                     
            self.chronoStats[hdr] = {
                'user'   : stat[0],
                'system' : stat[1],
                'real'   : stat[2],
                }
            del stat
            self.stats[hdr] = Resource(
                float(self.logFile.get(hdr, "cpu_user_mean")),
                float(self.logFile.get(hdr, "cpu_system_mean")),
                float(self.logFile.get(hdr, "cpu_real_mean"))
                )
        pass

    def getStats(self, key):
        return self.stats[key]

    def getPoolStats(self, storeGateKey, ioMode = "r" ):
        ioKey = storeGateKey
        # 'normalize' key
        if ioMode.lower() == "r":
            ioKey = storeGateKey.replace(ChronoStatReport.ReadKeyHdr,"")
            ioKey = ChronoStatReport.ReadKeyHdr + ioKey
        elif ioMode.lower() == "w":
            ioKey = storeGateKey.replace(ChronoStatReport.WriteKeyHdr,"")
            ioKey = ChronoStatReport.WriteKeyHdr + ioKey
        else:
            pass

        if not self.stats.has_key( ioKey ):
            print "Warning: no such key [%s] in stats !" % ioKey
            print "Available keys:",self.stats.keys()
            pass
        return self.stats[ ioKey ]

    def getPoolKeys(self):
        return [ k for k in self.stats.keys() \
                 if k.count(ChronoStatReport.WriteKeyHdr) > 0 ]
    
    pass # ChronoStatReport

            
###-----------------------------------------------------
## For compatibility with ATN tests
def workDir( fileName ):
    """Function to provide an automatic work dir, compatible with ATN tests
    """
    if os.environ.has_key('ATN_WORK_AREA'):
        workArea = os.environ['ATN_WORK_AREA']
    else:
        workArea = "/tmp"
        pass
    if not os.path.exists(workArea):
        os.makedirs(workArea)
    return os.path.join( workArea, fileName )

class ScOutput(object):

    def __init__(self, statusCode = 0, outputLog = ""):
        object.__init__(self)
        self.sc  = statusCode
        self.out = outputLog
        return

    pass # ScOutput

###-----------------------------------------------------
## Little helper to validate output of jobs
def doValidation( dbFiles, key ):
    """Helper function to validate output of jobs against 'registered' ASCII
    files.
    """
    import commands
    from TestTools.iobench import ScOutput
    print "## Validation of ASCII files [%s]:" % key
    print "## %15s : %s" % ( 'ref', dbFiles[key]['ref'] )
    print "## %15s : %s" % ( 'chk', dbFiles[key]['chk'] )
    sc,out = commands.getstatusoutput( "diff %s %s" %
                                       ( dbFiles[key]['ref'],
                                         dbFiles[key]['chk'] ) )
    if sc == 0 and len(out) == 0:
        print "==> Validation [OK]"
    else:
        print "==> Validation [ERROR]"
        pass
    return ScOutput(sc,out)

###-----------------------------------------------------
## Little helper to validate output of jobs
def doPostCheck( validationName, refFileName, chkFileName, chkFilter ):
    import commands
    print "## Validation of [%s]" % validationName
    print "## ref:    %s"   % refFileName
    print "## chk:    %s"   % chkFileName
    print "## filter: [%s]" % chkFilter
    sc, out = commands.getstatusoutput( "cat %s | %s | diff -u %s -" % \
                                        ( chkFileName, chkFilter,
                                          refFileName ) )
    if sc == 0 and len(out) == 0: print "==> Validation [OK]"
    else:                         print "==> Validation [ERROR]\n",\
                                        "*"*80,out,"*"*80
    return ScOutput(sc, out)

###-----------------------------------------------------
from AthenaCommon import ChapPy
from tempfile import NamedTemporaryFile
class AthBench(object):

    def __init__( self,
                  athenaJob,
                  logFile,
                  nTimes = 1,
                  stdout = sys.stdout,
                  stderr = sys.stderr,
                  ioStatsLogFile = workDir("ioStats.out") ):
        object.__init__(self)

        self.athena = athenaJob
        self.logFileName = logFile
        self.nTimes = nTimes
        self.data = []
        self.chronoStats= []
        self.ioStatsFileName = ioStatsLogFile
        
    def run( self ):

        self.data = []
        self.chronoStats= []
        self.athena.jobOptions += [
            ChapPy.JobOptions( "TestTools/IoAuditor_fragment.py" ),
            ChapPy.JobOptionsCmd( "svcMgr.ChronoStatSvc.AsciiStatsOutputFile = \"%s\"" % self.ioStatsFileName )
            ]
        for i in range(self.nTimes):
            self.athena.logFile = open( "%s.%s" % (self.logFileName,i), "w" )
            iStart = getResources()
            out = self.athena.run()
            self.data.append( getResources() - iStart )
            self.chronoStats.append( ChronoStatReport(self.ioStatsFileName) )
            pass

        return

    def __printStat(self, res, title="Overall", isIO = False, keyType = ""):
        if isIO:
            u = "us/evt"
        else:
            u = "s"
            pass
        if   keyType == ChronoStatReport.WriteKeyHdr: keyType = "[WRITE]"
        elif keyType == ChronoStatReport.ReadKeyHdr:  keyType = "[READ]"
        else:
            pass
        print ""
        print "## stats : [%s] (nbenchs = %i) %s" % (title,
                                                     self.nTimes,
                                                     keyType)
        print " time<User> = %12.3f %s" % (res.user() / float(self.nTimes), u)
        print " time<Sys > = %12.3f %s" % (res.sys()  / float(self.nTimes), u)
        print " time<Real> = %12.3f %s" % (res.real() / float(self.nTimes), u)
        
    def ioStats(self, ioKeys = [], ioMode = "r"):

        if len(ioKeys) == 0:
            ioKeys = self.chronoStats[0].getPoolKeys()
            pass
        keyHdr = ""
        if ioMode.lower() == "r":
            keyHdr = ChronoStatReport.ReadKeyHdr
        elif ioMode.lower() == "w":
            keyHdr = ChronoStatReport.WriteKeyHdr
        for ioKey in ioKeys:
            mean = Resource( 0., 0., 0. )
            for d in self.chronoStats:
                mean += d.getPoolStats(ioKey, ioMode)
                pass
            self.__printStat(mean,
                             ioKey.replace(keyHdr,""),
                             isIO = True,
                             keyType = keyHdr)
            pass
        
        return
    
    def stats( self, doIoStats = False ):

        ## IO stats
        if doIoStats:
            self.ioStats()
        
        ## Overall stats
        mean = Resource( 0., 0., 0. )
        for d in self.data:
            mean += d
            pass
        self.__printStat(mean)
        return

    def save( self, fileName = "iobench.log" ):
        f = open( fileName, "w" )
        for data in self.data:
            f.writelines( "%s %s %s %s" % ( data.user(),
                                            data.sys(),
                                            data.real(),
                                            os.linesep ) )
            pass
        f.close()
        return
    
    pass # AthBench

class BenchSequence(object):
    """
    Class which holds results of benchs (exit codes) and declares victory
    when all the benchs returned successfully.
    """

    def __init__(self, name = "My Bench suite"):
        object.__init__(self)
        self.name   = name
        self.benchs = []

        return

    def __iadd__(self, rhs):
        if not isinstance( rhs, ScOutput ) and \
           not isinstance( rhs, list ):
            raise Exception, \
                  "attempt to add a '%s' to the BenchSuite !" % \
                  type(rhs).__name__
        
        if isinstance( rhs, ScOutput ):
            self.benchs.append( rhs )
            return self
        
        if isinstance( rhs, list ):
            for i in rhs:
                self += i
                pass
            return self

        return self

    def status(self):
        import math
        sc = 0
        for i in self.benchs:
            sc += math.fabs(i.sc)
            pass
        return sc == 0

    def printStatus(self):
        if self.status(): print "## [All tests SUCCESSFULLY completed]"
        else:             print "## [ERROR in at least one test !!]"
        return
    
    pass # BenchSequence