blob: 6cb369b9f3af565e4ecef65941f6a4d8c9a3f252 [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
Jiaxi Luo421608e2014-07-07 14:38:00 -070013from autotest_lib.client.common_lib import global_config, priorities
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
Jiaxi Luo15cbf372014-07-01 19:20:20 -070094def extra_job_status_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
Jiaxi Luo15cbf372014-07-01 19:20:20 -0700125def extra_job_type_filters(extra_args, suite=False,
126 sub=False, standalone=False):
127 """\
128 Generate a SQL WHERE clause for job status filtering, and return it in
129 a dict of keyword args to pass to query.extra().
130
131 param extra_args: a dict of existing extra_args.
132
133 No more than one of the parameters should be passed as True:
134 * suite: job which is parent of other jobs
135 * sub: job with a parent job
136 * standalone: job with no child or parent jobs
137 """
138 assert not ((suite and sub) or
139 (suite and standalone) or
140 (sub and standalone)), ('Cannot specify more than one '
141 'filter to this function')
142
143 where = extra_args.get('where', [])
144 parent_job_id = ('DISTINCT parent_job_id')
145 child_job_id = ('id')
146 filter_common = ('(SELECT %s FROM afe_jobs '
147 'WHERE parent_job_id IS NOT NULL)')
148
149 if suite:
150 where.append('id IN ' + filter_common % parent_job_id)
151 elif sub:
152 where.append('id IN ' + filter_common % child_job_id)
153 elif standalone:
154 where.append('NOT EXISTS (SELECT 1 from afe_jobs AS sub_query '
155 'WHERE parent_job_id IS NOT NULL'
156 ' AND (sub_query.parent_job_id=afe_jobs.id'
157 ' OR sub_query.id=afe_jobs.id))')
158 else:
159 return extra_args
160
161 extra_args['where'] = where
162 return extra_args
163
164
165
showard87cc38f2009-08-20 23:37:04 +0000166def extra_host_filters(multiple_labels=()):
jadmanski0afbb632008-06-06 21:10:57 +0000167 """\
168 Generate SQL WHERE clauses for matching hosts in an intersection of
169 labels.
170 """
171 extra_args = {}
showardeab66ce2009-12-23 00:03:56 +0000172 where_str = ('afe_hosts.id in (select host_id from afe_hosts_labels '
jadmanski0afbb632008-06-06 21:10:57 +0000173 'where label_id=%s)')
174 extra_args['where'] = [where_str] * len(multiple_labels)
175 extra_args['params'] = [models.Label.smart_get(label).id
176 for label in multiple_labels]
177 return extra_args
showard8e3aa5e2008-04-08 19:42:32 +0000178
179
showard87cc38f2009-08-20 23:37:04 +0000180def get_host_query(multiple_labels, exclude_only_if_needed_labels,
showard8aa84fc2009-09-16 17:17:55 +0000181 exclude_atomic_group_hosts, valid_only, filter_data):
182 if valid_only:
183 query = models.Host.valid_objects.all()
184 else:
185 query = models.Host.objects.all()
186
showard43a3d262008-11-12 18:17:05 +0000187 if exclude_only_if_needed_labels:
188 only_if_needed_labels = models.Label.valid_objects.filter(
189 only_if_needed=True)
showardf7eac6f2008-11-13 21:18:01 +0000190 if only_if_needed_labels.count() > 0:
showard87cc38f2009-08-20 23:37:04 +0000191 only_if_needed_ids = ','.join(
192 str(label['id'])
193 for label in only_if_needed_labels.values('id'))
showardf7eac6f2008-11-13 21:18:01 +0000194 query = models.Host.objects.add_join(
showardeab66ce2009-12-23 00:03:56 +0000195 query, 'afe_hosts_labels', join_key='host_id',
196 join_condition=('afe_hosts_labels_exclude_OIN.label_id IN (%s)'
showard87cc38f2009-08-20 23:37:04 +0000197 % only_if_needed_ids),
198 suffix='_exclude_OIN', exclude=True)
showard8aa84fc2009-09-16 17:17:55 +0000199
showard87cc38f2009-08-20 23:37:04 +0000200 if exclude_atomic_group_hosts:
201 atomic_group_labels = models.Label.valid_objects.filter(
202 atomic_group__isnull=False)
203 if atomic_group_labels.count() > 0:
204 atomic_group_label_ids = ','.join(
205 str(atomic_group['id'])
206 for atomic_group in atomic_group_labels.values('id'))
207 query = models.Host.objects.add_join(
showardeab66ce2009-12-23 00:03:56 +0000208 query, 'afe_hosts_labels', join_key='host_id',
209 join_condition=(
210 'afe_hosts_labels_exclude_AG.label_id IN (%s)'
211 % atomic_group_label_ids),
showard87cc38f2009-08-20 23:37:04 +0000212 suffix='_exclude_AG', exclude=True)
Fang Deng04d30612013-04-10 18:13:13 -0700213 try:
214 assert 'extra_args' not in filter_data
215 filter_data['extra_args'] = extra_host_filters(multiple_labels)
216 return models.Host.query_objects(filter_data, initial_query=query)
217 except models.Label.DoesNotExist as e:
218 return models.Host.objects.none()
showard43a3d262008-11-12 18:17:05 +0000219
220
showard8fd58242008-03-10 21:29:07 +0000221class InconsistencyException(Exception):
jadmanski0afbb632008-06-06 21:10:57 +0000222 'Raised when a list of objects does not have a consistent value'
showard8fd58242008-03-10 21:29:07 +0000223
224
225def get_consistent_value(objects, field):
mblighc5ddfd12008-08-04 17:15:00 +0000226 if not objects:
227 # well a list of nothing is consistent
228 return None
229
jadmanski0afbb632008-06-06 21:10:57 +0000230 value = getattr(objects[0], field)
231 for obj in objects:
232 this_value = getattr(obj, field)
233 if this_value != value:
234 raise InconsistencyException(objects[0], obj)
235 return value
showard8fd58242008-03-10 21:29:07 +0000236
237
showard2b9a88b2008-06-13 20:55:03 +0000238def prepare_generate_control_file(tests, kernel, label, profilers):
jadmanski0afbb632008-06-06 21:10:57 +0000239 test_objects = [models.Test.smart_get(test) for test in tests]
showard2b9a88b2008-06-13 20:55:03 +0000240 profiler_objects = [models.Profiler.smart_get(profiler)
241 for profiler in profilers]
jadmanski0afbb632008-06-06 21:10:57 +0000242 # ensure tests are all the same type
243 try:
244 test_type = get_consistent_value(test_objects, 'test_type')
245 except InconsistencyException, exc:
246 test1, test2 = exc.args
mblighec5546d2008-06-16 16:51:28 +0000247 raise model_logic.ValidationError(
jadmanski0afbb632008-06-06 21:10:57 +0000248 {'tests' : 'You cannot run both server- and client-side '
249 'tests together (tests %s and %s differ' % (
250 test1.name, test2.name)})
showard8fd58242008-03-10 21:29:07 +0000251
Aviv Keshet3dd8beb2013-05-13 17:36:04 -0700252 is_server = (test_type == control_data.CONTROL_TYPE.SERVER)
showard14374b12009-01-31 00:11:54 +0000253 if test_objects:
254 synch_count = max(test.sync_count for test in test_objects)
255 else:
256 synch_count = 1
jadmanski0afbb632008-06-06 21:10:57 +0000257 if label:
258 label = models.Label.smart_get(label)
mblighe8819cd2008-02-15 16:48:40 +0000259
showard989f25d2008-10-01 11:38:11 +0000260 dependencies = set(label.name for label
261 in models.Label.objects.filter(test__in=test_objects))
262
showard2bab8f42008-11-12 18:15:22 +0000263 cf_info = dict(is_server=is_server, synch_count=synch_count,
264 dependencies=list(dependencies))
265 return cf_info, test_objects, profiler_objects, label
showard989f25d2008-10-01 11:38:11 +0000266
267
268def check_job_dependencies(host_objects, job_dependencies):
269 """
270 Check that a set of machines satisfies a job's dependencies.
271 host_objects: list of models.Host objects
272 job_dependencies: list of names of labels
273 """
274 # check that hosts satisfy dependencies
275 host_ids = [host.id for host in host_objects]
276 hosts_in_job = models.Host.objects.filter(id__in=host_ids)
277 ok_hosts = hosts_in_job
278 for index, dependency in enumerate(job_dependencies):
Alex Milleraa772002014-04-10 17:51:21 -0700279 if not provision.is_for_special_action(dependency):
Aviv Keshetc68807e2013-07-31 16:13:01 -0700280 ok_hosts = ok_hosts.filter(labels__name=dependency)
showard989f25d2008-10-01 11:38:11 +0000281 failing_hosts = (set(host.hostname for host in host_objects) -
282 set(host.hostname for host in ok_hosts))
283 if failing_hosts:
284 raise model_logic.ValidationError(
Eric Lie0493a42010-11-15 13:05:43 -0800285 {'hosts' : 'Host(s) failed to meet job dependencies (' +
286 (', '.join(job_dependencies)) + '): ' +
287 (', '.join(failing_hosts))})
288
showard989f25d2008-10-01 11:38:11 +0000289
Alex Miller4a193692013-08-21 13:59:01 -0700290def check_job_metahost_dependencies(metahost_objects, job_dependencies):
291 """
292 Check that at least one machine within the metahost spec satisfies the job's
293 dependencies.
294
295 @param metahost_objects A list of label objects representing the metahosts.
296 @param job_dependencies A list of strings of the required label names.
297 @raises NoEligibleHostException If a metahost cannot run the job.
298 """
299 for metahost in metahost_objects:
300 hosts = models.Host.objects.filter(labels=metahost)
301 for label_name in job_dependencies:
Alex Milleraa772002014-04-10 17:51:21 -0700302 if not provision.is_for_special_action(label_name):
Alex Miller4a193692013-08-21 13:59:01 -0700303 hosts = hosts.filter(labels__name=label_name)
304 if not any(hosts):
305 raise error.NoEligibleHostException("No hosts within %s satisfy %s."
306 % (metahost.name, ', '.join(job_dependencies)))
307
showard2bab8f42008-11-12 18:15:22 +0000308
309def _execution_key_for(host_queue_entry):
310 return (host_queue_entry.job.id, host_queue_entry.execution_subdir)
311
312
313def check_abort_synchronous_jobs(host_queue_entries):
314 # ensure user isn't aborting part of a synchronous autoserv execution
315 count_per_execution = {}
316 for queue_entry in host_queue_entries:
317 key = _execution_key_for(queue_entry)
318 count_per_execution.setdefault(key, 0)
319 count_per_execution[key] += 1
320
321 for queue_entry in host_queue_entries:
322 if not queue_entry.execution_subdir:
323 continue
324 execution_count = count_per_execution[_execution_key_for(queue_entry)]
325 if execution_count < queue_entry.job.synch_count:
mbligh1ef218d2009-08-03 16:57:56 +0000326 raise model_logic.ValidationError(
327 {'' : 'You cannot abort part of a synchronous job execution '
328 '(%d/%s), %d included, %d expected'
329 % (queue_entry.job.id, queue_entry.execution_subdir,
330 execution_count, queue_entry.job.synch_count)})
showard8fbae652009-01-20 23:23:10 +0000331
332
showardc92da832009-04-07 18:14:34 +0000333def check_atomic_group_create_job(synch_count, host_objects, metahost_objects,
Alex Miller871291b2013-08-08 01:19:20 -0700334 dependencies, atomic_group):
showardc92da832009-04-07 18:14:34 +0000335 """
336 Attempt to reject create_job requests with an atomic group that
337 will be impossible to schedule. The checks are not perfect but
338 should catch the most obvious issues.
339
340 @param synch_count - The job's minimum synch count.
341 @param host_objects - A list of models.Host instances.
342 @param metahost_objects - A list of models.Label instances.
343 @param dependencies - A list of job dependency label names.
showardc92da832009-04-07 18:14:34 +0000344 @param labels_by_name - A dictionary mapping label names to models.Label
345 instance. Used to look up instances for dependencies.
346
347 @raises model_logic.ValidationError - When an issue is found.
348 """
349 # If specific host objects were supplied with an atomic group, verify
350 # that there are enough to satisfy the synch_count.
351 minimum_required = synch_count or 1
352 if (host_objects and not metahost_objects and
353 len(host_objects) < minimum_required):
354 raise model_logic.ValidationError(
355 {'hosts':
356 'only %d hosts provided for job with synch_count = %d' %
357 (len(host_objects), synch_count)})
358
359 # Check that the atomic group has a hope of running this job
360 # given any supplied metahosts and dependancies that may limit.
361
362 # Get a set of hostnames in the atomic group.
363 possible_hosts = set()
364 for label in atomic_group.label_set.all():
365 possible_hosts.update(h.hostname for h in label.host_set.all())
366
367 # Filter out hosts that don't match all of the job dependency labels.
Alex Miller871291b2013-08-08 01:19:20 -0700368 for label in models.Label.objects.filter(name__in=dependencies):
showardc92da832009-04-07 18:14:34 +0000369 hosts_in_label = (h.hostname for h in label.host_set.all())
370 possible_hosts.intersection_update(hosts_in_label)
371
showard225bdc12009-04-13 16:09:21 +0000372 if not host_objects and not metahost_objects:
373 # No hosts or metahosts are required to queue an atomic group Job.
374 # However, if they are given, we respect them below.
375 host_set = possible_hosts
376 else:
377 host_set = set(host.hostname for host in host_objects)
378 unusable_host_set = host_set.difference(possible_hosts)
379 if unusable_host_set:
380 raise model_logic.ValidationError(
381 {'hosts': 'Hosts "%s" are not in Atomic Group "%s"' %
382 (', '.join(sorted(unusable_host_set)), atomic_group.name)})
showardc92da832009-04-07 18:14:34 +0000383
384 # Lookup hosts provided by each meta host and merge them into the
385 # host_set for final counting.
386 for meta_host in metahost_objects:
387 meta_possible = possible_hosts.copy()
388 hosts_in_meta_host = (h.hostname for h in meta_host.host_set.all())
389 meta_possible.intersection_update(hosts_in_meta_host)
390
391 # Count all hosts that this meta_host will provide.
392 host_set.update(meta_possible)
393
394 if len(host_set) < minimum_required:
395 raise model_logic.ValidationError(
396 {'atomic_group_name':
397 'Insufficient hosts in Atomic Group "%s" with the'
398 ' supplied dependencies and meta_hosts.' %
399 (atomic_group.name,)})
400
401
showardbe0d8692009-08-20 23:42:44 +0000402def check_modify_host(update_data):
403 """
404 Sanity check modify_host* requests.
405
406 @param update_data: A dictionary with the changes to make to a host
407 or hosts.
408 """
409 # Only the scheduler (monitor_db) is allowed to modify Host status.
410 # Otherwise race conditions happen as a hosts state is changed out from
411 # beneath tasks being run on a host.
412 if 'status' in update_data:
413 raise model_logic.ValidationError({
414 'status': 'Host status can not be modified by the frontend.'})
415
416
showardce7c0922009-09-11 18:39:24 +0000417def check_modify_host_locking(host, update_data):
418 """
419 Checks when locking/unlocking has been requested if the host is already
420 locked/unlocked.
421
422 @param host: models.Host object to be modified
423 @param update_data: A dictionary with the changes to make to the host.
424 """
425 locked = update_data.get('locked', None)
426 if locked is not None:
427 if locked and host.locked:
428 raise model_logic.ValidationError({
429 'locked': 'Host already locked by %s on %s.' %
430 (host.locked_by, host.lock_time)})
431 if not locked and not host.locked:
432 raise model_logic.ValidationError({
433 'locked': 'Host already unlocked.'})
434
435
showard8fbae652009-01-20 23:23:10 +0000436def get_motd():
437 dirname = os.path.dirname(__file__)
438 filename = os.path.join(dirname, "..", "..", "motd.txt")
439 text = ''
440 try:
441 fp = open(filename, "r")
442 try:
443 text = fp.read()
444 finally:
445 fp.close()
446 except:
447 pass
448
449 return text
showard29f7cd22009-04-29 21:16:24 +0000450
451
452def _get_metahost_counts(metahost_objects):
453 metahost_counts = {}
454 for metahost in metahost_objects:
455 metahost_counts.setdefault(metahost, 0)
456 metahost_counts[metahost] += 1
457 return metahost_counts
458
459
showarda965cef2009-05-15 23:17:41 +0000460def get_job_info(job, preserve_metahosts=False, queue_entry_filter_data=None):
showard29f7cd22009-04-29 21:16:24 +0000461 hosts = []
462 one_time_hosts = []
463 meta_hosts = []
464 atomic_group = None
jamesren2275ef12010-04-12 18:25:06 +0000465 hostless = False
showard29f7cd22009-04-29 21:16:24 +0000466
showard4d077562009-05-08 18:24:36 +0000467 queue_entries = job.hostqueueentry_set.all()
showarda965cef2009-05-15 23:17:41 +0000468 if queue_entry_filter_data:
469 queue_entries = models.HostQueueEntry.query_objects(
470 queue_entry_filter_data, initial_query=queue_entries)
showard4d077562009-05-08 18:24:36 +0000471
472 for queue_entry in queue_entries:
showard29f7cd22009-04-29 21:16:24 +0000473 if (queue_entry.host and (preserve_metahosts or
474 not queue_entry.meta_host)):
475 if queue_entry.deleted:
476 continue
477 if queue_entry.host.invalid:
478 one_time_hosts.append(queue_entry.host)
479 else:
480 hosts.append(queue_entry.host)
jamesren2275ef12010-04-12 18:25:06 +0000481 elif queue_entry.meta_host:
showard29f7cd22009-04-29 21:16:24 +0000482 meta_hosts.append(queue_entry.meta_host)
jamesren2275ef12010-04-12 18:25:06 +0000483 else:
484 hostless = True
485
showard29f7cd22009-04-29 21:16:24 +0000486 if atomic_group is None:
487 if queue_entry.atomic_group is not None:
488 atomic_group = queue_entry.atomic_group
489 else:
490 assert atomic_group.name == queue_entry.atomic_group.name, (
491 'DB inconsistency. HostQueueEntries with multiple atomic'
492 ' groups on job %s: %s != %s' % (
493 id, atomic_group.name, queue_entry.atomic_group.name))
494
495 meta_host_counts = _get_metahost_counts(meta_hosts)
496
497 info = dict(dependencies=[label.name for label
498 in job.dependency_labels.all()],
499 hosts=hosts,
500 meta_hosts=meta_hosts,
501 meta_host_counts=meta_host_counts,
502 one_time_hosts=one_time_hosts,
jamesren2275ef12010-04-12 18:25:06 +0000503 atomic_group=atomic_group,
504 hostless=hostless)
showard29f7cd22009-04-29 21:16:24 +0000505 return info
506
507
showard09d80f92009-11-19 01:01:19 +0000508def check_for_duplicate_hosts(host_objects):
509 host_ids = set()
510 duplicate_hostnames = set()
511 for host in host_objects:
512 if host.id in host_ids:
513 duplicate_hostnames.add(host.hostname)
514 host_ids.add(host.id)
515
516 if duplicate_hostnames:
517 raise model_logic.ValidationError(
518 {'hosts' : 'Duplicate hosts: %s'
519 % ', '.join(duplicate_hostnames)})
520
521
showarda1e74b32009-05-12 17:32:04 +0000522def create_new_job(owner, options, host_objects, metahost_objects,
523 atomic_group=None):
showard29f7cd22009-04-29 21:16:24 +0000524 all_host_objects = host_objects + metahost_objects
525 metahost_counts = _get_metahost_counts(metahost_objects)
showarda1e74b32009-05-12 17:32:04 +0000526 dependencies = options.get('dependencies', [])
527 synch_count = options.get('synch_count')
showard29f7cd22009-04-29 21:16:24 +0000528
showard29f7cd22009-04-29 21:16:24 +0000529 if atomic_group:
530 check_atomic_group_create_job(
531 synch_count, host_objects, metahost_objects,
Alex Miller871291b2013-08-08 01:19:20 -0700532 dependencies, atomic_group)
showard29f7cd22009-04-29 21:16:24 +0000533 else:
534 if synch_count is not None and synch_count > len(all_host_objects):
535 raise model_logic.ValidationError(
536 {'hosts':
537 'only %d hosts provided for job with synch_count = %d' %
538 (len(all_host_objects), synch_count)})
539 atomic_hosts = models.Host.objects.filter(
540 id__in=[host.id for host in host_objects],
541 labels__atomic_group=True)
542 unusable_host_names = [host.hostname for host in atomic_hosts]
543 if unusable_host_names:
544 raise model_logic.ValidationError(
545 {'hosts':
546 'Host(s) "%s" are atomic group hosts but no '
547 'atomic group was specified for this job.' %
548 (', '.join(unusable_host_names),)})
549
showard09d80f92009-11-19 01:01:19 +0000550 check_for_duplicate_hosts(host_objects)
showard29f7cd22009-04-29 21:16:24 +0000551
Aviv Keshetc68807e2013-07-31 16:13:01 -0700552 for label_name in dependencies:
Alex Milleraa772002014-04-10 17:51:21 -0700553 if provision.is_for_special_action(label_name):
Aviv Keshetc68807e2013-07-31 16:13:01 -0700554 # TODO: We could save a few queries
555 # if we had a bulk ensure-label-exists function, which used
556 # a bulk .get() call. The win is probably very small.
Alex Miller871291b2013-08-08 01:19:20 -0700557 _ensure_label_exists(label_name)
Aviv Keshetc68807e2013-07-31 16:13:01 -0700558
Alex Miller4a193692013-08-21 13:59:01 -0700559 # This only checks targeted hosts, not hosts eligible due to the metahost
560 check_job_dependencies(host_objects, dependencies)
561 check_job_metahost_dependencies(metahost_objects, dependencies)
562
Alex Miller871291b2013-08-08 01:19:20 -0700563 options['dependencies'] = list(
564 models.Label.objects.filter(name__in=dependencies))
showard29f7cd22009-04-29 21:16:24 +0000565
showarda1e74b32009-05-12 17:32:04 +0000566 for label in metahost_objects + options['dependencies']:
showard29f7cd22009-04-29 21:16:24 +0000567 if label.atomic_group and not atomic_group:
568 raise model_logic.ValidationError(
569 {'atomic_group_name':
showardc8730322009-06-30 01:56:38 +0000570 'Dependency %r requires an atomic group but no '
571 'atomic_group_name or meta_host in an atomic group was '
572 'specified for this job.' % label.name})
showard29f7cd22009-04-29 21:16:24 +0000573 elif (label.atomic_group and
574 label.atomic_group.name != atomic_group.name):
575 raise model_logic.ValidationError(
576 {'atomic_group_name':
showardc8730322009-06-30 01:56:38 +0000577 'meta_hosts or dependency %r requires atomic group '
578 '%r instead of the supplied atomic_group_name=%r.' %
579 (label.name, label.atomic_group.name, atomic_group.name)})
showard29f7cd22009-04-29 21:16:24 +0000580
showarda1e74b32009-05-12 17:32:04 +0000581 job = models.Job.create(owner=owner, options=options,
582 hosts=all_host_objects)
showard29f7cd22009-04-29 21:16:24 +0000583 job.queue(all_host_objects, atomic_group=atomic_group,
showarda1e74b32009-05-12 17:32:04 +0000584 is_template=options.get('is_template', False))
showard29f7cd22009-04-29 21:16:24 +0000585 return job.id
showard0957a842009-05-11 19:25:08 +0000586
587
Aviv Keshetc68807e2013-07-31 16:13:01 -0700588def _ensure_label_exists(name):
589 """
590 Ensure that a label called |name| exists in the Django models.
591
592 This function is to be called from within afe rpcs only, as an
593 alternative to server.cros.provision.ensure_label_exists(...). It works
594 by Django model manipulation, rather than by making another create_label
595 rpc call.
596
597 @param name: the label to check for/create.
598 @raises ValidationError: There was an error in the response that was
599 not because the label already existed.
600 @returns True is a label was created, False otherwise.
601 """
602 try:
603 models.Label.objects.get(name=name)
604 except models.Label.DoesNotExist:
605 new_label = models.Label.objects.create(name=name)
606 new_label.save()
607 return True
608 return False
609
610
showard909c9142009-07-07 20:54:42 +0000611def find_platform_and_atomic_group(host):
612 """
613 Figure out the platform name and atomic group name for the given host
614 object. If none, the return value for either will be None.
615
616 @returns (platform name, atomic group name) for the given host.
617 """
showard0957a842009-05-11 19:25:08 +0000618 platforms = [label.name for label in host.label_list if label.platform]
619 if not platforms:
showard909c9142009-07-07 20:54:42 +0000620 platform = None
621 else:
622 platform = platforms[0]
showard0957a842009-05-11 19:25:08 +0000623 if len(platforms) > 1:
624 raise ValueError('Host %s has more than one platform: %s' %
625 (host.hostname, ', '.join(platforms)))
showard909c9142009-07-07 20:54:42 +0000626 for label in host.label_list:
627 if label.atomic_group:
628 atomic_group_name = label.atomic_group.name
629 break
630 else:
631 atomic_group_name = None
632 # Don't check for multiple atomic groups on a host here. That is an
633 # error but should not trip up the RPC interface. monitor_db_cleanup
634 # deals with it. This just returns the first one found.
635 return platform, atomic_group_name
showardc0ac3a72009-07-08 21:14:45 +0000636
637
638# support for get_host_queue_entries_and_special_tasks()
639
640def _common_entry_to_dict(entry, type, job_dict):
641 return dict(type=type,
642 host=entry.host.get_object_dict(),
643 job=job_dict,
644 execution_path=entry.execution_path(),
645 status=entry.status,
646 started_on=entry.started_on,
Jiaxi Luocb91d2e2014-06-30 10:37:22 -0700647 id=str(entry.id) + type,
648 oid=entry.id)
showardc0ac3a72009-07-08 21:14:45 +0000649
650
651def _special_task_to_dict(special_task):
652 job_dict = None
653 if special_task.queue_entry:
654 job_dict = special_task.queue_entry.job.get_object_dict()
655 return _common_entry_to_dict(special_task, special_task.task, job_dict)
656
657
658def _queue_entry_to_dict(queue_entry):
659 return _common_entry_to_dict(queue_entry, 'Job',
660 queue_entry.job.get_object_dict())
661
662
663def _compute_next_job_for_tasks(queue_entries, special_tasks):
664 """
665 For each task, try to figure out the next job that ran after that task.
666 This is done using two pieces of information:
667 * if the task has a queue entry, we can use that entry's job ID.
668 * if the task has a time_started, we can try to compare that against the
669 started_on field of queue_entries. this isn't guaranteed to work perfectly
670 since queue_entries may also have null started_on values.
671 * if the task has neither, or if use of time_started fails, just use the
672 last computed job ID.
673 """
674 next_job_id = None # most recently computed next job
675 hqe_index = 0 # index for scanning by started_on times
676 for task in special_tasks:
677 if task.queue_entry:
678 next_job_id = task.queue_entry.job.id
679 elif task.time_started is not None:
680 for queue_entry in queue_entries[hqe_index:]:
681 if queue_entry.started_on is None:
682 continue
683 if queue_entry.started_on < task.time_started:
684 break
685 next_job_id = queue_entry.job.id
686
687 task.next_job_id = next_job_id
688
689 # advance hqe_index to just after next_job_id
690 if next_job_id is not None:
691 for queue_entry in queue_entries[hqe_index:]:
692 if queue_entry.job.id < next_job_id:
693 break
694 hqe_index += 1
695
696
697def interleave_entries(queue_entries, special_tasks):
698 """
699 Both lists should be ordered by descending ID.
700 """
701 _compute_next_job_for_tasks(queue_entries, special_tasks)
702
703 # start with all special tasks that've run since the last job
704 interleaved_entries = []
705 for task in special_tasks:
706 if task.next_job_id is not None:
707 break
708 interleaved_entries.append(_special_task_to_dict(task))
709
710 # now interleave queue entries with the remaining special tasks
711 special_task_index = len(interleaved_entries)
712 for queue_entry in queue_entries:
713 interleaved_entries.append(_queue_entry_to_dict(queue_entry))
714 # add all tasks that ran between this job and the previous one
715 for task in special_tasks[special_task_index:]:
716 if task.next_job_id < queue_entry.job.id:
717 break
718 interleaved_entries.append(_special_task_to_dict(task))
719 special_task_index += 1
720
721 return interleaved_entries
jamesren4a41e012010-07-16 22:33:48 +0000722
723
724def get_create_job_common_args(local_args):
725 """
726 Returns a dict containing only the args that apply for create_job_common
727
728 Returns a subset of local_args, which contains only the arguments that can
729 be passed in to create_job_common().
730 """
Alex Miller7d658cf2013-09-04 16:00:35 -0700731 # This code is only here to not kill suites scheduling tests when priority
732 # becomes an int instead of a string.
733 if isinstance(local_args['priority'], str):
734 local_args['priority'] = priorities.Priority.DEFAULT
735 # </migration hack>
jamesren4a41e012010-07-16 22:33:48 +0000736 arg_names, _, _, _ = inspect.getargspec(create_job_common)
737 return dict(item for item in local_args.iteritems() if item[0] in arg_names)
738
739
740def create_job_common(name, priority, control_type, control_file=None,
741 hosts=(), meta_hosts=(), one_time_hosts=(),
742 atomic_group_name=None, synch_count=None,
Simran Basi7e605742013-11-12 13:43:36 -0800743 is_template=False, timeout=None, timeout_mins=None,
744 max_runtime_mins=None, run_verify=True, email_list='',
745 dependencies=(), reboot_before=None, reboot_after=None,
jamesren4a41e012010-07-16 22:33:48 +0000746 parse_failed_repair=None, hostless=False, keyvals=None,
Aviv Keshet18308922013-02-19 17:49:49 -0800747 drone_set=None, parameterized_job=None,
Dan Shi07e09af2013-04-12 09:31:29 -0700748 parent_job_id=None, test_retry=0, run_reset=True):
Aviv Keshet18308922013-02-19 17:49:49 -0800749 #pylint: disable-msg=C0111
jamesren4a41e012010-07-16 22:33:48 +0000750 """
751 Common code between creating "standard" jobs and creating parameterized jobs
752 """
753 user = models.User.current_user()
754 owner = user.login
755
jamesren4a41e012010-07-16 22:33:48 +0000756 # input validation
757 if not (hosts or meta_hosts or one_time_hosts or atomic_group_name
758 or hostless):
759 raise model_logic.ValidationError({
760 'arguments' : "You must pass at least one of 'hosts', "
761 "'meta_hosts', 'one_time_hosts', "
762 "'atomic_group_name', or 'hostless'"
763 })
764
765 if hostless:
766 if hosts or meta_hosts or one_time_hosts or atomic_group_name:
767 raise model_logic.ValidationError({
768 'hostless': 'Hostless jobs cannot include any hosts!'})
Aviv Keshet3dd8beb2013-05-13 17:36:04 -0700769 server_type = control_data.CONTROL_TYPE_NAMES.SERVER
jamesren4a41e012010-07-16 22:33:48 +0000770 if control_type != server_type:
771 raise model_logic.ValidationError({
772 'control_type': 'Hostless jobs cannot use client-side '
773 'control files'})
774
Alex Miller871291b2013-08-08 01:19:20 -0700775 atomic_groups_by_name = dict((ag.name, ag)
jamesren4a41e012010-07-16 22:33:48 +0000776 for ag in models.AtomicGroup.objects.all())
Alex Miller871291b2013-08-08 01:19:20 -0700777 label_objects = list(models.Label.objects.filter(name__in=meta_hosts))
jamesren4a41e012010-07-16 22:33:48 +0000778
779 # Schedule on an atomic group automagically if one of the labels given
780 # is an atomic group label and no explicit atomic_group_name was supplied.
781 if not atomic_group_name:
Alex Miller871291b2013-08-08 01:19:20 -0700782 for label in label_objects:
jamesren4a41e012010-07-16 22:33:48 +0000783 if label and label.atomic_group:
784 atomic_group_name = label.atomic_group.name
785 break
786
787 # convert hostnames & meta hosts to host/label objects
788 host_objects = models.Host.smart_get_bulk(hosts)
789 metahost_objects = []
Alex Miller871291b2013-08-08 01:19:20 -0700790 meta_host_labels_by_name = {label.name: label for label in label_objects}
jamesren4a41e012010-07-16 22:33:48 +0000791 for label_name in meta_hosts or []:
Alex Miller871291b2013-08-08 01:19:20 -0700792 if label_name in meta_host_labels_by_name:
793 metahost_objects.append(meta_host_labels_by_name[label_name])
jamesren4a41e012010-07-16 22:33:48 +0000794 elif label_name in atomic_groups_by_name:
795 # If given a metahost name that isn't a Label, check to
796 # see if the user was specifying an Atomic Group instead.
797 atomic_group = atomic_groups_by_name[label_name]
798 if atomic_group_name and atomic_group_name != atomic_group.name:
799 raise model_logic.ValidationError({
800 'meta_hosts': (
801 'Label "%s" not found. If assumed to be an '
802 'atomic group it would conflict with the '
803 'supplied atomic group "%s".' % (
804 label_name, atomic_group_name))})
805 atomic_group_name = atomic_group.name
806 else:
807 raise model_logic.ValidationError(
808 {'meta_hosts' : 'Label "%s" not found' % label_name})
809
810 # Create and sanity check an AtomicGroup object if requested.
811 if atomic_group_name:
812 if one_time_hosts:
813 raise model_logic.ValidationError(
814 {'one_time_hosts':
815 'One time hosts cannot be used with an Atomic Group.'})
816 atomic_group = models.AtomicGroup.smart_get(atomic_group_name)
817 if synch_count and synch_count > atomic_group.max_number_of_machines:
818 raise model_logic.ValidationError(
819 {'atomic_group_name' :
820 'You have requested a synch_count (%d) greater than the '
821 'maximum machines in the requested Atomic Group (%d).' %
822 (synch_count, atomic_group.max_number_of_machines)})
823 else:
824 atomic_group = None
825
826 for host in one_time_hosts or []:
827 this_host = models.Host.create_one_time_host(host)
828 host_objects.append(this_host)
829
830 options = dict(name=name,
831 priority=priority,
832 control_file=control_file,
833 control_type=control_type,
834 is_template=is_template,
835 timeout=timeout,
Simran Basi7e605742013-11-12 13:43:36 -0800836 timeout_mins=timeout_mins,
Simran Basi34217022012-11-06 13:43:15 -0800837 max_runtime_mins=max_runtime_mins,
jamesren4a41e012010-07-16 22:33:48 +0000838 synch_count=synch_count,
839 run_verify=run_verify,
840 email_list=email_list,
841 dependencies=dependencies,
842 reboot_before=reboot_before,
843 reboot_after=reboot_after,
844 parse_failed_repair=parse_failed_repair,
845 keyvals=keyvals,
846 drone_set=drone_set,
Aviv Keshet18308922013-02-19 17:49:49 -0800847 parameterized_job=parameterized_job,
Aviv Keshetcd1ff9b2013-03-01 14:55:19 -0800848 parent_job_id=parent_job_id,
Dan Shi07e09af2013-04-12 09:31:29 -0700849 test_retry=test_retry,
850 run_reset=run_reset)
jamesren4a41e012010-07-16 22:33:48 +0000851 return create_new_job(owner=owner,
852 options=options,
853 host_objects=host_objects,
854 metahost_objects=metahost_objects,
855 atomic_group=atomic_group)
Simran Basib6ec8ae2014-04-23 12:05:08 -0700856
857
858def encode_ascii(control_file):
859 """Force a control file to only contain ascii characters.
860
861 @param control_file: Control file to encode.
862
863 @returns the control file in an ascii encoding.
864
865 @raises error.ControlFileMalformed: if encoding fails.
866 """
867 try:
868 return control_file.encode('ascii')
869 except UnicodeDecodeError as e:
Jiaxi Luo421608e2014-07-07 14:38:00 -0700870 raise error.ControlFileMalformed(str(e))
871
872
873def get_wmatrix_url():
874 """Get wmatrix url from config file.
875
876 @returns the wmatrix url or an empty string.
877 """
878 return global_config.global_config.get_config_value('AUTOTEST_WEB',
879 'wmatrix_url',
Jiaxi Luo15cbf372014-07-01 19:20:20 -0700880 default='')