-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathcrashes.py
1533 lines (1288 loc) · 52.1 KB
/
crashes.py
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
#!/usr/bin/env python3
import json
import hashlib
import os
import pprint
import re
import sys
import html
import getopt
import threading
import itertools
import time
import requests
import math
import string
import pygal
from string import Template
from collections import Counter
from urllib.request import urlopen
from urllib import request
from datetime import datetime, timedelta, date
# python -m pip install SomePackage
# python.exe -m pip install --upgrade SomePackage
# python.exe -m pip install --upgrade fx_crash_sig
import fx_crash_sig
from fx_crash_sig.crash_processor import CrashProcessor
# process types
# https://searchfox.org/mozilla-central/source/toolkit/components/crashes/CrashManager.jsm#162
###########################################################
# Usage
###########################################################
# -u (url) : redash rest endpoint url
# -k (str) : redash user api key
# -q (query id) : redash api query id
# -c (value) : redash cache value in minutes (0 is the default)
# -n (name) : local json cache filename to use (excluding extension)
# -d (name) : local html output filename to use (excluding extension)
# -c (count) : number of reports to process, overrides the default
# -p (k=v) : k=v redash query parameters to pass to the query request.
# -z : debugging: load and dump the first few records of the local databases. requires -d.
# -s (sig) : search for a token in reports
# python crashes.py -n nightly -d nightly -u https://sql.telemetry.mozilla.org -k (userapikey) -q 79354 -p process_type=gpu -p version=89 -p channel=nightly
## TODO
## stats statistics when loaded or written
## report struct may not need to os, osver, and arch info anymore since we added stats
## signatures that went away feature
## annotation signature keywords
## click handler should ignore clicks if there's selection in the page
## popup panel layout (Fixed By and Notes) is confusing, and wide when it doesn't need to be.
## Remove reliance on version numbers? Need to get signature headers hooked up, and choose the latest releases for main reports
## build id (nightly / beta)
## linux distro information someplace
## clean up the startup crash icons
## better annotations support
## add dates to annotations
## improve signature header information layout, particular fx version numbers. We can easily expand this down and host info similar to crash stats summary pages.
## - filter graphing and the list based on clicks on the header data (version, os, arch)
###########################################################
# Globals
###########################################################
# The default symbolication server to use.
SymbolServerUrl = "https://symbolication.stage.mozaws.net/symbolicate/v5"
# Max stack depth for symbolication
MaxStackDepth = 50
# Maximum number of raw crashes to process. This matches
# the limit value of re:dash queries. Reduce for testing
# purposes.
CrashProcessMax = 7500
# Signature list length of the resulting top crashes report
MostCommonLength = 50
# When generating a report, signatures with crash counts
# lower than this value will not be included in the report.
MinCrashCount = 1
# When generating a report, signatures with client counts
# lower than this value will not be included in the report.
ReportLowerClientLimit = 2 # filter out single client crashes
# Maximum number of crash reports to include for each signature
# in the final report. Limits the size of the resulting html.
MaxReportCount = 100
# Default redash max_age value in minutes
MaxAge = 43200
# Set to True to target a local json file for testing
LoadLocally = False
LocalJsonFile = "GPU_Raw_Crash_Data_2021_03_19.json"
proc = CrashProcessor(MaxStackDepth, SymbolServerUrl)
pp = pprint.PrettyPrinter(indent=1, width=260)
def symbolicate(ping):
try:
return proc.symbolicate(ping)
except:
return None
def generateSignature(payload):
if payload is None:
return ""
try:
return proc.get_signature_from_symbolicated(payload).signature
except:
return ""
###########################################################
# Progress indicator
###########################################################
def progress(count, total, status=''):
bar_len = 60
filled_len = int(round(bar_len * count / float(total)))
percents = round(100.0 * count / float(total), 1)
bar = '=' * filled_len + '-' * (bar_len - filled_len)
sys.stdout.write('[%s] %s%s ...%s\r' % (bar, percents, '%', status))
sys.stdout.flush()
class Spinner:
def __init__(self, message, delay=0.1):
self.spinner = itertools.cycle(['-', '/', '|', '\\'])
self.delay = delay
self.busy = False
self.spinner_visible = False
sys.stdout.write(message)
def write_next(self):
with self._screen_lock:
if not self.spinner_visible:
sys.stdout.write(next(self.spinner))
self.spinner_visible = True
sys.stdout.flush()
def remove_spinner(self, cleanup=False):
with self._screen_lock:
if self.spinner_visible:
sys.stdout.write('\b')
self.spinner_visible = False
if cleanup:
sys.stdout.write(' ') # overwrite spinner with blank
sys.stdout.write('\r') # move to next line
sys.stdout.flush()
def spinner_task(self):
while self.busy:
self.write_next()
time.sleep(self.delay)
self.remove_spinner()
def __enter__(self):
if sys.stdout.isatty():
self._screen_lock = threading.Lock()
self.busy = True
self.thread = threading.Thread(target=self.spinner_task)
self.thread.start()
def __exit__(self, exception, value, tb):
if sys.stdout.isatty():
self.busy = False
self.remove_spinner(cleanup=True)
else:
sys.stdout.write('\r')
def poll_job(s, redash_url, job):
while job['status'] not in (3,4):
response = s.get('{}/api/jobs/{}'.format(redash_url, job['id']))
job = response.json()['job']
time.sleep(1)
if job['status'] == 3:
return job['query_result_id']
return None
###########################################################
# Redash queries
###########################################################
def getRedashQueryResult(redash_url, query_id, api_key, cacheValue, params):
s = requests.Session()
s.headers.update({'Authorization': 'Key {}'.format(api_key)})
# max_age is a redash value that controls cached results. If there is a cached query result
# newer than this time (in seconds) it will be returned instead of a fresh query.
# 86400 = 24 hours, 43200 = 12 hours, 0 = refresh query
#
# Note sometimes the redash caching feature gets 'stuck' on an old cache. Side effect is
# that all reports will eventually be older than 7 days and as such will be filtered out
# by this script's age checks in processRedashDataset. Crash lists will shrink to zero
# as a result.
payload = dict(max_age=cacheValue, parameters=params)
url = "%s/api/queries/%s/results" % (redash_url, query_id)
response = s.post(url, data=json.dumps(payload))
if response.status_code != 200:
print("\nquery error '%s'" % response)
pp.pprint(payload)
raise Exception('Redash query failed.')
#{ 'job': { 'error': '',
# 'id': '21429857-5fd0-443d-ba4b-fb9cc6d49add',
# 'query_result_id': None,
# 'result': None,
# 'status': 1,
# 'updated_at': 0}}
# ...or, we just get back the result
try:
result = response.json()['job']
except KeyError:
return response.json()
result_id = poll_job(s, redash_url, response.json()['job'])
response = s.get('{}/api/queries/{}/results/{}.json'.format(redash_url, query_id, result_id))
if response.status_code != 200:
raise Exception('Failed getting results. (Check your redash query for errors.) statuscode=%d' % response.status_code)
return response.json()
###########################################################
# HTML and Text Formatting Utilities
###########################################################
def escapeBugLinks(text):
# convert bug references to links
# https://bugzilla.mozilla.org/show_bug.cgi?id=1323439
pattern = "bug ([0-9]*)"
replacement = "<a href='https://bugzilla.mozilla.org/show_bug.cgi?id=\\1'>Bug \\1</a>"
result = re.sub(pattern, replacement, text, flags=re.IGNORECASE)
return result
def createBugLink(id):
# convert bug references to links
return "<a href='https://bugzilla.mozilla.org/show_bug.cgi?id=" + str(id) + "'>bug " + str(id) + "</a>"
safe = string.ascii_letters + string.digits + '_-.'
def stripWhitespace(text):
text = text.strip(' \t\n')
return text
def stringToHtmlId(s):
s = ''.join([letter for letter in s if letter in safe])
return s
def generateSourceLink(frame):
# examples:
# https://hg.mozilla.org/mozilla-central/file/2da6d806f45732e169fd8e7ea9a9761fa7fed93d/netwerk/protocol/http/OpaqueResponseUtils.cpp#l208
# https://crash-stats.mozilla.org/sources/highlight/?url=https://gecko-generated-sources.s3.amazonaws.com/7d3f7c890af...e97be06f948921153/ipc/ipdl/PCompositorManagerParent.cpp&line=200#L-200
# 'file': 's3:gecko-generated-sources:8276fd848664bea270...8e363bdbc972cdb7eb661c4043de93ce27810b54/ipc/ipdl/PWebGLParent.cpp:',
# 'file': 'hg:hg.mozilla.org/mozilla-central:dom/canvas/WebGLParent.cpp:52d2c9e672d0a0c50af4d6c93cc0239b9e751d18',
# 'line': 59,
srcLineNumer = str()
srcfileData = str()
srcUrl = str()
try:
srcLineNumber = frame['line']
srcfileData = frame['file']
tokenList = srcfileData.split(':')
if (len(tokenList) != 4):
print("bad token list " + tokenList)
return str()
except:
return str()
if tokenList[0].find('s3') == 0:
srcUrl = 'https://crash-stats.mozilla.org/sources/highlight/?url=https://gecko-generated-sources.s3.amazonaws.com/'
srcUrl += tokenList[2]
srcUrl += '&line='
srcUrl += str(srcLineNumber)
srcUrl += '#L-'
srcUrl += str(srcLineNumber)
elif tokenList[0].find('hg') == 0:
srcUrl = 'https://'
srcUrl += tokenList[1]
srcUrl += '/file/'
srcUrl += tokenList[3]
srcUrl += '/'
srcUrl += tokenList[2]
srcUrl += '#l' + str(srcLineNumber)
else:
#print("Unknown src annoutation source") this happens a lot
return str()
return srcUrl
def escape(text):
return html.escape(text)
###########################################################
# Crash Report Utilities
###########################################################
def processStack(frames):
# Normalized function names we can consider the same in calculating
# unique reports. We replace the regex match with the key using sub.
coelesceFrameDict = {
'RtlUserThreadStart': '[_]+RtlUserThreadStart'
}
# Functions we can replace with the normalized version, filters
# out odd platform parameter differences.
coelesceFunctionList = [
'thread_start<'
]
dataStack = list() # [idx] = { 'frame': '(frame)', 'srcUrl': '(url)' }
for frame in frames:
frameIndex = '?'
try:
frameIndex = frame['frame'] # zero based frame index
except KeyError:
continue
except TypeError:
#print("TypeError while indexing frame.");
continue
dataStack.insert(frameIndex, { 'index': frameIndex, 'frame': '', 'srcUrl': '', 'module': '' })
functionCall = ''
module = 'unknown'
offset = 'unknown'
try:
offset = frame['module_offset']
except:
pass
try:
module = frame['module']
except:
pass
try:
functionCall = frame['function']
except KeyError:
dataStack[frameIndex]['frame'] = offset
dataStack[frameIndex]['module'] = module
continue
except TypeError:
print("TypeError while indexing function.");
dataStack[frameIndex]['frame'] = "(missing function)"
continue
for k, v in coelesceFrameDict.items():
functionCall = re.sub(v, k, functionCall, 1)
break
for v in coelesceFunctionList:
if re.search(v, functionCall) != None:
normalizedFunction = functionCall
try:
normalizedFunction = frame['normalized']
except KeyError:
pass
except TypeError:
pass
functionCall = normalizedFunction
break
srcUrl = generateSourceLink(frame)
dataStack[frameIndex]['srcUrl'] = srcUrl
dataStack[frameIndex]['frame'] = functionCall
dataStack[frameIndex]['module'] = module
return dataStack
def generateSignatureHash(signature, os, osVer, arch, fxVer):
hashData = signature
# Append any crash meta data to our hashData so it applies to uniqueness.
# Any variance in this data will cause this signature to be broken out as
# a separate signature in the final top crash list.
#hashData += os
#hashData += osVer
#hashData += arch
# The redash queries we are currently using target specific versions, so this
# doesn't have much of an impact except on beta, where we want to see the effect
# of beta fixes that get uplifted.
#hashData += fxVer
return hashlib.md5(hashData.encode('utf-8')).hexdigest()
###########################################################
# Reports data structure utilities
###########################################################
def getDatasetStats(reports):
sigCount = len(reports)
reportCount = 0
for hash in reports:
reportCount += len(reports[hash]['reportList'])
return sigCount, reportCount
def processRedashDataset(dbFilename, jsonUrl, queryId, userKey, cacheValue, parameters):
props = list()
reports = dict()
totals = {
'processed': 0,
'skippedBadSig': 0,
'alreadyProcessed': 0,
'outdated': 0
}
# load up our database of processed crash ids
# returns an empty dict() if no data is loaded.
reports, stats = loadReports(dbFilename)
if LoadLocally:
with open(LocalJsonFile) as f:
dataset = json.load(f)
else:
with Spinner("loading from redash..."):
dataset = getRedashQueryResult(jsonUrl, queryId, userKey, cacheValue, parameters)
print(" done.")
crashesToProcess = len(dataset["query_result"]["data"]["rows"])
if crashesToProcess > CrashProcessMax:
crashesToProcess = CrashProcessMax
print('%04d total reports loaded.' % crashesToProcess)
for recrow in dataset["query_result"]["data"]["rows"]:
if totals['processed'] >= CrashProcessMax:
break
# pull some redash props out of the recrow. You can add these
# by modifying the sql query.
operatingSystem = recrow['normalized_os']
operatingSystemVer = recrow['normalized_os_version']
firefoxVer = recrow['display_version']
buildId = recrow['build_id']
compositor = recrow['compositor']
arch = recrow['arch']
oomSize = recrow['oom_size']
devVendor = recrow['vendor']
devGen = recrow['gen']
devChipset = recrow['chipset']
devDevice = recrow['device']
drvVer = recrow['driver_version']
drvDate = recrow['driver_date']
clientId = recrow['client_id']
devDesc = recrow['device_description']
# Load the json crash payload from recrow
props = json.loads(recrow["payload"])
# touch up for the crash symbolication package
props['stackTraces'] = props['stack_traces']
crashId = props['crash_id']
crashDate = props['crash_date']
minidumpHash = props['minidump_sha256_hash']
crashReason = props['metadata']['moz_crash_reason']
crashInfo = props['stack_traces']['crash_info']
startupCrash = int(recrow['startup_crash'])
fissionEnabled = int(recrow['fission_enabled'])
lockdownVal = int(recrow['lockdown_enabled'])
lockdownEnabled = False
if lockdownVal == 1:
lockdownEnabled = True
if crashReason != None:
crashReason = crashReason.strip('\n')
# Ignore crashes older than 7 days
if not checkCrashAge(crashDate):
totals['processed'] += 1
totals['outdated'] += 1
progress(totals['processed'], crashesToProcess)
continue
# check if the crash id is processed, if so continue
## note, this search has become quite slow. optimize me.
found = False
signature = ""
for sighash in reports: # reports is a dictionary of signature hashes
for report in reports[sighash]['reportList']: # reportList is a list of dictionaries
if report['crashid'] == crashId: # string compare, slow
found = True
# if you add a new value to the sql queries, you can update
# the local json cache we have in memory here. Saves having
# to delete the file and symbolicate everything again.
#report['fission'] = fissionEnabled
#report['lockdown'] = lockdownEnabled
break
if found:
totals['processed'] += 1
totals['alreadyProcessed'] += 1
progress(totals['processed'], crashesToProcess)
continue
# symbolicate and return payload result
payload = symbolicate(props)
signature = generateSignature(payload)
if skipProcessSignature(signature):
totals['processed'] += 1
totals['skippedBadSig'] += 1
progress(totals['processed'], crashesToProcess)
continue
# pull stack information for the crashing thread
try:
crashingThreadIndex = payload['crashing_thread']
except KeyError:
#print("KeyError on crashing_thread for report");
continue
threads = payload['threads']
try:
frames = threads[crashingThreadIndex]['frames']
except IndexError:
print("IndexError while indexing crashing thread");
continue
except TypeError:
print("TypeError while indexing crashing thread");
continue
# build up a pretty stack
stack = processStack(frames)
# generate a tracking hash
hash = generateSignatureHash(signature, operatingSystem, operatingSystemVer, arch, firefoxVer)
if hash not in reports.keys():
# Set up this signature's meta data we track in the signature header.
reports[hash] = {
'signature': signature,
'operatingsystem': [operatingSystem],
'osversion': [operatingSystemVer],
'firefoxver': [firefoxVer],
'arch': [arch],
'reportList': list()
}
# Update meta data we track in the report header.
if operatingSystem not in reports[hash]['operatingsystem']:
reports[hash]['operatingsystem'].append(operatingSystem)
if operatingSystemVer not in reports[hash]['osversion']:
reports[hash]['osversion'].append(operatingSystemVer)
if firefoxVer not in reports[hash]['firefoxver']:
reports[hash]['firefoxver'].append(firefoxVer)
if arch not in reports[hash]['arch']:
reports[hash]['arch'].append(arch)
# create our report with per crash meta data
report = {
'clientid': clientId,
'crashid': crashId,
'crashdate': crashDate,
'compositor': compositor,
'stack': stack,
'oomsize': oomSize,
'type': crashInfo['type'],
'devvendor': devVendor,
'devgen': devGen,
'devchipset': devChipset,
'devdevice': devDevice,
'devdescription': devDesc,
'driverversion' : drvVer,
'driverdate': drvDate,
'minidumphash': minidumpHash,
'crashreason': crashReason,
'startup': startupCrash,
'fission': fissionEnabled,
'lockdown': lockdownEnabled,
# Duplicated but useful if we decide to change the hashing algo
# and need to reprocess reports.
'operatingsystem': operatingSystem,
'osversion': operatingSystemVer,
'firefoxver': firefoxVer,
'arch': arch
}
# save this crash in our report list
reports[hash]['reportList'].append(report)
if hash not in stats.keys():
stats[hash] = {
'signature': signature,
'crashdata': {}
}
# check to see if stats has a date entry that matches crashDate
if crashDate not in stats[hash]['crashdata']:
stats[hash]['crashdata'][crashDate] = { 'crashids': [], 'clientids':[] }
if operatingSystem not in stats[hash]['crashdata'][crashDate]:
stats[hash]['crashdata'][crashDate][operatingSystem] = {}
if operatingSystemVer not in stats[hash]['crashdata'][crashDate][operatingSystem]:
stats[hash]['crashdata'][crashDate][operatingSystem][operatingSystemVer] = {}
if arch not in stats[hash]['crashdata'][crashDate][operatingSystem][operatingSystemVer]:
stats[hash]['crashdata'][crashDate][operatingSystem][operatingSystemVer][arch] = {}
if firefoxVer not in stats[hash]['crashdata'][crashDate][operatingSystem][operatingSystemVer][arch]:
stats[hash]['crashdata'][crashDate][operatingSystem][operatingSystemVer][arch][firefoxVer] = { 'clientcount': 0, 'crashcount': 0 }
if crashId not in stats[hash]['crashdata'][crashDate]['crashids']:
stats[hash]['crashdata'][crashDate]['crashids'].append(crashId)
stats[hash]['crashdata'][crashDate][operatingSystem][operatingSystemVer][arch][firefoxVer]['crashcount'] += 1
if clientId not in stats[hash]['crashdata'][crashDate]['clientids']:
stats[hash]['crashdata'][crashDate][operatingSystem][operatingSystemVer][arch][firefoxVer]['clientcount'] += 1
stats[hash]['crashdata'][crashDate]['clientids'].append(clientId)
totals['processed'] += 1
progress(totals['processed'], crashesToProcess)
print('\n')
print('%04d - reports processed' % totals['processed'])
print('%04d - cached results' % totals['alreadyProcessed'])
print('%04d - reports skipped, bad signature' % totals['skippedBadSig'])
print('%04d - reports skipped, out dated' % totals['outdated'])
if totals['processed'] == 0:
exit()
# Post processing steps
# Purge signatures from our reports list that are outdated (based
# on crash date and version). This keeps our crash lists current,
# especially after a merge. Note this doesn't clear stats, just reports.
queryFxVersion = parameters['version']
purgeOldReports(reports, queryFxVersion)
# purge old crash and client ids from the stats database.
cleanupStats(reports, stats)
# calculate unique client id counts for each signature. These are client counts
# associated with the current redash query, and apply only to a seven day time
# window. They are stored in the reports database and displayed in the top crash
# reports.
clientCounts = dict()
needsUpdate = False
for hash in reports:
clientCounts[hash] = list()
for report in reports[hash]['reportList']:
clientId = report['clientid']
if clientId not in clientCounts[hash]:
clientCounts[hash].append(clientId)
reports[hash]['clientcount'] = len(clientCounts[hash])
return reports, stats, totals['processed']
def checkCrashAge(dateStr):
try:
date = datetime.fromisoformat(dateStr)
except:
return False
oldestDate = datetime.today() - timedelta(days=7)
return (date >= oldestDate)
def getMainVer(version):
return version.split('.')[0]
def purgeOldReports(reports, fxVersion):
# Purge obsolete reports.
# 89.0b7 89.0 90.0.1
totalReportsDropped = 0
for hash in reports:
keepRepList = list()
origRepLen = len(reports[hash]['reportList'])
for report in reports[hash]['reportList']:
reportVer = ''
try:
reportVer = getMainVer(report['firefoxver'])
except:
pass
if fxVersion == reportVer:
keepRepList.append(report)
totalReportsDropped += (origRepLen - len(keepRepList))
reports[hash]['reportList'] = keepRepList
print("Removed %d older reports." % totalReportsDropped)
# Purge signatures that have no reports
delSigList = list()
for hash in reports:
newRepList = list()
for report in reports[hash]['reportList']:
# "crash_date":"2021-03-22"
dateStr = report['crashdate']
if checkCrashAge(dateStr):
newRepList.append(report)
reports[hash]['reportList'] = newRepList
if len(newRepList) == 0:
# add this signature to our purge list
delSigList.append(hash)
for hash in reports:
if len(reports[hash]['reportList']) == 0:
if hash not in delSigList:
delSigList.append(hash)
# purge old signatures that no longer have reports
# associated with them.
for hash in delSigList:
del reports[hash]
print("Removed %d older signatures from our reports database." % len(delSigList))
def cleanupStats(reports, stats):
# remove old crash and client ids we no longer have reports for
clientList = list()
crashList = list()
for hash in reports:
for report in reports[hash]['reportList']:
clientid = report['clientid']
crashid = report['crashid']
if clientid not in clientList:
clientList.append(clientid)
if crashid not in crashList:
crashList.append(crashid)
purgeClientIdList = list()
purgeCrashIdList = list()
for hash in stats:
for date in stats[hash]['crashdata'].keys():
for crashid in stats[hash]['crashdata'][date]['crashids']:
if crashid not in crashList:
if crashid not in purgeCrashIdList:
purgeCrashIdList.append(crashid)
for clientid in stats[hash]['crashdata'][date]['clientids']:
if clientid not in clientList:
if clientid not in purgeClientIdList:
purgeClientIdList.append(clientid)
for crashid in purgeCrashIdList:
for hash in stats:
for date in stats[hash]['crashdata'].keys():
if crashid in stats[hash]['crashdata'][date]['crashids']:
stats[hash]['crashdata'][date]['crashids'].remove(crashid)
for clientid in purgeClientIdList:
for hash in stats:
for date in stats[hash]['crashdata'].keys():
if clientid in stats[hash]['crashdata'][date]['clientids']:
stats[hash]['crashdata'][date]['clientids'].remove(clientid)
print("Removed %d old client ids and %d old crash ids tracked in stats." % (len(purgeClientIdList), len(purgeCrashIdList)))
return True
# return true if we should skip processing this signature
def skipProcessSignature(signature):
if len(signature) == 0:
return True
elif signature == 'EMPTY: no crashing thread identified':
return True
elif signature == 'EMPTY: no frame data available':
return True
elif signature == "<T>":
print("sig <T>")
return True
return False
def isFissionRelated(reports):
isFission = True
for report in reports:
try:
if report['fission'] == 0:
isFission = False
except:
pass
return isFission
def isLockdownRelated(reports):
isLockdown = True
for report in reports:
try:
if report['lockdown'] == 0:
isLockdown = False
except:
pass
return isLockdown
def generateTopReportsList(reports):
# For certain types of reasons like RustMozCrash, organize
# the most common for a report list. Otherwise just dump the
# first MaxReportCount.
reasonCounter = Counter()
for report in reports:
crashReason = report['crashreason']
reasonCounter[crashReason] += 1
reportCol = reasonCounter.most_common(MaxReportCount)
if len(reportCol) < MaxReportCount:
return reports
colCount = len(reportCol)
maxReasonCount = int(math.ceil(MaxReportCount / colCount))
reportList = list()
count = 0
for reason, count in reportCol:
for report in reports:
if report['crashreason'] == reason:
reportList.append(report)
count += 1
if count > maxReasonCount:
break # next reason
return reportList
def dumpDatabase(reports, annoFilename):
print("= Reports =======================================================================================")
pp.pprint(reports)
print("= Annotations ===================================================================================")
reports = loadAnnotations(annoFilename)
pp.pprint(reports)
def doMaintenance(dbFilename):
exit()
# load up our database of processed crash ids
reports, stats = loadReports(dbFilename)
for hash in reports:
signature = reports[hash]['signature']
clientcount = reports[hash]['clientcount']
operatingSystem = reports[hash]['operatingsystem']
del reports[hash]['operatingsystem']
reports[hash]['operatingsystem'] = [operatingSystem]
operatingSystemVer = reports[hash]['osversion']
del reports[hash]['osversion']
reports[hash]['osversion'] = [operatingSystemVer]
firefoxVer = reports[hash]['firefoxver']
del reports[hash]['firefoxver']
reports[hash]['firefoxver'] = [firefoxVer]
arch = reports[hash]['arch']
del reports[hash]['arch']
reports[hash]['arch'] = [arch]
#dumpDatabase(reports)
# Caching of reports
#cacheReports(reports, stats, dbFilename)
###########################################################
# File utilities
###########################################################
# Load the local report database
def loadReports(dbFilename):
reportsFile = ("%s-reports.json" % dbFilename)
statsFile = ("%s-stats.json" % dbFilename)
reports = dict()
stats = dict()
try:
with open(reportsFile) as database:
reports = json.load(database)
except FileNotFoundError:
pass
try:
with open(statsFile) as database:
stats = json.load(database)
except FileNotFoundError:
pass
sigCount, reportCount = getDatasetStats(reports)
print("Existing database stats: %d signatures, %d reports." % (sigCount, reportCount))
return reports, stats
# Cache the reports database to a local json file. Speeds
# up symbolication runs across days by avoid re-symbolicating
# reports.
def cacheReports(reports, stats, dbFilename):
reportsFile = ("%s-reports.json" % dbFilename)
statsFile = ("%s-stats.json" % dbFilename)
with open(reportsFile, "w") as database:
database.write(json.dumps(reports))
with open(statsFile, "w") as database:
database.write(json.dumps(stats))
sigCount, reportCount = getDatasetStats(reports)
print("Cache database stats: %d signatures, %d reports." % (sigCount, reportCount))
def loadAnnotations(filename):
file = "%s.json" % filename
try:
with open(file) as database:
annotations = json.load(database)
print("Loading %s annotations file." % file)
except FileNotFoundError:
print("Could not find %s file." % file)
return dict()
except json.decoder.JSONDecodeError:
print("Json error parsing %s" % file)
return dict()
return annotations
###########################################################
# HTML Template Utilities
###########################################################
def extractTemplate(token, srcTemplate):
# This returns the inner template from srcTemplate, minus any
# identifying tag data.
# token would be something like 'signature' used
# in identifying tags like:
# <!-- start of signature template -->
# <!-- end of signature template -->
start = '<!-- start of ' + token + ' template -->'
end = '<!-- end of ' + token + ' template -->'
sIndex = srcTemplate.index(start)
eIndex = srcTemplate.index(end)
if sIndex == -1 or eIndex == -1:
raise Exception("Bad HTML template tokens!")
template = srcTemplate[sIndex + len(start) : eIndex + len(end)]
return template
def extractAndTokenizeTemplate(token, srcTemplate, insertToken):
# This returns the inner template from srcTemplate, minus any
# identifying tag data, and we also return srcTemplate with
# $insertToken replacing the block we clipped out.
start = '<!-- start of ' + token + ' template -->'
end = '<!-- end of ' + token + ' template -->'
sIndex = srcTemplate.index(start)
eIndex = srcTemplate.index(end)
if sIndex == -1 or eIndex == -1:
raise Exception("Bad HTML template tokens!")
header = srcTemplate[0:sIndex]
footer = srcTemplate[eIndex + len(end):]
template = srcTemplate[sIndex + len(start) : eIndex]
return template, (header + '$' + insertToken + footer)
def dumpTemplates():
print('mainPage -----')
print(mainPage)
print('outerSigTemplate-----')
print(outerSigTemplate)
print('outerSigMetaTemplate-----')
print(outerSigMetaTemplate)
print('outerReportTemplate-----')
print(outerReportTemplate)
print('outerStackTemplate-----')
print(outerStackTemplate)
print('innerStackTemplate-----')
print(innerStackTemplate)
exit()
###########################################################
### Report generation
###########################################################
def generateSignatureReport(signature):
reports, stats = loadReports()
reports = reports[sig]
if len(reports) == 0:
print("signature not found in database.")
exit()
#for report in reports:
exit()
def generateSparklineJS(sigStats, operatingSystems, operatingSystemVers, firefoxVers, archs, className):
# generate stats data for crash rate over time graphs
# data = [ {name: "Bitcoin", date: "2017-01-01", value: 967.6}, ]
#"Windows": {
# "6.1": {
# "x86": {
# "91.0a1": {
# "clientcount": 1,
# "crashcount": 3
# }
# }
# }
#}
rawData = dict()
for dateStr in sigStats['crashdata']:
for os in operatingSystems:
for osver in operatingSystemVers:
for arch in archs:
for fxver in firefoxVers:
try: