-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic_cycle_analyze.py
More file actions
1265 lines (1208 loc) · 51.7 KB
/
Copy pathbasic_cycle_analyze.py
File metadata and controls
1265 lines (1208 loc) · 51.7 KB
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
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# basic_cycle_analyze.py
#
import argparse
import os
import sys
import time
import logging
import sqorm
import cPickle
import pprint
import re
import ConfigParser
from operator import itemgetter
from collections import Counter
import networkx as nx
import StringIO
import csv
import subprocess
import datetime
import heapq
from itertools import combinations
from mypytools import mean, stdev, variance
pp = pprint.PrettyPrinter( indent = 4 )
__MY_VERSION__ = 5
ATIME = 0
DTIME = 1
SIZE = 2
TYPE = 3
REASON = 4
def setup_logger( targetdir = ".",
filename = "basic_cycle_analyze.log",
logger_name = 'basic_cycle_analyze',
debugflag = 0 ):
# Set up main logger
logger = logging.getLogger( logger_name )
formatter = logging.Formatter( '[%(funcName)s] : %(message)s' )
filehandler = logging.FileHandler( os.path.join( targetdir, filename ) , 'w' )
if debugflag:
logger.setLevel( logging.DEBUG )
filehandler.setLevel( logging.DEBUG )
else:
filehandler.setLevel( logging.ERROR )
logger.setLevel( logging.ERROR )
filehandler.setFormatter( formatter )
logger.addHandler( filehandler )
return logger
def debug_lifetimes( G, cycle, bmark, logger ):
global pp
for x in cycle:
if G.node[x]["lifetime"] <= 0:
n = G.node[x]
# print "XXX %s: [ %d - %s ] lifetime: %d" % \
# (bmark, x, n["type"], n["lifetime"])
logger.critical( "XXX: [ %d - %s ] lifetime: %d" %
(x, n["type"], n["lifetime"]) )
def get_trace_fp( tracefile = None,
logger = None ):
if not os.path.isfile( tracefile ) and not os.path.islink( tracefile ):
# File does not exist
logger.error( "Unable to open %s" % str(tracefile) )
print "Unable to open %s" % str(tracefile)
exit(21)
bz2re = re.compile( "(.*)\.bz2$", re.IGNORECASE )
gzre = re.compile( "(.*)\.gz$", re.IGNORECASE )
bz2match = bz2re.search( tracefile )
gzmatch = gzre.search( tracefile )
if bz2match:
# bzip2 file
fp = subprocess.Popen( [ "bzcat", tracefile ],
stdout = subprocess.PIPE,
stderr = subprocess.PIPE ).stdout
elif gzmatch:
# gz file
fp = subprocess.Popen( [ "zcat", tracefile ],
stdout = subprocess.PIPE,
stderr = subprocess.PIPE ).stdout
else:
fp = open( tracefile, "r")
return fp
#
# Main processing
#
def create_edge_dictionary( edges = None,
selfloops = None ):
edgedict = {}
for edge in edges:
src = edge[0]
tgt = edge[1]
if src == tgt:
selfloops.add( src )
if src not in edgedict:
edgedict[src] = [ tgt ]
else:
edgedict[src].append(tgt)
for src, tgtlist in edgedict.iteritems():
edgedict[src] = set(tgtlist)
return edgedict
def create_graph( cycle_info_list = None,
edgedict = None,
logger = None ):
global pp
g = nx.DiGraph()
nodeset = set([])
for mytuple in cycle_info_list:
node, mytype, mysize, lifetime = mytuple
nodeset.add(node)
g.add_node( n = node,
type = mytype,
lifetime = lifetime,
size = mysize )
if node in edgedict:
for tgt in edgedict[node]:
g.add_edge( node, tgt )
return g
class ObjDB:
def __init__( self,
objdb1 = None,
objdb2 = None,
objdb_all = None,
debugflag = False,
logger = None ):
self.objdb1 = objdb1
self.objdb2 = objdb2
self.objdb_all = objdb_all
self.sqodb_all = None
self.alldb = False
self.sqObj1 = None
self.sqObj2 = None
self.logger = logger
assert( os.path.isfile( objdb_all ) or
(os.path.isfile( objdb1 ) and os.path.isfile( objdb2 )) )
if os.path.isfile( objdb_all ):
try:
self.sqodb_all = sqorm.Sqorm( tgtpath = objdb_all,
table = "objects",
keyfield = "objId" )
print "ALL:", objdb_all
self.alldb = True
return
except:
logger.error( "Unable to load DB ALL file %s" % str(objdb) )
print "Unable to load DB ALL file %s" % str(objdb)
if os.path.isfile( objdb1 ):
try:
self.sqObj1 = sqorm.Sqorm( tgtpath = objdb1,
table = "objects",
keyfield = "objId" )
except:
logger.error( "Unable to load DB 1 file %s" % str(objdb) )
print "Unable to load DB 1 file %s" % str(objdb)
assert( False )
assert(self.sqObj1 != None)
if os.path.isfile( objdb2 ):
try:
self.sqObj2 = sqorm.Sqorm( tgtpath = objdb2,
table = "objects",
keyfield = "objId" )
except:
logger.error( "Unable to load DB 2 file %s" % str(objdb) )
print "Unable to load DB 2 file %s" % str(objdb)
assert( False )
def get_record( self, objId ):
if self.alldb:
try:
obj = self.sqodb_all[objId]
db_objId, db_oType, db_oSize, db_oLen, db_oAtime, db_oDtime, db_oSite = obj
except:
# self.logger.error( "Objid [ %s ] not found." % str(objId) )
return None
else:
if objId in self.sqObj1:
try:
obj = self.sqObj1[objId]
db_objId, db_oType, db_oSize, db_oLen, db_oAtime, db_oDtime, db_oSite = obj
except:
self.logger.error( "Objid [ %s ] not found in DB1." % str(objId) )
if objId in self.sqObj2:
try:
obj = self.sqObj1[objId]
db_objId, db_oType, db_oSize, db_oLen, db_oAtime, db_oDtime, db_oSite = obj
except:
self.logger.error( "Objid [ %s ] not found in DB2." % str(objId) )
# print "Objid [ %s ] not found in DB2." % str(objId)
return None
rec = { "objId" : db_objId,
"type" : db_oType,
"size" : db_oSize,
"len" : db_oLen,
"atime" : db_oAtime,
"dtime" : db_oDtime,
"site" : db_oSite }
return rec
def get_type( self, objId ):
db_oType = None
if self.alldb:
try:
obj = self.sqodb_all[objId]
db_objId, db_oType, db_oSize, db_oLen, db_oAtime, db_oDtime, db_oSite = obj
except:
# self.logger.error( "Objid [ %s ] not found." % str(objId) )
return None
else:
if objId in self.sqObj1:
try:
obj = self.sqObj1[objId]
db_objId, db_oType, db_oSize, db_oLen, db_oAtime, db_oDtime, db_oSite = obj
except:
self.logger.error( "Objid [ %s ] not found in DB1." % str(objId) )
if objId in self.sqObj2:
try:
obj = self.sqObj1[objId]
db_objId, db_oType, db_oSize, db_oLen, db_oAtime, db_oDtime, db_oSite = obj
except:
self.logger.error( "Objid [ %s ] not found in DB2." % str(objId) )
print "Objid [ %s ] not found in DB2." % str(objId)
return None
return db_oType
def get_types( G, cycle ):
return [ G.node[x]["type"] for x in cycle ]
def get_types_and_save_index( G, cycle ):
return [ (x, G.node[x]["type"]) for x in cycle ]
def DEBUG_types( largest_by_types_with_index, largest_scc ):
l = largest_by_types_with_index
if len(largest_scc) == 1:
print "LEN1: %s <-> %s" % (str(largest_scc), l)
if l[0][1] == '[B':
print "DEBUG id: %d" % l[0][0]
# elif len(largest_scc) == 2:
def debug_cycle_algorithms( largest_scc, cyclelist, G ):
global pp
print "=================================================="
other = max( cyclelist, key = len )
print "SC[ %d ] SIMP[ %d ]" % (len(largest_scc), len(other))
if len(largest_scc) == 1:
node = list(largest_scc)[0]
if node == 166451:
print "Found 166451. Writing out graphs in %s" % str(os.getcwd())
nx.write_gexf( G, "DEBUG-ALL-166451.gexf" )
nx.write_gexf( G.subgraph( list(largest_scc) ),"DEBUG-SC-166451.gexf" )
print "DONE DEBUG."
exit(222)
print "=================================================="
def get_types_debug( G, cycle ):
result = []
for x in cycle:
try:
mynode = G.node[x]
except:
print "Unable to get node[ %d ]" % x
continue
try:
mytype = mynode["type"]
except:
print "Unable to get type for node[ %d ] -> %s" % (x, str(mynode))
continue
result.append(mytype)
return result
def get_lifetimes( G, cycle ):
return [ G.node[x]["lifetime"] for x in cycle ]
def get_lifetimes_debug( G, cycle ):
result = []
for x in cycle:
try:
mynode = G.node[x]
except:
print "Unable to get node[ %d ]" % x
continue
try:
mylifetime = mynode["lifetime"]
except:
print "Unable to get lifetime for node[ %d ] -> %s" % (x, str(mynode))
continue
result.append(mylifetime)
return result
def get_sizes( G, cycle ):
return [ G.node[x]["size"] for x in cycle ]
def get_summary( summary_path ):
start = False
done = False
summary = []
with open(summary_path) as fp:
for line in fp:
line = line.rstrip()
line = line.rstrip(",")
if line.find("---------------[ SUMMARY INFO") == 0:
start = True if not start else False
if start:
continue
else:
done = True
break
if start:
row = line.split(",")
row[1] = int(row[1])
summary.append(row)
assert(done)
return dict(summary)
def get_edges( edgepath ):
start = False
done = False
edges = set([])
with get_trace_fp(edgepath) as fp:
for line in fp:
line = line.rstrip()
if line.find("---------------[ EDGE INFO") == 0:
start = True if not start else False
if start:
print "START--"
continue
else:
print "--DONE"
done = True
break
if start:
row = [ int(x) for x in line.split(",") ]
edges.add(tuple(row))
assert(done)
edges = set( sorted( list(edges), key = itemgetter(0, 1) ) )
return edges
def get_edge_info( edgeinfo_path ):
start = False
done = False
edge_info = {}
with open(edgeinfo_path) as fp:
# Map edge (src,tgt) -> (alloctime, deathtime)
for line in fp:
line = line.rstrip()
if line.find("---------------[ EDGE INFO") == 0:
start = True if not start else False
if start:
continue
else:
done = True
break
if start:
rowtmp = line.split(",")
row = tuple([ int(x) for x in rowtmp[2:] ])
edge_info[ (int(rowtmp[0]), int(rowtmp[1])) ] = row
assert(done)
return edge_info
def get_typeId( mytype, typedict, rev_typedict ):
if mytype in typedict:
return typedict[mytype]
else:
lastkey = len(typedict.keys())
typedict[mytype] = lastkey + 1
rev_typedict[lastkey + 1] = mytype
return lastkey + 1
# Input: objectinfo_path that points to the object information
# Output:
# typedict: typeId -> actual type
# rev_typedict: actual type -> typeId
def get_object_info( objectinfo_path, typedict, rev_typedict ):
start = False
done = False
object_info = {}
with open(objectinfo_path) as fp:
for line in fp:
line = line.rstrip()
if line.find("---------------[ OBJECT INFO") == 0:
start = True if not start else False
if start:
continue
else:
done = True
break
if start:
rowtmp = line.split(",")
row = [ int(x) for x in rowtmp[1:4] ]
mytype = rowtmp[-2]
row.append( get_typeId( mytype, typedict, rev_typedict ) )
row.append( rowtmp[-1] )
object_info[int(rowtmp[0])] = tuple(row)
assert(done)
return object_info
def get_cycles( tgtpath ):
global pp
with open(tgtpath) as fp:
start = False
done = False
cycles = []
for line in fp:
line = line.rstrip()
if line.find("---------------[ CYCLES") == 0:
start = not start
if start:
continue
else:
done = True
break
if start:
line = line.rstrip(",")
row = line.split(",")
row = [ int(x) for x in row ]
cycles.append(row)
assert(done)
return cycles
def get_cycle_info_list( cycle = None,
objinfo_dict = None,
# objdb = None,
logger = None ):
cycle_info_list = []
odict = objinfo_dict
for node in cycle:
try:
# rec = objdb.get_record(node)
rec = odict[node]
mytype = rec[TYPE]
mysize = rec[SIZE]
atime = rec[ATIME]
dtime = rec[DTIME]
lifetime = (dtime - atime) if ((dtime > atime) and (dtime != 0)) \
else 0
cycle_info_list.append( (node, mytype, mysize, lifetime) )
except:
logger.critical("Missing node[ %s ]" % str(node))
mytype = "<NONE>"
mysize = 0
lifetime = 0
cycle_info_list.append( (node, mytype, mysize, lifetime) )
return cycle_info_list
g_regex = re.compile( "([^\$]+)\$(.*)" )
def is_inner_class( mytype ):
global g_regex
m = g_regex.match(mytype)
return True if m else False
def extract_small_cycles( small_summary = None,
bmark = None,
objinfo_dict = None,
rev_typedict = None,
logger = None ):
global pp
with open(bmark + "-size1.csv", "wb") as fp1, \
open(bmark + "-size2.csv", "wb") as fp2, \
open(bmark + "-size3.csv", "wb") as fp3, \
open(bmark + "-size4.csv", "wb") as fp4:
writer = [ None,
csv.writer(fp1),
csv.writer(fp2),
csv.writer(fp3),
csv.writer(fp4) ]
result = [ None, [], [], [], [] ]
counterlist = {}
regex = re.compile( "([^\$]+)\$(.*)" )
total_cycles = 0
inner_classes_count = Counter()
# TODO DELETE
# for feature, fdict in summary.iteritems():
for size, mylist in small_summary.iteritems():
for cycle in mylist:
assert( len(cycle) > 0 )
assert( len(cycle) <= 4 )
cycle_info_list = []
for record in cycle:
node, saved_type = record
try:
rec = objinfo_dict[node]
mytype = rec[TYPE]
mysize = rec[SIZE]
atime = rec[ATIME]
dtime = rec[DTIME]
lifetime = (dtime - atime) if ((dtime > atime) and (dtime != 0)) \
else 0
cycle_info_list.append( (node, mytype, mysize, lifetime) )
except:
logger.critical("Missing node[ %s ]" % str(node))
mytype = "<NONE>"
mysize = 0
lifetime = 0
cycle_info_list.append( (node, mytype, mysize, lifetime) )
type_tuple = tuple( sorted( [ rev_typedict[x[1]] for x in cycle_info_list ] ) )
# type_tuple contains all the types in the strongly connected component.
# This is sorted so that there's a canonical labeling of the type group/tuple.
assert( len(cycle) == size )
result[size].append( type_tuple )
total_cycles += 1
flag = False
for tmp in list(type_tuple):
if is_inner_class(tmp):
inner_classes_count.update( [ tmp ] )
counterlist[size] = Counter(result[size])
for row in ( list(key) + [ val ] for key, val
in counterlist[size].iteritems() ):
writer[size].writerow( row )
pp.pprint( counterlist )
return { "total_cycles" : total_cycles,
"inner_classes_count" : inner_classes_count }
def row_to_string( row ):
result = None
strout = StringIO.StringIO()
csvwriter = csv.writer(strout)
# Is the list comprehension necessary? Doesn't seem like it.
csvwriter.writerow( [ x for x in row ] )
result = strout.getvalue()
strout.close()
return result.replace("\r", "")
def render_histogram( histfile = None,
title = None ):
outpng = histfile + ".png"
cmd = [ "/data/rveroy/bin/Rscript",
"/data/rveroy/pulsrc/etanalyzer/Rgraph/histogram.R", # TODO Hard coded for now.
# Put into config. TODO TODO TODO
histfile, outpng,
"800", "800",
title, ]
print "Running histogram.R on %s -> %s" % (histfile, outpng)
print "[ %s ]" % cmd
renderproc = subprocess.Popen( cmd,
stdout = subprocess.PIPE,
stdin = subprocess.PIPE,
stderr = subprocess.PIPE )
result = renderproc.communicate()
print "--------------------------------------------------------------------------------"
for x in result:
print x
print "--------------------------------------------------------------------------------"
def write_histogram( results = None,
tgtbase = None,
title = None ):
# TODO Use a list and a for loop to refactor.
tgtpath_totals = tgtbase + "-totals.csv"
tgtpath_cycles = tgtbase + "-cycles.csv"
tgtpath_types = tgtbase + "-types.csv"
with open(tgtpath_totals, 'wb') as fp_totals, \
open(tgtpath_cycles, 'wb') as fp_cycles, \
open(tgtpath_types, 'wb') as fp_types:
# TODO REFACTOR into a loop
# TODO 2015-1103 - RLV TODO
header = [ "benchmark", "total" ]
csvw = {}
csvw["totals"] = csv.writer( fp_totals,
quotechar = '"',
quoting = csv.QUOTE_NONNUMERIC )
csvw["largest_cycle"] = csv.writer( fp_cycles,
quotechar = '"',
quoting = csv.QUOTE_NONNUMERIC )
csvw["largest_cycle_types_set"] = csv.writer( fp_types,
quotechar = '"',
quoting = csv.QUOTE_NONNUMERIC )
keys = csvw.keys()
dframe = {}
for key in keys:
csvw[key].writerow( header )
dframe[key] = []
for benchmark, infodict in results.iteritems():
for key in keys:
assert( key in infodict )
for item in infodict[key]:
row = [ benchmark, item ] if key == "totals" \
else [ benchmark, len(item) ]
dframe[key].append(row)
sorted_result = [ (key, sorted( dframe[key], key = itemgetter(0) )) for key in keys ]
for key, result in sorted_result:
for csvrow in result:
csvw[key].writerow( csvrow )
# TODO TODO TODO TODO
# TODO TODO TODO: SPAWN OFF THREAD
# TODO TODO TODO TODO
render_histogram( histfile = tgtpath_totals,
title = title )
render_histogram( histfile = tgtpath_cycles,
title = title )
render_histogram( histfile = tgtpath_types,
title = title )
def output_R( benchmark = None ):
pass
# Need benchmark.
# TODO: Do we need this?
def output_results( output_path = None,
results = None ):
# Print out results in this format:
# ========= <- divider
# benchmark:
# size, 1, 4, 5, 2, etc
# largest_cycle, 1, 2, 5, 1, etc
# number_types, 1, 1, 2, 1, etc
with open(output_path, "wb") as fp:
for bmark, infodict in results.iteritems():
fp.write("================================================================================\n")
fp.write("%s:\n" % bmark)
# Totals
contents = row_to_string( infodict["totals"] )
fp.write("totals,%s" % contents)
# Actual largest cycle
contents = row_to_string( [ len(x) for x in infodict["largest_cycle"] ] )
fp.write("largest_cycle,%s" % contents)
# Types
contents = row_to_string( [ len(x) for x in infodict["largest_cycle_types_set"] ] )
fp.write("types,%s" % contents)
hist_output_base = output_path + "-histogram"
write_histogram( results = results,
tgtbase = hist_output_base,
title = "Historgram TODO" )
def output_results_transpose( output_path = None,
results = None ):
# Print out results in this format:
# ========= <- divider
# benchmark:
# size,largest_cycle, number_types, lifetime_ave, lifetime_sd, min, max
# 10, 5, 2, 22, 5, 2, 50
for bmark, infodict in results.iteritems():
bmark_path = bmark + "-" + output_path
with open(bmark_path, "wb") as fp:
csvwriter = csv.writer(fp)
header = [ "totals", "largest_cycle", "num_types",
"lifetime_mean", "lifetime_stdev", "liftime_min",
"lifetime_max",
"size_largest_cycle", "size_all", ]
csvwriter.writerow( header )
totals = infodict["totals"]
largest_cycle = infodict["largest_cycle"]
types_set = infodict["largest_cycle_types_set"]
lifetimes = infodict["lifetimes"]
ltime_mean = infodict["lifetime_mean"]
ltime_sd = infodict["lifetime_sd"]
ltime_min = infodict["lifetime_min"]
ltime_max = infodict["lifetime_max"]
for i in xrange(len(infodict["totals"])):
row = [ totals[i], len(largest_cycle[i]),
len(types_set[i]), ltime_mean[i],
ltime_sd[i], ltime_min[i], ltime_max[i],
sum(infodict["sizes_largest_scc"][i]),
sum(infodict["sizes_all"][i]), ]
csvwriter.writerow( row )
def output_summary( output_path = None,
summary = None ):
# Print out results in this format:
# ========= <- divider
# benchmark:
# size,largest_cycle, number_types, lifetime_ave, lifetime_sd, min, max
# 10, 5, 2, 22, 5, 2, 50
with open(output_path, "wb") as fp:
csvwriter = csv.writer(fp)
header = [ "benchmark", "total_objects", "total_edges", "died_by_heap",
"died_by_stack", "died_by_stack_after_heap", "died_by_stack_only",
"last_update_null", "number_of_selfloops",
"died_by_stack_size", "died_by_heap_size",
"last_update_null_heap", "last_update_null_stack", "max_live_size",
"last_update_null_size", "last_update_null_heap_size", "last_update_null_stack_size",
"died_by_stack_after_heap_size", "died_by_stack_only_size", ]
csvwriter.writerow( header )
for bmark, d in summary.iteritems():
row = [ bmark, d["number_of_objects"], d["number_of_edges"], d["died_by_heap"],
d["died_by_stack"], d["died_by_stack_after_heap"], d["died_by_stack_only"],
d["last_update_null"], d["number_of_selfloops"],
d["size_died_by_stack"], d["size_died_by_heap"],
d["last_update_null_heap"], d["last_update_null_stack"], d["max_live_size"],
d["last_update_null_size"], d["last_update_null_heap_size"], d["last_update_null_stack_size"],
d["died_by_stack_after_heap_size"], d["died_by_stack_only_size"],
]
csvwriter.writerow( row )
def create_work_directory( work_dir, logger = None, interactive = False ):
os.chdir( work_dir )
today = datetime.date.today()
today = today.strftime("%Y-%m%d")
if os.path.isfile(today):
print "Can not create %s as directory." % today
exit(11)
if not os.path.isdir( today ):
os.mkdir( today )
else:
print "WARNING: %s directory exists." % today
logger.warning( "WARNING: %s directory exists." % today )
if interactive:
raw_input("Press ENTER to continue:")
else:
print "....continuing!!!"
return today
def save_interesting_small_cycles( largest_scc, summary ):
# Interesting is defined to be 4 or smaller
length = len(largest_scc)
if length > 0 and length <= 4:
summary["by_size"][length].append( largest_scc )
def save_largest_cycles( graphlist = None, num = None ):
largelist = heapq.nlargest( num, graphlist, key = len )
return largelist
def append_largest_SCC( ldict = None,
scclist = None,
selfloops = None,
logger = None ):
maxscc_len = max( ( len(x) for x in scclist ) )
if maxscc_len == 1:
# When the largest strongly connected component is a single node,
# We can't use the largest, because all nodes will be a SCC.
# We instead have to use the selfloops
selfies = set()
for cycle in scclist:
cycle = list(cycle)
node = cycle[0]
if node in selfloops:
selfies.add( node )
assert( len(selfies) > 0 )
if len(selfies) > 1:
logger.critical( "More than one selfie in list: %s" % str(selfies) )
largest_scc = [ selfies.pop() ]
else:
largest_scc = max( scclist, key = len )
ldict.append(largest_scc)
return largest_scc
def get_last_edge_from_result( edge_list ):
ledge = edge_list[0]
latest = ledge[4]
for newedge in edge_list[1:]:
if newedge[4] > latest:
ledge = newedge
return ledge
def get_last_edge( largest_scc, edge_info_db ):
mylist = list(largest_scc)
print "======================================================================"
print mylist
print "----"
last_edge_list = []
for tgt in mylist:
try:
result = edge_info_db.get_all( tgt ) # TODO: temporary debug
print "XXX: %d" % tgt
except KeyError:
result = []
print "ZZZ: %d" % tgt
print result
# The edge tuple is:
# (tgtId, srcId, fieldId, alloc time, death time )
# => Get the edge with the latest death time whose source ID isn't in
# the cycle.
last_edge = get_last_edge_from_result( result )
last_edge_list.append( last_edge )
print "====[ END ]==========================================================="
last_edge = get_last_edge_from_result( last_edge_list )
return (last_edge[1], last_edge[0])
def print_summary( summary ):
global pp
for bmark, fdict in summary.iteritems():
print "[%s]:" % bmark
for key, value in fdict.iteritems():
if key == "by_size":
continue
if key == "types" or key == "sbysize":
print " [%s]: %s" % (key, pp.pformat(value))
else:
print " [%s]: %d" % (key, value)
def skip_benchmark(bmark):
return ( bmark == "tradebeans" or # Permanent ignore
bmark == "tradesoap" or # Permanent ignore
bmark != "xalan"
# bmark == "lusearch" or
# ( bmark != "batik" and
# bmark != "lusearch" and
# bmark != "luindex" and
# bmark != "specjbb" and
# bmark != "avrora" and
# bmark != "tomcat" and
# bmark != "pmd" and
# bmark != "fop"
# )
)
def summary_by_size( objinfo = None,
cycles = None,
typedict = None,
summary = None,
logger = None ):
print summary.keys()
sbysize = summary["sbysize"]
exit(1000)
dbh = 0
dbs = 0
total_size = 0
# TODO
dbs_after_heap = 0
dbs_only = 0
last_update_null = 0
# END TODO
tmp = 0
for cycle in cycles:
for c in cycle:
mysize = objinfo[c][SIZE]
total_size += mysize
reason = objinfo[c][REASON]
if reason == "S":
dbs += mysize
elif reason == "H":
dbh += mysize
sbysize = { "died_by_heap" : dbh, # size
"died_by_stack" : dbs, # size
"died_by_stack_after_heap" : dbs_after_heap, # subset of died_by_stack TODO
"died_by_stack_only" : dbs_only, # subset of died_by_stack TODO
"last_update_null" : last_update_null, # subset of died_by_heap TODO
"size" : total_size, }
return sbysize
def main_process( output = None,
main_config = None,
benchmark = None,
lastedgeflag = False,
etanalyze_config = None,
global_config = None,
edge_config = None,
edgeinfo_config = None,
objectinfo_config = None,
summary_config = None,
debugflag = False,
logger = None ):
global pp
# HERE: TODO
# 1. Cyclic garbage vs ref count reclaimed:
# * Number of objects
# * size of objects
# 2. Number of cycles
# 3. Size of cycles
cycle_cpp_dir = global_config["cycle_cpp_dir"]
work_dir = main_config["directory"]
results = {}
summary = {}
typedict = {} # Type dictionary is ACROSS all benchmarks
rev_typedict = {} # Type dictionary is ACROSS all benchmarks
count = 0
today = create_work_directory( work_dir, logger = logger )
olddir = os.getcwd()
os.chdir( today )
for bmark, filename in etanalyze_config.iteritems():
# if skip_benchmark(bmark):
if ( (benchmark != "_ALL_") and (bmark != benchmark) ):
print "SKIP:", bmark
continue
print "=======[ %s ]=========================================================" \
% bmark
logger.critical( "=======[ %s ]========================================================="
% bmark )
abspath = os.path.join(cycle_cpp_dir, filename)
if os.path.isfile(abspath):
#----------------------------------------------------------------------
# SETUP
#----------------------------------------------------------------------
group = 1
graphs = []
# Counters TODO: do we need this?
cycle_total_counter = Counter()
actual_cycle_counter = Counter()
cycle_type_counter = Counter()
logger.critical( "Opening %s." % abspath )
#----------------------------------------------------------------------
# SUMMARY
#----------------------------------------------------------------------
# Get summary
summary_path = os.path.join(cycle_cpp_dir, summary_config[bmark])
summary_sim = get_summary( summary_path )
# get summary by size
number_of_objects = summary_sim["number_of_objects"]
number_of_edges = summary_sim["number_of_edges"]
died_by_stack = summary_sim["died_by_stack"]
died_by_heap = summary_sim["died_by_heap"]
died_by_stack_after_heap = summary_sim["died_by_stack_after_heap"]
died_by_stack_only = summary_sim["died_by_stack_only"]
died_by_stack_after_heap_size = summary_sim["died_by_stack_after_heap_size"]
died_by_stack_only_size = summary_sim["died_by_stack_only_size"]
size_died_by_stack = summary_sim["size_died_by_stack"]
size_died_by_heap = summary_sim["size_died_by_heap"]
last_update_null = summary_sim["last_update_null"]
last_update_null_heap = summary_sim["last_update_null_heap"]
last_update_null_stack = summary_sim["last_update_null_stack"]
last_update_null_size = summary_sim["last_update_null_size"]
last_update_null_heap_size = summary_sim["last_update_null_heap_size"]
last_update_null_stack_size = summary_sim["last_update_null_stack_size"]
max_live_size = summary_sim["max_live_size"]
final_time = summary_sim["final_time"]
selfloops = set()
results[bmark] = { "totals" : [],
"graph" : [],
"largest_cycle" : [],
"largest_cycle_types_set" : [],
"lifetimes" : [],
"lifetime_mean" : [],
"lifetime_sd" : [],
"lifetime_max" : [],
"lifetime_min" : [],
"sizes_largest_scc" : [],
"sizes_all" : [], }
summary[bmark] = { "by_size" : { 1 : [], 2 : [], 3 : [], 4 : [] },
# by_size contains apriori sizes 1 to 4 and the
# cycles with these sizes. The cycle is encoded
# as a list of object IDs (objId). by_size here means by cycle size
"died_by_heap" : died_by_heap, # total of
"died_by_stack" : died_by_stack, # total of
"died_by_stack_after_heap" : died_by_stack_after_heap, # subset of died_by_stack
"died_by_stack_only" : died_by_stack_only, # subset of died_by_stack
"died_by_stack_after_heap_size" : died_by_stack_after_heap_size, # size of
"died_by_stack_only_size" : died_by_stack_only_size, # size of
"last_update_null" : last_update_null, # subset of died_by_heap
"last_update_null_heap" : last_update_null_heap, # subset of died_by_heap
"last_update_null_stack" : last_update_null_stack, # subset of died_by_heap
"last_update_null_size" : last_update_null_size, # size of
"last_update_null_heap_size" : last_update_null_heap_size, # size of
"last_update_null_stack_size" : last_update_null_stack_size, # size of
"max_live_size" : max_live_size,
"number_of_objects" : number_of_objects,
"number_of_edges" : number_of_edges,
"number_of_selfloops" : 0,
"types" : Counter(), # counts of types using type IDs
"size_died_by_stack" : size_died_by_stack, # size, not object count
"size_died_by_heap" : size_died_by_heap, # size, not object count
}
#----------------------------------------------------------------------
# CYCLES
#----------------------------------------------------------------------
# Get cycles
cycles = get_cycles( abspath )
# TODO What is this?
# TODO get_cycles_result = {}
# Get edges
edgepath = os.path.join(cycle_cpp_dir, edge_config[bmark])
edges = get_edges( edgepath )
edgedict = create_edge_dictionary( edges, selfloops )
# Get edge information
edgeinfo_path = os.path.join(cycle_cpp_dir, edgeinfo_config[bmark])
edge_info_dict = get_edge_info( edgeinfo_path)
# Get object dictionary information that has types and sizes
objectinfo_path = os.path.join(cycle_cpp_dir, objectinfo_config[bmark])
object_info_dict = get_object_info( objectinfo_path, typedict, rev_typedict )
for index in xrange(len(cycles)):
cycle = cycles[index]
cycle_info_list = get_cycle_info_list( cycle = cycle,
objinfo_dict = object_info_dict,
# objdb,
logger = logger )
if len(cycle_info_list) == 0:
continue
# GRAPH
G = create_graph( cycle_info_list = cycle_info_list,
edgedict = edgedict,
logger = logger )
# Get the actual cycle - LARGEST
# Sanity check 1: Is it a DAG?
if nx.is_directed_acyclic_graph(G):
logger.error( "Not a cycle." )
logger.error( "Nodes: %s" % str(G.nodes()) )
logger.error( "Edges: %s" % str(G.edges()) )
continue
ctmplist = list( nx.simple_cycles(G) )
# Sanity check 2: Check to see it's not empty.
if len(ctmplist) == 0:
# No cycles!!!
logger.error( "Not a cycle." )
logger.error( "Nodes: %s" % str(G.nodes()) )
logger.error( "Edges: %s" % str(G.edges()) )
continue
# TODO TODO TODO
# Interesting cases are:
# - largest is size 1 (self-loops)
# - multiple largest cycles?
# * Option 1: choose only one?
# * Option 2: ????
#
# Get Strongly Connected Components