blob: 491aa52161518c5db2ed886435f7dced49b52b99 [file] [log] [blame]
jadmanski430dca92008-12-16 20:56:53 +00001import os, pickle, datetime, itertools, operator
showard35444862008-08-07 22:35:30 +00002from django.db import models as dbmodels
showard35444862008-08-07 22:35:30 +00003from autotest_lib.frontend.afe import rpc_utils, model_logic
showard64a95952010-01-13 21:27:16 +00004from autotest_lib.frontend.afe import models as afe_models, readonly_connection
showard250d84d2010-01-12 21:59:48 +00005from autotest_lib.frontend.tko import models, tko_rpc_utils, graphing_utils
6from autotest_lib.frontend.tko import preconfigs
showard35444862008-08-07 22:35:30 +00007
8# table/spreadsheet view support
9
10def get_test_views(**filter_data):
11 return rpc_utils.prepare_for_serialization(
12 models.TestView.list_objects(filter_data))
13
14
15def get_num_test_views(**filter_data):
16 return models.TestView.query_count(filter_data)
17
18
showard8bfb5cb2009-10-07 20:49:15 +000019def get_group_counts(group_by, header_groups=None, fixed_headers=None,
showard8b0ea222009-12-23 19:23:03 +000020 extra_select_fields=None, **filter_data):
showard35444862008-08-07 22:35:30 +000021 """
22 Queries against TestView grouping by the specified fields and computings
23 counts for each group.
24 * group_by should be a list of field names.
25 * extra_select_fields can be used to specify additional fields to select
26 (usually for aggregate functions).
27 * header_groups can be used to get lists of unique combinations of group
28 fields. It should be a list of tuples of fields from group_by. It's
29 primarily for use by the spreadsheet view.
showardf2489522008-10-23 23:08:00 +000030 * fixed_headers can map header fields to lists of values. the header will
31 guaranteed to return exactly those value. this does not work together
32 with header_groups.
showard35444862008-08-07 22:35:30 +000033
34 Returns a dictionary with two keys:
35 * header_values contains a list of lists, one for each header group in
36 header_groups. Each list contains all the values for the corresponding
37 header group as tuples.
38 * groups contains a list of dicts, one for each row. Each dict contains
39 keys for each of the group_by fields, plus a 'group_count' key for the
40 total count in the group, plus keys for each of the extra_select_fields.
41 The keys for the extra_select_fields are determined by the "AS" alias of
42 the field.
43 """
showard8b0ea222009-12-23 19:23:03 +000044 query = models.TestView.objects.get_query_set_with_joins(filter_data)
showard8bfb5cb2009-10-07 20:49:15 +000045 # don't apply presentation yet, since we have extra selects to apply
46 query = models.TestView.query_objects(filter_data, initial_query=query,
47 apply_presentation=False)
showard7c199df2008-10-03 10:17:15 +000048 count_alias, count_sql = models.TestView.objects.get_count_sql(query)
showard8bfb5cb2009-10-07 20:49:15 +000049 query = query.extra(select={count_alias: count_sql})
50 if extra_select_fields:
51 query = query.extra(select=extra_select_fields)
showard8bfb5cb2009-10-07 20:49:15 +000052 query = models.TestView.apply_presentation(query, filter_data)
showard35444862008-08-07 22:35:30 +000053
showard8a6eb0c2008-10-01 11:38:59 +000054 group_processor = tko_rpc_utils.GroupDataProcessor(query, group_by,
showard8bfb5cb2009-10-07 20:49:15 +000055 header_groups or [],
56 fixed_headers or {})
showard8a6eb0c2008-10-01 11:38:59 +000057 group_processor.process_group_dicts()
58 return rpc_utils.prepare_for_serialization(group_processor.get_info_dict())
showard35444862008-08-07 22:35:30 +000059
60
61def get_num_groups(group_by, **filter_data):
62 """
63 Gets the count of unique groups with the given grouping fields.
64 """
showardd2b0c882009-10-19 18:34:11 +000065 query = models.TestView.objects.get_query_set_with_joins(filter_data)
66 query = models.TestView.query_objects(filter_data, initial_query=query)
showard35444862008-08-07 22:35:30 +000067 return models.TestView.objects.get_num_groups(query, group_by)
68
69
showard8c9b8392008-09-30 10:38:21 +000070def get_status_counts(group_by, header_groups=[], fixed_headers={},
showard8b0ea222009-12-23 19:23:03 +000071 **filter_data):
showard35444862008-08-07 22:35:30 +000072 """
73 Like get_group_counts, but also computes counts of passed, complete (and
74 valid), and incomplete tests, stored in keys "pass_count', 'complete_count',
75 and 'incomplete_count', respectively.
76 """
showard8c9b8392008-09-30 10:38:21 +000077 return get_group_counts(group_by, header_groups=header_groups,
78 fixed_headers=fixed_headers,
showard7c199df2008-10-03 10:17:15 +000079 extra_select_fields=tko_rpc_utils.STATUS_FIELDS,
80 **filter_data)
showard35444862008-08-07 22:35:30 +000081
82
showard8a6eb0c2008-10-01 11:38:59 +000083def get_latest_tests(group_by, header_groups=[], fixed_headers={},
showard8b0ea222009-12-23 19:23:03 +000084 extra_info=[], **filter_data):
showard8a6eb0c2008-10-01 11:38:59 +000085 """
86 Similar to get_status_counts, but return only the latest test result per
87 group. It still returns the same information (i.e. with pass count etc.)
showard79097322010-01-20 01:12:25 +000088 for compatibility. It includes an additional field "test_idx" with each
89 group.
showard77401f32009-05-26 19:34:05 +000090 @param extra_info a list containing the field names that should be returned
91 with each cell. The fields are returned in the extra_info
92 field of the return dictionary.
showard8a6eb0c2008-10-01 11:38:59 +000093 """
94 # find latest test per group
showard79097322010-01-20 01:12:25 +000095 initial_query = models.TestView.objects.get_query_set_with_joins(
96 filter_data)
97 query = models.TestView.query_objects(filter_data,
98 initial_query=initial_query,
showard8bfb5cb2009-10-07 20:49:15 +000099 apply_presentation=False)
showard763fd242009-12-10 21:40:16 +0000100 query = query.exclude(status__in=tko_rpc_utils._INVALID_STATUSES)
showard8bfb5cb2009-10-07 20:49:15 +0000101 query = query.extra(
102 select={'latest_test_idx' : 'MAX(%s)' %
103 models.TestView.objects.get_key_on_this_table('test_idx')})
showard8bfb5cb2009-10-07 20:49:15 +0000104 query = models.TestView.apply_presentation(query, filter_data)
showard8a6eb0c2008-10-01 11:38:59 +0000105
106 group_processor = tko_rpc_utils.GroupDataProcessor(query, group_by,
107 header_groups,
showard8bfb5cb2009-10-07 20:49:15 +0000108 fixed_headers)
showard8a6eb0c2008-10-01 11:38:59 +0000109 group_processor.process_group_dicts()
110 info = group_processor.get_info_dict()
111
112 # fetch full info for these tests so we can access their statuses
113 all_test_ids = [group['latest_test_idx'] for group in info['groups']]
showard79097322010-01-20 01:12:25 +0000114 test_views = initial_query.in_bulk(all_test_ids)
showard8a6eb0c2008-10-01 11:38:59 +0000115
116 for group_dict in info['groups']:
117 test_idx = group_dict.pop('latest_test_idx')
118 group_dict['test_idx'] = test_idx
showard77401f32009-05-26 19:34:05 +0000119 test_view = test_views[test_idx]
120
121 tko_rpc_utils.add_status_counts(group_dict, test_view.status)
122 group_dict['extra_info'] = []
123 for field in extra_info:
124 group_dict['extra_info'].append(getattr(test_view, field))
125
126 return rpc_utils.prepare_for_serialization(info)
showard8a6eb0c2008-10-01 11:38:59 +0000127
128
showard35444862008-08-07 22:35:30 +0000129def get_job_ids(**filter_data):
130 """
131 Returns AFE job IDs for all tests matching the filters.
132 """
133 query = models.TestView.query_objects(filter_data)
134 job_ids = set()
135 for test_view in query.values('job_tag').distinct():
136 # extract job ID from tag
showardec281562009-02-07 02:10:27 +0000137 first_tag_component = test_view['job_tag'].split('-')[0]
138 try:
139 job_id = int(first_tag_component)
140 job_ids.add(job_id)
141 except ValueError:
142 # a nonstandard job tag, i.e. from contributed results
143 pass
showard35444862008-08-07 22:35:30 +0000144 return list(job_ids)
145
146
showarde732ee72008-09-23 19:15:43 +0000147# test detail view
148
jadmanski430dca92008-12-16 20:56:53 +0000149def _attributes_to_dict(attribute_list):
showardf8b19042009-05-12 17:22:49 +0000150 return dict((attribute.attribute, attribute.value)
151 for attribute in attribute_list)
jadmanski430dca92008-12-16 20:56:53 +0000152
153
154def _iteration_attributes_to_dict(attribute_list):
showardf8b19042009-05-12 17:22:49 +0000155 iter_keyfunc = operator.attrgetter('iteration')
jadmanski430dca92008-12-16 20:56:53 +0000156 attribute_list.sort(key=iter_keyfunc)
157 iterations = {}
158 for key, group in itertools.groupby(attribute_list, iter_keyfunc):
159 iterations[key] = _attributes_to_dict(group)
160 return iterations
161
162
showardf8b19042009-05-12 17:22:49 +0000163def _format_iteration_keyvals(test):
164 iteration_attr = _iteration_attributes_to_dict(test.iteration_attributes)
165 iteration_perf = _iteration_attributes_to_dict(test.iteration_results)
166
167 all_iterations = iteration_attr.keys() + iteration_perf.keys()
168 max_iterations = max(all_iterations + [0])
169
170 # merge the iterations into a single list of attr & perf dicts
171 return [{'attr': iteration_attr.get(index, {}),
172 'perf': iteration_perf.get(index, {})}
173 for index in xrange(1, max_iterations + 1)]
174
175
showarde732ee72008-09-23 19:15:43 +0000176def get_detailed_test_views(**filter_data):
177 test_views = models.TestView.list_objects(filter_data)
showardf8b19042009-05-12 17:22:49 +0000178 tests_by_id = models.Test.objects.in_bulk([test_view['test_idx']
179 for test_view in test_views])
180 tests = tests_by_id.values()
181 models.Test.objects.populate_relationships(tests, models.TestAttribute,
182 'attributes')
183 models.Test.objects.populate_relationships(tests, models.IterationAttribute,
184 'iteration_attributes')
185 models.Test.objects.populate_relationships(tests, models.IterationResult,
186 'iteration_results')
187 models.Test.objects.populate_relationships(tests, models.TestLabel,
188 'labels')
showarde732ee72008-09-23 19:15:43 +0000189 for test_view in test_views:
showardf8b19042009-05-12 17:22:49 +0000190 test = tests_by_id[test_view['test_idx']]
191 test_view['attributes'] = _attributes_to_dict(test.attributes)
192 test_view['iterations'] = _format_iteration_keyvals(test)
193 test_view['labels'] = [label.name for label in test.labels]
showarde732ee72008-09-23 19:15:43 +0000194 return rpc_utils.prepare_for_serialization(test_views)
195
showard35444862008-08-07 22:35:30 +0000196# graphing view support
197
198def get_hosts_and_tests():
199 """\
200 Gets every host that has had a benchmark run on it. Additionally, also
201 gets a dictionary mapping the host names to the benchmarks.
202 """
203
204 host_info = {}
205 q = (dbmodels.Q(test_name__startswith='kernbench') |
206 dbmodels.Q(test_name__startswith='dbench') |
207 dbmodels.Q(test_name__startswith='tbench') |
208 dbmodels.Q(test_name__startswith='unixbench') |
209 dbmodels.Q(test_name__startswith='iozone'))
210 test_query = models.TestView.objects.filter(q).values(
211 'test_name', 'hostname', 'machine_idx').distinct()
212 for result_dict in test_query:
213 hostname = result_dict['hostname']
214 test = result_dict['test_name']
215 machine_idx = result_dict['machine_idx']
216 host_info.setdefault(hostname, {})
217 host_info[hostname].setdefault('tests', [])
218 host_info[hostname]['tests'].append(test)
219 host_info[hostname]['id'] = machine_idx
220 return rpc_utils.prepare_for_serialization(host_info)
221
222
showardfbdab0b2009-04-29 19:49:50 +0000223def create_metrics_plot(queries, plot, invert, drilldown_callback,
224 normalize=None):
225 return graphing_utils.create_metrics_plot(
226 queries, plot, invert, normalize, drilldown_callback=drilldown_callback)
showardce12f552008-09-19 00:48:59 +0000227
228
showardfbdab0b2009-04-29 19:49:50 +0000229def create_qual_histogram(query, filter_string, interval, drilldown_callback):
230 return graphing_utils.create_qual_histogram(
231 query, filter_string, interval, drilldown_callback=drilldown_callback)
showardce12f552008-09-19 00:48:59 +0000232
233
showarde5ae1652009-02-11 23:37:20 +0000234# TODO(showard) - this extremely generic RPC is used only by one place in the
235# client. We should come up with a more opaque RPC for that place to call and
236# get rid of this.
showardce12f552008-09-19 00:48:59 +0000237def execute_query_with_param(query, param):
showard56e93772008-10-06 10:06:22 +0000238 cursor = readonly_connection.connection().cursor()
showardce12f552008-09-19 00:48:59 +0000239 cursor.execute(query, param)
240 return cursor.fetchall()
241
242
showardce12f552008-09-19 00:48:59 +0000243def get_preconfig(name, type):
showarde5ae1652009-02-11 23:37:20 +0000244 return preconfigs.manager.get_preconfig(name, type)
showardce12f552008-09-19 00:48:59 +0000245
246
247def get_embedding_id(url_token, graph_type, params):
248 try:
249 model = models.EmbeddedGraphingQuery.objects.get(url_token=url_token)
250 except models.EmbeddedGraphingQuery.DoesNotExist:
251 params_str = pickle.dumps(params)
252 now = datetime.datetime.now()
253 model = models.EmbeddedGraphingQuery(url_token=url_token,
254 graph_type=graph_type,
255 params=params_str,
256 last_updated=now)
257 model.cached_png = graphing_utils.create_embedded_plot(model,
258 now.ctime())
259 model.save()
260
261 return model.id
262
263
264def get_embedded_query_url_token(id):
265 model = models.EmbeddedGraphingQuery.objects.get(id=id)
266 return model.url_token
267
268
showard35444862008-08-07 22:35:30 +0000269# test label management
270
271def add_test_label(name, description=None):
272 return models.TestLabel.add_object(name=name, description=description).id
273
274
275def modify_test_label(label_id, **data):
276 models.TestLabel.smart_get(label_id).update_object(data)
277
278
279def delete_test_label(label_id):
280 models.TestLabel.smart_get(label_id).delete()
281
282
283def get_test_labels(**filter_data):
284 return rpc_utils.prepare_for_serialization(
285 models.TestLabel.list_objects(filter_data))
286
287
288def get_test_labels_for_tests(**test_filter_data):
showard02813502008-08-20 20:52:56 +0000289 label_ids = models.TestView.objects.query_test_label_ids(test_filter_data)
290 labels = models.TestLabel.list_objects({'id__in' : label_ids})
showard35444862008-08-07 22:35:30 +0000291 return rpc_utils.prepare_for_serialization(labels)
292
293
294def test_label_add_tests(label_id, **test_filter_data):
showard02813502008-08-20 20:52:56 +0000295 test_ids = models.TestView.objects.query_test_ids(test_filter_data)
296 models.TestLabel.smart_get(label_id).tests.add(*test_ids)
showard35444862008-08-07 22:35:30 +0000297
298
299def test_label_remove_tests(label_id, **test_filter_data):
showard02813502008-08-20 20:52:56 +0000300 label = models.TestLabel.smart_get(label_id)
301
302 # only include tests that actually have this label
303 extra_where = test_filter_data.get('extra_where', '')
304 if extra_where:
305 extra_where = '(' + extra_where + ') AND '
showardeab66ce2009-12-23 00:03:56 +0000306 extra_where += 'tko_test_labels.id = %s' % label.id
showard02813502008-08-20 20:52:56 +0000307 test_filter_data['extra_where'] = extra_where
308 test_ids = models.TestView.objects.query_test_ids(test_filter_data)
309
310 label.tests.remove(*test_ids)
showard35444862008-08-07 22:35:30 +0000311
312
showardf8b19042009-05-12 17:22:49 +0000313# user-created test attributes
314
315def set_test_attribute(attribute, value, **test_filter_data):
316 """
317 * attribute - string name of attribute
318 * value - string, or None to delete an attribute
319 * test_filter_data - filter data to apply to TestView to choose tests to act
320 upon
321 """
322 assert test_filter_data # disallow accidental actions on all hosts
323 test_ids = models.TestView.objects.query_test_ids(test_filter_data)
324 tests = models.Test.objects.in_bulk(test_ids)
325
326 for test in tests.itervalues():
327 test.set_or_delete_attribute(attribute, value)
328
329
showard35444862008-08-07 22:35:30 +0000330# saved queries
331
332def get_saved_queries(**filter_data):
333 return rpc_utils.prepare_for_serialization(
334 models.SavedQuery.list_objects(filter_data))
335
336
337def add_saved_query(name, url_token):
338 name = name.strip()
showard64a95952010-01-13 21:27:16 +0000339 owner = afe_models.User.current_user().login
showard35444862008-08-07 22:35:30 +0000340 existing_list = list(models.SavedQuery.objects.filter(owner=owner,
341 name=name))
342 if existing_list:
343 query_object = existing_list[0]
344 query_object.url_token = url_token
345 query_object.save()
346 return query_object.id
347
348 return models.SavedQuery.add_object(owner=owner, name=name,
349 url_token=url_token).id
350
351
352def delete_saved_queries(id_list):
showard64a95952010-01-13 21:27:16 +0000353 user = afe_models.User.current_user().login
showard35444862008-08-07 22:35:30 +0000354 query = models.SavedQuery.objects.filter(id__in=id_list, owner=user)
355 if query.count() == 0:
356 raise model_logic.ValidationError('No such queries found for this user')
357 query.delete()
358
359
360# other
showardb7a52fd2009-04-27 20:10:56 +0000361def get_motd():
362 return rpc_utils.get_motd()
showard35444862008-08-07 22:35:30 +0000363
showard35444862008-08-07 22:35:30 +0000364
365def get_static_data():
366 result = {}
367 group_fields = []
368 for field in models.TestView.group_fields:
369 if field in models.TestView.extra_fields:
370 name = models.TestView.extra_fields[field]
371 else:
372 name = models.TestView.get_field_dict()[field].verbose_name
373 group_fields.append((name.capitalize(), field))
374 model_fields = [(field.verbose_name.capitalize(), field.column)
375 for field in models.TestView._meta.fields]
376 extra_fields = [(field_name.capitalize(), field_sql)
377 for field_sql, field_name
378 in models.TestView.extra_fields.iteritems()]
showardce12f552008-09-19 00:48:59 +0000379
380 benchmark_key = {
381 'kernbench' : 'elapsed',
382 'dbench' : 'throughput',
383 'tbench' : 'throughput',
384 'unixbench' : 'score',
385 'iozone' : '32768-4096-fwrite'
386 }
387
showardeab66ce2009-12-23 00:03:56 +0000388 tko_perf_view = [
showardce12f552008-09-19 00:48:59 +0000389 ['Test Index', 'test_idx'],
390 ['Job Index', 'job_idx'],
391 ['Test Name', 'test_name'],
392 ['Subdirectory', 'subdir'],
393 ['Kernel Index', 'kernel_idx'],
394 ['Status Index', 'status_idx'],
395 ['Reason', 'reason'],
396 ['Host Index', 'machine_idx'],
397 ['Test Started Time', 'test_started_time'],
398 ['Test Finished Time', 'test_finished_time'],
399 ['Job Tag', 'job_tag'],
400 ['Job Name', 'job_name'],
401 ['Owner', 'job_owner'],
402 ['Job Queued Time', 'job_queued_time'],
403 ['Job Started Time', 'job_started_time'],
404 ['Job Finished Time', 'job_finished_time'],
405 ['Hostname', 'hostname'],
406 ['Platform', 'platform'],
407 ['Machine Owner', 'machine_owner'],
408 ['Kernel Hash', 'kernel_hash'],
409 ['Kernel Base', 'kernel_base'],
410 ['Kernel', 'kernel'],
411 ['Status', 'status'],
412 ['Iteration Number', 'iteration'],
413 ['Performance Keyval (Key)', 'iteration_key'],
414 ['Performance Keyval (Value)', 'iteration_value'],
415 ]
showard35444862008-08-07 22:35:30 +0000416
417 result['group_fields'] = sorted(group_fields)
418 result['all_fields'] = sorted(model_fields + extra_fields)
419 result['test_labels'] = get_test_labels(sort_by=['name'])
showard250d84d2010-01-12 21:59:48 +0000420 result['current_user'] = rpc_utils.prepare_for_serialization(
showard64a95952010-01-13 21:27:16 +0000421 afe_models.User.current_user().get_object_dict())
showardce12f552008-09-19 00:48:59 +0000422 result['benchmark_key'] = benchmark_key
showardeab66ce2009-12-23 00:03:56 +0000423 result['tko_perf_view'] = tko_perf_view
424 result['tko_test_view'] = model_fields
showarde5ae1652009-02-11 23:37:20 +0000425 result['preconfigs'] = preconfigs.manager.all_preconfigs()
showardedd58972009-04-16 03:08:27 +0000426 result['motd'] = rpc_utils.get_motd()
showardce12f552008-09-19 00:48:59 +0000427
showard35444862008-08-07 22:35:30 +0000428 return result