blob: 24af4c0534c3c153deab78a1e8edf7d5a00029f0 [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 Miller4a193692013-08-21 13:59:01 -070012from autotest_lib.client.common_lib import control_data, error
Aviv Keshetc68807e2013-07-31 16:13:01 -070013from autotest_lib.server.cros import provision
mblighe8819cd2008-02-15 16:48:40 +000014
showarda62866b2008-07-28 21:27:41 +000015NULL_DATETIME = datetime.datetime.max
16NULL_DATE = datetime.date.max
17
mblighe8819cd2008-02-15 16:48:40 +000018def prepare_for_serialization(objects):
jadmanski0afbb632008-06-06 21:10:57 +000019 """
20 Prepare Python objects to be returned via RPC.
Aviv Keshet18308922013-02-19 17:49:49 -080021 @param objects: objects to be prepared.
jadmanski0afbb632008-06-06 21:10:57 +000022 """
23 if (isinstance(objects, list) and len(objects) and
24 isinstance(objects[0], dict) and 'id' in objects[0]):
25 objects = gather_unique_dicts(objects)
26 return _prepare_data(objects)
showardb8d34242008-04-25 18:11:16 +000027
28
showardc92da832009-04-07 18:14:34 +000029def prepare_rows_as_nested_dicts(query, nested_dict_column_names):
30 """
31 Prepare a Django query to be returned via RPC as a sequence of nested
32 dictionaries.
33
34 @param query - A Django model query object with a select_related() method.
35 @param nested_dict_column_names - A list of column/attribute names for the
36 rows returned by query to expand into nested dictionaries using
37 their get_object_dict() method when not None.
38
39 @returns An list suitable to returned in an RPC.
40 """
41 all_dicts = []
42 for row in query.select_related():
43 row_dict = row.get_object_dict()
44 for column in nested_dict_column_names:
45 if row_dict[column] is not None:
46 row_dict[column] = getattr(row, column).get_object_dict()
47 all_dicts.append(row_dict)
48 return prepare_for_serialization(all_dicts)
49
50
showardb8d34242008-04-25 18:11:16 +000051def _prepare_data(data):
jadmanski0afbb632008-06-06 21:10:57 +000052 """
53 Recursively process data structures, performing necessary type
54 conversions to values in data to allow for RPC serialization:
55 -convert datetimes to strings
showard2b9a88b2008-06-13 20:55:03 +000056 -convert tuples and sets to lists
jadmanski0afbb632008-06-06 21:10:57 +000057 """
58 if isinstance(data, dict):
59 new_data = {}
60 for key, value in data.iteritems():
61 new_data[key] = _prepare_data(value)
62 return new_data
showard2b9a88b2008-06-13 20:55:03 +000063 elif (isinstance(data, list) or isinstance(data, tuple) or
64 isinstance(data, set)):
jadmanski0afbb632008-06-06 21:10:57 +000065 return [_prepare_data(item) for item in data]
showard98659972008-07-17 17:00:07 +000066 elif isinstance(data, datetime.date):
showarda62866b2008-07-28 21:27:41 +000067 if data is NULL_DATETIME or data is NULL_DATE:
68 return None
jadmanski0afbb632008-06-06 21:10:57 +000069 return str(data)
70 else:
71 return data
mblighe8819cd2008-02-15 16:48:40 +000072
73
showard3d6ae112009-05-02 00:45:48 +000074def raw_http_response(response_data, content_type=None):
75 response = django.http.HttpResponse(response_data, mimetype=content_type)
76 response['Content-length'] = str(len(response.content))
77 return response
78
79
showardb0dfb9f2008-06-06 18:08:02 +000080def gather_unique_dicts(dict_iterable):
jadmanski0afbb632008-06-06 21:10:57 +000081 """\
82 Pick out unique objects (by ID) from an iterable of object dicts.
83 """
84 id_set = set()
85 result = []
86 for obj in dict_iterable:
87 if obj['id'] not in id_set:
88 id_set.add(obj['id'])
89 result.append(obj)
90 return result
showardb0dfb9f2008-06-06 18:08:02 +000091
92
mblighe8819cd2008-02-15 16:48:40 +000093def extra_job_filters(not_yet_run=False, running=False, finished=False):
jadmanski0afbb632008-06-06 21:10:57 +000094 """\
95 Generate a SQL WHERE clause for job status filtering, and return it in
96 a dict of keyword args to pass to query.extra(). No more than one of
97 the parameters should be passed as True.
showard6c65d252009-10-01 18:45:22 +000098 * not_yet_run: all HQEs are Queued
99 * finished: all HQEs are complete
100 * running: everything else
jadmanski0afbb632008-06-06 21:10:57 +0000101 """
102 assert not ((not_yet_run and running) or
103 (not_yet_run and finished) or
104 (running and finished)), ('Cannot specify more than one '
105 'filter to this function')
showard6c65d252009-10-01 18:45:22 +0000106
showardeab66ce2009-12-23 00:03:56 +0000107 not_queued = ('(SELECT job_id FROM afe_host_queue_entries '
108 'WHERE status != "%s")'
showard6c65d252009-10-01 18:45:22 +0000109 % models.HostQueueEntry.Status.QUEUED)
showardeab66ce2009-12-23 00:03:56 +0000110 not_finished = ('(SELECT job_id FROM afe_host_queue_entries '
111 'WHERE not complete)')
showard6c65d252009-10-01 18:45:22 +0000112
jadmanski0afbb632008-06-06 21:10:57 +0000113 if not_yet_run:
showard6c65d252009-10-01 18:45:22 +0000114 where = ['id NOT IN ' + not_queued]
jadmanski0afbb632008-06-06 21:10:57 +0000115 elif running:
showard6c65d252009-10-01 18:45:22 +0000116 where = ['(id IN %s) AND (id IN %s)' % (not_queued, not_finished)]
jadmanski0afbb632008-06-06 21:10:57 +0000117 elif finished:
showard6c65d252009-10-01 18:45:22 +0000118 where = ['id NOT IN ' + not_finished]
jadmanski0afbb632008-06-06 21:10:57 +0000119 else:
showard10f41672009-05-13 21:28:25 +0000120 return {}
jadmanski0afbb632008-06-06 21:10:57 +0000121 return {'where': where}
mblighe8819cd2008-02-15 16:48:40 +0000122
123
showard87cc38f2009-08-20 23:37:04 +0000124def extra_host_filters(multiple_labels=()):
jadmanski0afbb632008-06-06 21:10:57 +0000125 """\
126 Generate SQL WHERE clauses for matching hosts in an intersection of
127 labels.
128 """
129 extra_args = {}
showardeab66ce2009-12-23 00:03:56 +0000130 where_str = ('afe_hosts.id in (select host_id from afe_hosts_labels '
jadmanski0afbb632008-06-06 21:10:57 +0000131 'where label_id=%s)')
132 extra_args['where'] = [where_str] * len(multiple_labels)
133 extra_args['params'] = [models.Label.smart_get(label).id
134 for label in multiple_labels]
135 return extra_args
showard8e3aa5e2008-04-08 19:42:32 +0000136
137
showard87cc38f2009-08-20 23:37:04 +0000138def get_host_query(multiple_labels, exclude_only_if_needed_labels,
showard8aa84fc2009-09-16 17:17:55 +0000139 exclude_atomic_group_hosts, valid_only, filter_data):
140 if valid_only:
141 query = models.Host.valid_objects.all()
142 else:
143 query = models.Host.objects.all()
144
showard43a3d262008-11-12 18:17:05 +0000145 if exclude_only_if_needed_labels:
146 only_if_needed_labels = models.Label.valid_objects.filter(
147 only_if_needed=True)
showardf7eac6f2008-11-13 21:18:01 +0000148 if only_if_needed_labels.count() > 0:
showard87cc38f2009-08-20 23:37:04 +0000149 only_if_needed_ids = ','.join(
150 str(label['id'])
151 for label in only_if_needed_labels.values('id'))
showardf7eac6f2008-11-13 21:18:01 +0000152 query = models.Host.objects.add_join(
showardeab66ce2009-12-23 00:03:56 +0000153 query, 'afe_hosts_labels', join_key='host_id',
154 join_condition=('afe_hosts_labels_exclude_OIN.label_id IN (%s)'
showard87cc38f2009-08-20 23:37:04 +0000155 % only_if_needed_ids),
156 suffix='_exclude_OIN', exclude=True)
showard8aa84fc2009-09-16 17:17:55 +0000157
showard87cc38f2009-08-20 23:37:04 +0000158 if exclude_atomic_group_hosts:
159 atomic_group_labels = models.Label.valid_objects.filter(
160 atomic_group__isnull=False)
161 if atomic_group_labels.count() > 0:
162 atomic_group_label_ids = ','.join(
163 str(atomic_group['id'])
164 for atomic_group in atomic_group_labels.values('id'))
165 query = models.Host.objects.add_join(
showardeab66ce2009-12-23 00:03:56 +0000166 query, 'afe_hosts_labels', join_key='host_id',
167 join_condition=(
168 'afe_hosts_labels_exclude_AG.label_id IN (%s)'
169 % atomic_group_label_ids),
showard87cc38f2009-08-20 23:37:04 +0000170 suffix='_exclude_AG', exclude=True)
Fang Deng04d30612013-04-10 18:13:13 -0700171 try:
172 assert 'extra_args' not in filter_data
173 filter_data['extra_args'] = extra_host_filters(multiple_labels)
174 return models.Host.query_objects(filter_data, initial_query=query)
175 except models.Label.DoesNotExist as e:
176 return models.Host.objects.none()
showard43a3d262008-11-12 18:17:05 +0000177
178
showard8fd58242008-03-10 21:29:07 +0000179class InconsistencyException(Exception):
jadmanski0afbb632008-06-06 21:10:57 +0000180 'Raised when a list of objects does not have a consistent value'
showard8fd58242008-03-10 21:29:07 +0000181
182
183def get_consistent_value(objects, field):
mblighc5ddfd12008-08-04 17:15:00 +0000184 if not objects:
185 # well a list of nothing is consistent
186 return None
187
jadmanski0afbb632008-06-06 21:10:57 +0000188 value = getattr(objects[0], field)
189 for obj in objects:
190 this_value = getattr(obj, field)
191 if this_value != value:
192 raise InconsistencyException(objects[0], obj)
193 return value
showard8fd58242008-03-10 21:29:07 +0000194
195
showard2b9a88b2008-06-13 20:55:03 +0000196def prepare_generate_control_file(tests, kernel, label, profilers):
jadmanski0afbb632008-06-06 21:10:57 +0000197 test_objects = [models.Test.smart_get(test) for test in tests]
showard2b9a88b2008-06-13 20:55:03 +0000198 profiler_objects = [models.Profiler.smart_get(profiler)
199 for profiler in profilers]
jadmanski0afbb632008-06-06 21:10:57 +0000200 # ensure tests are all the same type
201 try:
202 test_type = get_consistent_value(test_objects, 'test_type')
203 except InconsistencyException, exc:
204 test1, test2 = exc.args
mblighec5546d2008-06-16 16:51:28 +0000205 raise model_logic.ValidationError(
jadmanski0afbb632008-06-06 21:10:57 +0000206 {'tests' : 'You cannot run both server- and client-side '
207 'tests together (tests %s and %s differ' % (
208 test1.name, test2.name)})
showard8fd58242008-03-10 21:29:07 +0000209
Aviv Keshet3dd8beb2013-05-13 17:36:04 -0700210 is_server = (test_type == control_data.CONTROL_TYPE.SERVER)
showard14374b12009-01-31 00:11:54 +0000211 if test_objects:
212 synch_count = max(test.sync_count for test in test_objects)
213 else:
214 synch_count = 1
jadmanski0afbb632008-06-06 21:10:57 +0000215 if label:
216 label = models.Label.smart_get(label)
mblighe8819cd2008-02-15 16:48:40 +0000217
showard989f25d2008-10-01 11:38:11 +0000218 dependencies = set(label.name for label
219 in models.Label.objects.filter(test__in=test_objects))
220
showard2bab8f42008-11-12 18:15:22 +0000221 cf_info = dict(is_server=is_server, synch_count=synch_count,
222 dependencies=list(dependencies))
223 return cf_info, test_objects, profiler_objects, label
showard989f25d2008-10-01 11:38:11 +0000224
225
226def check_job_dependencies(host_objects, job_dependencies):
227 """
228 Check that a set of machines satisfies a job's dependencies.
229 host_objects: list of models.Host objects
230 job_dependencies: list of names of labels
231 """
232 # check that hosts satisfy dependencies
233 host_ids = [host.id for host in host_objects]
234 hosts_in_job = models.Host.objects.filter(id__in=host_ids)
235 ok_hosts = hosts_in_job
236 for index, dependency in enumerate(job_dependencies):
Aviv Keshetc68807e2013-07-31 16:13:01 -0700237 if not provision.can_provision(dependency):
238 ok_hosts = ok_hosts.filter(labels__name=dependency)
showard989f25d2008-10-01 11:38:11 +0000239 failing_hosts = (set(host.hostname for host in host_objects) -
240 set(host.hostname for host in ok_hosts))
241 if failing_hosts:
242 raise model_logic.ValidationError(
Eric Lie0493a42010-11-15 13:05:43 -0800243 {'hosts' : 'Host(s) failed to meet job dependencies (' +
244 (', '.join(job_dependencies)) + '): ' +
245 (', '.join(failing_hosts))})
246
showard989f25d2008-10-01 11:38:11 +0000247
Alex Miller4a193692013-08-21 13:59:01 -0700248def check_job_metahost_dependencies(metahost_objects, job_dependencies):
249 """
250 Check that at least one machine within the metahost spec satisfies the job's
251 dependencies.
252
253 @param metahost_objects A list of label objects representing the metahosts.
254 @param job_dependencies A list of strings of the required label names.
255 @raises NoEligibleHostException If a metahost cannot run the job.
256 """
257 for metahost in metahost_objects:
258 hosts = models.Host.objects.filter(labels=metahost)
259 for label_name in job_dependencies:
260 if not provision.can_provision(label_name):
261 hosts = hosts.filter(labels__name=label_name)
262 if not any(hosts):
263 raise error.NoEligibleHostException("No hosts within %s satisfy %s."
264 % (metahost.name, ', '.join(job_dependencies)))
265
showard2bab8f42008-11-12 18:15:22 +0000266
267def _execution_key_for(host_queue_entry):
268 return (host_queue_entry.job.id, host_queue_entry.execution_subdir)
269
270
271def check_abort_synchronous_jobs(host_queue_entries):
272 # ensure user isn't aborting part of a synchronous autoserv execution
273 count_per_execution = {}
274 for queue_entry in host_queue_entries:
275 key = _execution_key_for(queue_entry)
276 count_per_execution.setdefault(key, 0)
277 count_per_execution[key] += 1
278
279 for queue_entry in host_queue_entries:
280 if not queue_entry.execution_subdir:
281 continue
282 execution_count = count_per_execution[_execution_key_for(queue_entry)]
283 if execution_count < queue_entry.job.synch_count:
mbligh1ef218d2009-08-03 16:57:56 +0000284 raise model_logic.ValidationError(
285 {'' : 'You cannot abort part of a synchronous job execution '
286 '(%d/%s), %d included, %d expected'
287 % (queue_entry.job.id, queue_entry.execution_subdir,
288 execution_count, queue_entry.job.synch_count)})
showard8fbae652009-01-20 23:23:10 +0000289
290
showardc92da832009-04-07 18:14:34 +0000291def check_atomic_group_create_job(synch_count, host_objects, metahost_objects,
Alex Miller871291b2013-08-08 01:19:20 -0700292 dependencies, atomic_group):
showardc92da832009-04-07 18:14:34 +0000293 """
294 Attempt to reject create_job requests with an atomic group that
295 will be impossible to schedule. The checks are not perfect but
296 should catch the most obvious issues.
297
298 @param synch_count - The job's minimum synch count.
299 @param host_objects - A list of models.Host instances.
300 @param metahost_objects - A list of models.Label instances.
301 @param dependencies - A list of job dependency label names.
showardc92da832009-04-07 18:14:34 +0000302 @param labels_by_name - A dictionary mapping label names to models.Label
303 instance. Used to look up instances for dependencies.
304
305 @raises model_logic.ValidationError - When an issue is found.
306 """
307 # If specific host objects were supplied with an atomic group, verify
308 # that there are enough to satisfy the synch_count.
309 minimum_required = synch_count or 1
310 if (host_objects and not metahost_objects and
311 len(host_objects) < minimum_required):
312 raise model_logic.ValidationError(
313 {'hosts':
314 'only %d hosts provided for job with synch_count = %d' %
315 (len(host_objects), synch_count)})
316
317 # Check that the atomic group has a hope of running this job
318 # given any supplied metahosts and dependancies that may limit.
319
320 # Get a set of hostnames in the atomic group.
321 possible_hosts = set()
322 for label in atomic_group.label_set.all():
323 possible_hosts.update(h.hostname for h in label.host_set.all())
324
325 # Filter out hosts that don't match all of the job dependency labels.
Alex Miller871291b2013-08-08 01:19:20 -0700326 for label in models.Label.objects.filter(name__in=dependencies):
showardc92da832009-04-07 18:14:34 +0000327 hosts_in_label = (h.hostname for h in label.host_set.all())
328 possible_hosts.intersection_update(hosts_in_label)
329
showard225bdc12009-04-13 16:09:21 +0000330 if not host_objects and not metahost_objects:
331 # No hosts or metahosts are required to queue an atomic group Job.
332 # However, if they are given, we respect them below.
333 host_set = possible_hosts
334 else:
335 host_set = set(host.hostname for host in host_objects)
336 unusable_host_set = host_set.difference(possible_hosts)
337 if unusable_host_set:
338 raise model_logic.ValidationError(
339 {'hosts': 'Hosts "%s" are not in Atomic Group "%s"' %
340 (', '.join(sorted(unusable_host_set)), atomic_group.name)})
showardc92da832009-04-07 18:14:34 +0000341
342 # Lookup hosts provided by each meta host and merge them into the
343 # host_set for final counting.
344 for meta_host in metahost_objects:
345 meta_possible = possible_hosts.copy()
346 hosts_in_meta_host = (h.hostname for h in meta_host.host_set.all())
347 meta_possible.intersection_update(hosts_in_meta_host)
348
349 # Count all hosts that this meta_host will provide.
350 host_set.update(meta_possible)
351
352 if len(host_set) < minimum_required:
353 raise model_logic.ValidationError(
354 {'atomic_group_name':
355 'Insufficient hosts in Atomic Group "%s" with the'
356 ' supplied dependencies and meta_hosts.' %
357 (atomic_group.name,)})
358
359
showardbe0d8692009-08-20 23:42:44 +0000360def check_modify_host(update_data):
361 """
362 Sanity check modify_host* requests.
363
364 @param update_data: A dictionary with the changes to make to a host
365 or hosts.
366 """
367 # Only the scheduler (monitor_db) is allowed to modify Host status.
368 # Otherwise race conditions happen as a hosts state is changed out from
369 # beneath tasks being run on a host.
370 if 'status' in update_data:
371 raise model_logic.ValidationError({
372 'status': 'Host status can not be modified by the frontend.'})
373
374
showardce7c0922009-09-11 18:39:24 +0000375def check_modify_host_locking(host, update_data):
376 """
377 Checks when locking/unlocking has been requested if the host is already
378 locked/unlocked.
379
380 @param host: models.Host object to be modified
381 @param update_data: A dictionary with the changes to make to the host.
382 """
383 locked = update_data.get('locked', None)
384 if locked is not None:
385 if locked and host.locked:
386 raise model_logic.ValidationError({
387 'locked': 'Host already locked by %s on %s.' %
388 (host.locked_by, host.lock_time)})
389 if not locked and not host.locked:
390 raise model_logic.ValidationError({
391 'locked': 'Host already unlocked.'})
392
393
showard8fbae652009-01-20 23:23:10 +0000394def get_motd():
395 dirname = os.path.dirname(__file__)
396 filename = os.path.join(dirname, "..", "..", "motd.txt")
397 text = ''
398 try:
399 fp = open(filename, "r")
400 try:
401 text = fp.read()
402 finally:
403 fp.close()
404 except:
405 pass
406
407 return text
showard29f7cd22009-04-29 21:16:24 +0000408
409
410def _get_metahost_counts(metahost_objects):
411 metahost_counts = {}
412 for metahost in metahost_objects:
413 metahost_counts.setdefault(metahost, 0)
414 metahost_counts[metahost] += 1
415 return metahost_counts
416
417
showarda965cef2009-05-15 23:17:41 +0000418def get_job_info(job, preserve_metahosts=False, queue_entry_filter_data=None):
showard29f7cd22009-04-29 21:16:24 +0000419 hosts = []
420 one_time_hosts = []
421 meta_hosts = []
422 atomic_group = None
jamesren2275ef12010-04-12 18:25:06 +0000423 hostless = False
showard29f7cd22009-04-29 21:16:24 +0000424
showard4d077562009-05-08 18:24:36 +0000425 queue_entries = job.hostqueueentry_set.all()
showarda965cef2009-05-15 23:17:41 +0000426 if queue_entry_filter_data:
427 queue_entries = models.HostQueueEntry.query_objects(
428 queue_entry_filter_data, initial_query=queue_entries)
showard4d077562009-05-08 18:24:36 +0000429
430 for queue_entry in queue_entries:
showard29f7cd22009-04-29 21:16:24 +0000431 if (queue_entry.host and (preserve_metahosts or
432 not queue_entry.meta_host)):
433 if queue_entry.deleted:
434 continue
435 if queue_entry.host.invalid:
436 one_time_hosts.append(queue_entry.host)
437 else:
438 hosts.append(queue_entry.host)
jamesren2275ef12010-04-12 18:25:06 +0000439 elif queue_entry.meta_host:
showard29f7cd22009-04-29 21:16:24 +0000440 meta_hosts.append(queue_entry.meta_host)
jamesren2275ef12010-04-12 18:25:06 +0000441 else:
442 hostless = True
443
showard29f7cd22009-04-29 21:16:24 +0000444 if atomic_group is None:
445 if queue_entry.atomic_group is not None:
446 atomic_group = queue_entry.atomic_group
447 else:
448 assert atomic_group.name == queue_entry.atomic_group.name, (
449 'DB inconsistency. HostQueueEntries with multiple atomic'
450 ' groups on job %s: %s != %s' % (
451 id, atomic_group.name, queue_entry.atomic_group.name))
452
453 meta_host_counts = _get_metahost_counts(meta_hosts)
454
455 info = dict(dependencies=[label.name for label
456 in job.dependency_labels.all()],
457 hosts=hosts,
458 meta_hosts=meta_hosts,
459 meta_host_counts=meta_host_counts,
460 one_time_hosts=one_time_hosts,
jamesren2275ef12010-04-12 18:25:06 +0000461 atomic_group=atomic_group,
462 hostless=hostless)
showard29f7cd22009-04-29 21:16:24 +0000463 return info
464
465
showard09d80f92009-11-19 01:01:19 +0000466def check_for_duplicate_hosts(host_objects):
467 host_ids = set()
468 duplicate_hostnames = set()
469 for host in host_objects:
470 if host.id in host_ids:
471 duplicate_hostnames.add(host.hostname)
472 host_ids.add(host.id)
473
474 if duplicate_hostnames:
475 raise model_logic.ValidationError(
476 {'hosts' : 'Duplicate hosts: %s'
477 % ', '.join(duplicate_hostnames)})
478
479
showarda1e74b32009-05-12 17:32:04 +0000480def create_new_job(owner, options, host_objects, metahost_objects,
481 atomic_group=None):
showard29f7cd22009-04-29 21:16:24 +0000482 all_host_objects = host_objects + metahost_objects
483 metahost_counts = _get_metahost_counts(metahost_objects)
showarda1e74b32009-05-12 17:32:04 +0000484 dependencies = options.get('dependencies', [])
485 synch_count = options.get('synch_count')
showard29f7cd22009-04-29 21:16:24 +0000486
showard29f7cd22009-04-29 21:16:24 +0000487 if atomic_group:
488 check_atomic_group_create_job(
489 synch_count, host_objects, metahost_objects,
Alex Miller871291b2013-08-08 01:19:20 -0700490 dependencies, atomic_group)
showard29f7cd22009-04-29 21:16:24 +0000491 else:
492 if synch_count is not None and synch_count > len(all_host_objects):
493 raise model_logic.ValidationError(
494 {'hosts':
495 'only %d hosts provided for job with synch_count = %d' %
496 (len(all_host_objects), synch_count)})
497 atomic_hosts = models.Host.objects.filter(
498 id__in=[host.id for host in host_objects],
499 labels__atomic_group=True)
500 unusable_host_names = [host.hostname for host in atomic_hosts]
501 if unusable_host_names:
502 raise model_logic.ValidationError(
503 {'hosts':
504 'Host(s) "%s" are atomic group hosts but no '
505 'atomic group was specified for this job.' %
506 (', '.join(unusable_host_names),)})
507
showard09d80f92009-11-19 01:01:19 +0000508 check_for_duplicate_hosts(host_objects)
showard29f7cd22009-04-29 21:16:24 +0000509
Aviv Keshetc68807e2013-07-31 16:13:01 -0700510 for label_name in dependencies:
511 if provision.can_provision(label_name):
512 # TODO: We could save a few queries
513 # if we had a bulk ensure-label-exists function, which used
514 # a bulk .get() call. The win is probably very small.
Alex Miller871291b2013-08-08 01:19:20 -0700515 _ensure_label_exists(label_name)
Aviv Keshetc68807e2013-07-31 16:13:01 -0700516
Alex Miller4a193692013-08-21 13:59:01 -0700517 # This only checks targeted hosts, not hosts eligible due to the metahost
518 check_job_dependencies(host_objects, dependencies)
519 check_job_metahost_dependencies(metahost_objects, dependencies)
520
Alex Miller871291b2013-08-08 01:19:20 -0700521 options['dependencies'] = list(
522 models.Label.objects.filter(name__in=dependencies))
showard29f7cd22009-04-29 21:16:24 +0000523
showarda1e74b32009-05-12 17:32:04 +0000524 for label in metahost_objects + options['dependencies']:
showard29f7cd22009-04-29 21:16:24 +0000525 if label.atomic_group and not atomic_group:
526 raise model_logic.ValidationError(
527 {'atomic_group_name':
showardc8730322009-06-30 01:56:38 +0000528 'Dependency %r requires an atomic group but no '
529 'atomic_group_name or meta_host in an atomic group was '
530 'specified for this job.' % label.name})
showard29f7cd22009-04-29 21:16:24 +0000531 elif (label.atomic_group and
532 label.atomic_group.name != atomic_group.name):
533 raise model_logic.ValidationError(
534 {'atomic_group_name':
showardc8730322009-06-30 01:56:38 +0000535 'meta_hosts or dependency %r requires atomic group '
536 '%r instead of the supplied atomic_group_name=%r.' %
537 (label.name, label.atomic_group.name, atomic_group.name)})
showard29f7cd22009-04-29 21:16:24 +0000538
showarda1e74b32009-05-12 17:32:04 +0000539 job = models.Job.create(owner=owner, options=options,
540 hosts=all_host_objects)
showard29f7cd22009-04-29 21:16:24 +0000541 job.queue(all_host_objects, atomic_group=atomic_group,
showarda1e74b32009-05-12 17:32:04 +0000542 is_template=options.get('is_template', False))
showard29f7cd22009-04-29 21:16:24 +0000543 return job.id
showard0957a842009-05-11 19:25:08 +0000544
545
Aviv Keshetc68807e2013-07-31 16:13:01 -0700546def _ensure_label_exists(name):
547 """
548 Ensure that a label called |name| exists in the Django models.
549
550 This function is to be called from within afe rpcs only, as an
551 alternative to server.cros.provision.ensure_label_exists(...). It works
552 by Django model manipulation, rather than by making another create_label
553 rpc call.
554
555 @param name: the label to check for/create.
556 @raises ValidationError: There was an error in the response that was
557 not because the label already existed.
558 @returns True is a label was created, False otherwise.
559 """
560 try:
561 models.Label.objects.get(name=name)
562 except models.Label.DoesNotExist:
563 new_label = models.Label.objects.create(name=name)
564 new_label.save()
565 return True
566 return False
567
568
showard909c9142009-07-07 20:54:42 +0000569def find_platform_and_atomic_group(host):
570 """
571 Figure out the platform name and atomic group name for the given host
572 object. If none, the return value for either will be None.
573
574 @returns (platform name, atomic group name) for the given host.
575 """
showard0957a842009-05-11 19:25:08 +0000576 platforms = [label.name for label in host.label_list if label.platform]
577 if not platforms:
showard909c9142009-07-07 20:54:42 +0000578 platform = None
579 else:
580 platform = platforms[0]
showard0957a842009-05-11 19:25:08 +0000581 if len(platforms) > 1:
582 raise ValueError('Host %s has more than one platform: %s' %
583 (host.hostname, ', '.join(platforms)))
showard909c9142009-07-07 20:54:42 +0000584 for label in host.label_list:
585 if label.atomic_group:
586 atomic_group_name = label.atomic_group.name
587 break
588 else:
589 atomic_group_name = None
590 # Don't check for multiple atomic groups on a host here. That is an
591 # error but should not trip up the RPC interface. monitor_db_cleanup
592 # deals with it. This just returns the first one found.
593 return platform, atomic_group_name
showardc0ac3a72009-07-08 21:14:45 +0000594
595
596# support for get_host_queue_entries_and_special_tasks()
597
598def _common_entry_to_dict(entry, type, job_dict):
599 return dict(type=type,
600 host=entry.host.get_object_dict(),
601 job=job_dict,
602 execution_path=entry.execution_path(),
603 status=entry.status,
604 started_on=entry.started_on,
showard8fb1fde2009-07-11 01:47:16 +0000605 id=str(entry.id) + type)
showardc0ac3a72009-07-08 21:14:45 +0000606
607
608def _special_task_to_dict(special_task):
609 job_dict = None
610 if special_task.queue_entry:
611 job_dict = special_task.queue_entry.job.get_object_dict()
612 return _common_entry_to_dict(special_task, special_task.task, job_dict)
613
614
615def _queue_entry_to_dict(queue_entry):
616 return _common_entry_to_dict(queue_entry, 'Job',
617 queue_entry.job.get_object_dict())
618
619
620def _compute_next_job_for_tasks(queue_entries, special_tasks):
621 """
622 For each task, try to figure out the next job that ran after that task.
623 This is done using two pieces of information:
624 * if the task has a queue entry, we can use that entry's job ID.
625 * if the task has a time_started, we can try to compare that against the
626 started_on field of queue_entries. this isn't guaranteed to work perfectly
627 since queue_entries may also have null started_on values.
628 * if the task has neither, or if use of time_started fails, just use the
629 last computed job ID.
630 """
631 next_job_id = None # most recently computed next job
632 hqe_index = 0 # index for scanning by started_on times
633 for task in special_tasks:
634 if task.queue_entry:
635 next_job_id = task.queue_entry.job.id
636 elif task.time_started is not None:
637 for queue_entry in queue_entries[hqe_index:]:
638 if queue_entry.started_on is None:
639 continue
640 if queue_entry.started_on < task.time_started:
641 break
642 next_job_id = queue_entry.job.id
643
644 task.next_job_id = next_job_id
645
646 # advance hqe_index to just after next_job_id
647 if next_job_id is not None:
648 for queue_entry in queue_entries[hqe_index:]:
649 if queue_entry.job.id < next_job_id:
650 break
651 hqe_index += 1
652
653
654def interleave_entries(queue_entries, special_tasks):
655 """
656 Both lists should be ordered by descending ID.
657 """
658 _compute_next_job_for_tasks(queue_entries, special_tasks)
659
660 # start with all special tasks that've run since the last job
661 interleaved_entries = []
662 for task in special_tasks:
663 if task.next_job_id is not None:
664 break
665 interleaved_entries.append(_special_task_to_dict(task))
666
667 # now interleave queue entries with the remaining special tasks
668 special_task_index = len(interleaved_entries)
669 for queue_entry in queue_entries:
670 interleaved_entries.append(_queue_entry_to_dict(queue_entry))
671 # add all tasks that ran between this job and the previous one
672 for task in special_tasks[special_task_index:]:
673 if task.next_job_id < queue_entry.job.id:
674 break
675 interleaved_entries.append(_special_task_to_dict(task))
676 special_task_index += 1
677
678 return interleaved_entries
jamesren4a41e012010-07-16 22:33:48 +0000679
680
681def get_create_job_common_args(local_args):
682 """
683 Returns a dict containing only the args that apply for create_job_common
684
685 Returns a subset of local_args, which contains only the arguments that can
686 be passed in to create_job_common().
687 """
688 arg_names, _, _, _ = inspect.getargspec(create_job_common)
689 return dict(item for item in local_args.iteritems() if item[0] in arg_names)
690
691
692def create_job_common(name, priority, control_type, control_file=None,
693 hosts=(), meta_hosts=(), one_time_hosts=(),
694 atomic_group_name=None, synch_count=None,
Simran Basi34217022012-11-06 13:43:15 -0800695 is_template=False, timeout=None, max_runtime_mins=None,
jamesren4a41e012010-07-16 22:33:48 +0000696 run_verify=True, email_list='', dependencies=(),
697 reboot_before=None, reboot_after=None,
698 parse_failed_repair=None, hostless=False, keyvals=None,
Aviv Keshet18308922013-02-19 17:49:49 -0800699 drone_set=None, parameterized_job=None,
Dan Shi07e09af2013-04-12 09:31:29 -0700700 parent_job_id=None, test_retry=0, run_reset=True):
Aviv Keshet18308922013-02-19 17:49:49 -0800701 #pylint: disable-msg=C0111
jamesren4a41e012010-07-16 22:33:48 +0000702 """
703 Common code between creating "standard" jobs and creating parameterized jobs
704 """
705 user = models.User.current_user()
706 owner = user.login
707
jamesren4a41e012010-07-16 22:33:48 +0000708 # input validation
709 if not (hosts or meta_hosts or one_time_hosts or atomic_group_name
710 or hostless):
711 raise model_logic.ValidationError({
712 'arguments' : "You must pass at least one of 'hosts', "
713 "'meta_hosts', 'one_time_hosts', "
714 "'atomic_group_name', or 'hostless'"
715 })
716
717 if hostless:
718 if hosts or meta_hosts or one_time_hosts or atomic_group_name:
719 raise model_logic.ValidationError({
720 'hostless': 'Hostless jobs cannot include any hosts!'})
Aviv Keshet3dd8beb2013-05-13 17:36:04 -0700721 server_type = control_data.CONTROL_TYPE_NAMES.SERVER
jamesren4a41e012010-07-16 22:33:48 +0000722 if control_type != server_type:
723 raise model_logic.ValidationError({
724 'control_type': 'Hostless jobs cannot use client-side '
725 'control files'})
726
Alex Miller871291b2013-08-08 01:19:20 -0700727 atomic_groups_by_name = dict((ag.name, ag)
jamesren4a41e012010-07-16 22:33:48 +0000728 for ag in models.AtomicGroup.objects.all())
Alex Miller871291b2013-08-08 01:19:20 -0700729 label_objects = list(models.Label.objects.filter(name__in=meta_hosts))
jamesren4a41e012010-07-16 22:33:48 +0000730
731 # Schedule on an atomic group automagically if one of the labels given
732 # is an atomic group label and no explicit atomic_group_name was supplied.
733 if not atomic_group_name:
Alex Miller871291b2013-08-08 01:19:20 -0700734 for label in label_objects:
jamesren4a41e012010-07-16 22:33:48 +0000735 if label and label.atomic_group:
736 atomic_group_name = label.atomic_group.name
737 break
738
739 # convert hostnames & meta hosts to host/label objects
740 host_objects = models.Host.smart_get_bulk(hosts)
741 metahost_objects = []
Alex Miller871291b2013-08-08 01:19:20 -0700742 meta_host_labels_by_name = {label.name: label for label in label_objects}
jamesren4a41e012010-07-16 22:33:48 +0000743 for label_name in meta_hosts or []:
Alex Miller871291b2013-08-08 01:19:20 -0700744 if label_name in meta_host_labels_by_name:
745 metahost_objects.append(meta_host_labels_by_name[label_name])
jamesren4a41e012010-07-16 22:33:48 +0000746 elif label_name in atomic_groups_by_name:
747 # If given a metahost name that isn't a Label, check to
748 # see if the user was specifying an Atomic Group instead.
749 atomic_group = atomic_groups_by_name[label_name]
750 if atomic_group_name and atomic_group_name != atomic_group.name:
751 raise model_logic.ValidationError({
752 'meta_hosts': (
753 'Label "%s" not found. If assumed to be an '
754 'atomic group it would conflict with the '
755 'supplied atomic group "%s".' % (
756 label_name, atomic_group_name))})
757 atomic_group_name = atomic_group.name
758 else:
759 raise model_logic.ValidationError(
760 {'meta_hosts' : 'Label "%s" not found' % label_name})
761
762 # Create and sanity check an AtomicGroup object if requested.
763 if atomic_group_name:
764 if one_time_hosts:
765 raise model_logic.ValidationError(
766 {'one_time_hosts':
767 'One time hosts cannot be used with an Atomic Group.'})
768 atomic_group = models.AtomicGroup.smart_get(atomic_group_name)
769 if synch_count and synch_count > atomic_group.max_number_of_machines:
770 raise model_logic.ValidationError(
771 {'atomic_group_name' :
772 'You have requested a synch_count (%d) greater than the '
773 'maximum machines in the requested Atomic Group (%d).' %
774 (synch_count, atomic_group.max_number_of_machines)})
775 else:
776 atomic_group = None
777
778 for host in one_time_hosts or []:
779 this_host = models.Host.create_one_time_host(host)
780 host_objects.append(this_host)
781
782 options = dict(name=name,
783 priority=priority,
784 control_file=control_file,
785 control_type=control_type,
786 is_template=is_template,
787 timeout=timeout,
Simran Basi34217022012-11-06 13:43:15 -0800788 max_runtime_mins=max_runtime_mins,
jamesren4a41e012010-07-16 22:33:48 +0000789 synch_count=synch_count,
790 run_verify=run_verify,
791 email_list=email_list,
792 dependencies=dependencies,
793 reboot_before=reboot_before,
794 reboot_after=reboot_after,
795 parse_failed_repair=parse_failed_repair,
796 keyvals=keyvals,
797 drone_set=drone_set,
Aviv Keshet18308922013-02-19 17:49:49 -0800798 parameterized_job=parameterized_job,
Aviv Keshetcd1ff9b2013-03-01 14:55:19 -0800799 parent_job_id=parent_job_id,
Dan Shi07e09af2013-04-12 09:31:29 -0700800 test_retry=test_retry,
801 run_reset=run_reset)
jamesren4a41e012010-07-16 22:33:48 +0000802 return create_new_job(owner=owner,
803 options=options,
804 host_objects=host_objects,
805 metahost_objects=metahost_objects,
806 atomic_group=atomic_group)