blob: 3e617d59e67f52cd97fdf2c538876bc09c3daa8a [file] [log] [blame]
mblighe8819cd2008-02-15 16:48:40 +00001"""\
2Utility functions for rpc_interface.py. We keep them in a separate file so that
3only RPC interface functions go into that file.
4"""
5
6__author__ = 'showard@google.com (Steve Howard)'
7
showard26b7ec72009-12-21 22:43:57 +00008import datetime, os, sys
showard3d6ae112009-05-02 00:45:48 +00009import django.http
showarda5288b42009-07-28 20:06:08 +000010from autotest_lib.frontend.afe import models, model_logic
mblighe8819cd2008-02-15 16:48:40 +000011
showarda62866b2008-07-28 21:27:41 +000012NULL_DATETIME = datetime.datetime.max
13NULL_DATE = datetime.date.max
14
mblighe8819cd2008-02-15 16:48:40 +000015def prepare_for_serialization(objects):
jadmanski0afbb632008-06-06 21:10:57 +000016 """
17 Prepare Python objects to be returned via RPC.
18 """
19 if (isinstance(objects, list) and len(objects) and
20 isinstance(objects[0], dict) and 'id' in objects[0]):
21 objects = gather_unique_dicts(objects)
22 return _prepare_data(objects)
showardb8d34242008-04-25 18:11:16 +000023
24
showardc92da832009-04-07 18:14:34 +000025def prepare_rows_as_nested_dicts(query, nested_dict_column_names):
26 """
27 Prepare a Django query to be returned via RPC as a sequence of nested
28 dictionaries.
29
30 @param query - A Django model query object with a select_related() method.
31 @param nested_dict_column_names - A list of column/attribute names for the
32 rows returned by query to expand into nested dictionaries using
33 their get_object_dict() method when not None.
34
35 @returns An list suitable to returned in an RPC.
36 """
37 all_dicts = []
38 for row in query.select_related():
39 row_dict = row.get_object_dict()
40 for column in nested_dict_column_names:
41 if row_dict[column] is not None:
42 row_dict[column] = getattr(row, column).get_object_dict()
43 all_dicts.append(row_dict)
44 return prepare_for_serialization(all_dicts)
45
46
showardb8d34242008-04-25 18:11:16 +000047def _prepare_data(data):
jadmanski0afbb632008-06-06 21:10:57 +000048 """
49 Recursively process data structures, performing necessary type
50 conversions to values in data to allow for RPC serialization:
51 -convert datetimes to strings
showard2b9a88b2008-06-13 20:55:03 +000052 -convert tuples and sets to lists
jadmanski0afbb632008-06-06 21:10:57 +000053 """
54 if isinstance(data, dict):
55 new_data = {}
56 for key, value in data.iteritems():
57 new_data[key] = _prepare_data(value)
58 return new_data
showard2b9a88b2008-06-13 20:55:03 +000059 elif (isinstance(data, list) or isinstance(data, tuple) or
60 isinstance(data, set)):
jadmanski0afbb632008-06-06 21:10:57 +000061 return [_prepare_data(item) for item in data]
showard98659972008-07-17 17:00:07 +000062 elif isinstance(data, datetime.date):
showarda62866b2008-07-28 21:27:41 +000063 if data is NULL_DATETIME or data is NULL_DATE:
64 return None
jadmanski0afbb632008-06-06 21:10:57 +000065 return str(data)
66 else:
67 return data
mblighe8819cd2008-02-15 16:48:40 +000068
69
showard3d6ae112009-05-02 00:45:48 +000070def raw_http_response(response_data, content_type=None):
71 response = django.http.HttpResponse(response_data, mimetype=content_type)
72 response['Content-length'] = str(len(response.content))
73 return response
74
75
showardb0dfb9f2008-06-06 18:08:02 +000076def gather_unique_dicts(dict_iterable):
jadmanski0afbb632008-06-06 21:10:57 +000077 """\
78 Pick out unique objects (by ID) from an iterable of object dicts.
79 """
80 id_set = set()
81 result = []
82 for obj in dict_iterable:
83 if obj['id'] not in id_set:
84 id_set.add(obj['id'])
85 result.append(obj)
86 return result
showardb0dfb9f2008-06-06 18:08:02 +000087
88
mblighe8819cd2008-02-15 16:48:40 +000089def extra_job_filters(not_yet_run=False, running=False, finished=False):
jadmanski0afbb632008-06-06 21:10:57 +000090 """\
91 Generate a SQL WHERE clause for job status filtering, and return it in
92 a dict of keyword args to pass to query.extra(). No more than one of
93 the parameters should be passed as True.
showard6c65d252009-10-01 18:45:22 +000094 * not_yet_run: all HQEs are Queued
95 * finished: all HQEs are complete
96 * running: everything else
jadmanski0afbb632008-06-06 21:10:57 +000097 """
98 assert not ((not_yet_run and running) or
99 (not_yet_run and finished) or
100 (running and finished)), ('Cannot specify more than one '
101 'filter to this function')
showard6c65d252009-10-01 18:45:22 +0000102
showardeab66ce2009-12-23 00:03:56 +0000103 not_queued = ('(SELECT job_id FROM afe_host_queue_entries '
104 'WHERE status != "%s")'
showard6c65d252009-10-01 18:45:22 +0000105 % models.HostQueueEntry.Status.QUEUED)
showardeab66ce2009-12-23 00:03:56 +0000106 not_finished = ('(SELECT job_id FROM afe_host_queue_entries '
107 'WHERE not complete)')
showard6c65d252009-10-01 18:45:22 +0000108
jadmanski0afbb632008-06-06 21:10:57 +0000109 if not_yet_run:
showard6c65d252009-10-01 18:45:22 +0000110 where = ['id NOT IN ' + not_queued]
jadmanski0afbb632008-06-06 21:10:57 +0000111 elif running:
showard6c65d252009-10-01 18:45:22 +0000112 where = ['(id IN %s) AND (id IN %s)' % (not_queued, not_finished)]
jadmanski0afbb632008-06-06 21:10:57 +0000113 elif finished:
showard6c65d252009-10-01 18:45:22 +0000114 where = ['id NOT IN ' + not_finished]
jadmanski0afbb632008-06-06 21:10:57 +0000115 else:
showard10f41672009-05-13 21:28:25 +0000116 return {}
jadmanski0afbb632008-06-06 21:10:57 +0000117 return {'where': where}
mblighe8819cd2008-02-15 16:48:40 +0000118
119
showard87cc38f2009-08-20 23:37:04 +0000120def extra_host_filters(multiple_labels=()):
jadmanski0afbb632008-06-06 21:10:57 +0000121 """\
122 Generate SQL WHERE clauses for matching hosts in an intersection of
123 labels.
124 """
125 extra_args = {}
showardeab66ce2009-12-23 00:03:56 +0000126 where_str = ('afe_hosts.id in (select host_id from afe_hosts_labels '
jadmanski0afbb632008-06-06 21:10:57 +0000127 'where label_id=%s)')
128 extra_args['where'] = [where_str] * len(multiple_labels)
129 extra_args['params'] = [models.Label.smart_get(label).id
130 for label in multiple_labels]
131 return extra_args
showard8e3aa5e2008-04-08 19:42:32 +0000132
133
showard87cc38f2009-08-20 23:37:04 +0000134def get_host_query(multiple_labels, exclude_only_if_needed_labels,
showard8aa84fc2009-09-16 17:17:55 +0000135 exclude_atomic_group_hosts, valid_only, filter_data):
136 if valid_only:
137 query = models.Host.valid_objects.all()
138 else:
139 query = models.Host.objects.all()
140
showard43a3d262008-11-12 18:17:05 +0000141 if exclude_only_if_needed_labels:
142 only_if_needed_labels = models.Label.valid_objects.filter(
143 only_if_needed=True)
showardf7eac6f2008-11-13 21:18:01 +0000144 if only_if_needed_labels.count() > 0:
showard87cc38f2009-08-20 23:37:04 +0000145 only_if_needed_ids = ','.join(
146 str(label['id'])
147 for label in only_if_needed_labels.values('id'))
showardf7eac6f2008-11-13 21:18:01 +0000148 query = models.Host.objects.add_join(
showardeab66ce2009-12-23 00:03:56 +0000149 query, 'afe_hosts_labels', join_key='host_id',
150 join_condition=('afe_hosts_labels_exclude_OIN.label_id IN (%s)'
showard87cc38f2009-08-20 23:37:04 +0000151 % only_if_needed_ids),
152 suffix='_exclude_OIN', exclude=True)
showard8aa84fc2009-09-16 17:17:55 +0000153
showard87cc38f2009-08-20 23:37:04 +0000154 if exclude_atomic_group_hosts:
155 atomic_group_labels = models.Label.valid_objects.filter(
156 atomic_group__isnull=False)
157 if atomic_group_labels.count() > 0:
158 atomic_group_label_ids = ','.join(
159 str(atomic_group['id'])
160 for atomic_group in atomic_group_labels.values('id'))
161 query = models.Host.objects.add_join(
showardeab66ce2009-12-23 00:03:56 +0000162 query, 'afe_hosts_labels', join_key='host_id',
163 join_condition=(
164 'afe_hosts_labels_exclude_AG.label_id IN (%s)'
165 % atomic_group_label_ids),
showard87cc38f2009-08-20 23:37:04 +0000166 suffix='_exclude_AG', exclude=True)
showard8aa84fc2009-09-16 17:17:55 +0000167
168 assert 'extra_args' not in filter_data
169 filter_data['extra_args'] = extra_host_filters(multiple_labels)
showard43a3d262008-11-12 18:17:05 +0000170 return models.Host.query_objects(filter_data, initial_query=query)
171
172
showard8fd58242008-03-10 21:29:07 +0000173class InconsistencyException(Exception):
jadmanski0afbb632008-06-06 21:10:57 +0000174 'Raised when a list of objects does not have a consistent value'
showard8fd58242008-03-10 21:29:07 +0000175
176
177def get_consistent_value(objects, field):
mblighc5ddfd12008-08-04 17:15:00 +0000178 if not objects:
179 # well a list of nothing is consistent
180 return None
181
jadmanski0afbb632008-06-06 21:10:57 +0000182 value = getattr(objects[0], field)
183 for obj in objects:
184 this_value = getattr(obj, field)
185 if this_value != value:
186 raise InconsistencyException(objects[0], obj)
187 return value
showard8fd58242008-03-10 21:29:07 +0000188
189
showard2b9a88b2008-06-13 20:55:03 +0000190def prepare_generate_control_file(tests, kernel, label, profilers):
jadmanski0afbb632008-06-06 21:10:57 +0000191 test_objects = [models.Test.smart_get(test) for test in tests]
showard2b9a88b2008-06-13 20:55:03 +0000192 profiler_objects = [models.Profiler.smart_get(profiler)
193 for profiler in profilers]
jadmanski0afbb632008-06-06 21:10:57 +0000194 # ensure tests are all the same type
195 try:
196 test_type = get_consistent_value(test_objects, 'test_type')
197 except InconsistencyException, exc:
198 test1, test2 = exc.args
mblighec5546d2008-06-16 16:51:28 +0000199 raise model_logic.ValidationError(
jadmanski0afbb632008-06-06 21:10:57 +0000200 {'tests' : 'You cannot run both server- and client-side '
201 'tests together (tests %s and %s differ' % (
202 test1.name, test2.name)})
showard8fd58242008-03-10 21:29:07 +0000203
jadmanski0afbb632008-06-06 21:10:57 +0000204 is_server = (test_type == models.Test.Types.SERVER)
showard14374b12009-01-31 00:11:54 +0000205 if test_objects:
206 synch_count = max(test.sync_count for test in test_objects)
207 else:
208 synch_count = 1
jadmanski0afbb632008-06-06 21:10:57 +0000209 if label:
210 label = models.Label.smart_get(label)
mblighe8819cd2008-02-15 16:48:40 +0000211
showard989f25d2008-10-01 11:38:11 +0000212 dependencies = set(label.name for label
213 in models.Label.objects.filter(test__in=test_objects))
214
showard2bab8f42008-11-12 18:15:22 +0000215 cf_info = dict(is_server=is_server, synch_count=synch_count,
216 dependencies=list(dependencies))
217 return cf_info, test_objects, profiler_objects, label
showard989f25d2008-10-01 11:38:11 +0000218
219
220def check_job_dependencies(host_objects, job_dependencies):
221 """
222 Check that a set of machines satisfies a job's dependencies.
223 host_objects: list of models.Host objects
224 job_dependencies: list of names of labels
225 """
226 # check that hosts satisfy dependencies
227 host_ids = [host.id for host in host_objects]
228 hosts_in_job = models.Host.objects.filter(id__in=host_ids)
229 ok_hosts = hosts_in_job
230 for index, dependency in enumerate(job_dependencies):
showarda5288b42009-07-28 20:06:08 +0000231 ok_hosts = ok_hosts.filter(labels__name=dependency)
showard989f25d2008-10-01 11:38:11 +0000232 failing_hosts = (set(host.hostname for host in host_objects) -
233 set(host.hostname for host in ok_hosts))
234 if failing_hosts:
235 raise model_logic.ValidationError(
236 {'hosts' : 'Host(s) failed to meet job dependencies: ' +
237 ', '.join(failing_hosts)})
238
showard2bab8f42008-11-12 18:15:22 +0000239
240def _execution_key_for(host_queue_entry):
241 return (host_queue_entry.job.id, host_queue_entry.execution_subdir)
242
243
244def check_abort_synchronous_jobs(host_queue_entries):
245 # ensure user isn't aborting part of a synchronous autoserv execution
246 count_per_execution = {}
247 for queue_entry in host_queue_entries:
248 key = _execution_key_for(queue_entry)
249 count_per_execution.setdefault(key, 0)
250 count_per_execution[key] += 1
251
252 for queue_entry in host_queue_entries:
253 if not queue_entry.execution_subdir:
254 continue
255 execution_count = count_per_execution[_execution_key_for(queue_entry)]
256 if execution_count < queue_entry.job.synch_count:
mbligh1ef218d2009-08-03 16:57:56 +0000257 raise model_logic.ValidationError(
258 {'' : 'You cannot abort part of a synchronous job execution '
259 '(%d/%s), %d included, %d expected'
260 % (queue_entry.job.id, queue_entry.execution_subdir,
261 execution_count, queue_entry.job.synch_count)})
showard8fbae652009-01-20 23:23:10 +0000262
263
showardc92da832009-04-07 18:14:34 +0000264def check_atomic_group_create_job(synch_count, host_objects, metahost_objects,
265 dependencies, atomic_group, labels_by_name):
266 """
267 Attempt to reject create_job requests with an atomic group that
268 will be impossible to schedule. The checks are not perfect but
269 should catch the most obvious issues.
270
271 @param synch_count - The job's minimum synch count.
272 @param host_objects - A list of models.Host instances.
273 @param metahost_objects - A list of models.Label instances.
274 @param dependencies - A list of job dependency label names.
275 @param atomic_group - The models.AtomicGroup instance.
276 @param labels_by_name - A dictionary mapping label names to models.Label
277 instance. Used to look up instances for dependencies.
278
279 @raises model_logic.ValidationError - When an issue is found.
280 """
281 # If specific host objects were supplied with an atomic group, verify
282 # that there are enough to satisfy the synch_count.
283 minimum_required = synch_count or 1
284 if (host_objects and not metahost_objects and
285 len(host_objects) < minimum_required):
286 raise model_logic.ValidationError(
287 {'hosts':
288 'only %d hosts provided for job with synch_count = %d' %
289 (len(host_objects), synch_count)})
290
291 # Check that the atomic group has a hope of running this job
292 # given any supplied metahosts and dependancies that may limit.
293
294 # Get a set of hostnames in the atomic group.
295 possible_hosts = set()
296 for label in atomic_group.label_set.all():
297 possible_hosts.update(h.hostname for h in label.host_set.all())
298
299 # Filter out hosts that don't match all of the job dependency labels.
300 for label_name in set(dependencies):
301 label = labels_by_name[label_name]
302 hosts_in_label = (h.hostname for h in label.host_set.all())
303 possible_hosts.intersection_update(hosts_in_label)
304
showard225bdc12009-04-13 16:09:21 +0000305 if not host_objects and not metahost_objects:
306 # No hosts or metahosts are required to queue an atomic group Job.
307 # However, if they are given, we respect them below.
308 host_set = possible_hosts
309 else:
310 host_set = set(host.hostname for host in host_objects)
311 unusable_host_set = host_set.difference(possible_hosts)
312 if unusable_host_set:
313 raise model_logic.ValidationError(
314 {'hosts': 'Hosts "%s" are not in Atomic Group "%s"' %
315 (', '.join(sorted(unusable_host_set)), atomic_group.name)})
showardc92da832009-04-07 18:14:34 +0000316
317 # Lookup hosts provided by each meta host and merge them into the
318 # host_set for final counting.
319 for meta_host in metahost_objects:
320 meta_possible = possible_hosts.copy()
321 hosts_in_meta_host = (h.hostname for h in meta_host.host_set.all())
322 meta_possible.intersection_update(hosts_in_meta_host)
323
324 # Count all hosts that this meta_host will provide.
325 host_set.update(meta_possible)
326
327 if len(host_set) < minimum_required:
328 raise model_logic.ValidationError(
329 {'atomic_group_name':
330 'Insufficient hosts in Atomic Group "%s" with the'
331 ' supplied dependencies and meta_hosts.' %
332 (atomic_group.name,)})
333
334
showardbe0d8692009-08-20 23:42:44 +0000335def check_modify_host(update_data):
336 """
337 Sanity check modify_host* requests.
338
339 @param update_data: A dictionary with the changes to make to a host
340 or hosts.
341 """
342 # Only the scheduler (monitor_db) is allowed to modify Host status.
343 # Otherwise race conditions happen as a hosts state is changed out from
344 # beneath tasks being run on a host.
345 if 'status' in update_data:
346 raise model_logic.ValidationError({
347 'status': 'Host status can not be modified by the frontend.'})
348
349
showardce7c0922009-09-11 18:39:24 +0000350def check_modify_host_locking(host, update_data):
351 """
352 Checks when locking/unlocking has been requested if the host is already
353 locked/unlocked.
354
355 @param host: models.Host object to be modified
356 @param update_data: A dictionary with the changes to make to the host.
357 """
358 locked = update_data.get('locked', None)
359 if locked is not None:
360 if locked and host.locked:
361 raise model_logic.ValidationError({
362 'locked': 'Host already locked by %s on %s.' %
363 (host.locked_by, host.lock_time)})
364 if not locked and not host.locked:
365 raise model_logic.ValidationError({
366 'locked': 'Host already unlocked.'})
367
368
showard8fbae652009-01-20 23:23:10 +0000369def get_motd():
370 dirname = os.path.dirname(__file__)
371 filename = os.path.join(dirname, "..", "..", "motd.txt")
372 text = ''
373 try:
374 fp = open(filename, "r")
375 try:
376 text = fp.read()
377 finally:
378 fp.close()
379 except:
380 pass
381
382 return text
showard29f7cd22009-04-29 21:16:24 +0000383
384
385def _get_metahost_counts(metahost_objects):
386 metahost_counts = {}
387 for metahost in metahost_objects:
388 metahost_counts.setdefault(metahost, 0)
389 metahost_counts[metahost] += 1
390 return metahost_counts
391
392
showarda965cef2009-05-15 23:17:41 +0000393def get_job_info(job, preserve_metahosts=False, queue_entry_filter_data=None):
showard29f7cd22009-04-29 21:16:24 +0000394 hosts = []
395 one_time_hosts = []
396 meta_hosts = []
397 atomic_group = None
398
showard4d077562009-05-08 18:24:36 +0000399 queue_entries = job.hostqueueentry_set.all()
showarda965cef2009-05-15 23:17:41 +0000400 if queue_entry_filter_data:
401 queue_entries = models.HostQueueEntry.query_objects(
402 queue_entry_filter_data, initial_query=queue_entries)
showard4d077562009-05-08 18:24:36 +0000403
404 for queue_entry in queue_entries:
showard29f7cd22009-04-29 21:16:24 +0000405 if (queue_entry.host and (preserve_metahosts or
406 not queue_entry.meta_host)):
407 if queue_entry.deleted:
408 continue
409 if queue_entry.host.invalid:
410 one_time_hosts.append(queue_entry.host)
411 else:
412 hosts.append(queue_entry.host)
413 else:
414 meta_hosts.append(queue_entry.meta_host)
415 if atomic_group is None:
416 if queue_entry.atomic_group is not None:
417 atomic_group = queue_entry.atomic_group
418 else:
419 assert atomic_group.name == queue_entry.atomic_group.name, (
420 'DB inconsistency. HostQueueEntries with multiple atomic'
421 ' groups on job %s: %s != %s' % (
422 id, atomic_group.name, queue_entry.atomic_group.name))
423
424 meta_host_counts = _get_metahost_counts(meta_hosts)
425
426 info = dict(dependencies=[label.name for label
427 in job.dependency_labels.all()],
428 hosts=hosts,
429 meta_hosts=meta_hosts,
430 meta_host_counts=meta_host_counts,
431 one_time_hosts=one_time_hosts,
432 atomic_group=atomic_group)
433 return info
434
435
showard09d80f92009-11-19 01:01:19 +0000436def check_for_duplicate_hosts(host_objects):
437 host_ids = set()
438 duplicate_hostnames = set()
439 for host in host_objects:
440 if host.id in host_ids:
441 duplicate_hostnames.add(host.hostname)
442 host_ids.add(host.id)
443
444 if duplicate_hostnames:
445 raise model_logic.ValidationError(
446 {'hosts' : 'Duplicate hosts: %s'
447 % ', '.join(duplicate_hostnames)})
448
449
showarda1e74b32009-05-12 17:32:04 +0000450def create_new_job(owner, options, host_objects, metahost_objects,
451 atomic_group=None):
showard29f7cd22009-04-29 21:16:24 +0000452 labels_by_name = dict((label.name, label)
showarda1e74b32009-05-12 17:32:04 +0000453 for label in models.Label.objects.all())
showard29f7cd22009-04-29 21:16:24 +0000454 all_host_objects = host_objects + metahost_objects
455 metahost_counts = _get_metahost_counts(metahost_objects)
showarda1e74b32009-05-12 17:32:04 +0000456 dependencies = options.get('dependencies', [])
457 synch_count = options.get('synch_count')
showard29f7cd22009-04-29 21:16:24 +0000458
showard29f7cd22009-04-29 21:16:24 +0000459 if atomic_group:
460 check_atomic_group_create_job(
461 synch_count, host_objects, metahost_objects,
462 dependencies, atomic_group, labels_by_name)
463 else:
464 if synch_count is not None and synch_count > len(all_host_objects):
465 raise model_logic.ValidationError(
466 {'hosts':
467 'only %d hosts provided for job with synch_count = %d' %
468 (len(all_host_objects), synch_count)})
469 atomic_hosts = models.Host.objects.filter(
470 id__in=[host.id for host in host_objects],
471 labels__atomic_group=True)
472 unusable_host_names = [host.hostname for host in atomic_hosts]
473 if unusable_host_names:
474 raise model_logic.ValidationError(
475 {'hosts':
476 'Host(s) "%s" are atomic group hosts but no '
477 'atomic group was specified for this job.' %
478 (', '.join(unusable_host_names),)})
479
showard09d80f92009-11-19 01:01:19 +0000480 check_for_duplicate_hosts(host_objects)
showard29f7cd22009-04-29 21:16:24 +0000481
482 check_job_dependencies(host_objects, dependencies)
showarda1e74b32009-05-12 17:32:04 +0000483 options['dependencies'] = [labels_by_name[label_name]
484 for label_name in dependencies]
showard29f7cd22009-04-29 21:16:24 +0000485
showarda1e74b32009-05-12 17:32:04 +0000486 for label in metahost_objects + options['dependencies']:
showard29f7cd22009-04-29 21:16:24 +0000487 if label.atomic_group and not atomic_group:
488 raise model_logic.ValidationError(
489 {'atomic_group_name':
showardc8730322009-06-30 01:56:38 +0000490 'Dependency %r requires an atomic group but no '
491 'atomic_group_name or meta_host in an atomic group was '
492 'specified for this job.' % label.name})
showard29f7cd22009-04-29 21:16:24 +0000493 elif (label.atomic_group and
494 label.atomic_group.name != atomic_group.name):
495 raise model_logic.ValidationError(
496 {'atomic_group_name':
showardc8730322009-06-30 01:56:38 +0000497 'meta_hosts or dependency %r requires atomic group '
498 '%r instead of the supplied atomic_group_name=%r.' %
499 (label.name, label.atomic_group.name, atomic_group.name)})
showard29f7cd22009-04-29 21:16:24 +0000500
showarda1e74b32009-05-12 17:32:04 +0000501 job = models.Job.create(owner=owner, options=options,
502 hosts=all_host_objects)
showard29f7cd22009-04-29 21:16:24 +0000503 job.queue(all_host_objects, atomic_group=atomic_group,
showarda1e74b32009-05-12 17:32:04 +0000504 is_template=options.get('is_template', False))
showard29f7cd22009-04-29 21:16:24 +0000505 return job.id
showard0957a842009-05-11 19:25:08 +0000506
507
showard909c9142009-07-07 20:54:42 +0000508def find_platform_and_atomic_group(host):
509 """
510 Figure out the platform name and atomic group name for the given host
511 object. If none, the return value for either will be None.
512
513 @returns (platform name, atomic group name) for the given host.
514 """
showard0957a842009-05-11 19:25:08 +0000515 platforms = [label.name for label in host.label_list if label.platform]
516 if not platforms:
showard909c9142009-07-07 20:54:42 +0000517 platform = None
518 else:
519 platform = platforms[0]
showard0957a842009-05-11 19:25:08 +0000520 if len(platforms) > 1:
521 raise ValueError('Host %s has more than one platform: %s' %
522 (host.hostname, ', '.join(platforms)))
showard909c9142009-07-07 20:54:42 +0000523 for label in host.label_list:
524 if label.atomic_group:
525 atomic_group_name = label.atomic_group.name
526 break
527 else:
528 atomic_group_name = None
529 # Don't check for multiple atomic groups on a host here. That is an
530 # error but should not trip up the RPC interface. monitor_db_cleanup
531 # deals with it. This just returns the first one found.
532 return platform, atomic_group_name
showardc0ac3a72009-07-08 21:14:45 +0000533
534
535# support for get_host_queue_entries_and_special_tasks()
536
537def _common_entry_to_dict(entry, type, job_dict):
538 return dict(type=type,
539 host=entry.host.get_object_dict(),
540 job=job_dict,
541 execution_path=entry.execution_path(),
542 status=entry.status,
543 started_on=entry.started_on,
showard8fb1fde2009-07-11 01:47:16 +0000544 id=str(entry.id) + type)
showardc0ac3a72009-07-08 21:14:45 +0000545
546
547def _special_task_to_dict(special_task):
548 job_dict = None
549 if special_task.queue_entry:
550 job_dict = special_task.queue_entry.job.get_object_dict()
551 return _common_entry_to_dict(special_task, special_task.task, job_dict)
552
553
554def _queue_entry_to_dict(queue_entry):
555 return _common_entry_to_dict(queue_entry, 'Job',
556 queue_entry.job.get_object_dict())
557
558
559def _compute_next_job_for_tasks(queue_entries, special_tasks):
560 """
561 For each task, try to figure out the next job that ran after that task.
562 This is done using two pieces of information:
563 * if the task has a queue entry, we can use that entry's job ID.
564 * if the task has a time_started, we can try to compare that against the
565 started_on field of queue_entries. this isn't guaranteed to work perfectly
566 since queue_entries may also have null started_on values.
567 * if the task has neither, or if use of time_started fails, just use the
568 last computed job ID.
569 """
570 next_job_id = None # most recently computed next job
571 hqe_index = 0 # index for scanning by started_on times
572 for task in special_tasks:
573 if task.queue_entry:
574 next_job_id = task.queue_entry.job.id
575 elif task.time_started is not None:
576 for queue_entry in queue_entries[hqe_index:]:
577 if queue_entry.started_on is None:
578 continue
579 if queue_entry.started_on < task.time_started:
580 break
581 next_job_id = queue_entry.job.id
582
583 task.next_job_id = next_job_id
584
585 # advance hqe_index to just after next_job_id
586 if next_job_id is not None:
587 for queue_entry in queue_entries[hqe_index:]:
588 if queue_entry.job.id < next_job_id:
589 break
590 hqe_index += 1
591
592
593def interleave_entries(queue_entries, special_tasks):
594 """
595 Both lists should be ordered by descending ID.
596 """
597 _compute_next_job_for_tasks(queue_entries, special_tasks)
598
599 # start with all special tasks that've run since the last job
600 interleaved_entries = []
601 for task in special_tasks:
602 if task.next_job_id is not None:
603 break
604 interleaved_entries.append(_special_task_to_dict(task))
605
606 # now interleave queue entries with the remaining special tasks
607 special_task_index = len(interleaved_entries)
608 for queue_entry in queue_entries:
609 interleaved_entries.append(_queue_entry_to_dict(queue_entry))
610 # add all tasks that ran between this job and the previous one
611 for task in special_tasks[special_task_index:]:
612 if task.next_job_id < queue_entry.job.id:
613 break
614 interleaved_entries.append(_special_task_to_dict(task))
615 special_task_index += 1
616
617 return interleaved_entries