blob: 3628d906f2ae0d6290c85337d63e701c9d3255f0 [file] [log] [blame]
Aviv Keshet18308922013-02-19 17:49:49 -08001#pylint: disable-msg=C0111
mblighe8819cd2008-02-15 16:48:40 +00002"""\
3Utility functions for rpc_interface.py. We keep them in a separate file so that
4only RPC interface functions go into that file.
5"""
6
7__author__ = 'showard@google.com (Steve Howard)'
8
Aviv Keshet18308922013-02-19 17:49:49 -08009import datetime, os, inspect
showard3d6ae112009-05-02 00:45:48 +000010import django.http
Dan Shi07e09af2013-04-12 09:31:29 -070011from autotest_lib.frontend.afe import models, model_logic
Alex Miller7d658cf2013-09-04 16:00:35 -070012from autotest_lib.client.common_lib import priorities
Alex Miller4a193692013-08-21 13:59:01 -070013from autotest_lib.client.common_lib import control_data, error
Aviv Keshetc68807e2013-07-31 16:13:01 -070014from autotest_lib.server.cros import provision
mblighe8819cd2008-02-15 16:48:40 +000015
showarda62866b2008-07-28 21:27:41 +000016NULL_DATETIME = datetime.datetime.max
17NULL_DATE = datetime.date.max
18
mblighe8819cd2008-02-15 16:48:40 +000019def prepare_for_serialization(objects):
jadmanski0afbb632008-06-06 21:10:57 +000020 """
21 Prepare Python objects to be returned via RPC.
Aviv Keshet18308922013-02-19 17:49:49 -080022 @param objects: objects to be prepared.
jadmanski0afbb632008-06-06 21:10:57 +000023 """
24 if (isinstance(objects, list) and len(objects) and
25 isinstance(objects[0], dict) and 'id' in objects[0]):
26 objects = gather_unique_dicts(objects)
27 return _prepare_data(objects)
showardb8d34242008-04-25 18:11:16 +000028
29
showardc92da832009-04-07 18:14:34 +000030def prepare_rows_as_nested_dicts(query, nested_dict_column_names):
31 """
32 Prepare a Django query to be returned via RPC as a sequence of nested
33 dictionaries.
34
35 @param query - A Django model query object with a select_related() method.
36 @param nested_dict_column_names - A list of column/attribute names for the
37 rows returned by query to expand into nested dictionaries using
38 their get_object_dict() method when not None.
39
40 @returns An list suitable to returned in an RPC.
41 """
42 all_dicts = []
43 for row in query.select_related():
44 row_dict = row.get_object_dict()
45 for column in nested_dict_column_names:
46 if row_dict[column] is not None:
47 row_dict[column] = getattr(row, column).get_object_dict()
48 all_dicts.append(row_dict)
49 return prepare_for_serialization(all_dicts)
50
51
showardb8d34242008-04-25 18:11:16 +000052def _prepare_data(data):
jadmanski0afbb632008-06-06 21:10:57 +000053 """
54 Recursively process data structures, performing necessary type
55 conversions to values in data to allow for RPC serialization:
56 -convert datetimes to strings
showard2b9a88b2008-06-13 20:55:03 +000057 -convert tuples and sets to lists
jadmanski0afbb632008-06-06 21:10:57 +000058 """
59 if isinstance(data, dict):
60 new_data = {}
61 for key, value in data.iteritems():
62 new_data[key] = _prepare_data(value)
63 return new_data
showard2b9a88b2008-06-13 20:55:03 +000064 elif (isinstance(data, list) or isinstance(data, tuple) or
65 isinstance(data, set)):
jadmanski0afbb632008-06-06 21:10:57 +000066 return [_prepare_data(item) for item in data]
showard98659972008-07-17 17:00:07 +000067 elif isinstance(data, datetime.date):
showarda62866b2008-07-28 21:27:41 +000068 if data is NULL_DATETIME or data is NULL_DATE:
69 return None
jadmanski0afbb632008-06-06 21:10:57 +000070 return str(data)
71 else:
72 return data
mblighe8819cd2008-02-15 16:48:40 +000073
74
showard3d6ae112009-05-02 00:45:48 +000075def raw_http_response(response_data, content_type=None):
76 response = django.http.HttpResponse(response_data, mimetype=content_type)
77 response['Content-length'] = str(len(response.content))
78 return response
79
80
showardb0dfb9f2008-06-06 18:08:02 +000081def gather_unique_dicts(dict_iterable):
jadmanski0afbb632008-06-06 21:10:57 +000082 """\
83 Pick out unique objects (by ID) from an iterable of object dicts.
84 """
85 id_set = set()
86 result = []
87 for obj in dict_iterable:
88 if obj['id'] not in id_set:
89 id_set.add(obj['id'])
90 result.append(obj)
91 return result
showardb0dfb9f2008-06-06 18:08:02 +000092
93
mblighe8819cd2008-02-15 16:48:40 +000094def extra_job_filters(not_yet_run=False, running=False, finished=False):
jadmanski0afbb632008-06-06 21:10:57 +000095 """\
96 Generate a SQL WHERE clause for job status filtering, and return it in
97 a dict of keyword args to pass to query.extra(). No more than one of
98 the parameters should be passed as True.
showard6c65d252009-10-01 18:45:22 +000099 * not_yet_run: all HQEs are Queued
100 * finished: all HQEs are complete
101 * running: everything else
jadmanski0afbb632008-06-06 21:10:57 +0000102 """
103 assert not ((not_yet_run and running) or
104 (not_yet_run and finished) or
105 (running and finished)), ('Cannot specify more than one '
106 'filter to this function')
showard6c65d252009-10-01 18:45:22 +0000107
showardeab66ce2009-12-23 00:03:56 +0000108 not_queued = ('(SELECT job_id FROM afe_host_queue_entries '
109 'WHERE status != "%s")'
showard6c65d252009-10-01 18:45:22 +0000110 % models.HostQueueEntry.Status.QUEUED)
showardeab66ce2009-12-23 00:03:56 +0000111 not_finished = ('(SELECT job_id FROM afe_host_queue_entries '
112 'WHERE not complete)')
showard6c65d252009-10-01 18:45:22 +0000113
jadmanski0afbb632008-06-06 21:10:57 +0000114 if not_yet_run:
showard6c65d252009-10-01 18:45:22 +0000115 where = ['id NOT IN ' + not_queued]
jadmanski0afbb632008-06-06 21:10:57 +0000116 elif running:
showard6c65d252009-10-01 18:45:22 +0000117 where = ['(id IN %s) AND (id IN %s)' % (not_queued, not_finished)]
jadmanski0afbb632008-06-06 21:10:57 +0000118 elif finished:
showard6c65d252009-10-01 18:45:22 +0000119 where = ['id NOT IN ' + not_finished]
jadmanski0afbb632008-06-06 21:10:57 +0000120 else:
showard10f41672009-05-13 21:28:25 +0000121 return {}
jadmanski0afbb632008-06-06 21:10:57 +0000122 return {'where': where}
mblighe8819cd2008-02-15 16:48:40 +0000123
124
showard87cc38f2009-08-20 23:37:04 +0000125def extra_host_filters(multiple_labels=()):
jadmanski0afbb632008-06-06 21:10:57 +0000126 """\
127 Generate SQL WHERE clauses for matching hosts in an intersection of
128 labels.
129 """
130 extra_args = {}
showardeab66ce2009-12-23 00:03:56 +0000131 where_str = ('afe_hosts.id in (select host_id from afe_hosts_labels '
jadmanski0afbb632008-06-06 21:10:57 +0000132 'where label_id=%s)')
133 extra_args['where'] = [where_str] * len(multiple_labels)
134 extra_args['params'] = [models.Label.smart_get(label).id
135 for label in multiple_labels]
136 return extra_args
showard8e3aa5e2008-04-08 19:42:32 +0000137
138
showard87cc38f2009-08-20 23:37:04 +0000139def get_host_query(multiple_labels, exclude_only_if_needed_labels,
showard8aa84fc2009-09-16 17:17:55 +0000140 exclude_atomic_group_hosts, valid_only, filter_data):
141 if valid_only:
142 query = models.Host.valid_objects.all()
143 else:
144 query = models.Host.objects.all()
145
showard43a3d262008-11-12 18:17:05 +0000146 if exclude_only_if_needed_labels:
147 only_if_needed_labels = models.Label.valid_objects.filter(
148 only_if_needed=True)
showardf7eac6f2008-11-13 21:18:01 +0000149 if only_if_needed_labels.count() > 0:
showard87cc38f2009-08-20 23:37:04 +0000150 only_if_needed_ids = ','.join(
151 str(label['id'])
152 for label in only_if_needed_labels.values('id'))
showardf7eac6f2008-11-13 21:18:01 +0000153 query = models.Host.objects.add_join(
showardeab66ce2009-12-23 00:03:56 +0000154 query, 'afe_hosts_labels', join_key='host_id',
155 join_condition=('afe_hosts_labels_exclude_OIN.label_id IN (%s)'
showard87cc38f2009-08-20 23:37:04 +0000156 % only_if_needed_ids),
157 suffix='_exclude_OIN', exclude=True)
showard8aa84fc2009-09-16 17:17:55 +0000158
showard87cc38f2009-08-20 23:37:04 +0000159 if exclude_atomic_group_hosts:
160 atomic_group_labels = models.Label.valid_objects.filter(
161 atomic_group__isnull=False)
162 if atomic_group_labels.count() > 0:
163 atomic_group_label_ids = ','.join(
164 str(atomic_group['id'])
165 for atomic_group in atomic_group_labels.values('id'))
166 query = models.Host.objects.add_join(
showardeab66ce2009-12-23 00:03:56 +0000167 query, 'afe_hosts_labels', join_key='host_id',
168 join_condition=(
169 'afe_hosts_labels_exclude_AG.label_id IN (%s)'
170 % atomic_group_label_ids),
showard87cc38f2009-08-20 23:37:04 +0000171 suffix='_exclude_AG', exclude=True)
Fang Deng04d30612013-04-10 18:13:13 -0700172 try:
173 assert 'extra_args' not in filter_data
174 filter_data['extra_args'] = extra_host_filters(multiple_labels)
175 return models.Host.query_objects(filter_data, initial_query=query)
176 except models.Label.DoesNotExist as e:
177 return models.Host.objects.none()
showard43a3d262008-11-12 18:17:05 +0000178
179
showard8fd58242008-03-10 21:29:07 +0000180class InconsistencyException(Exception):
jadmanski0afbb632008-06-06 21:10:57 +0000181 'Raised when a list of objects does not have a consistent value'
showard8fd58242008-03-10 21:29:07 +0000182
183
184def get_consistent_value(objects, field):
mblighc5ddfd12008-08-04 17:15:00 +0000185 if not objects:
186 # well a list of nothing is consistent
187 return None
188
jadmanski0afbb632008-06-06 21:10:57 +0000189 value = getattr(objects[0], field)
190 for obj in objects:
191 this_value = getattr(obj, field)
192 if this_value != value:
193 raise InconsistencyException(objects[0], obj)
194 return value
showard8fd58242008-03-10 21:29:07 +0000195
196
showard2b9a88b2008-06-13 20:55:03 +0000197def prepare_generate_control_file(tests, kernel, label, profilers):
jadmanski0afbb632008-06-06 21:10:57 +0000198 test_objects = [models.Test.smart_get(test) for test in tests]
showard2b9a88b2008-06-13 20:55:03 +0000199 profiler_objects = [models.Profiler.smart_get(profiler)
200 for profiler in profilers]
jadmanski0afbb632008-06-06 21:10:57 +0000201 # ensure tests are all the same type
202 try:
203 test_type = get_consistent_value(test_objects, 'test_type')
204 except InconsistencyException, exc:
205 test1, test2 = exc.args
mblighec5546d2008-06-16 16:51:28 +0000206 raise model_logic.ValidationError(
jadmanski0afbb632008-06-06 21:10:57 +0000207 {'tests' : 'You cannot run both server- and client-side '
208 'tests together (tests %s and %s differ' % (
209 test1.name, test2.name)})
showard8fd58242008-03-10 21:29:07 +0000210
Aviv Keshet3dd8beb2013-05-13 17:36:04 -0700211 is_server = (test_type == control_data.CONTROL_TYPE.SERVER)
showard14374b12009-01-31 00:11:54 +0000212 if test_objects:
213 synch_count = max(test.sync_count for test in test_objects)
214 else:
215 synch_count = 1
jadmanski0afbb632008-06-06 21:10:57 +0000216 if label:
217 label = models.Label.smart_get(label)
mblighe8819cd2008-02-15 16:48:40 +0000218
showard989f25d2008-10-01 11:38:11 +0000219 dependencies = set(label.name for label
220 in models.Label.objects.filter(test__in=test_objects))
221
showard2bab8f42008-11-12 18:15:22 +0000222 cf_info = dict(is_server=is_server, synch_count=synch_count,
223 dependencies=list(dependencies))
224 return cf_info, test_objects, profiler_objects, label
showard989f25d2008-10-01 11:38:11 +0000225
226
227def check_job_dependencies(host_objects, job_dependencies):
228 """
229 Check that a set of machines satisfies a job's dependencies.
230 host_objects: list of models.Host objects
231 job_dependencies: list of names of labels
232 """
233 # check that hosts satisfy dependencies
234 host_ids = [host.id for host in host_objects]
235 hosts_in_job = models.Host.objects.filter(id__in=host_ids)
236 ok_hosts = hosts_in_job
237 for index, dependency in enumerate(job_dependencies):
Aviv Keshetc68807e2013-07-31 16:13:01 -0700238 if not provision.can_provision(dependency):
239 ok_hosts = ok_hosts.filter(labels__name=dependency)
showard989f25d2008-10-01 11:38:11 +0000240 failing_hosts = (set(host.hostname for host in host_objects) -
241 set(host.hostname for host in ok_hosts))
242 if failing_hosts:
243 raise model_logic.ValidationError(
Eric Lie0493a42010-11-15 13:05:43 -0800244 {'hosts' : 'Host(s) failed to meet job dependencies (' +
245 (', '.join(job_dependencies)) + '): ' +
246 (', '.join(failing_hosts))})
247
showard989f25d2008-10-01 11:38:11 +0000248
Alex Miller4a193692013-08-21 13:59:01 -0700249def check_job_metahost_dependencies(metahost_objects, job_dependencies):
250 """
251 Check that at least one machine within the metahost spec satisfies the job's
252 dependencies.
253
254 @param metahost_objects A list of label objects representing the metahosts.
255 @param job_dependencies A list of strings of the required label names.
256 @raises NoEligibleHostException If a metahost cannot run the job.
257 """
258 for metahost in metahost_objects:
259 hosts = models.Host.objects.filter(labels=metahost)
260 for label_name in job_dependencies:
261 if not provision.can_provision(label_name):
262 hosts = hosts.filter(labels__name=label_name)
263 if not any(hosts):
264 raise error.NoEligibleHostException("No hosts within %s satisfy %s."
265 % (metahost.name, ', '.join(job_dependencies)))
266
showard2bab8f42008-11-12 18:15:22 +0000267
268def _execution_key_for(host_queue_entry):
269 return (host_queue_entry.job.id, host_queue_entry.execution_subdir)
270
271
272def check_abort_synchronous_jobs(host_queue_entries):
273 # ensure user isn't aborting part of a synchronous autoserv execution
274 count_per_execution = {}
275 for queue_entry in host_queue_entries:
276 key = _execution_key_for(queue_entry)
277 count_per_execution.setdefault(key, 0)
278 count_per_execution[key] += 1
279
280 for queue_entry in host_queue_entries:
281 if not queue_entry.execution_subdir:
282 continue
283 execution_count = count_per_execution[_execution_key_for(queue_entry)]
284 if execution_count < queue_entry.job.synch_count:
mbligh1ef218d2009-08-03 16:57:56 +0000285 raise model_logic.ValidationError(
286 {'' : 'You cannot abort part of a synchronous job execution '
287 '(%d/%s), %d included, %d expected'
288 % (queue_entry.job.id, queue_entry.execution_subdir,
289 execution_count, queue_entry.job.synch_count)})
showard8fbae652009-01-20 23:23:10 +0000290
291
showardc92da832009-04-07 18:14:34 +0000292def check_atomic_group_create_job(synch_count, host_objects, metahost_objects,
Alex Miller871291b2013-08-08 01:19:20 -0700293 dependencies, atomic_group):
showardc92da832009-04-07 18:14:34 +0000294 """
295 Attempt to reject create_job requests with an atomic group that
296 will be impossible to schedule. The checks are not perfect but
297 should catch the most obvious issues.
298
299 @param synch_count - The job's minimum synch count.
300 @param host_objects - A list of models.Host instances.
301 @param metahost_objects - A list of models.Label instances.
302 @param dependencies - A list of job dependency label names.
showardc92da832009-04-07 18:14:34 +0000303 @param labels_by_name - A dictionary mapping label names to models.Label
304 instance. Used to look up instances for dependencies.
305
306 @raises model_logic.ValidationError - When an issue is found.
307 """
308 # If specific host objects were supplied with an atomic group, verify
309 # that there are enough to satisfy the synch_count.
310 minimum_required = synch_count or 1
311 if (host_objects and not metahost_objects and
312 len(host_objects) < minimum_required):
313 raise model_logic.ValidationError(
314 {'hosts':
315 'only %d hosts provided for job with synch_count = %d' %
316 (len(host_objects), synch_count)})
317
318 # Check that the atomic group has a hope of running this job
319 # given any supplied metahosts and dependancies that may limit.
320
321 # Get a set of hostnames in the atomic group.
322 possible_hosts = set()
323 for label in atomic_group.label_set.all():
324 possible_hosts.update(h.hostname for h in label.host_set.all())
325
326 # Filter out hosts that don't match all of the job dependency labels.
Alex Miller871291b2013-08-08 01:19:20 -0700327 for label in models.Label.objects.filter(name__in=dependencies):
showardc92da832009-04-07 18:14:34 +0000328 hosts_in_label = (h.hostname for h in label.host_set.all())
329 possible_hosts.intersection_update(hosts_in_label)
330
showard225bdc12009-04-13 16:09:21 +0000331 if not host_objects and not metahost_objects:
332 # No hosts or metahosts are required to queue an atomic group Job.
333 # However, if they are given, we respect them below.
334 host_set = possible_hosts
335 else:
336 host_set = set(host.hostname for host in host_objects)
337 unusable_host_set = host_set.difference(possible_hosts)
338 if unusable_host_set:
339 raise model_logic.ValidationError(
340 {'hosts': 'Hosts "%s" are not in Atomic Group "%s"' %
341 (', '.join(sorted(unusable_host_set)), atomic_group.name)})
showardc92da832009-04-07 18:14:34 +0000342
343 # Lookup hosts provided by each meta host and merge them into the
344 # host_set for final counting.
345 for meta_host in metahost_objects:
346 meta_possible = possible_hosts.copy()
347 hosts_in_meta_host = (h.hostname for h in meta_host.host_set.all())
348 meta_possible.intersection_update(hosts_in_meta_host)
349
350 # Count all hosts that this meta_host will provide.
351 host_set.update(meta_possible)
352
353 if len(host_set) < minimum_required:
354 raise model_logic.ValidationError(
355 {'atomic_group_name':
356 'Insufficient hosts in Atomic Group "%s" with the'
357 ' supplied dependencies and meta_hosts.' %
358 (atomic_group.name,)})
359
360
showardbe0d8692009-08-20 23:42:44 +0000361def check_modify_host(update_data):
362 """
363 Sanity check modify_host* requests.
364
365 @param update_data: A dictionary with the changes to make to a host
366 or hosts.
367 """
368 # Only the scheduler (monitor_db) is allowed to modify Host status.
369 # Otherwise race conditions happen as a hosts state is changed out from
370 # beneath tasks being run on a host.
371 if 'status' in update_data:
372 raise model_logic.ValidationError({
373 'status': 'Host status can not be modified by the frontend.'})
374
375
showardce7c0922009-09-11 18:39:24 +0000376def check_modify_host_locking(host, update_data):
377 """
378 Checks when locking/unlocking has been requested if the host is already
379 locked/unlocked.
380
381 @param host: models.Host object to be modified
382 @param update_data: A dictionary with the changes to make to the host.
383 """
384 locked = update_data.get('locked', None)
385 if locked is not None:
386 if locked and host.locked:
387 raise model_logic.ValidationError({
388 'locked': 'Host already locked by %s on %s.' %
389 (host.locked_by, host.lock_time)})
390 if not locked and not host.locked:
391 raise model_logic.ValidationError({
392 'locked': 'Host already unlocked.'})
393
394
showard8fbae652009-01-20 23:23:10 +0000395def get_motd():
396 dirname = os.path.dirname(__file__)
397 filename = os.path.join(dirname, "..", "..", "motd.txt")
398 text = ''
399 try:
400 fp = open(filename, "r")
401 try:
402 text = fp.read()
403 finally:
404 fp.close()
405 except:
406 pass
407
408 return text
showard29f7cd22009-04-29 21:16:24 +0000409
410
411def _get_metahost_counts(metahost_objects):
412 metahost_counts = {}
413 for metahost in metahost_objects:
414 metahost_counts.setdefault(metahost, 0)
415 metahost_counts[metahost] += 1
416 return metahost_counts
417
418
showarda965cef2009-05-15 23:17:41 +0000419def get_job_info(job, preserve_metahosts=False, queue_entry_filter_data=None):
showard29f7cd22009-04-29 21:16:24 +0000420 hosts = []
421 one_time_hosts = []
422 meta_hosts = []
423 atomic_group = None
jamesren2275ef12010-04-12 18:25:06 +0000424 hostless = False
showard29f7cd22009-04-29 21:16:24 +0000425
showard4d077562009-05-08 18:24:36 +0000426 queue_entries = job.hostqueueentry_set.all()
showarda965cef2009-05-15 23:17:41 +0000427 if queue_entry_filter_data:
428 queue_entries = models.HostQueueEntry.query_objects(
429 queue_entry_filter_data, initial_query=queue_entries)
showard4d077562009-05-08 18:24:36 +0000430
431 for queue_entry in queue_entries:
showard29f7cd22009-04-29 21:16:24 +0000432 if (queue_entry.host and (preserve_metahosts or
433 not queue_entry.meta_host)):
434 if queue_entry.deleted:
435 continue
436 if queue_entry.host.invalid:
437 one_time_hosts.append(queue_entry.host)
438 else:
439 hosts.append(queue_entry.host)
jamesren2275ef12010-04-12 18:25:06 +0000440 elif queue_entry.meta_host:
showard29f7cd22009-04-29 21:16:24 +0000441 meta_hosts.append(queue_entry.meta_host)
jamesren2275ef12010-04-12 18:25:06 +0000442 else:
443 hostless = True
444
showard29f7cd22009-04-29 21:16:24 +0000445 if atomic_group is None:
446 if queue_entry.atomic_group is not None:
447 atomic_group = queue_entry.atomic_group
448 else:
449 assert atomic_group.name == queue_entry.atomic_group.name, (
450 'DB inconsistency. HostQueueEntries with multiple atomic'
451 ' groups on job %s: %s != %s' % (
452 id, atomic_group.name, queue_entry.atomic_group.name))
453
454 meta_host_counts = _get_metahost_counts(meta_hosts)
455
456 info = dict(dependencies=[label.name for label
457 in job.dependency_labels.all()],
458 hosts=hosts,
459 meta_hosts=meta_hosts,
460 meta_host_counts=meta_host_counts,
461 one_time_hosts=one_time_hosts,
jamesren2275ef12010-04-12 18:25:06 +0000462 atomic_group=atomic_group,
463 hostless=hostless)
showard29f7cd22009-04-29 21:16:24 +0000464 return info
465
466
showard09d80f92009-11-19 01:01:19 +0000467def check_for_duplicate_hosts(host_objects):
468 host_ids = set()
469 duplicate_hostnames = set()
470 for host in host_objects:
471 if host.id in host_ids:
472 duplicate_hostnames.add(host.hostname)
473 host_ids.add(host.id)
474
475 if duplicate_hostnames:
476 raise model_logic.ValidationError(
477 {'hosts' : 'Duplicate hosts: %s'
478 % ', '.join(duplicate_hostnames)})
479
480
showarda1e74b32009-05-12 17:32:04 +0000481def create_new_job(owner, options, host_objects, metahost_objects,
482 atomic_group=None):
showard29f7cd22009-04-29 21:16:24 +0000483 all_host_objects = host_objects + metahost_objects
484 metahost_counts = _get_metahost_counts(metahost_objects)
showarda1e74b32009-05-12 17:32:04 +0000485 dependencies = options.get('dependencies', [])
486 synch_count = options.get('synch_count')
showard29f7cd22009-04-29 21:16:24 +0000487
showard29f7cd22009-04-29 21:16:24 +0000488 if atomic_group:
489 check_atomic_group_create_job(
490 synch_count, host_objects, metahost_objects,
Alex Miller871291b2013-08-08 01:19:20 -0700491 dependencies, atomic_group)
showard29f7cd22009-04-29 21:16:24 +0000492 else:
493 if synch_count is not None and synch_count > len(all_host_objects):
494 raise model_logic.ValidationError(
495 {'hosts':
496 'only %d hosts provided for job with synch_count = %d' %
497 (len(all_host_objects), synch_count)})
498 atomic_hosts = models.Host.objects.filter(
499 id__in=[host.id for host in host_objects],
500 labels__atomic_group=True)
501 unusable_host_names = [host.hostname for host in atomic_hosts]
502 if unusable_host_names:
503 raise model_logic.ValidationError(
504 {'hosts':
505 'Host(s) "%s" are atomic group hosts but no '
506 'atomic group was specified for this job.' %
507 (', '.join(unusable_host_names),)})
508
showard09d80f92009-11-19 01:01:19 +0000509 check_for_duplicate_hosts(host_objects)
showard29f7cd22009-04-29 21:16:24 +0000510
Aviv Keshetc68807e2013-07-31 16:13:01 -0700511 for label_name in dependencies:
512 if provision.can_provision(label_name):
513 # TODO: We could save a few queries
514 # if we had a bulk ensure-label-exists function, which used
515 # a bulk .get() call. The win is probably very small.
Alex Miller871291b2013-08-08 01:19:20 -0700516 _ensure_label_exists(label_name)
Aviv Keshetc68807e2013-07-31 16:13:01 -0700517
Alex Miller4a193692013-08-21 13:59:01 -0700518 # This only checks targeted hosts, not hosts eligible due to the metahost
519 check_job_dependencies(host_objects, dependencies)
520 check_job_metahost_dependencies(metahost_objects, dependencies)
521
Alex Miller871291b2013-08-08 01:19:20 -0700522 options['dependencies'] = list(
523 models.Label.objects.filter(name__in=dependencies))
showard29f7cd22009-04-29 21:16:24 +0000524
showarda1e74b32009-05-12 17:32:04 +0000525 for label in metahost_objects + options['dependencies']:
showard29f7cd22009-04-29 21:16:24 +0000526 if label.atomic_group and not atomic_group:
527 raise model_logic.ValidationError(
528 {'atomic_group_name':
showardc8730322009-06-30 01:56:38 +0000529 'Dependency %r requires an atomic group but no '
530 'atomic_group_name or meta_host in an atomic group was '
531 'specified for this job.' % label.name})
showard29f7cd22009-04-29 21:16:24 +0000532 elif (label.atomic_group and
533 label.atomic_group.name != atomic_group.name):
534 raise model_logic.ValidationError(
535 {'atomic_group_name':
showardc8730322009-06-30 01:56:38 +0000536 'meta_hosts or dependency %r requires atomic group '
537 '%r instead of the supplied atomic_group_name=%r.' %
538 (label.name, label.atomic_group.name, atomic_group.name)})
showard29f7cd22009-04-29 21:16:24 +0000539
showarda1e74b32009-05-12 17:32:04 +0000540 job = models.Job.create(owner=owner, options=options,
541 hosts=all_host_objects)
showard29f7cd22009-04-29 21:16:24 +0000542 job.queue(all_host_objects, atomic_group=atomic_group,
showarda1e74b32009-05-12 17:32:04 +0000543 is_template=options.get('is_template', False))
showard29f7cd22009-04-29 21:16:24 +0000544 return job.id
showard0957a842009-05-11 19:25:08 +0000545
546
Aviv Keshetc68807e2013-07-31 16:13:01 -0700547def _ensure_label_exists(name):
548 """
549 Ensure that a label called |name| exists in the Django models.
550
551 This function is to be called from within afe rpcs only, as an
552 alternative to server.cros.provision.ensure_label_exists(...). It works
553 by Django model manipulation, rather than by making another create_label
554 rpc call.
555
556 @param name: the label to check for/create.
557 @raises ValidationError: There was an error in the response that was
558 not because the label already existed.
559 @returns True is a label was created, False otherwise.
560 """
561 try:
562 models.Label.objects.get(name=name)
563 except models.Label.DoesNotExist:
564 new_label = models.Label.objects.create(name=name)
565 new_label.save()
566 return True
567 return False
568
569
showard909c9142009-07-07 20:54:42 +0000570def find_platform_and_atomic_group(host):
571 """
572 Figure out the platform name and atomic group name for the given host
573 object. If none, the return value for either will be None.
574
575 @returns (platform name, atomic group name) for the given host.
576 """
showard0957a842009-05-11 19:25:08 +0000577 platforms = [label.name for label in host.label_list if label.platform]
578 if not platforms:
showard909c9142009-07-07 20:54:42 +0000579 platform = None
580 else:
581 platform = platforms[0]
showard0957a842009-05-11 19:25:08 +0000582 if len(platforms) > 1:
583 raise ValueError('Host %s has more than one platform: %s' %
584 (host.hostname, ', '.join(platforms)))
showard909c9142009-07-07 20:54:42 +0000585 for label in host.label_list:
586 if label.atomic_group:
587 atomic_group_name = label.atomic_group.name
588 break
589 else:
590 atomic_group_name = None
591 # Don't check for multiple atomic groups on a host here. That is an
592 # error but should not trip up the RPC interface. monitor_db_cleanup
593 # deals with it. This just returns the first one found.
594 return platform, atomic_group_name
showardc0ac3a72009-07-08 21:14:45 +0000595
596
597# support for get_host_queue_entries_and_special_tasks()
598
599def _common_entry_to_dict(entry, type, job_dict):
600 return dict(type=type,
601 host=entry.host.get_object_dict(),
602 job=job_dict,
603 execution_path=entry.execution_path(),
604 status=entry.status,
605 started_on=entry.started_on,
showard8fb1fde2009-07-11 01:47:16 +0000606 id=str(entry.id) + type)
showardc0ac3a72009-07-08 21:14:45 +0000607
608
609def _special_task_to_dict(special_task):
610 job_dict = None
611 if special_task.queue_entry:
612 job_dict = special_task.queue_entry.job.get_object_dict()
613 return _common_entry_to_dict(special_task, special_task.task, job_dict)
614
615
616def _queue_entry_to_dict(queue_entry):
617 return _common_entry_to_dict(queue_entry, 'Job',
618 queue_entry.job.get_object_dict())
619
620
621def _compute_next_job_for_tasks(queue_entries, special_tasks):
622 """
623 For each task, try to figure out the next job that ran after that task.
624 This is done using two pieces of information:
625 * if the task has a queue entry, we can use that entry's job ID.
626 * if the task has a time_started, we can try to compare that against the
627 started_on field of queue_entries. this isn't guaranteed to work perfectly
628 since queue_entries may also have null started_on values.
629 * if the task has neither, or if use of time_started fails, just use the
630 last computed job ID.
631 """
632 next_job_id = None # most recently computed next job
633 hqe_index = 0 # index for scanning by started_on times
634 for task in special_tasks:
635 if task.queue_entry:
636 next_job_id = task.queue_entry.job.id
637 elif task.time_started is not None:
638 for queue_entry in queue_entries[hqe_index:]:
639 if queue_entry.started_on is None:
640 continue
641 if queue_entry.started_on < task.time_started:
642 break
643 next_job_id = queue_entry.job.id
644
645 task.next_job_id = next_job_id
646
647 # advance hqe_index to just after next_job_id
648 if next_job_id is not None:
649 for queue_entry in queue_entries[hqe_index:]:
650 if queue_entry.job.id < next_job_id:
651 break
652 hqe_index += 1
653
654
655def interleave_entries(queue_entries, special_tasks):
656 """
657 Both lists should be ordered by descending ID.
658 """
659 _compute_next_job_for_tasks(queue_entries, special_tasks)
660
661 # start with all special tasks that've run since the last job
662 interleaved_entries = []
663 for task in special_tasks:
664 if task.next_job_id is not None:
665 break
666 interleaved_entries.append(_special_task_to_dict(task))
667
668 # now interleave queue entries with the remaining special tasks
669 special_task_index = len(interleaved_entries)
670 for queue_entry in queue_entries:
671 interleaved_entries.append(_queue_entry_to_dict(queue_entry))
672 # add all tasks that ran between this job and the previous one
673 for task in special_tasks[special_task_index:]:
674 if task.next_job_id < queue_entry.job.id:
675 break
676 interleaved_entries.append(_special_task_to_dict(task))
677 special_task_index += 1
678
679 return interleaved_entries
jamesren4a41e012010-07-16 22:33:48 +0000680
681
682def get_create_job_common_args(local_args):
683 """
684 Returns a dict containing only the args that apply for create_job_common
685
686 Returns a subset of local_args, which contains only the arguments that can
687 be passed in to create_job_common().
688 """
Alex Miller7d658cf2013-09-04 16:00:35 -0700689 # This code is only here to not kill suites scheduling tests when priority
690 # becomes an int instead of a string.
691 if isinstance(local_args['priority'], str):
692 local_args['priority'] = priorities.Priority.DEFAULT
693 # </migration hack>
jamesren4a41e012010-07-16 22:33:48 +0000694 arg_names, _, _, _ = inspect.getargspec(create_job_common)
695 return dict(item for item in local_args.iteritems() if item[0] in arg_names)
696
697
698def create_job_common(name, priority, control_type, control_file=None,
699 hosts=(), meta_hosts=(), one_time_hosts=(),
700 atomic_group_name=None, synch_count=None,
Simran Basi34217022012-11-06 13:43:15 -0800701 is_template=False, timeout=None, max_runtime_mins=None,
jamesren4a41e012010-07-16 22:33:48 +0000702 run_verify=True, email_list='', dependencies=(),
703 reboot_before=None, reboot_after=None,
704 parse_failed_repair=None, hostless=False, keyvals=None,
Aviv Keshet18308922013-02-19 17:49:49 -0800705 drone_set=None, parameterized_job=None,
Dan Shi07e09af2013-04-12 09:31:29 -0700706 parent_job_id=None, test_retry=0, run_reset=True):
Aviv Keshet18308922013-02-19 17:49:49 -0800707 #pylint: disable-msg=C0111
jamesren4a41e012010-07-16 22:33:48 +0000708 """
709 Common code between creating "standard" jobs and creating parameterized jobs
710 """
711 user = models.User.current_user()
712 owner = user.login
713
jamesren4a41e012010-07-16 22:33:48 +0000714 # input validation
715 if not (hosts or meta_hosts or one_time_hosts or atomic_group_name
716 or hostless):
717 raise model_logic.ValidationError({
718 'arguments' : "You must pass at least one of 'hosts', "
719 "'meta_hosts', 'one_time_hosts', "
720 "'atomic_group_name', or 'hostless'"
721 })
722
723 if hostless:
724 if hosts or meta_hosts or one_time_hosts or atomic_group_name:
725 raise model_logic.ValidationError({
726 'hostless': 'Hostless jobs cannot include any hosts!'})
Aviv Keshet3dd8beb2013-05-13 17:36:04 -0700727 server_type = control_data.CONTROL_TYPE_NAMES.SERVER
jamesren4a41e012010-07-16 22:33:48 +0000728 if control_type != server_type:
729 raise model_logic.ValidationError({
730 'control_type': 'Hostless jobs cannot use client-side '
731 'control files'})
732
Alex Miller871291b2013-08-08 01:19:20 -0700733 atomic_groups_by_name = dict((ag.name, ag)
jamesren4a41e012010-07-16 22:33:48 +0000734 for ag in models.AtomicGroup.objects.all())
Alex Miller871291b2013-08-08 01:19:20 -0700735 label_objects = list(models.Label.objects.filter(name__in=meta_hosts))
jamesren4a41e012010-07-16 22:33:48 +0000736
737 # Schedule on an atomic group automagically if one of the labels given
738 # is an atomic group label and no explicit atomic_group_name was supplied.
739 if not atomic_group_name:
Alex Miller871291b2013-08-08 01:19:20 -0700740 for label in label_objects:
jamesren4a41e012010-07-16 22:33:48 +0000741 if label and label.atomic_group:
742 atomic_group_name = label.atomic_group.name
743 break
744
745 # convert hostnames & meta hosts to host/label objects
746 host_objects = models.Host.smart_get_bulk(hosts)
747 metahost_objects = []
Alex Miller871291b2013-08-08 01:19:20 -0700748 meta_host_labels_by_name = {label.name: label for label in label_objects}
jamesren4a41e012010-07-16 22:33:48 +0000749 for label_name in meta_hosts or []:
Alex Miller871291b2013-08-08 01:19:20 -0700750 if label_name in meta_host_labels_by_name:
751 metahost_objects.append(meta_host_labels_by_name[label_name])
jamesren4a41e012010-07-16 22:33:48 +0000752 elif label_name in atomic_groups_by_name:
753 # If given a metahost name that isn't a Label, check to
754 # see if the user was specifying an Atomic Group instead.
755 atomic_group = atomic_groups_by_name[label_name]
756 if atomic_group_name and atomic_group_name != atomic_group.name:
757 raise model_logic.ValidationError({
758 'meta_hosts': (
759 'Label "%s" not found. If assumed to be an '
760 'atomic group it would conflict with the '
761 'supplied atomic group "%s".' % (
762 label_name, atomic_group_name))})
763 atomic_group_name = atomic_group.name
764 else:
765 raise model_logic.ValidationError(
766 {'meta_hosts' : 'Label "%s" not found' % label_name})
767
768 # Create and sanity check an AtomicGroup object if requested.
769 if atomic_group_name:
770 if one_time_hosts:
771 raise model_logic.ValidationError(
772 {'one_time_hosts':
773 'One time hosts cannot be used with an Atomic Group.'})
774 atomic_group = models.AtomicGroup.smart_get(atomic_group_name)
775 if synch_count and synch_count > atomic_group.max_number_of_machines:
776 raise model_logic.ValidationError(
777 {'atomic_group_name' :
778 'You have requested a synch_count (%d) greater than the '
779 'maximum machines in the requested Atomic Group (%d).' %
780 (synch_count, atomic_group.max_number_of_machines)})
781 else:
782 atomic_group = None
783
784 for host in one_time_hosts or []:
785 this_host = models.Host.create_one_time_host(host)
786 host_objects.append(this_host)
787
788 options = dict(name=name,
789 priority=priority,
790 control_file=control_file,
791 control_type=control_type,
792 is_template=is_template,
793 timeout=timeout,
Simran Basi34217022012-11-06 13:43:15 -0800794 max_runtime_mins=max_runtime_mins,
jamesren4a41e012010-07-16 22:33:48 +0000795 synch_count=synch_count,
796 run_verify=run_verify,
797 email_list=email_list,
798 dependencies=dependencies,
799 reboot_before=reboot_before,
800 reboot_after=reboot_after,
801 parse_failed_repair=parse_failed_repair,
802 keyvals=keyvals,
803 drone_set=drone_set,
Aviv Keshet18308922013-02-19 17:49:49 -0800804 parameterized_job=parameterized_job,
Aviv Keshetcd1ff9b2013-03-01 14:55:19 -0800805 parent_job_id=parent_job_id,
Dan Shi07e09af2013-04-12 09:31:29 -0700806 test_retry=test_retry,
807 run_reset=run_reset)
jamesren4a41e012010-07-16 22:33:48 +0000808 return create_new_job(owner=owner,
809 options=options,
810 host_objects=host_objects,
811 metahost_objects=metahost_objects,
812 atomic_group=atomic_group)