-
Notifications
You must be signed in to change notification settings - Fork 218
/
tcbs.py
286 lines (256 loc) · 10.7 KB
/
tcbs.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
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import logging
logger = logging.getLogger("webapi")
import socorro.database.database as db
from socorro.lib import datetimeutil, util
import datetime
"""
theoretical sample output
[ [ (key, rank, rankDelta, ...), ... ], ... ]
{
"resource": "http://socorro.mozilla.org/trends/topcrashes/bysig/"
"Firefox/3.5.3/from/2009-10-03/to/2009-10-13/page/0",
"page": "0",
"previous": "null",
"next": "http://socorro.mozilla.org/trends/topcrashes/bysig/"
"Firefox/3.5.3/from/2009-10-03/to/2009-10-13/page/0",
"ranks":[
{"signature": "LdrAlternateResourcesEnabled",
"previousRank": 3,
"currentRank": 8,
"change": -5},
{"signature": "OtherSignature",
"previousRank": "null",
"currentRank": 10,
"change": 10}
],
}
"""
def getListOfTopCrashersBySignature(aCursor, dbParams):
"""
Answers a generator of tcbs rows
"""
assertPairs = {
'startDate': (datetime.date, datetime.datetime),
'to_date': (datetime.date, datetime.datetime),
'product': basestring,
'version': basestring,
'limit': int
}
for param in assertPairs:
if not isinstance(dbParams[param], assertPairs[param]):
raise ValueError(type(dbParams[param]))
order_by = 'report_count' # default order field
where = [''] # trick for the later join
if dbParams['crash_type'] != 'all':
where.append("process_type = '%s'" % (dbParams['crash_type'],))
if dbParams['os']:
order_by = '%s_count' % dbParams['os'][0:3].lower()
where.append("%s > 0" % order_by)
where = ' AND '.join(where)
table_to_use = 'tcbs'
date_range_field = 'report_date'
if dbParams['date_range_type'] == 'build':
table_to_use = 'tcbs_build'
date_range_field = 'build_date'
sql = """
WITH tcbs_r as (
SELECT tcbs.signature_id,
signature,
pv.product_name,
version_string,
sum(report_count) as report_count,
sum(win_count) as win_count,
sum(lin_count) as lin_count,
sum(mac_count) as mac_count,
sum(hang_count) as hang_count,
plugin_count(process_type,report_count) as plugin_count,
content_count(process_type,report_count) as content_count,
first_report,
version_list,
sum(startup_count) as startup_count
FROM %s tcbs
JOIN signatures USING (signature_id)
JOIN product_versions AS pv USING (product_version_id)
JOIN signature_products_rollup AS spr
ON spr.signature_id = tcbs.signature_id
AND spr.product_name = pv.product_name
WHERE pv.product_name = '%s'
AND version_string = '%s'
AND tcbs.%s BETWEEN '%s' AND '%s'
%s
GROUP BY tcbs.signature_id, signature, pv.product_name, version_string,
first_report, spr.version_list
),
tcbs_window AS (
SELECT tcbs_r.*,
sum(report_count) over () as total_crashes,
dense_rank() over (order by report_count desc) as ranking
FROM
tcbs_r
)
SELECT signature,
report_count,
win_count,
lin_count,
mac_count,
hang_count,
plugin_count,
content_count,
first_report,
version_list,
%s / total_crashes::float as percent_of_total,
startup_count / %s::float as startup_percent
FROM tcbs_window
ORDER BY %s DESC
LIMIT %s
""" % (table_to_use, dbParams["product"], dbParams["version"],
date_range_field, dbParams["startDate"],
dbParams["to_date"], where, order_by, order_by, order_by,
dbParams["limit"])
#logger.debug(aCursor.mogrify(sql, dbParams))
return db.execute(aCursor, sql)
def rangeOfQueriesGenerator(aCursor, dbParams, queryFunction):
"""
returns a list of the results of multiple queries.
"""
i = dbParams.startDate
to_date = dbParams.to_date
while i < to_date:
params = {}
params.update(dbParams)
params['startDate'] = i
params['to_date'] = i + dbParams.duration
dbParams.logger.debug("rangeOfQueriesGenerator for %s to %s",
params['startDate'],
params['to_date'])
yield queryFunction(aCursor, params)
i += dbParams.duration
class DictList(object):
def __init__(self, sourceIterable):
super(DictList, self).__init__()
self.rowsBySignature = {}
self.indexes = {}
self.rows = list(sourceIterable)
for i, x in enumerate(self.rows):
self.rowsBySignature[x['signature']] = x
self.indexes[x['signature']] = i
def find(self, aSignature):
return (self.indexes[aSignature],
self.rowsBySignature[aSignature]['percentOfTotal'])
def __iter__(self):
return iter(self.rows)
def listOfListsWithChangeInRank(listOfQueryResultsIterable):
"""
Step through a list of query results, altering them by adding prior
ranking. Answers all but the very first item of the input.
"""
listOfTopCrasherLists = []
for aListOfTopCrashers in listOfQueryResultsIterable:
try:
previousList = DictList(listOfTopCrasherLists[-1])
except IndexError:
# 1st processed - has no previous history
previousList = DictList([])
currentListOfTopCrashers = []
aRowAsDict = None
for rank, aRow in enumerate(aListOfTopCrashers):
#logger.debug(aRowAsDict)
aRowAsDict = dict(zip(['signature', 'count', 'win_count',
'linux_count', 'mac_count', 'hang_count',
'plugin_count', 'content_count',
'first_report_exact', 'versions',
'percentOfTotal', 'startup_percent'], aRow))
aRowAsDict['currentRank'] = rank
aRowAsDict['first_report'] = (
aRowAsDict['first_report_exact'].strftime('%Y-%m-%d'))
aRowAsDict['first_report_exact'] = (
aRowAsDict['first_report_exact'].strftime('%Y-%m-%d %H:%M:%S'))
versions = aRowAsDict['versions']
aRowAsDict['versions_count'] = len(versions)
aRowAsDict['versions'] = ', '.join(versions)
try:
(aRowAsDict['previousRank'],
aRowAsDict['previousPercentOfTotal']) = previousList.find(
aRowAsDict['signature'])
aRowAsDict['changeInRank'] = aRowAsDict['previousRank'] - rank
aRowAsDict['changeInPercentOfTotal'] = (
aRowAsDict['percentOfTotal'] -
aRowAsDict['previousPercentOfTotal'])
except KeyError:
aRowAsDict['previousRank'] = "null"
aRowAsDict['previousPercentOfTotal'] = "null"
aRowAsDict['changeInRank'] = "new"
aRowAsDict['changeInPercentOfTotal'] = "new"
currentListOfTopCrashers.append(aRowAsDict)
listOfTopCrasherLists.append(currentListOfTopCrashers)
return listOfTopCrasherLists[1:]
def latestEntryBeforeOrEqualTo(aCursor, aDate, product, version):
"""
Retrieve the closest report date containing the provided product and
version that does not exceed the provided date.
We append a day to the max(report_date) to ensure that we
capture reports to the end of the day, not the beginning.
"""
sql = """
SELECT
max(report_date) + 1
FROM
tcbs JOIN product_versions USING (product_version_id)
WHERE
tcbs.report_date <= %s
AND product_name = %s
AND version_string = %s
"""
try:
result = db.singleValueSql(aCursor, sql, (aDate, product, version))
except:
result = None
return result or aDate
def twoPeriodTopCrasherComparison(
databaseCursor, context,
closestEntryFunction=latestEntryBeforeOrEqualTo,
listOfTopCrashersFunction=getListOfTopCrashersBySignature):
try:
context['logger'].debug('entered twoPeriodTopCrasherComparison')
except KeyError:
context['logger'] = util.SilentFakeLogger()
assertions = ['to_date', 'duration', 'product', 'version']
for param in assertions:
assert param in context, (
"%s is missing from the configuration" % param)
context['numberOfComparisonPoints'] = 2
if not context['limit']:
context['limit'] = 100
#context['logger'].debug('about to latestEntryBeforeOrEqualTo')
context['to_date'] = closestEntryFunction(databaseCursor,
context['to_date'],
context['product'],
context['version'])
context['logger'].debug('New to_date: %s' % context['to_date'])
context['startDate'] = context.to_date - (context.duration *
context.numberOfComparisonPoints)
#context['logger'].debug('after %s' % context)
listOfTopCrashers = listOfListsWithChangeInRank(
rangeOfQueriesGenerator(
databaseCursor,
context,
listOfTopCrashersFunction))[0]
#context['logger'].debug('listOfTopCrashers %s' % listOfTopCrashers)
totalNumberOfCrashes = totalPercentOfTotal = 0
for x in listOfTopCrashers:
totalNumberOfCrashes += x.get('count', 0)
totalPercentOfTotal += x.get('percentOfTotal', 0)
result = {
'crashes': listOfTopCrashers,
'start_date': datetimeutil.date_to_string(
context.to_date - context.duration
),
'end_date': datetimeutil.date_to_string(context.to_date),
'totalNumberOfCrashes': totalNumberOfCrashes,
'totalPercentage': totalPercentOfTotal,
}
#logger.debug("about to return %s", result)
return result