blob: c6e48820bdd7e9ac850dbeb46aec4b845d45fda5 [file] [log] [blame]
Richard Barnette6c2b70a2017-01-26 13:40:51 -08001# pylint: disable=missing-docstring
Don Garretta06ea082017-01-13 00:04:26 +00002
mblighe8819cd2008-02-15 16:48:40 +00003"""\
4Functions to expose over the RPC interface.
5
6For all modify* and delete* functions that ask for an 'id' parameter to
7identify the object to operate on, the id may be either
8 * the database row ID
9 * the name of the object (label name, hostname, user login, etc.)
10 * a dictionary containing uniquely identifying field (this option should seldom
11 be used)
12
13When specifying foreign key fields (i.e. adding hosts to a label, or adding
14users to an ACL group), the given value may be either the database row ID or the
15name of the object.
16
17All get* functions return lists of dictionaries. Each dictionary represents one
18object and maps field names to values.
19
20Some examples:
21modify_host(2, hostname='myhost') # modify hostname of host with database ID 2
22modify_host('ipaj2', hostname='myhost') # modify hostname of host 'ipaj2'
23modify_test('sleeptest', test_type='Client', params=', seconds=60')
24delete_acl_group(1) # delete by ID
25delete_acl_group('Everyone') # delete by name
26acl_group_add_users('Everyone', ['mbligh', 'showard'])
27get_jobs(owner='showard', status='Queued')
28
mbligh93c80e62009-02-03 17:48:30 +000029See doctests/001_rpc_test.txt for (lots) more examples.
mblighe8819cd2008-02-15 16:48:40 +000030"""
31
32__author__ = 'showard@google.com (Steve Howard)'
33
Michael Tang6dc174e2016-05-31 23:13:42 -070034import ast
showard29f7cd22009-04-29 21:16:24 +000035import datetime
Shuqian Zhao4c0d2902016-01-12 17:03:15 -080036import logging
Allen Licdd00f22017-02-01 18:01:52 -080037import os
Dan Shi4a3deb82016-10-27 21:32:30 -070038import sys
MK Ryu9c5fbbe2015-02-11 15:46:22 -080039
Moises Osorio2dc7a102014-12-02 18:24:02 -080040from django.db.models import Count
Allen Licdd00f22017-02-01 18:01:52 -080041
showardcafd16e2009-05-29 18:37:49 +000042import common
Aviv Keshet14cac442016-11-20 21:44:11 -080043# TODO(akeshet): Replace with monarch stats once we know how to instrument rpc
44# server with ts_mon.
Gabe Black1e1c41b2015-02-04 23:55:15 -080045from autotest_lib.client.common_lib.cros.graphite import autotest_stats
Allen Licdd00f22017-02-01 18:01:52 -080046from autotest_lib.client.common_lib import control_data
47from autotest_lib.client.common_lib import error
48from autotest_lib.client.common_lib import global_config
49from autotest_lib.client.common_lib import priorities
50from autotest_lib.client.common_lib import time_utils
51from autotest_lib.client.common_lib.cros import dev_server
Allen Lia59b1262016-12-14 12:53:51 -080052from autotest_lib.frontend.afe import control_file as control_file_lib
Allen Licdd00f22017-02-01 18:01:52 -080053from autotest_lib.frontend.afe import model_attributes
54from autotest_lib.frontend.afe import model_logic
55from autotest_lib.frontend.afe import models
Allen Lia59b1262016-12-14 12:53:51 -080056from autotest_lib.frontend.afe import rpc_utils
Moises Osorio2dc7a102014-12-02 18:24:02 -080057from autotest_lib.frontend.tko import models as tko_models
Jiaxi Luoaac54572014-06-04 13:57:02 -070058from autotest_lib.frontend.tko import rpc_interface as tko_rpc_interface
J. Richard Barnetteb5164d62015-04-13 12:59:31 -070059from autotest_lib.server import frontend
Simran Basi71206ef2014-08-13 13:51:18 -070060from autotest_lib.server import utils
Dan Shid215dbe2015-06-18 16:14:59 -070061from autotest_lib.server.cros import provision
Allen Licdd00f22017-02-01 18:01:52 -080062from autotest_lib.server.cros.dynamic_suite import constants
63from autotest_lib.server.cros.dynamic_suite import control_file_getter
64from autotest_lib.server.cros.dynamic_suite import suite as SuiteBase
Jiaxi Luo90190c92014-06-18 12:35:57 -070065from autotest_lib.server.cros.dynamic_suite import tools
Allen Licdd00f22017-02-01 18:01:52 -080066from autotest_lib.server.cros.dynamic_suite.suite import Suite
Aviv Keshet7ee95862016-08-30 15:18:27 -070067from autotest_lib.server.lib import status_history
Allen Licdd00f22017-02-01 18:01:52 -080068from autotest_lib.site_utils import host_history
69from autotest_lib.site_utils import job_history
70from autotest_lib.site_utils import server_manager_utils
71from autotest_lib.site_utils import stable_version_utils
mblighe8819cd2008-02-15 16:48:40 +000072
Moises Osorio2dc7a102014-12-02 18:24:02 -080073
Allen Licdd00f22017-02-01 18:01:52 -080074_CONFIG = global_config.global_config
75
76# Relevant CrosDynamicSuiteExceptions are defined in client/common_lib/error.py.
77
Eric Lid23bc192011-02-09 14:38:57 -080078def get_parameterized_autoupdate_image_url(job):
79 """Get the parameterized autoupdate image url from a parameterized job."""
80 known_test_obj = models.Test.smart_get('autoupdate_ParameterizedJob')
81 image_parameter = known_test_obj.testparameter_set.get(test=known_test_obj,
beeps8bb1f7d2013-08-05 01:30:09 -070082 name='image')
Eric Lid23bc192011-02-09 14:38:57 -080083 para_set = job.parameterized_job.parameterizedjobparameter_set
84 job_test_para = para_set.get(test_parameter=image_parameter)
85 return job_test_para.parameter_value
86
87
mblighe8819cd2008-02-15 16:48:40 +000088# labels
89
mblighe8819cd2008-02-15 16:48:40 +000090def modify_label(id, **data):
MK Ryu8c554cf2015-06-12 11:45:50 -070091 """Modify a label.
92
93 @param id: id or name of a label. More often a label name.
94 @param data: New data for a label.
95 """
96 label_model = models.Label.smart_get(id)
MK Ryu8e2c2d02016-01-06 15:24:38 -080097 label_model.update_object(data)
MK Ryu8c554cf2015-06-12 11:45:50 -070098
99 # Master forwards the RPC to shards
100 if not utils.is_shard():
101 rpc_utils.fanout_rpc(label_model.host_set.all(), 'modify_label', False,
102 id=id, **data)
103
mblighe8819cd2008-02-15 16:48:40 +0000104
105def delete_label(id):
MK Ryu8c554cf2015-06-12 11:45:50 -0700106 """Delete a label.
107
108 @param id: id or name of a label. More often a label name.
109 """
110 label_model = models.Label.smart_get(id)
MK Ryu8e2c2d02016-01-06 15:24:38 -0800111 # Hosts that have the label to be deleted. Save this info before
112 # the label is deleted to use it later.
113 hosts = []
114 for h in label_model.host_set.all():
115 hosts.append(models.Host.smart_get(h.id))
116 label_model.delete()
MK Ryu8c554cf2015-06-12 11:45:50 -0700117
118 # Master forwards the RPC to shards
119 if not utils.is_shard():
MK Ryu8e2c2d02016-01-06 15:24:38 -0800120 rpc_utils.fanout_rpc(hosts, 'delete_label', False, id=id)
mblighe8819cd2008-02-15 16:48:40 +0000121
Prashanth Balasubramanian744898f2015-01-13 05:04:16 -0800122
MK Ryu9c5fbbe2015-02-11 15:46:22 -0800123def add_label(name, ignore_exception_if_exists=False, **kwargs):
MK Ryucf027c62015-03-04 12:00:50 -0800124 """Adds a new label of a given name.
MK Ryu9c5fbbe2015-02-11 15:46:22 -0800125
126 @param name: label name.
127 @param ignore_exception_if_exists: If True and the exception was
128 thrown due to the duplicated label name when adding a label,
129 then suppress the exception. Default is False.
130 @param kwargs: keyword args that store more info about a label
131 other than the name.
132 @return: int/long id of a new label.
133 """
134 # models.Label.add_object() throws model_logic.ValidationError
135 # when it is given a label name that already exists.
136 # However, ValidationError can be thrown with different errors,
137 # and those errors should be thrown up to the call chain.
138 try:
139 label = models.Label.add_object(name=name, **kwargs)
140 except:
141 exc_info = sys.exc_info()
142 if ignore_exception_if_exists:
143 label = rpc_utils.get_label(name)
144 # If the exception is raised not because of duplicated
145 # "name", then raise the original exception.
146 if label is None:
147 raise exc_info[0], exc_info[1], exc_info[2]
148 else:
149 raise exc_info[0], exc_info[1], exc_info[2]
150 return label.id
151
152
153def add_label_to_hosts(id, hosts):
MK Ryucf027c62015-03-04 12:00:50 -0800154 """Adds a label of the given id to the given hosts only in local DB.
MK Ryu9c5fbbe2015-02-11 15:46:22 -0800155
156 @param id: id or name of a label. More often a label name.
157 @param hosts: The hostnames of hosts that need the label.
158
159 @raises models.Label.DoesNotExist: If the label with id doesn't exist.
160 """
161 label = models.Label.smart_get(id)
162 host_objs = models.Host.smart_get_bulk(hosts)
163 if label.platform:
164 models.Host.check_no_platform(host_objs)
Shuqian Zhao40e182b2016-10-11 11:55:11 -0700165 # Ensure a host has no more than one board label with it.
166 if label.name.startswith('board:'):
Dan Shib5b8b4f2016-11-02 14:04:02 -0700167 models.Host.check_board_labels_allowed(host_objs, [label.name])
MK Ryu9c5fbbe2015-02-11 15:46:22 -0800168 label.host_set.add(*host_objs)
169
170
Kevin Chengbdfc57d2016-04-14 13:46:58 -0700171def _create_label_everywhere(id, hosts):
172 """
173 Yet another method to create labels.
174
175 ALERT! This method should be run only on master not shards!
176 DO NOT RUN THIS ON A SHARD!!! Deputies will hate you if you do!!!
177
178 This method exists primarily to serve label_add_hosts() and
179 host_add_labels(). Basically it pulls out the label check/add logic
180 from label_add_hosts() into this nice method that not only creates
181 the label but also tells the shards that service the hosts to also
182 create the label.
183
184 @param id: id or name of a label. More often a label name.
185 @param hosts: A list of hostnames or ids. More often hostnames.
186 """
187 try:
188 label = models.Label.smart_get(id)
189 except models.Label.DoesNotExist:
190 # This matches the type checks in smart_get, which is a hack
191 # in and off itself. The aim here is to create any non-existent
192 # label, which we cannot do if the 'id' specified isn't a label name.
193 if isinstance(id, basestring):
194 label = models.Label.smart_get(add_label(id))
195 else:
196 raise ValueError('Label id (%s) does not exist. Please specify '
197 'the argument, id, as a string (label name).'
198 % id)
199
200 # Make sure the label exists on the shard with the same id
201 # as it is on the master.
202 # It is possible that the label is already in a shard because
203 # we are adding a new label only to shards of hosts that the label
204 # is going to be attached.
205 # For example, we add a label L1 to a host in shard S1.
206 # Master and S1 will have L1 but other shards won't.
207 # Later, when we add the same label L1 to hosts in shards S1 and S2,
208 # S1 already has the label but S2 doesn't.
209 # S2 should have the new label without any problem.
210 # We ignore exception in such a case.
211 host_objs = models.Host.smart_get_bulk(hosts)
212 rpc_utils.fanout_rpc(
213 host_objs, 'add_label', include_hostnames=False,
214 name=label.name, ignore_exception_if_exists=True,
215 id=label.id, platform=label.platform)
216
217
MK Ryufbb002c2015-06-08 14:13:16 -0700218@rpc_utils.route_rpc_to_master
MK Ryu9c5fbbe2015-02-11 15:46:22 -0800219def label_add_hosts(id, hosts):
MK Ryucf027c62015-03-04 12:00:50 -0800220 """Adds a label with the given id to the given hosts.
MK Ryu9c5fbbe2015-02-11 15:46:22 -0800221
222 This method should be run only on master not shards.
Prashanth Balasubramanian5949b4a2014-11-23 12:58:30 -0800223 The given label will be created if it doesn't exist, provided the `id`
224 supplied is a label name not an int/long id.
225
MK Ryu9c5fbbe2015-02-11 15:46:22 -0800226 @param id: id or name of a label. More often a label name.
Prashanth Balasubramanian5949b4a2014-11-23 12:58:30 -0800227 @param hosts: A list of hostnames or ids. More often hostnames.
228
MK Ryu9c5fbbe2015-02-11 15:46:22 -0800229 @raises ValueError: If the id specified is an int/long (label id)
230 while the label does not exist.
Prashanth Balasubramanian5949b4a2014-11-23 12:58:30 -0800231 """
Kevin Chengbdfc57d2016-04-14 13:46:58 -0700232 # Create the label.
233 _create_label_everywhere(id, hosts)
234
235 # Add it to the master.
MK Ryu8e2c2d02016-01-06 15:24:38 -0800236 add_label_to_hosts(id, hosts)
MK Ryucf027c62015-03-04 12:00:50 -0800237
Kevin Chengbdfc57d2016-04-14 13:46:58 -0700238 # Add it to the shards.
MK Ryucf027c62015-03-04 12:00:50 -0800239 host_objs = models.Host.smart_get_bulk(hosts)
MK Ryu9c5fbbe2015-02-11 15:46:22 -0800240 rpc_utils.fanout_rpc(host_objs, 'add_label_to_hosts', id=id)
showardbbabf502008-06-06 00:02:02 +0000241
242
MK Ryucf027c62015-03-04 12:00:50 -0800243def remove_label_from_hosts(id, hosts):
244 """Removes a label of the given id from the given hosts only in local DB.
245
246 @param id: id or name of a label.
247 @param hosts: The hostnames of hosts that need to remove the label from.
248 """
showardbe3ec042008-11-12 18:16:07 +0000249 host_objs = models.Host.smart_get_bulk(hosts)
jadmanski0afbb632008-06-06 21:10:57 +0000250 models.Label.smart_get(id).host_set.remove(*host_objs)
showardbbabf502008-06-06 00:02:02 +0000251
252
MK Ryufbb002c2015-06-08 14:13:16 -0700253@rpc_utils.route_rpc_to_master
MK Ryucf027c62015-03-04 12:00:50 -0800254def label_remove_hosts(id, hosts):
255 """Removes a label of the given id from the given hosts.
256
257 This method should be run only on master not shards.
258
259 @param id: id or name of a label.
260 @param hosts: A list of hostnames or ids. More often hostnames.
261 """
MK Ryucf027c62015-03-04 12:00:50 -0800262 host_objs = models.Host.smart_get_bulk(hosts)
MK Ryu26f0c932015-05-28 18:14:33 -0700263 remove_label_from_hosts(id, hosts)
264
MK Ryu8e2c2d02016-01-06 15:24:38 -0800265 rpc_utils.fanout_rpc(host_objs, 'remove_label_from_hosts', id=id)
266
MK Ryucf027c62015-03-04 12:00:50 -0800267
Jiaxi Luo31874592014-06-11 10:36:35 -0700268def get_labels(exclude_filters=(), **filter_data):
showardc92da832009-04-07 18:14:34 +0000269 """\
Jiaxi Luo31874592014-06-11 10:36:35 -0700270 @param exclude_filters: A sequence of dictionaries of filters.
271
showardc92da832009-04-07 18:14:34 +0000272 @returns A sequence of nested dictionaries of label information.
273 """
Jiaxi Luo31874592014-06-11 10:36:35 -0700274 labels = models.Label.query_objects(filter_data)
275 for exclude_filter in exclude_filters:
276 labels = labels.exclude(**exclude_filter)
277 return rpc_utils.prepare_rows_as_nested_dicts(labels, ('atomic_group',))
showardc92da832009-04-07 18:14:34 +0000278
279
280# atomic groups
281
showarde9450c92009-06-30 01:58:52 +0000282def add_atomic_group(name, max_number_of_machines=None, description=None):
showardc92da832009-04-07 18:14:34 +0000283 return models.AtomicGroup.add_object(
284 name=name, max_number_of_machines=max_number_of_machines,
285 description=description).id
286
287
288def modify_atomic_group(id, **data):
289 models.AtomicGroup.smart_get(id).update_object(data)
290
291
292def delete_atomic_group(id):
293 models.AtomicGroup.smart_get(id).delete()
294
295
296def atomic_group_add_labels(id, labels):
297 label_objs = models.Label.smart_get_bulk(labels)
298 models.AtomicGroup.smart_get(id).label_set.add(*label_objs)
299
300
301def atomic_group_remove_labels(id, labels):
302 label_objs = models.Label.smart_get_bulk(labels)
303 models.AtomicGroup.smart_get(id).label_set.remove(*label_objs)
304
305
306def get_atomic_groups(**filter_data):
jadmanski0afbb632008-06-06 21:10:57 +0000307 return rpc_utils.prepare_for_serialization(
showardc92da832009-04-07 18:14:34 +0000308 models.AtomicGroup.list_objects(filter_data))
mblighe8819cd2008-02-15 16:48:40 +0000309
310
311# hosts
312
Matthew Sartori68186332015-04-27 17:19:53 -0700313def add_host(hostname, status=None, locked=None, lock_reason='', protection=None):
314 if locked and not lock_reason:
315 raise model_logic.ValidationError(
316 {'locked': 'Please provide a reason for locking when adding host.'})
317
jadmanski0afbb632008-06-06 21:10:57 +0000318 return models.Host.add_object(hostname=hostname, status=status,
Matthew Sartori68186332015-04-27 17:19:53 -0700319 locked=locked, lock_reason=lock_reason,
320 protection=protection).id
mblighe8819cd2008-02-15 16:48:40 +0000321
322
MK Ryu33889612015-09-04 14:32:35 -0700323@rpc_utils.route_rpc_to_master
324def modify_host(id, **kwargs):
Jakob Juelich50e91f72014-10-01 12:43:23 -0700325 """Modify local attributes of a host.
326
327 If this is called on the master, but the host is assigned to a shard, this
MK Ryu33889612015-09-04 14:32:35 -0700328 will call `modify_host_local` RPC to the responsible shard. This means if
329 a host is being locked using this function, this change will also propagate
330 to shards.
331 When this is called on a shard, the shard just routes the RPC to the master
332 and does nothing.
Jakob Juelich50e91f72014-10-01 12:43:23 -0700333
334 @param id: id of the host to modify.
MK Ryu33889612015-09-04 14:32:35 -0700335 @param kwargs: key=value pairs of values to set on the host.
Jakob Juelich50e91f72014-10-01 12:43:23 -0700336 """
MK Ryu33889612015-09-04 14:32:35 -0700337 rpc_utils.check_modify_host(kwargs)
showardce7c0922009-09-11 18:39:24 +0000338 host = models.Host.smart_get(id)
Shuqian Zhao4c0d2902016-01-12 17:03:15 -0800339 try:
340 rpc_utils.check_modify_host_locking(host, kwargs)
341 except model_logic.ValidationError as e:
342 if not kwargs.get('force_modify_locking', False):
343 raise
344 logging.exception('The following exception will be ignored and lock '
345 'modification will be enforced. %s', e)
Jakob Juelich50e91f72014-10-01 12:43:23 -0700346
MK Ryud53e1492015-12-15 12:09:03 -0800347 # This is required to make `lock_time` for a host be exactly same
348 # between the master and a shard.
349 if kwargs.get('locked', None) and 'lock_time' not in kwargs:
350 kwargs['lock_time'] = datetime.datetime.now()
MK Ryu8e2c2d02016-01-06 15:24:38 -0800351 host.update_object(kwargs)
MK Ryud53e1492015-12-15 12:09:03 -0800352
Shuqian Zhao4c0d2902016-01-12 17:03:15 -0800353 # force_modifying_locking is not an internal field in database, remove.
354 kwargs.pop('force_modify_locking', None)
MK Ryu33889612015-09-04 14:32:35 -0700355 rpc_utils.fanout_rpc([host], 'modify_host_local',
356 include_hostnames=False, id=id, **kwargs)
mblighe8819cd2008-02-15 16:48:40 +0000357
358
MK Ryu33889612015-09-04 14:32:35 -0700359def modify_host_local(id, **kwargs):
360 """Modify host attributes in local DB.
361
362 @param id: Host id.
363 @param kwargs: key=value pairs of values to set on the host.
364 """
365 models.Host.smart_get(id).update_object(kwargs)
366
367
368@rpc_utils.route_rpc_to_master
showard276f9442009-05-20 00:33:16 +0000369def modify_hosts(host_filter_data, update_data):
Jakob Juelich50e91f72014-10-01 12:43:23 -0700370 """Modify local attributes of multiple hosts.
371
372 If this is called on the master, but one of the hosts in that match the
MK Ryu33889612015-09-04 14:32:35 -0700373 filters is assigned to a shard, this will call `modify_hosts_local` RPC
374 to the responsible shard.
375 When this is called on a shard, the shard just routes the RPC to the master
376 and does nothing.
Jakob Juelich50e91f72014-10-01 12:43:23 -0700377
378 The filters are always applied on the master, not on the shards. This means
379 if the states of a host differ on the master and a shard, the state on the
380 master will be used. I.e. this means:
381 A host was synced to Shard 1. On Shard 1 the status of the host was set to
382 'Repair Failed'.
383 - A call to modify_hosts with host_filter_data={'status': 'Ready'} will
384 update the host (both on the shard and on the master), because the state
385 of the host as the master knows it is still 'Ready'.
386 - A call to modify_hosts with host_filter_data={'status': 'Repair failed'
387 will not update the host, because the filter doesn't apply on the master.
388
showardbe0d8692009-08-20 23:42:44 +0000389 @param host_filter_data: Filters out which hosts to modify.
390 @param update_data: A dictionary with the changes to make to the hosts.
showard276f9442009-05-20 00:33:16 +0000391 """
MK Ryu93161712015-12-21 10:41:32 -0800392 update_data = update_data.copy()
showardbe0d8692009-08-20 23:42:44 +0000393 rpc_utils.check_modify_host(update_data)
showard276f9442009-05-20 00:33:16 +0000394 hosts = models.Host.query_objects(host_filter_data)
Jakob Juelich50e91f72014-10-01 12:43:23 -0700395
396 affected_shard_hostnames = set()
397 affected_host_ids = []
398
Alex Miller9658a952013-05-14 16:40:02 -0700399 # Check all hosts before changing data for exception safety.
400 for host in hosts:
Shuqian Zhao4c0d2902016-01-12 17:03:15 -0800401 try:
402 rpc_utils.check_modify_host_locking(host, update_data)
403 except model_logic.ValidationError as e:
404 if not update_data.get('force_modify_locking', False):
405 raise
406 logging.exception('The following exception will be ignored and '
407 'lock modification will be enforced. %s', e)
408
Jakob Juelich50e91f72014-10-01 12:43:23 -0700409 if host.shard:
Prashanth Balasubramanian8c98ac12014-12-23 11:26:44 -0800410 affected_shard_hostnames.add(host.shard.rpc_hostname())
Jakob Juelich50e91f72014-10-01 12:43:23 -0700411 affected_host_ids.append(host.id)
412
MK Ryud53e1492015-12-15 12:09:03 -0800413 # This is required to make `lock_time` for a host be exactly same
414 # between the master and a shard.
415 if update_data.get('locked', None) and 'lock_time' not in update_data:
416 update_data['lock_time'] = datetime.datetime.now()
MK Ryu8e2c2d02016-01-06 15:24:38 -0800417 for host in hosts:
418 host.update_object(update_data)
MK Ryud53e1492015-12-15 12:09:03 -0800419
Shuqian Zhao4c0d2902016-01-12 17:03:15 -0800420 update_data.pop('force_modify_locking', None)
MK Ryu33889612015-09-04 14:32:35 -0700421 # Caution: Changing the filter from the original here. See docstring.
422 rpc_utils.run_rpc_on_multiple_hostnames(
423 'modify_hosts_local', affected_shard_hostnames,
Jakob Juelich50e91f72014-10-01 12:43:23 -0700424 host_filter_data={'id__in': affected_host_ids},
425 update_data=update_data)
426
showard276f9442009-05-20 00:33:16 +0000427
MK Ryu33889612015-09-04 14:32:35 -0700428def modify_hosts_local(host_filter_data, update_data):
429 """Modify attributes of hosts in local DB.
430
431 @param host_filter_data: Filters out which hosts to modify.
432 @param update_data: A dictionary with the changes to make to the hosts.
433 """
434 for host in models.Host.query_objects(host_filter_data):
435 host.update_object(update_data)
436
437
MK Ryufbb002c2015-06-08 14:13:16 -0700438def add_labels_to_host(id, labels):
439 """Adds labels to a given host only in local DB.
showardcafd16e2009-05-29 18:37:49 +0000440
MK Ryufbb002c2015-06-08 14:13:16 -0700441 @param id: id or hostname for a host.
442 @param labels: ids or names for labels.
443 """
444 label_objs = models.Label.smart_get_bulk(labels)
445 models.Host.smart_get(id).labels.add(*label_objs)
446
447
448@rpc_utils.route_rpc_to_master
449def host_add_labels(id, labels):
450 """Adds labels to a given host.
451
452 @param id: id or hostname for a host.
453 @param labels: ids or names for labels.
454
Shuqian Zhao40e182b2016-10-11 11:55:11 -0700455 @raises ValidationError: If adding more than one platform/board label.
MK Ryufbb002c2015-06-08 14:13:16 -0700456 """
Kevin Chengbdfc57d2016-04-14 13:46:58 -0700457 # Create the labels on the master/shards.
458 for label in labels:
459 _create_label_everywhere(label, [id])
460
MK Ryufbb002c2015-06-08 14:13:16 -0700461 label_objs = models.Label.smart_get_bulk(labels)
462 platforms = [label.name for label in label_objs if label.platform]
Shuqian Zhao40e182b2016-10-11 11:55:11 -0700463 boards = [label.name for label in label_objs
464 if label.name.startswith('board:')]
Dan Shib5b8b4f2016-11-02 14:04:02 -0700465 if len(platforms) > 1 or not utils.board_labels_allowed(boards):
showardcafd16e2009-05-29 18:37:49 +0000466 raise model_logic.ValidationError(
Dan Shib5b8b4f2016-11-02 14:04:02 -0700467 {'labels': ('Adding more than one platform label, or a list of '
468 'non-compatible board labels.: %s %s' %
469 (', '.join(platforms), ', '.join(boards)))})
MK Ryufbb002c2015-06-08 14:13:16 -0700470
471 host_obj = models.Host.smart_get(id)
Dan Shi4a3deb82016-10-27 21:32:30 -0700472 if platforms:
MK Ryufbb002c2015-06-08 14:13:16 -0700473 models.Host.check_no_platform([host_obj])
Dan Shi4a3deb82016-10-27 21:32:30 -0700474 if boards:
Dan Shib5b8b4f2016-11-02 14:04:02 -0700475 models.Host.check_board_labels_allowed([host_obj], labels)
MK Ryu8e2c2d02016-01-06 15:24:38 -0800476 add_labels_to_host(id, labels)
MK Ryufbb002c2015-06-08 14:13:16 -0700477
478 rpc_utils.fanout_rpc([host_obj], 'add_labels_to_host', False,
479 id=id, labels=labels)
mblighe8819cd2008-02-15 16:48:40 +0000480
481
MK Ryufbb002c2015-06-08 14:13:16 -0700482def remove_labels_from_host(id, labels):
483 """Removes labels from a given host only in local DB.
484
485 @param id: id or hostname for a host.
486 @param labels: ids or names for labels.
487 """
488 label_objs = models.Label.smart_get_bulk(labels)
489 models.Host.smart_get(id).labels.remove(*label_objs)
490
491
492@rpc_utils.route_rpc_to_master
mblighe8819cd2008-02-15 16:48:40 +0000493def host_remove_labels(id, labels):
MK Ryufbb002c2015-06-08 14:13:16 -0700494 """Removes labels from a given host.
495
496 @param id: id or hostname for a host.
497 @param labels: ids or names for labels.
498 """
MK Ryu8e2c2d02016-01-06 15:24:38 -0800499 remove_labels_from_host(id, labels)
500
MK Ryufbb002c2015-06-08 14:13:16 -0700501 host_obj = models.Host.smart_get(id)
502 rpc_utils.fanout_rpc([host_obj], 'remove_labels_from_host', False,
503 id=id, labels=labels)
mblighe8819cd2008-02-15 16:48:40 +0000504
505
MK Ryuacf35922014-10-03 14:56:49 -0700506def get_host_attribute(attribute, **host_filter_data):
507 """
508 @param attribute: string name of attribute
509 @param host_filter_data: filter data to apply to Hosts to choose hosts to
510 act upon
511 """
512 hosts = rpc_utils.get_host_query((), False, False, True, host_filter_data)
513 hosts = list(hosts)
514 models.Host.objects.populate_relationships(hosts, models.HostAttribute,
515 'attribute_list')
516 host_attr_dicts = []
517 for host_obj in hosts:
518 for attr_obj in host_obj.attribute_list:
519 if attr_obj.attribute == attribute:
520 host_attr_dicts.append(attr_obj.get_object_dict())
521 return rpc_utils.prepare_for_serialization(host_attr_dicts)
522
523
showard0957a842009-05-11 19:25:08 +0000524def set_host_attribute(attribute, value, **host_filter_data):
525 """
MK Ryu26f0c932015-05-28 18:14:33 -0700526 @param attribute: string name of attribute
527 @param value: string, or None to delete an attribute
528 @param host_filter_data: filter data to apply to Hosts to choose hosts to
529 act upon
showard0957a842009-05-11 19:25:08 +0000530 """
531 assert host_filter_data # disallow accidental actions on all hosts
532 hosts = models.Host.query_objects(host_filter_data)
533 models.AclGroup.check_for_acl_violation_hosts(hosts)
MK Ryu8e2c2d02016-01-06 15:24:38 -0800534 for host in hosts:
535 host.set_or_delete_attribute(attribute, value)
showard0957a842009-05-11 19:25:08 +0000536
MK Ryu26f0c932015-05-28 18:14:33 -0700537 # Master forwards this RPC to shards.
538 if not utils.is_shard():
539 rpc_utils.fanout_rpc(hosts, 'set_host_attribute', False,
540 attribute=attribute, value=value, **host_filter_data)
541
showard0957a842009-05-11 19:25:08 +0000542
Jakob Juelich50e91f72014-10-01 12:43:23 -0700543@rpc_utils.forward_single_host_rpc_to_shard
mblighe8819cd2008-02-15 16:48:40 +0000544def delete_host(id):
jadmanski0afbb632008-06-06 21:10:57 +0000545 models.Host.smart_get(id).delete()
mblighe8819cd2008-02-15 16:48:40 +0000546
547
showard87cc38f2009-08-20 23:37:04 +0000548def get_hosts(multiple_labels=(), exclude_only_if_needed_labels=False,
Dan Shi37df54d2015-12-14 11:16:28 -0800549 exclude_atomic_group_hosts=False, valid_only=True,
550 include_current_job=False, **filter_data):
551 """Get a list of dictionaries which contains the information of hosts.
552
showard87cc38f2009-08-20 23:37:04 +0000553 @param multiple_labels: match hosts in all of the labels given. Should
554 be a list of label names.
555 @param exclude_only_if_needed_labels: Exclude hosts with at least one
556 "only_if_needed" label applied.
557 @param exclude_atomic_group_hosts: Exclude hosts that have one or more
558 atomic group labels associated with them.
Dan Shi37df54d2015-12-14 11:16:28 -0800559 @param include_current_job: Set to True to include ids of currently running
560 job and special task.
jadmanski0afbb632008-06-06 21:10:57 +0000561 """
showard43a3d262008-11-12 18:17:05 +0000562 hosts = rpc_utils.get_host_query(multiple_labels,
563 exclude_only_if_needed_labels,
showard87cc38f2009-08-20 23:37:04 +0000564 exclude_atomic_group_hosts,
showard8aa84fc2009-09-16 17:17:55 +0000565 valid_only, filter_data)
showard0957a842009-05-11 19:25:08 +0000566 hosts = list(hosts)
567 models.Host.objects.populate_relationships(hosts, models.Label,
568 'label_list')
569 models.Host.objects.populate_relationships(hosts, models.AclGroup,
570 'acl_list')
571 models.Host.objects.populate_relationships(hosts, models.HostAttribute,
572 'attribute_list')
showard43a3d262008-11-12 18:17:05 +0000573 host_dicts = []
574 for host_obj in hosts:
575 host_dict = host_obj.get_object_dict()
showard0957a842009-05-11 19:25:08 +0000576 host_dict['labels'] = [label.name for label in host_obj.label_list]
showard909c9142009-07-07 20:54:42 +0000577 host_dict['platform'], host_dict['atomic_group'] = (rpc_utils.
578 find_platform_and_atomic_group(host_obj))
showard0957a842009-05-11 19:25:08 +0000579 host_dict['acls'] = [acl.name for acl in host_obj.acl_list]
580 host_dict['attributes'] = dict((attribute.attribute, attribute.value)
581 for attribute in host_obj.attribute_list)
Dan Shi37df54d2015-12-14 11:16:28 -0800582 if include_current_job:
583 host_dict['current_job'] = None
584 host_dict['current_special_task'] = None
585 entries = models.HostQueueEntry.objects.filter(
586 host_id=host_dict['id'], active=True, complete=False)
587 if entries:
588 host_dict['current_job'] = (
589 entries[0].get_object_dict()['job'])
590 tasks = models.SpecialTask.objects.filter(
591 host_id=host_dict['id'], is_active=True, is_complete=False)
592 if tasks:
593 host_dict['current_special_task'] = (
594 '%d-%s' % (tasks[0].get_object_dict()['id'],
595 tasks[0].get_object_dict()['task'].lower()))
showard43a3d262008-11-12 18:17:05 +0000596 host_dicts.append(host_dict)
597 return rpc_utils.prepare_for_serialization(host_dicts)
mblighe8819cd2008-02-15 16:48:40 +0000598
599
showard87cc38f2009-08-20 23:37:04 +0000600def get_num_hosts(multiple_labels=(), exclude_only_if_needed_labels=False,
showard8aa84fc2009-09-16 17:17:55 +0000601 exclude_atomic_group_hosts=False, valid_only=True,
602 **filter_data):
showard87cc38f2009-08-20 23:37:04 +0000603 """
604 Same parameters as get_hosts().
605
606 @returns The number of matching hosts.
607 """
showard43a3d262008-11-12 18:17:05 +0000608 hosts = rpc_utils.get_host_query(multiple_labels,
609 exclude_only_if_needed_labels,
showard87cc38f2009-08-20 23:37:04 +0000610 exclude_atomic_group_hosts,
showard8aa84fc2009-09-16 17:17:55 +0000611 valid_only, filter_data)
showard43a3d262008-11-12 18:17:05 +0000612 return hosts.count()
showard1385b162008-03-13 15:59:40 +0000613
mblighe8819cd2008-02-15 16:48:40 +0000614
615# tests
616
mblighe8819cd2008-02-15 16:48:40 +0000617def get_tests(**filter_data):
jadmanski0afbb632008-06-06 21:10:57 +0000618 return rpc_utils.prepare_for_serialization(
619 models.Test.list_objects(filter_data))
mblighe8819cd2008-02-15 16:48:40 +0000620
621
Moises Osorio2dc7a102014-12-02 18:24:02 -0800622def get_tests_status_counts_by_job_name_label(job_name_prefix, label_name):
623 """Gets the counts of all passed and failed tests from the matching jobs.
624
Allen Licdd00f22017-02-01 18:01:52 -0800625 @param job_name_prefix: Name prefix of the jobs to get the summary
626 from, e.g., 'butterfly-release/R40-6457.21.0/bvt-cq/'.
Moises Osorio2dc7a102014-12-02 18:24:02 -0800627 @param label_name: Label that must be set in the jobs, e.g.,
628 'cros-version:butterfly-release/R40-6457.21.0'.
629
630 @returns A summary of the counts of all the passed and failed tests.
631 """
632 job_ids = list(models.Job.objects.filter(
633 name__startswith=job_name_prefix,
634 dependency_labels__name=label_name).values_list(
635 'pk', flat=True))
636 summary = {'passed': 0, 'failed': 0}
637 if not job_ids:
638 return summary
639
640 counts = (tko_models.TestView.objects.filter(
641 afe_job_id__in=job_ids).exclude(
642 test_name='SERVER_JOB').exclude(
643 test_name__startswith='CLIENT_JOB').values(
644 'status').annotate(
645 count=Count('status')))
646 for status in counts:
647 if status['status'] == 'GOOD':
648 summary['passed'] += status['count']
649 else:
650 summary['failed'] += status['count']
651 return summary
652
653
showard2b9a88b2008-06-13 20:55:03 +0000654# profilers
655
656def add_profiler(name, description=None):
657 return models.Profiler.add_object(name=name, description=description).id
658
659
660def modify_profiler(id, **data):
661 models.Profiler.smart_get(id).update_object(data)
662
663
664def delete_profiler(id):
665 models.Profiler.smart_get(id).delete()
666
667
668def get_profilers(**filter_data):
669 return rpc_utils.prepare_for_serialization(
670 models.Profiler.list_objects(filter_data))
671
672
mblighe8819cd2008-02-15 16:48:40 +0000673# users
674
mblighe8819cd2008-02-15 16:48:40 +0000675def get_users(**filter_data):
jadmanski0afbb632008-06-06 21:10:57 +0000676 return rpc_utils.prepare_for_serialization(
677 models.User.list_objects(filter_data))
mblighe8819cd2008-02-15 16:48:40 +0000678
679
680# acl groups
681
682def add_acl_group(name, description=None):
showard04f2cd82008-07-25 20:53:31 +0000683 group = models.AclGroup.add_object(name=name, description=description)
showard64a95952010-01-13 21:27:16 +0000684 group.users.add(models.User.current_user())
showard04f2cd82008-07-25 20:53:31 +0000685 return group.id
mblighe8819cd2008-02-15 16:48:40 +0000686
687
688def modify_acl_group(id, **data):
showard04f2cd82008-07-25 20:53:31 +0000689 group = models.AclGroup.smart_get(id)
690 group.check_for_acl_violation_acl_group()
691 group.update_object(data)
692 group.add_current_user_if_empty()
mblighe8819cd2008-02-15 16:48:40 +0000693
694
695def acl_group_add_users(id, users):
jadmanski0afbb632008-06-06 21:10:57 +0000696 group = models.AclGroup.smart_get(id)
showard04f2cd82008-07-25 20:53:31 +0000697 group.check_for_acl_violation_acl_group()
showardbe3ec042008-11-12 18:16:07 +0000698 users = models.User.smart_get_bulk(users)
jadmanski0afbb632008-06-06 21:10:57 +0000699 group.users.add(*users)
mblighe8819cd2008-02-15 16:48:40 +0000700
701
702def acl_group_remove_users(id, users):
jadmanski0afbb632008-06-06 21:10:57 +0000703 group = models.AclGroup.smart_get(id)
showard04f2cd82008-07-25 20:53:31 +0000704 group.check_for_acl_violation_acl_group()
showardbe3ec042008-11-12 18:16:07 +0000705 users = models.User.smart_get_bulk(users)
jadmanski0afbb632008-06-06 21:10:57 +0000706 group.users.remove(*users)
showard04f2cd82008-07-25 20:53:31 +0000707 group.add_current_user_if_empty()
mblighe8819cd2008-02-15 16:48:40 +0000708
709
710def acl_group_add_hosts(id, hosts):
jadmanski0afbb632008-06-06 21:10:57 +0000711 group = models.AclGroup.smart_get(id)
showard04f2cd82008-07-25 20:53:31 +0000712 group.check_for_acl_violation_acl_group()
showardbe3ec042008-11-12 18:16:07 +0000713 hosts = models.Host.smart_get_bulk(hosts)
jadmanski0afbb632008-06-06 21:10:57 +0000714 group.hosts.add(*hosts)
showard08f981b2008-06-24 21:59:03 +0000715 group.on_host_membership_change()
mblighe8819cd2008-02-15 16:48:40 +0000716
717
718def acl_group_remove_hosts(id, hosts):
jadmanski0afbb632008-06-06 21:10:57 +0000719 group = models.AclGroup.smart_get(id)
showard04f2cd82008-07-25 20:53:31 +0000720 group.check_for_acl_violation_acl_group()
showardbe3ec042008-11-12 18:16:07 +0000721 hosts = models.Host.smart_get_bulk(hosts)
jadmanski0afbb632008-06-06 21:10:57 +0000722 group.hosts.remove(*hosts)
showard08f981b2008-06-24 21:59:03 +0000723 group.on_host_membership_change()
mblighe8819cd2008-02-15 16:48:40 +0000724
725
726def delete_acl_group(id):
jadmanski0afbb632008-06-06 21:10:57 +0000727 models.AclGroup.smart_get(id).delete()
mblighe8819cd2008-02-15 16:48:40 +0000728
729
730def get_acl_groups(**filter_data):
jadmanski0afbb632008-06-06 21:10:57 +0000731 acl_groups = models.AclGroup.list_objects(filter_data)
732 for acl_group in acl_groups:
733 acl_group_obj = models.AclGroup.objects.get(id=acl_group['id'])
734 acl_group['users'] = [user.login
735 for user in acl_group_obj.users.all()]
736 acl_group['hosts'] = [host.hostname
737 for host in acl_group_obj.hosts.all()]
738 return rpc_utils.prepare_for_serialization(acl_groups)
mblighe8819cd2008-02-15 16:48:40 +0000739
740
741# jobs
742
Richard Barnette8e33b4e2016-05-21 12:12:26 -0700743def generate_control_file(tests=(), profilers=(),
showard91f85102009-10-12 20:34:52 +0000744 client_control_file='', use_container=False,
Richard Barnette8e33b4e2016-05-21 12:12:26 -0700745 profile_only=None, db_tests=True,
746 test_source_build=None):
jadmanski0afbb632008-06-06 21:10:57 +0000747 """
Richard Barnette8e33b4e2016-05-21 12:12:26 -0700748 Generates a client-side control file to run tests.
mbligh120351e2009-01-24 01:40:45 +0000749
Matthew Sartori10438092015-06-24 14:30:18 -0700750 @param tests List of tests to run. See db_tests for more information.
mbligh120351e2009-01-24 01:40:45 +0000751 @param profilers List of profilers to activate during the job.
752 @param client_control_file The contents of a client-side control file to
753 run at the end of all tests. If this is supplied, all tests must be
754 client side.
755 TODO: in the future we should support server control files directly
756 to wrap with a kernel. That'll require changing the parameter
757 name and adding a boolean to indicate if it is a client or server
758 control file.
759 @param use_container unused argument today. TODO: Enable containers
760 on the host during a client side test.
showard91f85102009-10-12 20:34:52 +0000761 @param profile_only A boolean that indicates what default profile_only
762 mode to use in the control file. Passing None will generate a
763 control file that does not explcitly set the default mode at all.
Matthew Sartori10438092015-06-24 14:30:18 -0700764 @param db_tests: if True, the test object can be found in the database
765 backing the test model. In this case, tests is a tuple
766 of test IDs which are used to retrieve the test objects
767 from the database. If False, tests is a tuple of test
768 dictionaries stored client-side in the AFE.
Michael Tang84a2ecf2016-06-07 15:10:53 -0700769 @param test_source_build: Build to be used to retrieve test code. Default
770 to None.
mbligh120351e2009-01-24 01:40:45 +0000771
772 @returns a dict with the following keys:
773 control_file: str, The control file text.
774 is_server: bool, is the control file a server-side control file?
775 synch_count: How many machines the job uses per autoserv execution.
776 synch_count == 1 means the job is asynchronous.
777 dependencies: A list of the names of labels on which the job depends.
778 """
showardd86debe2009-06-10 17:37:56 +0000779 if not tests and not client_control_file:
showard2bab8f42008-11-12 18:15:22 +0000780 return dict(control_file='', is_server=False, synch_count=1,
showard989f25d2008-10-01 11:38:11 +0000781 dependencies=[])
mblighe8819cd2008-02-15 16:48:40 +0000782
Richard Barnette8e33b4e2016-05-21 12:12:26 -0700783 cf_info, test_objects, profiler_objects = (
784 rpc_utils.prepare_generate_control_file(tests, profilers,
785 db_tests))
Allen Lia59b1262016-12-14 12:53:51 -0800786 cf_info['control_file'] = control_file_lib.generate_control(
Richard Barnette8e33b4e2016-05-21 12:12:26 -0700787 tests=test_objects, profilers=profiler_objects,
788 is_server=cf_info['is_server'],
showard232b7ae2009-11-10 00:46:48 +0000789 client_control_file=client_control_file, profile_only=profile_only,
Michael Tang84a2ecf2016-06-07 15:10:53 -0700790 test_source_build=test_source_build)
showard989f25d2008-10-01 11:38:11 +0000791 return cf_info
mblighe8819cd2008-02-15 16:48:40 +0000792
793
Allen Li41e47c12016-12-14 12:43:44 -0800794def create_parameterized_job(
795 name,
796 priority,
797 test,
798 parameters,
799 kernel=None,
800 label=None,
801 profilers=(),
802 profiler_parameters=None,
803 use_container=False,
804 profile_only=None,
805 upload_kernel_config=False,
806 hosts=(),
807 meta_hosts=(),
808 one_time_hosts=(),
809 atomic_group_name=None,
810 synch_count=None,
811 is_template=False,
812 timeout=None,
813 timeout_mins=None,
814 max_runtime_mins=None,
815 run_verify=False,
816 email_list='',
817 dependencies=(),
818 reboot_before=None,
819 reboot_after=None,
820 parse_failed_repair=None,
821 hostless=False,
822 keyvals=None,
823 drone_set=None,
824 run_reset=True,
825 require_ssp=None):
Shuqian Zhao54a5b672016-05-11 22:12:17 +0000826 """
827 Creates and enqueues a parameterized job.
828
829 Most parameters a combination of the parameters for generate_control_file()
830 and create_job(), with the exception of:
831
832 @param test name or ID of the test to run
833 @param parameters a map of parameter name ->
834 tuple of (param value, param type)
835 @param profiler_parameters a dictionary of parameters for the profilers:
836 key: profiler name
837 value: dict of param name -> tuple of
838 (param value,
839 param type)
840 """
Shuqian Zhao54a5b672016-05-11 22:12:17 +0000841 # Set up the parameterized job configs
842 test_obj = models.Test.smart_get(test)
843 control_type = test_obj.test_type
844
845 try:
846 label = models.Label.smart_get(label)
847 except models.Label.DoesNotExist:
848 label = None
849
850 kernel_objs = models.Kernel.create_kernels(kernel)
851 profiler_objs = [models.Profiler.smart_get(profiler)
852 for profiler in profilers]
853
854 parameterized_job = models.ParameterizedJob.objects.create(
855 test=test_obj, label=label, use_container=use_container,
856 profile_only=profile_only,
857 upload_kernel_config=upload_kernel_config)
858 parameterized_job.kernels.add(*kernel_objs)
859
860 for profiler in profiler_objs:
861 parameterized_profiler = models.ParameterizedJobProfiler.objects.create(
862 parameterized_job=parameterized_job,
863 profiler=profiler)
864 profiler_params = profiler_parameters.get(profiler.name, {})
865 for name, (value, param_type) in profiler_params.iteritems():
866 models.ParameterizedJobProfilerParameter.objects.create(
867 parameterized_job_profiler=parameterized_profiler,
868 parameter_name=name,
869 parameter_value=value,
870 parameter_type=param_type)
871
872 try:
873 for parameter in test_obj.testparameter_set.all():
874 if parameter.name in parameters:
875 param_value, param_type = parameters.pop(parameter.name)
876 parameterized_job.parameterizedjobparameter_set.create(
877 test_parameter=parameter, parameter_value=param_value,
878 parameter_type=param_type)
879
880 if parameters:
881 raise Exception('Extra parameters remain: %r' % parameters)
882
883 return rpc_utils.create_job_common(
Allen Li81996a82016-12-14 13:01:37 -0800884 name=name,
885 priority=priority,
886 control_type=control_type,
887 hosts=hosts,
888 meta_hosts=meta_hosts,
889 one_time_hosts=one_time_hosts,
890 atomic_group_name=atomic_group_name,
891 synch_count=synch_count,
892 is_template=is_template,
893 timeout=timeout,
894 timeout_mins=timeout_mins,
895 max_runtime_mins=max_runtime_mins,
896 run_verify=run_verify,
897 email_list=email_list,
898 dependencies=dependencies,
899 reboot_before=reboot_before,
900 reboot_after=reboot_after,
901 parse_failed_repair=parse_failed_repair,
902 hostless=hostless,
903 keyvals=keyvals,
904 drone_set=drone_set,
905 parameterized_job=parameterized_job.id,
906 run_reset=run_reset,
907 require_ssp=require_ssp)
Shuqian Zhao54a5b672016-05-11 22:12:17 +0000908 except:
909 parameterized_job.delete()
910 raise
911
912
Simran Basib6ec8ae2014-04-23 12:05:08 -0700913def create_job_page_handler(name, priority, control_file, control_type,
Dan Shid215dbe2015-06-18 16:14:59 -0700914 image=None, hostless=False, firmware_rw_build=None,
915 firmware_ro_build=None, test_source_build=None,
Michael Tang84a2ecf2016-06-07 15:10:53 -0700916 is_cloning=False, **kwargs):
Simran Basib6ec8ae2014-04-23 12:05:08 -0700917 """\
918 Create and enqueue a job.
919
920 @param name name of this job
921 @param priority Integer priority of this job. Higher is more important.
922 @param control_file String contents of the control file.
923 @param control_type Type of control file, Client or Server.
Dan Shid215dbe2015-06-18 16:14:59 -0700924 @param image: ChromeOS build to be installed in the dut. Default to None.
925 @param firmware_rw_build: Firmware build to update RW firmware. Default to
926 None, i.e., RW firmware will not be updated.
927 @param firmware_ro_build: Firmware build to update RO firmware. Default to
928 None, i.e., RO firmware will not be updated.
929 @param test_source_build: Build to be used to retrieve test code. Default
930 to None.
Michael Tang6dc174e2016-05-31 23:13:42 -0700931 @param is_cloning: True if creating a cloning job.
Simran Basib6ec8ae2014-04-23 12:05:08 -0700932 @param kwargs extra args that will be required by create_suite_job or
933 create_job.
934
935 @returns The created Job id number.
936 """
Michael Tang6dc174e2016-05-31 23:13:42 -0700937 if is_cloning:
938 logging.info('Start to clone a new job')
Shuqian Zhao61f5d312016-08-05 17:15:23 -0700939 # When cloning a job, hosts and meta_hosts should not exist together,
940 # which would cause host-scheduler to schedule two hqe jobs to one host
941 # at the same time, and crash itself. Clear meta_hosts for this case.
942 if kwargs.get('hosts') and kwargs.get('meta_hosts'):
943 kwargs['meta_hosts'] = []
Michael Tang6dc174e2016-05-31 23:13:42 -0700944 else:
945 logging.info('Start to create a new job')
Simran Basib6ec8ae2014-04-23 12:05:08 -0700946 control_file = rpc_utils.encode_ascii(control_file)
Jiaxi Luodd67beb2014-07-18 16:28:31 -0700947 if not control_file:
948 raise model_logic.ValidationError({
949 'control_file' : "Control file cannot be empty"})
Simran Basib6ec8ae2014-04-23 12:05:08 -0700950
951 if image and hostless:
Dan Shid215dbe2015-06-18 16:14:59 -0700952 builds = {}
953 builds[provision.CROS_VERSION_PREFIX] = image
954 if firmware_rw_build:
Dan Shi0723bf52015-06-24 10:52:38 -0700955 builds[provision.FW_RW_VERSION_PREFIX] = firmware_rw_build
Dan Shid215dbe2015-06-18 16:14:59 -0700956 if firmware_ro_build:
957 builds[provision.FW_RO_VERSION_PREFIX] = firmware_ro_build
Allen Licdd00f22017-02-01 18:01:52 -0800958 return create_suite_job(
Simran Basib6ec8ae2014-04-23 12:05:08 -0700959 name=name, control_file=control_file, priority=priority,
Michael Tang6dc174e2016-05-31 23:13:42 -0700960 builds=builds, test_source_build=test_source_build,
961 is_cloning=is_cloning, **kwargs)
Simran Basib6ec8ae2014-04-23 12:05:08 -0700962 return create_job(name, priority, control_file, control_type, image=image,
Allen Liac199b62016-12-14 12:56:02 -0800963 hostless=hostless, **kwargs)
Simran Basib6ec8ae2014-04-23 12:05:08 -0700964
965
MK Ryue301eb72015-06-25 12:51:02 -0700966@rpc_utils.route_rpc_to_master
Allen Li8af9da02016-12-12 17:32:39 -0800967def create_job(
968 name,
969 priority,
970 control_file,
971 control_type,
972 hosts=(),
973 meta_hosts=(),
974 one_time_hosts=(),
975 atomic_group_name=None,
976 synch_count=None,
977 is_template=False,
978 timeout=None,
979 timeout_mins=None,
980 max_runtime_mins=None,
981 run_verify=False,
982 email_list='',
983 dependencies=(),
984 reboot_before=None,
985 reboot_after=None,
986 parse_failed_repair=None,
987 hostless=False,
988 keyvals=None,
989 drone_set=None,
990 image=None,
991 parent_job_id=None,
992 test_retry=0,
993 run_reset=True,
994 require_ssp=None,
995 args=(),
Allen Li8af9da02016-12-12 17:32:39 -0800996 **kwargs):
jadmanski0afbb632008-06-06 21:10:57 +0000997 """\
998 Create and enqueue a job.
mblighe8819cd2008-02-15 16:48:40 +0000999
showarda1e74b32009-05-12 17:32:04 +00001000 @param name name of this job
Alex Miller7d658cf2013-09-04 16:00:35 -07001001 @param priority Integer priority of this job. Higher is more important.
showarda1e74b32009-05-12 17:32:04 +00001002 @param control_file String contents of the control file.
1003 @param control_type Type of control file, Client or Server.
1004 @param synch_count How many machines the job uses per autoserv execution.
Jiaxi Luo90190c92014-06-18 12:35:57 -07001005 synch_count == 1 means the job is asynchronous. If an atomic group is
1006 given this value is treated as a minimum.
showarda1e74b32009-05-12 17:32:04 +00001007 @param is_template If true then create a template job.
1008 @param timeout Hours after this call returns until the job times out.
Simran Basi7e605742013-11-12 13:43:36 -08001009 @param timeout_mins Minutes after this call returns until the job times
Jiaxi Luo90190c92014-06-18 12:35:57 -07001010 out.
Simran Basi34217022012-11-06 13:43:15 -08001011 @param max_runtime_mins Minutes from job starting time until job times out
showarda1e74b32009-05-12 17:32:04 +00001012 @param run_verify Should the host be verified before running the test?
1013 @param email_list String containing emails to mail when the job is done
1014 @param dependencies List of label names on which this job depends
1015 @param reboot_before Never, If dirty, or Always
1016 @param reboot_after Never, If all tests passed, or Always
1017 @param parse_failed_repair if true, results of failed repairs launched by
Jiaxi Luo90190c92014-06-18 12:35:57 -07001018 this job will be parsed as part of the job.
showarda9545c02009-12-18 22:44:26 +00001019 @param hostless if true, create a hostless job
showardc1a98d12010-01-15 00:22:22 +00001020 @param keyvals dict of keyvals to associate with the job
showarda1e74b32009-05-12 17:32:04 +00001021 @param hosts List of hosts to run job on.
1022 @param meta_hosts List where each entry is a label name, and for each entry
Jiaxi Luo90190c92014-06-18 12:35:57 -07001023 one host will be chosen from that label to run the job on.
showarda1e74b32009-05-12 17:32:04 +00001024 @param one_time_hosts List of hosts not in the database to run the job on.
1025 @param atomic_group_name The name of an atomic group to schedule the job on.
jamesren76fcf192010-04-21 20:39:50 +00001026 @param drone_set The name of the drone set to run this test on.
Paul Pendlebury5a8c6ad2011-02-01 07:20:17 -08001027 @param image OS image to install before running job.
Aviv Keshet0b9cfc92013-02-05 11:36:02 -08001028 @param parent_job_id id of a job considered to be parent of created job.
Simran Basib6ec8ae2014-04-23 12:05:08 -07001029 @param test_retry Number of times to retry test if the test did not
Jiaxi Luo90190c92014-06-18 12:35:57 -07001030 complete successfully. (optional, default: 0)
Simran Basib6ec8ae2014-04-23 12:05:08 -07001031 @param run_reset Should the host be reset before running the test?
Dan Shiec1d47d2015-02-13 11:38:13 -08001032 @param require_ssp Set to True to require server-side packaging to run the
1033 test. If it's set to None, drone will still try to run
1034 the server side with server-side packaging. If the
1035 autotest-server package doesn't exist for the build or
1036 image is not set, drone will run the test without server-
1037 side packaging. Default is None.
Jiaxi Luo90190c92014-06-18 12:35:57 -07001038 @param args A list of args to be injected into control file.
Simran Basib6ec8ae2014-04-23 12:05:08 -07001039 @param kwargs extra keyword args. NOT USED.
showardc92da832009-04-07 18:14:34 +00001040
1041 @returns The created Job id number.
jadmanski0afbb632008-06-06 21:10:57 +00001042 """
Jiaxi Luo90190c92014-06-18 12:35:57 -07001043 if args:
1044 control_file = tools.inject_vars({'args': args}, control_file)
Richard Barnette6c2b70a2017-01-26 13:40:51 -08001045 if image:
1046 dependencies += (provision.image_version_to_label(image),)
jamesren4a41e012010-07-16 22:33:48 +00001047 return rpc_utils.create_job_common(
Allen Li81996a82016-12-14 13:01:37 -08001048 name=name,
1049 priority=priority,
1050 control_type=control_type,
1051 control_file=control_file,
1052 hosts=hosts,
1053 meta_hosts=meta_hosts,
1054 one_time_hosts=one_time_hosts,
1055 atomic_group_name=atomic_group_name,
1056 synch_count=synch_count,
1057 is_template=is_template,
1058 timeout=timeout,
1059 timeout_mins=timeout_mins,
1060 max_runtime_mins=max_runtime_mins,
1061 run_verify=run_verify,
1062 email_list=email_list,
1063 dependencies=dependencies,
1064 reboot_before=reboot_before,
1065 reboot_after=reboot_after,
1066 parse_failed_repair=parse_failed_repair,
1067 hostless=hostless,
1068 keyvals=keyvals,
1069 drone_set=drone_set,
Allen Li81996a82016-12-14 13:01:37 -08001070 parent_job_id=parent_job_id,
1071 test_retry=test_retry,
1072 run_reset=run_reset,
1073 require_ssp=require_ssp)
mblighe8819cd2008-02-15 16:48:40 +00001074
1075
showard9dbdcda2008-10-14 17:34:36 +00001076def abort_host_queue_entries(**filter_data):
jadmanski0afbb632008-06-06 21:10:57 +00001077 """\
showard9dbdcda2008-10-14 17:34:36 +00001078 Abort a set of host queue entries.
Fang Deng63b0e452014-12-19 14:38:15 -08001079
1080 @return: A list of dictionaries, each contains information
1081 about an aborted HQE.
jadmanski0afbb632008-06-06 21:10:57 +00001082 """
showard9dbdcda2008-10-14 17:34:36 +00001083 query = models.HostQueueEntry.query_objects(filter_data)
beepsfaecbce2013-10-29 11:35:10 -07001084
1085 # Dont allow aborts on:
1086 # 1. Jobs that have already completed (whether or not they were aborted)
1087 # 2. Jobs that we have already been aborted (but may not have completed)
1088 query = query.filter(complete=False).filter(aborted=False)
showarddc817512008-11-12 18:16:41 +00001089 models.AclGroup.check_abort_permissions(query)
showard9dbdcda2008-10-14 17:34:36 +00001090 host_queue_entries = list(query.select_related())
showard2bab8f42008-11-12 18:15:22 +00001091 rpc_utils.check_abort_synchronous_jobs(host_queue_entries)
mblighe8819cd2008-02-15 16:48:40 +00001092
Simran Basic1b26762013-06-26 14:23:21 -07001093 models.HostQueueEntry.abort_host_queue_entries(host_queue_entries)
Fang Deng63b0e452014-12-19 14:38:15 -08001094 hqe_info = [{'HostQueueEntry': hqe.id, 'Job': hqe.job_id,
1095 'Job name': hqe.job.name} for hqe in host_queue_entries]
1096 return hqe_info
showard9d821ab2008-07-11 16:54:29 +00001097
1098
beeps8bb1f7d2013-08-05 01:30:09 -07001099def abort_special_tasks(**filter_data):
1100 """\
1101 Abort the special task, or tasks, specified in the filter.
1102 """
1103 query = models.SpecialTask.query_objects(filter_data)
1104 special_tasks = query.filter(is_active=True)
1105 for task in special_tasks:
1106 task.abort()
1107
1108
Simran Basi73dae552013-02-25 14:57:46 -08001109def _call_special_tasks_on_hosts(task, hosts):
1110 """\
1111 Schedules a set of hosts for a special task.
1112
1113 @returns A list of hostnames that a special task was created for.
1114 """
1115 models.AclGroup.check_for_acl_violation_hosts(hosts)
Prashanth Balasubramanian6edaaf92014-11-24 16:36:25 -08001116 shard_host_map = rpc_utils.bucket_hosts_by_shard(hosts)
Prashanth Balasubramanian8c98ac12014-12-23 11:26:44 -08001117 if shard_host_map and not utils.is_shard():
Prashanth Balasubramanian6edaaf92014-11-24 16:36:25 -08001118 raise ValueError('The following hosts are on shards, please '
1119 'follow the link to the shards and create jobs '
1120 'there instead. %s.' % shard_host_map)
Simran Basi73dae552013-02-25 14:57:46 -08001121 for host in hosts:
1122 models.SpecialTask.schedule_special_task(host, task)
1123 return list(sorted(host.hostname for host in hosts))
1124
1125
MK Ryu5aa25042015-07-28 16:08:04 -07001126def _forward_special_tasks_on_hosts(task, rpc, **filter_data):
1127 """Forward special tasks to corresponding shards.
mbligh4e545a52009-12-19 05:30:39 +00001128
MK Ryu5aa25042015-07-28 16:08:04 -07001129 For master, when special tasks are fired on hosts that are sharded,
1130 forward the RPC to corresponding shards.
1131
1132 For shard, create special task records in local DB.
1133
1134 @param task: Enum value of frontend.afe.models.SpecialTask.Task
1135 @param rpc: RPC name to forward.
1136 @param filter_data: Filter keywords to be used for DB query.
1137
1138 @return: A list of hostnames that a special task was created for.
showard1ff7b2e2009-05-15 23:17:18 +00001139 """
Prashanth Balasubramanian40981232014-12-16 19:01:58 -08001140 hosts = models.Host.query_objects(filter_data)
1141 shard_host_map = rpc_utils.bucket_hosts_by_shard(hosts, rpc_hostnames=True)
1142
1143 # Filter out hosts on a shard from those on the master, forward
1144 # rpcs to the shard with an additional hostname__in filter, and
1145 # create a local SpecialTask for each remaining host.
Prashanth Balasubramanian8c98ac12014-12-23 11:26:44 -08001146 if shard_host_map and not utils.is_shard():
Prashanth Balasubramanian40981232014-12-16 19:01:58 -08001147 hosts = [h for h in hosts if h.shard is None]
1148 for shard, hostnames in shard_host_map.iteritems():
1149
1150 # The main client of this module is the frontend website, and
1151 # it invokes it with an 'id' or an 'id__in' filter. Regardless,
1152 # the 'hostname' filter should narrow down the list of hosts on
1153 # each shard even though we supply all the ids in filter_data.
1154 # This method uses hostname instead of id because it fits better
MK Ryu5aa25042015-07-28 16:08:04 -07001155 # with the overall architecture of redirection functions in
1156 # rpc_utils.
Prashanth Balasubramanian40981232014-12-16 19:01:58 -08001157 shard_filter = filter_data.copy()
1158 shard_filter['hostname__in'] = hostnames
1159 rpc_utils.run_rpc_on_multiple_hostnames(
MK Ryu5aa25042015-07-28 16:08:04 -07001160 rpc, [shard], **shard_filter)
Prashanth Balasubramanian40981232014-12-16 19:01:58 -08001161
1162 # There is a race condition here if someone assigns a shard to one of these
1163 # hosts before we create the task. The host will stay on the master if:
1164 # 1. The host is not Ready
1165 # 2. The host is Ready but has a task
1166 # But if the host is Ready and doesn't have a task yet, it will get sent
1167 # to the shard as we're creating a task here.
1168
1169 # Given that we only rarely verify Ready hosts it isn't worth putting this
1170 # entire method in a transaction. The worst case scenario is that we have
MK Ryu5aa25042015-07-28 16:08:04 -07001171 # a verify running on a Ready host while the shard is using it, if the
1172 # verify fails no subsequent tasks will be created against the host on the
1173 # master, and verifies are safe enough that this is OK.
1174 return _call_special_tasks_on_hosts(task, hosts)
1175
1176
1177def reverify_hosts(**filter_data):
1178 """\
1179 Schedules a set of hosts for verify.
1180
1181 @returns A list of hostnames that a verify task was created for.
1182 """
1183 return _forward_special_tasks_on_hosts(
1184 models.SpecialTask.Task.VERIFY, 'reverify_hosts', **filter_data)
Simran Basi73dae552013-02-25 14:57:46 -08001185
1186
1187def repair_hosts(**filter_data):
1188 """\
1189 Schedules a set of hosts for repair.
1190
1191 @returns A list of hostnames that a repair task was created for.
1192 """
MK Ryu5aa25042015-07-28 16:08:04 -07001193 return _forward_special_tasks_on_hosts(
1194 models.SpecialTask.Task.REPAIR, 'repair_hosts', **filter_data)
showard1ff7b2e2009-05-15 23:17:18 +00001195
1196
Jiaxi Luo15cbf372014-07-01 19:20:20 -07001197def get_jobs(not_yet_run=False, running=False, finished=False,
1198 suite=False, sub=False, standalone=False, **filter_data):
jadmanski0afbb632008-06-06 21:10:57 +00001199 """\
Jiaxi Luo15cbf372014-07-01 19:20:20 -07001200 Extra status filter args for get_jobs:
jadmanski0afbb632008-06-06 21:10:57 +00001201 -not_yet_run: Include only jobs that have not yet started running.
1202 -running: Include only jobs that have start running but for which not
1203 all hosts have completed.
1204 -finished: Include only jobs for which all hosts have completed (or
1205 aborted).
Jiaxi Luo15cbf372014-07-01 19:20:20 -07001206
1207 Extra type filter args for get_jobs:
1208 -suite: Include only jobs with child jobs.
1209 -sub: Include only jobs with a parent job.
1210 -standalone: Inlcude only jobs with no child or parent jobs.
1211 At most one of these three fields should be specified.
jadmanski0afbb632008-06-06 21:10:57 +00001212 """
Jiaxi Luo15cbf372014-07-01 19:20:20 -07001213 extra_args = rpc_utils.extra_job_status_filters(not_yet_run,
1214 running,
1215 finished)
1216 filter_data['extra_args'] = rpc_utils.extra_job_type_filters(extra_args,
1217 suite,
1218 sub,
1219 standalone)
showard0957a842009-05-11 19:25:08 +00001220 job_dicts = []
1221 jobs = list(models.Job.query_objects(filter_data))
1222 models.Job.objects.populate_relationships(jobs, models.Label,
1223 'dependencies')
showardc1a98d12010-01-15 00:22:22 +00001224 models.Job.objects.populate_relationships(jobs, models.JobKeyval, 'keyvals')
showard0957a842009-05-11 19:25:08 +00001225 for job in jobs:
1226 job_dict = job.get_object_dict()
1227 job_dict['dependencies'] = ','.join(label.name
1228 for label in job.dependencies)
showardc1a98d12010-01-15 00:22:22 +00001229 job_dict['keyvals'] = dict((keyval.key, keyval.value)
1230 for keyval in job.keyvals)
Eric Lid23bc192011-02-09 14:38:57 -08001231 if job.parameterized_job:
1232 job_dict['image'] = get_parameterized_autoupdate_image_url(job)
showard0957a842009-05-11 19:25:08 +00001233 job_dicts.append(job_dict)
1234 return rpc_utils.prepare_for_serialization(job_dicts)
mblighe8819cd2008-02-15 16:48:40 +00001235
1236
1237def get_num_jobs(not_yet_run=False, running=False, finished=False,
Jiaxi Luo15cbf372014-07-01 19:20:20 -07001238 suite=False, sub=False, standalone=False,
jadmanski0afbb632008-06-06 21:10:57 +00001239 **filter_data):
Aviv Keshet17660a52016-04-06 18:56:43 +00001240 """\
1241 See get_jobs() for documentation of extra filter parameters.
jadmanski0afbb632008-06-06 21:10:57 +00001242 """
Jiaxi Luo15cbf372014-07-01 19:20:20 -07001243 extra_args = rpc_utils.extra_job_status_filters(not_yet_run,
1244 running,
1245 finished)
1246 filter_data['extra_args'] = rpc_utils.extra_job_type_filters(extra_args,
1247 suite,
1248 sub,
1249 standalone)
Aviv Keshet17660a52016-04-06 18:56:43 +00001250 return models.Job.query_count(filter_data)
mblighe8819cd2008-02-15 16:48:40 +00001251
1252
mblighe8819cd2008-02-15 16:48:40 +00001253def get_jobs_summary(**filter_data):
jadmanski0afbb632008-06-06 21:10:57 +00001254 """\
Jiaxi Luoaac54572014-06-04 13:57:02 -07001255 Like get_jobs(), but adds 'status_counts' and 'result_counts' field.
1256
1257 'status_counts' filed is a dictionary mapping status strings to the number
1258 of hosts currently with that status, i.e. {'Queued' : 4, 'Running' : 2}.
1259
1260 'result_counts' field is piped to tko's rpc_interface and has the return
1261 format specified under get_group_counts.
jadmanski0afbb632008-06-06 21:10:57 +00001262 """
1263 jobs = get_jobs(**filter_data)
1264 ids = [job['id'] for job in jobs]
1265 all_status_counts = models.Job.objects.get_status_counts(ids)
1266 for job in jobs:
1267 job['status_counts'] = all_status_counts[job['id']]
Jiaxi Luoaac54572014-06-04 13:57:02 -07001268 job['result_counts'] = tko_rpc_interface.get_status_counts(
1269 ['afe_job_id', 'afe_job_id'],
1270 header_groups=[['afe_job_id'], ['afe_job_id']],
1271 **{'afe_job_id': job['id']})
jadmanski0afbb632008-06-06 21:10:57 +00001272 return rpc_utils.prepare_for_serialization(jobs)
mblighe8819cd2008-02-15 16:48:40 +00001273
1274
showarda965cef2009-05-15 23:17:41 +00001275def get_info_for_clone(id, preserve_metahosts, queue_entry_filter_data=None):
showarda8709c52008-07-03 19:44:54 +00001276 """\
1277 Retrieves all the information needed to clone a job.
1278 """
showarda8709c52008-07-03 19:44:54 +00001279 job = models.Job.objects.get(id=id)
showard29f7cd22009-04-29 21:16:24 +00001280 job_info = rpc_utils.get_job_info(job,
showarda965cef2009-05-15 23:17:41 +00001281 preserve_metahosts,
1282 queue_entry_filter_data)
showard945072f2008-09-03 20:34:59 +00001283
showardd9992fe2008-07-31 02:15:03 +00001284 host_dicts = []
showard29f7cd22009-04-29 21:16:24 +00001285 for host in job_info['hosts']:
1286 host_dict = get_hosts(id=host.id)[0]
1287 other_labels = host_dict['labels']
1288 if host_dict['platform']:
1289 other_labels.remove(host_dict['platform'])
1290 host_dict['other_labels'] = ', '.join(other_labels)
showardd9992fe2008-07-31 02:15:03 +00001291 host_dicts.append(host_dict)
showarda8709c52008-07-03 19:44:54 +00001292
showard29f7cd22009-04-29 21:16:24 +00001293 for host in job_info['one_time_hosts']:
1294 host_dict = dict(hostname=host.hostname,
1295 id=host.id,
1296 platform='(one-time host)',
1297 locked_text='')
1298 host_dicts.append(host_dict)
showarda8709c52008-07-03 19:44:54 +00001299
showard4d077562009-05-08 18:24:36 +00001300 # convert keys from Label objects to strings (names of labels)
showard29f7cd22009-04-29 21:16:24 +00001301 meta_host_counts = dict((meta_host.name, count) for meta_host, count
showard4d077562009-05-08 18:24:36 +00001302 in job_info['meta_host_counts'].iteritems())
showard29f7cd22009-04-29 21:16:24 +00001303
1304 info = dict(job=job.get_object_dict(),
1305 meta_host_counts=meta_host_counts,
1306 hosts=host_dicts)
1307 info['job']['dependencies'] = job_info['dependencies']
1308 if job_info['atomic_group']:
1309 info['atomic_group_name'] = (job_info['atomic_group']).name
1310 else:
1311 info['atomic_group_name'] = None
jamesren2275ef12010-04-12 18:25:06 +00001312 info['hostless'] = job_info['hostless']
jamesren76fcf192010-04-21 20:39:50 +00001313 info['drone_set'] = job.drone_set and job.drone_set.name
showarda8709c52008-07-03 19:44:54 +00001314
Michael Tang6dc174e2016-05-31 23:13:42 -07001315 image = _get_image_for_job(job, job_info['hostless'])
1316 if image:
1317 info['job']['image'] = image
Eric Lid23bc192011-02-09 14:38:57 -08001318
showarda8709c52008-07-03 19:44:54 +00001319 return rpc_utils.prepare_for_serialization(info)
1320
1321
Michael Tang6dc174e2016-05-31 23:13:42 -07001322def _get_image_for_job(job, hostless):
1323 """ Gets the image used for a job.
1324
1325 Gets the image used for an AFE job. If the job is a parameterized job, get
1326 the image from the job parameter; otherwise, tries to get the image from
1327 the job's keyvals 'build' or 'builds'. As a last resort, if the job is a
1328 hostless job, tries to get the image from its control file attributes
1329 'build' or 'builds'.
1330
1331 TODO(ntang): Needs to handle FAFT with two builds for ro/rw.
1332
1333 @param job An AFE job object.
1334 @param hostless Boolean on of the job is hostless.
1335
1336 @returns The image build used for the job.
1337 """
1338 image = None
1339 if job.parameterized_job:
1340 image = get_parameterized_autoupdate_image_url(job)
1341 else:
1342 keyvals = job.keyval_dict()
Michael Tang84a2ecf2016-06-07 15:10:53 -07001343 image = keyvals.get('build')
Michael Tang6dc174e2016-05-31 23:13:42 -07001344 if not image:
1345 value = keyvals.get('builds')
1346 builds = None
1347 if isinstance(value, dict):
1348 builds = value
1349 elif isinstance(value, basestring):
1350 builds = ast.literal_eval(value)
1351 if builds:
1352 image = builds.get('cros-version')
1353 if not image and hostless and job.control_file:
1354 try:
1355 control_obj = control_data.parse_control_string(
1356 job.control_file)
1357 if hasattr(control_obj, 'build'):
1358 image = getattr(control_obj, 'build')
1359 if not image and hasattr(control_obj, 'builds'):
1360 builds = getattr(control_obj, 'builds')
1361 image = builds.get('cros-version')
1362 except:
1363 logging.warning('Failed to parse control file for job: %s',
1364 job.name)
1365 return image
1366
showard34dc5fa2008-04-24 20:58:40 +00001367
Jiaxi Luo57bc1952014-07-22 15:27:30 -07001368def get_host_queue_entries(start_time=None, end_time=None, **filter_data):
jadmanski0afbb632008-06-06 21:10:57 +00001369 """\
showardc92da832009-04-07 18:14:34 +00001370 @returns A sequence of nested dictionaries of host and job information.
jadmanski0afbb632008-06-06 21:10:57 +00001371 """
Jiaxi Luo57bc1952014-07-22 15:27:30 -07001372 filter_data = rpc_utils.inject_times_to_filter('started_on__gte',
1373 'started_on__lte',
1374 start_time,
1375 end_time,
1376 **filter_data)
J. Richard Barnetteb5164d62015-04-13 12:59:31 -07001377 return rpc_utils.prepare_rows_as_nested_dicts(
1378 models.HostQueueEntry.query_objects(filter_data),
1379 ('host', 'atomic_group', 'job'))
showard34dc5fa2008-04-24 20:58:40 +00001380
1381
Jiaxi Luo57bc1952014-07-22 15:27:30 -07001382def get_num_host_queue_entries(start_time=None, end_time=None, **filter_data):
jadmanski0afbb632008-06-06 21:10:57 +00001383 """\
1384 Get the number of host queue entries associated with this job.
1385 """
Jiaxi Luo57bc1952014-07-22 15:27:30 -07001386 filter_data = rpc_utils.inject_times_to_filter('started_on__gte',
1387 'started_on__lte',
1388 start_time,
1389 end_time,
1390 **filter_data)
jadmanski0afbb632008-06-06 21:10:57 +00001391 return models.HostQueueEntry.query_count(filter_data)
showard34dc5fa2008-04-24 20:58:40 +00001392
1393
showard1e935f12008-07-11 00:11:36 +00001394def get_hqe_percentage_complete(**filter_data):
1395 """
showardc92da832009-04-07 18:14:34 +00001396 Computes the fraction of host queue entries matching the given filter data
showard1e935f12008-07-11 00:11:36 +00001397 that are complete.
1398 """
1399 query = models.HostQueueEntry.query_objects(filter_data)
1400 complete_count = query.filter(complete=True).count()
1401 total_count = query.count()
1402 if total_count == 0:
1403 return 1
1404 return float(complete_count) / total_count
1405
1406
showard1a5a4082009-07-28 20:01:37 +00001407# special tasks
1408
1409def get_special_tasks(**filter_data):
J. Richard Barnetteb5164d62015-04-13 12:59:31 -07001410 """Get special task entries from the local database.
1411
1412 Query the special tasks table for tasks matching the given
1413 `filter_data`, and return a list of the results. No attempt is
1414 made to forward the call to shards; the buck will stop here.
1415 The caller is expected to know the target shard for such reasons
1416 as:
1417 * The caller is a service (such as gs_offloader) configured
1418 to operate on behalf of one specific shard, and no other.
1419 * The caller has a host as a parameter, and knows that this is
1420 the shard assigned to that host.
1421
1422 @param filter_data Filter keywords to pass to the underlying
1423 database query.
1424
1425 """
J. Richard Barnettefdfcd662015-04-13 17:20:29 -07001426 return rpc_utils.prepare_rows_as_nested_dicts(
1427 models.SpecialTask.query_objects(filter_data),
1428 ('host', 'queue_entry'))
J. Richard Barnetteb5164d62015-04-13 12:59:31 -07001429
1430
1431def get_host_special_tasks(host_id, **filter_data):
1432 """Get special task entries for a given host.
1433
1434 Query the special tasks table for tasks that ran on the host
1435 given by `host_id` and matching the given `filter_data`.
1436 Return a list of the results. If the host is assigned to a
1437 shard, forward this call to that shard.
1438
1439 @param host_id Id in the database of the target host.
1440 @param filter_data Filter keywords to pass to the underlying
1441 database query.
1442
1443 """
MK Ryu0c1a37d2015-04-30 12:00:55 -07001444 # Retrieve host data even if the host is in an invalid state.
1445 host = models.Host.smart_get(host_id, False)
J. Richard Barnetteb5164d62015-04-13 12:59:31 -07001446 if not host.shard:
J. Richard Barnettefdfcd662015-04-13 17:20:29 -07001447 return get_special_tasks(host_id=host_id, **filter_data)
J. Richard Barnetteb5164d62015-04-13 12:59:31 -07001448 else:
J. Richard Barnette39255fa2015-04-14 17:23:41 -07001449 # The return values from AFE methods are post-processed
1450 # objects that aren't JSON-serializable. So, we have to
1451 # call AFE.run() to get the raw, serializable output from
1452 # the shard.
J. Richard Barnetteb5164d62015-04-13 12:59:31 -07001453 shard_afe = frontend.AFE(server=host.shard.rpc_hostname())
1454 return shard_afe.run('get_special_tasks',
1455 host_id=host_id, **filter_data)
showard1a5a4082009-07-28 20:01:37 +00001456
1457
MK Ryu0c1a37d2015-04-30 12:00:55 -07001458def get_num_special_tasks(**kwargs):
1459 """Get the number of special task entries from the local database.
1460
1461 Query the special tasks table for tasks matching the given 'kwargs',
1462 and return the number of the results. No attempt is made to forward
1463 the call to shards; the buck will stop here.
1464
1465 @param kwargs Filter keywords to pass to the underlying database query.
1466
1467 """
1468 return models.SpecialTask.query_count(kwargs)
1469
1470
1471def get_host_num_special_tasks(host, **kwargs):
1472 """Get special task entries for a given host.
1473
1474 Query the special tasks table for tasks that ran on the host
1475 given by 'host' and matching the given 'kwargs'.
1476 Return a list of the results. If the host is assigned to a
1477 shard, forward this call to that shard.
1478
1479 @param host id or name of a host. More often a hostname.
1480 @param kwargs Filter keywords to pass to the underlying database query.
1481
1482 """
1483 # Retrieve host data even if the host is in an invalid state.
1484 host_model = models.Host.smart_get(host, False)
1485 if not host_model.shard:
1486 return get_num_special_tasks(host=host, **kwargs)
1487 else:
1488 shard_afe = frontend.AFE(server=host_model.shard.rpc_hostname())
1489 return shard_afe.run('get_num_special_tasks', host=host, **kwargs)
1490
1491
J. Richard Barnette39255fa2015-04-14 17:23:41 -07001492def get_status_task(host_id, end_time):
J. Richard Barnette4d7e6e62015-05-01 10:47:34 -07001493 """Get the "status task" for a host from the local shard.
J. Richard Barnette39255fa2015-04-14 17:23:41 -07001494
J. Richard Barnette4d7e6e62015-05-01 10:47:34 -07001495 Returns a single special task representing the given host's
1496 "status task". The status task is a completed special task that
1497 identifies whether the corresponding host was working or broken
1498 when it completed. A successful task indicates a working host;
1499 a failed task indicates broken.
J. Richard Barnette39255fa2015-04-14 17:23:41 -07001500
J. Richard Barnette4d7e6e62015-05-01 10:47:34 -07001501 This call will not be forward to a shard; the receiving server
1502 must be the shard that owns the host.
1503
1504 @param host_id Id in the database of the target host.
1505 @param end_time Time reference for the host's status.
1506
1507 @return A single task; its status (successful or not)
1508 corresponds to the status of the host (working or
1509 broken) at the given time. If no task is found, return
1510 `None`.
1511
1512 """
1513 tasklist = rpc_utils.prepare_rows_as_nested_dicts(
1514 status_history.get_status_task(host_id, end_time),
1515 ('host', 'queue_entry'))
1516 return tasklist[0] if tasklist else None
1517
1518
1519def get_host_status_task(host_id, end_time):
1520 """Get the "status task" for a host from its owning shard.
1521
1522 Finds the given host's owning shard, and forwards to it a call
1523 to `get_status_task()` (see above).
J. Richard Barnette39255fa2015-04-14 17:23:41 -07001524
1525 @param host_id Id in the database of the target host.
1526 @param end_time Time reference for the host's status.
1527
1528 @return A single task; its status (successful or not)
1529 corresponds to the status of the host (working or
1530 broken) at the given time. If no task is found, return
1531 `None`.
1532
1533 """
1534 host = models.Host.smart_get(host_id)
1535 if not host.shard:
J. Richard Barnette4d7e6e62015-05-01 10:47:34 -07001536 return get_status_task(host_id, end_time)
J. Richard Barnette39255fa2015-04-14 17:23:41 -07001537 else:
1538 # The return values from AFE methods are post-processed
1539 # objects that aren't JSON-serializable. So, we have to
1540 # call AFE.run() to get the raw, serializable output from
1541 # the shard.
1542 shard_afe = frontend.AFE(server=host.shard.rpc_hostname())
1543 return shard_afe.run('get_status_task',
1544 host_id=host_id, end_time=end_time)
1545
1546
J. Richard Barnette8abbfd62015-06-23 12:46:54 -07001547def get_host_diagnosis_interval(host_id, end_time, success):
1548 """Find a "diagnosis interval" for a given host.
1549
1550 A "diagnosis interval" identifies a start and end time where
1551 the host went from "working" to "broken", or vice versa. The
1552 interval's starting time is the starting time of the last status
1553 task with the old status; the end time is the finish time of the
1554 first status task with the new status.
1555
1556 This routine finds the most recent diagnosis interval for the
1557 given host prior to `end_time`, with a starting status matching
1558 `success`. If `success` is true, the interval will start with a
1559 successful status task; if false the interval will start with a
1560 failed status task.
1561
1562 @param host_id Id in the database of the target host.
1563 @param end_time Time reference for the diagnosis interval.
1564 @param success Whether the diagnosis interval should start
1565 with a successful or failed status task.
1566
1567 @return A list of two strings. The first is the timestamp for
1568 the beginning of the interval; the second is the
1569 timestamp for the end. If the host has never changed
1570 state, the list is empty.
1571
1572 """
1573 host = models.Host.smart_get(host_id)
J. Richard Barnette78f281a2015-06-29 13:24:51 -07001574 if not host.shard or utils.is_shard():
J. Richard Barnette8abbfd62015-06-23 12:46:54 -07001575 return status_history.get_diagnosis_interval(
1576 host_id, end_time, success)
1577 else:
1578 shard_afe = frontend.AFE(server=host.shard.rpc_hostname())
1579 return shard_afe.get_host_diagnosis_interval(
1580 host_id, end_time, success)
1581
1582
showardc0ac3a72009-07-08 21:14:45 +00001583# support for host detail view
1584
MK Ryu0c1a37d2015-04-30 12:00:55 -07001585def get_host_queue_entries_and_special_tasks(host, query_start=None,
Jiaxi Luo57bc1952014-07-22 15:27:30 -07001586 query_limit=None, start_time=None,
1587 end_time=None):
showardc0ac3a72009-07-08 21:14:45 +00001588 """
1589 @returns an interleaved list of HostQueueEntries and SpecialTasks,
1590 in approximate run order. each dict contains keys for type, host,
1591 job, status, started_on, execution_path, and ID.
1592 """
1593 total_limit = None
1594 if query_limit is not None:
1595 total_limit = query_start + query_limit
MK Ryu0c1a37d2015-04-30 12:00:55 -07001596 filter_data_common = {'host': host,
Jiaxi Luo57bc1952014-07-22 15:27:30 -07001597 'query_limit': total_limit,
1598 'sort_by': ['-id']}
showardc0ac3a72009-07-08 21:14:45 +00001599
MK Ryu0c1a37d2015-04-30 12:00:55 -07001600 filter_data_special_tasks = rpc_utils.inject_times_to_filter(
1601 'time_started__gte', 'time_started__lte', start_time, end_time,
1602 **filter_data_common)
Jiaxi Luo57bc1952014-07-22 15:27:30 -07001603
MK Ryu0c1a37d2015-04-30 12:00:55 -07001604 queue_entries = get_host_queue_entries(
1605 start_time, end_time, **filter_data_common)
1606 special_tasks = get_host_special_tasks(host, **filter_data_special_tasks)
showardc0ac3a72009-07-08 21:14:45 +00001607
1608 interleaved_entries = rpc_utils.interleave_entries(queue_entries,
1609 special_tasks)
1610 if query_start is not None:
1611 interleaved_entries = interleaved_entries[query_start:]
1612 if query_limit is not None:
1613 interleaved_entries = interleaved_entries[:query_limit]
MK Ryu0c1a37d2015-04-30 12:00:55 -07001614 return rpc_utils.prepare_host_queue_entries_and_special_tasks(
1615 interleaved_entries, queue_entries)
showardc0ac3a72009-07-08 21:14:45 +00001616
1617
MK Ryu0c1a37d2015-04-30 12:00:55 -07001618def get_num_host_queue_entries_and_special_tasks(host, start_time=None,
Jiaxi Luo57bc1952014-07-22 15:27:30 -07001619 end_time=None):
MK Ryu0c1a37d2015-04-30 12:00:55 -07001620 filter_data_common = {'host': host}
Jiaxi Luo57bc1952014-07-22 15:27:30 -07001621
1622 filter_data_queue_entries, filter_data_special_tasks = (
1623 rpc_utils.inject_times_to_hqe_special_tasks_filters(
1624 filter_data_common, start_time, end_time))
1625
1626 return (models.HostQueueEntry.query_count(filter_data_queue_entries)
MK Ryu0c1a37d2015-04-30 12:00:55 -07001627 + get_host_num_special_tasks(**filter_data_special_tasks))
showardc0ac3a72009-07-08 21:14:45 +00001628
1629
mblighe8819cd2008-02-15 16:48:40 +00001630# other
1631
showarde0b63622008-08-04 20:58:47 +00001632def echo(data=""):
1633 """\
1634 Returns a passed in string. For doing a basic test to see if RPC calls
1635 can successfully be made.
1636 """
1637 return data
1638
1639
showardb7a52fd2009-04-27 20:10:56 +00001640def get_motd():
1641 """\
1642 Returns the message of the day as a string.
1643 """
1644 return rpc_utils.get_motd()
1645
1646
mblighe8819cd2008-02-15 16:48:40 +00001647def get_static_data():
jadmanski0afbb632008-06-06 21:10:57 +00001648 """\
1649 Returns a dictionary containing a bunch of data that shouldn't change
1650 often and is otherwise inaccessible. This includes:
showardc92da832009-04-07 18:14:34 +00001651
1652 priorities: List of job priority choices.
1653 default_priority: Default priority value for new jobs.
1654 users: Sorted list of all users.
Jiaxi Luo31874592014-06-11 10:36:35 -07001655 labels: Sorted list of labels not start with 'cros-version' and
1656 'fw-version'.
showardc92da832009-04-07 18:14:34 +00001657 atomic_groups: Sorted list of all atomic groups.
1658 tests: Sorted list of all tests.
1659 profilers: Sorted list of all profilers.
1660 current_user: Logged-in username.
1661 host_statuses: Sorted list of possible Host statuses.
1662 job_statuses: Sorted list of possible HostQueueEntry statuses.
Simran Basi7e605742013-11-12 13:43:36 -08001663 job_timeout_default: The default job timeout length in minutes.
showarda1e74b32009-05-12 17:32:04 +00001664 parse_failed_repair_default: Default value for the parse_failed_repair job
Jiaxi Luo31874592014-06-11 10:36:35 -07001665 option.
showardc92da832009-04-07 18:14:34 +00001666 reboot_before_options: A list of valid RebootBefore string enums.
1667 reboot_after_options: A list of valid RebootAfter string enums.
1668 motd: Server's message of the day.
1669 status_dictionary: A mapping from one word job status names to a more
1670 informative description.
jadmanski0afbb632008-06-06 21:10:57 +00001671 """
showard21baa452008-10-21 00:08:39 +00001672
jamesren76fcf192010-04-21 20:39:50 +00001673 default_drone_set_name = models.DroneSet.default_drone_set_name()
1674 drone_sets = ([default_drone_set_name] +
1675 sorted(drone_set.name for drone_set in
1676 models.DroneSet.objects.exclude(
1677 name=default_drone_set_name)))
showard21baa452008-10-21 00:08:39 +00001678
jadmanski0afbb632008-06-06 21:10:57 +00001679 result = {}
Alex Miller7d658cf2013-09-04 16:00:35 -07001680 result['priorities'] = priorities.Priority.choices()
Alex Miller7d658cf2013-09-04 16:00:35 -07001681 result['default_priority'] = 'Default'
1682 result['max_schedulable_priority'] = priorities.Priority.DEFAULT
jadmanski0afbb632008-06-06 21:10:57 +00001683 result['users'] = get_users(sort_by=['login'])
Jiaxi Luo31874592014-06-11 10:36:35 -07001684
1685 label_exclude_filters = [{'name__startswith': 'cros-version'},
Dan Shi65351d62015-08-03 12:03:23 -07001686 {'name__startswith': 'fw-version'},
1687 {'name__startswith': 'fwrw-version'},
Dan Shi27516972016-03-16 14:03:41 -07001688 {'name__startswith': 'fwro-version'},
1689 {'name__startswith': 'ab-version'},
1690 {'name__startswith': 'testbed-version'}]
Jiaxi Luo31874592014-06-11 10:36:35 -07001691 result['labels'] = get_labels(
1692 label_exclude_filters,
1693 sort_by=['-platform', 'name'])
1694
showardc92da832009-04-07 18:14:34 +00001695 result['atomic_groups'] = get_atomic_groups(sort_by=['name'])
jadmanski0afbb632008-06-06 21:10:57 +00001696 result['tests'] = get_tests(sort_by=['name'])
showard2b9a88b2008-06-13 20:55:03 +00001697 result['profilers'] = get_profilers(sort_by=['name'])
showard0fc38302008-10-23 00:44:07 +00001698 result['current_user'] = rpc_utils.prepare_for_serialization(
showard64a95952010-01-13 21:27:16 +00001699 models.User.current_user().get_object_dict())
showard2b9a88b2008-06-13 20:55:03 +00001700 result['host_statuses'] = sorted(models.Host.Status.names)
mbligh5a198b92008-12-11 19:33:29 +00001701 result['job_statuses'] = sorted(models.HostQueueEntry.Status.names)
Simran Basi7e605742013-11-12 13:43:36 -08001702 result['job_timeout_mins_default'] = models.Job.DEFAULT_TIMEOUT_MINS
Simran Basi34217022012-11-06 13:43:15 -08001703 result['job_max_runtime_mins_default'] = (
1704 models.Job.DEFAULT_MAX_RUNTIME_MINS)
showarda1e74b32009-05-12 17:32:04 +00001705 result['parse_failed_repair_default'] = bool(
1706 models.Job.DEFAULT_PARSE_FAILED_REPAIR)
jamesrendd855242010-03-02 22:23:44 +00001707 result['reboot_before_options'] = model_attributes.RebootBefore.names
1708 result['reboot_after_options'] = model_attributes.RebootAfter.names
showard8fbae652009-01-20 23:23:10 +00001709 result['motd'] = rpc_utils.get_motd()
jamesren76fcf192010-04-21 20:39:50 +00001710 result['drone_sets_enabled'] = models.DroneSet.drone_sets_enabled()
1711 result['drone_sets'] = drone_sets
jamesren4a41e012010-07-16 22:33:48 +00001712 result['parameterized_jobs'] = models.Job.parameterized_jobs_enabled()
showard8ac29b42008-07-17 17:01:55 +00001713
showardd3dc1992009-04-22 21:01:40 +00001714 result['status_dictionary'] = {"Aborted": "Aborted",
showard8ac29b42008-07-17 17:01:55 +00001715 "Verifying": "Verifying Host",
Alex Millerdfff2fd2013-05-28 13:05:06 -07001716 "Provisioning": "Provisioning Host",
showard8ac29b42008-07-17 17:01:55 +00001717 "Pending": "Waiting on other hosts",
1718 "Running": "Running autoserv",
1719 "Completed": "Autoserv completed",
1720 "Failed": "Failed to complete",
showardd823b362008-07-24 16:35:46 +00001721 "Queued": "Queued",
showard5deb6772008-11-04 21:54:33 +00001722 "Starting": "Next in host's queue",
1723 "Stopped": "Other host(s) failed verify",
showardd3dc1992009-04-22 21:01:40 +00001724 "Parsing": "Awaiting parse of final results",
showard29f7cd22009-04-29 21:16:24 +00001725 "Gathering": "Gathering log files",
mbligh4608b002010-01-05 18:22:35 +00001726 "Waiting": "Waiting for scheduler action",
Dan Shi07e09af2013-04-12 09:31:29 -07001727 "Archiving": "Archiving results",
1728 "Resetting": "Resetting hosts"}
Jiaxi Luo421608e2014-07-07 14:38:00 -07001729
1730 result['wmatrix_url'] = rpc_utils.get_wmatrix_url()
Simran Basi71206ef2014-08-13 13:51:18 -07001731 result['is_moblab'] = bool(utils.is_moblab())
Jiaxi Luo421608e2014-07-07 14:38:00 -07001732
jadmanski0afbb632008-06-06 21:10:57 +00001733 return result
showard29f7cd22009-04-29 21:16:24 +00001734
1735
1736def get_server_time():
1737 return datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
Kevin Cheng19521982016-09-22 12:27:23 -07001738
1739
1740def get_hosts_by_attribute(attribute, value):
1741 """
1742 Get the list of valid hosts that share the same host attribute value.
1743
1744 @param attribute: String of the host attribute to check.
1745 @param value: String of the value that is shared between hosts.
1746
1747 @returns List of hostnames that all have the same host attribute and
1748 value.
1749 """
1750 hosts = models.HostAttribute.query_objects({'attribute': attribute,
1751 'value': value})
1752 return [row.host.hostname for row in hosts if row.host.invalid == 0]
Allen Licdd00f22017-02-01 18:01:52 -08001753
1754
1755def canonicalize_suite_name(suite_name):
1756 """Canonicalize the suite's name.
1757
1758 @param suite_name: the name of the suite.
1759 """
1760 # Do not change this naming convention without updating
1761 # site_utils.parse_job_name.
1762 return 'test_suites/control.%s' % suite_name
1763
1764
1765def formatted_now():
1766 """Format the current datetime."""
1767 return datetime.datetime.now().strftime(time_utils.TIME_FMT)
1768
1769
1770def _get_control_file_by_build(build, ds, suite_name):
1771 """Return control file contents for |suite_name|.
1772
1773 Query the dev server at |ds| for the control file |suite_name|, included
1774 in |build| for |board|.
1775
1776 @param build: unique name by which to refer to the image from now on.
1777 @param ds: a dev_server.DevServer instance to fetch control file with.
1778 @param suite_name: canonicalized suite name, e.g. test_suites/control.bvt.
1779 @raises ControlFileNotFound if a unique suite control file doesn't exist.
1780 @raises NoControlFileList if we can't list the control files at all.
1781 @raises ControlFileEmpty if the control file exists on the server, but
1782 can't be read.
1783
1784 @return the contents of the desired control file.
1785 """
1786 getter = control_file_getter.DevServerGetter.create(build, ds)
1787 devserver_name = ds.hostname
1788 timer = autotest_stats.Timer('control_files.parse.%s.%s' %
1789 (devserver_name.replace('.', '_'),
1790 suite_name.rsplit('.')[-1]))
1791 # Get the control file for the suite.
1792 try:
1793 with timer:
1794 control_file_in = getter.get_control_file_contents_by_name(
1795 suite_name)
1796 except error.CrosDynamicSuiteException as e:
1797 raise type(e)('Failed to get control file for %s '
1798 '(devserver: %s) (error: %s)' %
1799 (build, devserver_name, e))
1800 if not control_file_in:
1801 raise error.ControlFileEmpty(
1802 "Fetching %s returned no data. (devserver: %s)" %
1803 (suite_name, devserver_name))
1804 # Force control files to only contain ascii characters.
1805 try:
1806 control_file_in.encode('ascii')
1807 except UnicodeDecodeError as e:
1808 raise error.ControlFileMalformed(str(e))
1809
1810 return control_file_in
1811
1812
1813def _get_control_file_by_suite(suite_name):
1814 """Get control file contents by suite name.
1815
1816 @param suite_name: Suite name as string.
1817 @returns: Control file contents as string.
1818 """
1819 getter = control_file_getter.FileSystemGetter(
Dan Shi6cd838f2017-02-02 15:30:18 -08001820 [_CONFIG.get_config_value('SCHEDULER',
1821 'drone_installation_directory')])
Allen Licdd00f22017-02-01 18:01:52 -08001822 return getter.get_control_file_contents_by_name(suite_name)
1823
1824
1825def _stage_build_artifacts(build, hostname=None):
1826 """
1827 Ensure components of |build| necessary for installing images are staged.
1828
1829 @param build image we want to stage.
1830 @param hostname hostname of a dut may run test on. This is to help to locate
1831 a devserver closer to duts if needed. Default is None.
1832
1833 @raises StageControlFileFailure: if the dev server throws 500 while staging
1834 suite control files.
1835
1836 @return: dev_server.ImageServer instance to use with this build.
1837 @return: timings dictionary containing staging start/end times.
1838 """
1839 timings = {}
1840 # Ensure components of |build| necessary for installing images are staged
1841 # on the dev server. However set synchronous to False to allow other
1842 # components to be downloaded in the background.
1843 ds = dev_server.resolve(build, hostname=hostname)
1844 ds_name = ds.hostname
1845 timings[constants.DOWNLOAD_STARTED_TIME] = formatted_now()
1846 timer = autotest_stats.Timer('control_files.stage.%s' % (
1847 ds_name.replace('.', '_')))
1848 try:
1849 with timer:
1850 ds.stage_artifacts(image=build, artifacts=['test_suites'])
1851 except dev_server.DevServerException as e:
1852 raise error.StageControlFileFailure(
1853 "Failed to stage %s on %s: %s" % (build, ds_name, e))
1854 timings[constants.PAYLOAD_FINISHED_TIME] = formatted_now()
1855 return (ds, timings)
1856
1857
1858@rpc_utils.route_rpc_to_master
1859def create_suite_job(
1860 name='',
1861 board='',
1862 pool='',
1863 control_file='',
1864 check_hosts=True,
1865 num=None,
1866 file_bugs=False,
1867 timeout=24,
1868 timeout_mins=None,
1869 priority=priorities.Priority.DEFAULT,
1870 suite_args=None,
1871 wait_for_results=True,
1872 job_retry=False,
1873 max_retries=None,
1874 max_runtime_mins=None,
1875 suite_min_duts=0,
1876 offload_failures_only=False,
1877 builds=None,
1878 test_source_build=None,
1879 run_prod_code=False,
1880 delay_minutes=0,
1881 is_cloning=False,
Shuqian Zhaoda1118d2017-02-13 16:22:58 -08001882 job_keyvals=None,
Allen Licdd00f22017-02-01 18:01:52 -08001883 **kwargs
1884):
1885 """
1886 Create a job to run a test suite on the given device with the given image.
1887
1888 When the timeout specified in the control file is reached, the
1889 job is guaranteed to have completed and results will be available.
1890
1891 @param name: The test name if control_file is supplied, otherwise the name
1892 of the test suite to run, e.g. 'bvt'.
1893 @param board: the kind of device to run the tests on.
1894 @param builds: the builds to install e.g.
1895 {'cros-version:': 'x86-alex-release/R18-1655.0.0',
1896 'fwrw-version:': 'x86-alex-firmware/R36-5771.50.0',
1897 'fwro-version:': 'x86-alex-firmware/R36-5771.49.0'}
1898 If builds is given a value, it overrides argument build.
1899 @param test_source_build: Build that contains the server-side test code.
1900 @param pool: Specify the pool of machines to use for scheduling
1901 purposes.
1902 @param control_file: the control file of the job.
1903 @param check_hosts: require appropriate live hosts to exist in the lab.
1904 @param num: Specify the number of machines to schedule across (integer).
1905 Leave unspecified or use None to use default sharding factor.
1906 @param file_bugs: File a bug on each test failure in this suite.
1907 @param timeout: The max lifetime of this suite, in hours.
1908 @param timeout_mins: The max lifetime of this suite, in minutes. Takes
1909 priority over timeout.
1910 @param priority: Integer denoting priority. Higher is more important.
1911 @param suite_args: Optional arguments which will be parsed by the suite
1912 control file. Used by control.test_that_wrapper to
1913 determine which tests to run.
1914 @param wait_for_results: Set to False to run the suite job without waiting
1915 for test jobs to finish. Default is True.
1916 @param job_retry: Set to True to enable job-level retry. Default is False.
1917 @param max_retries: Integer, maximum job retries allowed at suite level.
1918 None for no max.
1919 @param max_runtime_mins: Maximum amount of time a job can be running in
1920 minutes.
1921 @param suite_min_duts: Integer. Scheduler will prioritize getting the
1922 minimum number of machines for the suite when it is
1923 competing with another suite that has a higher
1924 priority but already got minimum machines it needs.
1925 @param offload_failures_only: Only enable gs_offloading for failed jobs.
1926 @param run_prod_code: If True, the suite will run the test code that
1927 lives in prod aka the test code currently on the
1928 lab servers. If False, the control files and test
1929 code for this suite run will be retrieved from the
1930 build artifacts.
1931 @param delay_minutes: Delay the creation of test jobs for a given number of
1932 minutes.
1933 @param is_cloning: True if creating a cloning job.
Shuqian Zhaoda1118d2017-02-13 16:22:58 -08001934 @param job_keyvals: A dict of job keyvals to be inject to control file.
Allen Licdd00f22017-02-01 18:01:52 -08001935 @param kwargs: extra keyword args. NOT USED.
1936
1937 @raises ControlFileNotFound: if a unique suite control file doesn't exist.
1938 @raises NoControlFileList: if we can't list the control files at all.
1939 @raises StageControlFileFailure: If the dev server throws 500 while
1940 staging test_suites.
1941 @raises ControlFileEmpty: if the control file exists on the server, but
1942 can't be read.
1943
1944 @return: the job ID of the suite; -1 on error.
1945 """
1946 if type(num) is not int and num is not None:
1947 raise error.SuiteArgumentException('Ill specified num argument %r. '
1948 'Must be an integer or None.' % num)
1949 if num == 0:
1950 logging.warning("Can't run on 0 hosts; using default.")
1951 num = None
1952
1953 if builds is None:
1954 builds = {}
1955
1956 # Default test source build to CrOS build if it's not specified and
1957 # run_prod_code is set to False.
1958 if not run_prod_code:
1959 test_source_build = Suite.get_test_source_build(
1960 builds, test_source_build=test_source_build)
1961
1962 sample_dut = rpc_utils.get_sample_dut(board, pool)
1963
1964 suite_name = canonicalize_suite_name(name)
1965 if run_prod_code:
1966 ds = dev_server.resolve(test_source_build, hostname=sample_dut)
1967 keyvals = {}
1968 else:
1969 (ds, keyvals) = _stage_build_artifacts(
1970 test_source_build, hostname=sample_dut)
1971 keyvals[constants.SUITE_MIN_DUTS_KEY] = suite_min_duts
1972
1973 # Do not change this naming convention without updating
1974 # site_utils.parse_job_name.
1975 if run_prod_code:
1976 # If run_prod_code is True, test_source_build is not set, use the
1977 # first build in the builds list for the sutie job name.
1978 name = '%s-%s' % (builds.values()[0], suite_name)
1979 else:
1980 name = '%s-%s' % (test_source_build, suite_name)
1981
1982 timeout_mins = timeout_mins or timeout * 60
1983 max_runtime_mins = max_runtime_mins or timeout * 60
1984
1985 if not board:
1986 board = utils.ParseBuildName(builds[provision.CROS_VERSION_PREFIX])[0]
1987
1988 if run_prod_code:
1989 control_file = _get_control_file_by_suite(suite_name)
1990
1991 if not control_file:
1992 # No control file was supplied so look it up from the build artifacts.
1993 control_file = _get_control_file_by_build(
1994 test_source_build, ds, suite_name)
1995
1996 # Prepend builds and board to the control file.
1997 if is_cloning:
1998 control_file = tools.remove_injection(control_file)
1999
2000 inject_dict = {
2001 'board': board,
2002 # `build` is needed for suites like AU to stage image inside suite
2003 # control file.
2004 'build': test_source_build,
2005 'builds': builds,
2006 'check_hosts': check_hosts,
2007 'pool': pool,
2008 'num': num,
2009 'file_bugs': file_bugs,
2010 'timeout': timeout,
2011 'timeout_mins': timeout_mins,
2012 'devserver_url': ds.url(),
2013 'priority': priority,
2014 'suite_args' : suite_args,
2015 'wait_for_results': wait_for_results,
2016 'job_retry': job_retry,
2017 'max_retries': max_retries,
2018 'max_runtime_mins': max_runtime_mins,
2019 'offload_failures_only': offload_failures_only,
2020 'test_source_build': test_source_build,
2021 'run_prod_code': run_prod_code,
2022 'delay_minutes': delay_minutes,
Shuqian Zhaoda1118d2017-02-13 16:22:58 -08002023 'job_keyvals': job_keyvals
Allen Licdd00f22017-02-01 18:01:52 -08002024 }
2025 control_file = tools.inject_vars(inject_dict, control_file)
2026
2027 return rpc_utils.create_job_common(name,
2028 priority=priority,
2029 timeout_mins=timeout_mins,
2030 max_runtime_mins=max_runtime_mins,
2031 control_type='Server',
2032 control_file=control_file,
2033 hostless=True,
2034 keyvals=keyvals)
2035
2036
2037def get_job_history(**filter_data):
2038 """Get history of the job, including the special tasks executed for the job
2039
2040 @param filter_data: filter for the call, should at least include
2041 {'job_id': [job id]}
2042 @returns: JSON string of the job's history, including the information such
2043 as the hosts run the job and the special tasks executed before
2044 and after the job.
2045 """
2046 job_id = filter_data['job_id']
2047 job_info = job_history.get_job_info(job_id)
2048 return rpc_utils.prepare_for_serialization(job_info.get_history())
2049
2050
2051def get_host_history(start_time, end_time, hosts=None, board=None, pool=None):
2052 """Get history of a list of host.
2053
2054 The return is a JSON string of host history for each host, for example,
2055 {'172.22.33.51': [{'status': 'Resetting'
2056 'start_time': '2014-08-07 10:02:16',
2057 'end_time': '2014-08-07 10:03:16',
2058 'log_url': 'http://autotest/reset-546546/debug',
2059 'dbg_str': 'Task: Special Task 19441991 (host ...)'},
2060 {'status': 'Running'
2061 'start_time': '2014-08-07 10:03:18',
2062 'end_time': '2014-08-07 10:13:00',
2063 'log_url': 'http://autotest/reset-546546/debug',
2064 'dbg_str': 'HQE: 15305005, for job: 14995562'}
2065 ]
2066 }
2067 @param start_time: start time to search for history, can be string value or
2068 epoch time.
2069 @param end_time: end time to search for history, can be string value or
2070 epoch time.
2071 @param hosts: A list of hosts to search for history. Default is None.
2072 @param board: board type of hosts. Default is None.
2073 @param pool: pool type of hosts. Default is None.
2074 @returns: JSON string of the host history.
2075 """
2076 return rpc_utils.prepare_for_serialization(
2077 host_history.get_history_details(
2078 start_time=start_time, end_time=end_time,
2079 hosts=hosts, board=board, pool=pool,
2080 process_pool_size=4))
2081
2082
2083def shard_heartbeat(shard_hostname, jobs=(), hqes=(), known_job_ids=(),
2084 known_host_ids=(), known_host_statuses=()):
2085 """Receive updates for job statuses from shards and assign hosts and jobs.
2086
2087 @param shard_hostname: Hostname of the calling shard
2088 @param jobs: Jobs in serialized form that should be updated with newer
2089 status from a shard.
2090 @param hqes: Hostqueueentries in serialized form that should be updated with
2091 newer status from a shard. Note that for every hostqueueentry
2092 the corresponding job must be in jobs.
2093 @param known_job_ids: List of ids of jobs the shard already has.
2094 @param known_host_ids: List of ids of hosts the shard already has.
2095 @param known_host_statuses: List of statuses of hosts the shard already has.
2096
2097 @returns: Serialized representations of hosts, jobs, suite job keyvals
2098 and their dependencies to be inserted into a shard's database.
2099 """
2100 # The following alternatives to sending host and job ids in every heartbeat
2101 # have been considered:
2102 # 1. Sending the highest known job and host ids. This would work for jobs:
2103 # Newer jobs always have larger ids. Also, if a job is not assigned to a
2104 # particular shard during a heartbeat, it never will be assigned to this
2105 # shard later.
2106 # This is not true for hosts though: A host that is leased won't be sent
2107 # to the shard now, but might be sent in a future heartbeat. This means
2108 # sometimes hosts should be transfered that have a lower id than the
2109 # maximum host id the shard knows.
2110 # 2. Send the number of jobs/hosts the shard knows to the master in each
2111 # heartbeat. Compare these to the number of records that already have
2112 # the shard_id set to this shard. In the normal case, they should match.
2113 # In case they don't, resend all entities of that type.
2114 # This would work well for hosts, because there aren't that many.
2115 # Resending all jobs is quite a big overhead though.
2116 # Also, this approach might run into edge cases when entities are
2117 # ever deleted.
2118 # 3. Mixtures of the above: Use 1 for jobs and 2 for hosts.
2119 # Using two different approaches isn't consistent and might cause
2120 # confusion. Also the issues with the case of deletions might still
2121 # occur.
2122 #
2123 # The overhead of sending all job and host ids in every heartbeat is low:
2124 # At peaks one board has about 1200 created but unfinished jobs.
2125 # See the numbers here: http://goo.gl/gQCGWH
2126 # Assuming that job id's have 6 digits and that json serialization takes a
2127 # comma and a space as overhead, the traffic per id sent is about 8 bytes.
2128 # If 5000 ids need to be sent, this means 40 kilobytes of traffic.
2129 # A NOT IN query with 5000 ids took about 30ms in tests made.
2130 # These numbers seem low enough to outweigh the disadvantages of the
2131 # solutions described above.
2132 timer = autotest_stats.Timer('shard_heartbeat')
2133 with timer:
2134 shard_obj = rpc_utils.retrieve_shard(shard_hostname=shard_hostname)
2135 rpc_utils.persist_records_sent_from_shard(shard_obj, jobs, hqes)
2136 assert len(known_host_ids) == len(known_host_statuses)
2137 for i in range(len(known_host_ids)):
2138 host_model = models.Host.objects.get(pk=known_host_ids[i])
2139 if host_model.status != known_host_statuses[i]:
2140 host_model.status = known_host_statuses[i]
2141 host_model.save()
2142
2143 hosts, jobs, suite_keyvals = rpc_utils.find_records_for_shard(
2144 shard_obj, known_job_ids=known_job_ids,
2145 known_host_ids=known_host_ids)
2146 return {
2147 'hosts': [host.serialize() for host in hosts],
2148 'jobs': [job.serialize() for job in jobs],
2149 'suite_keyvals': [kv.serialize() for kv in suite_keyvals],
2150 }
2151
2152
2153def get_shards(**filter_data):
2154 """Return a list of all shards.
2155
2156 @returns A sequence of nested dictionaries of shard information.
2157 """
2158 shards = models.Shard.query_objects(filter_data)
2159 serialized_shards = rpc_utils.prepare_rows_as_nested_dicts(shards, ())
2160 for serialized, shard in zip(serialized_shards, shards):
2161 serialized['labels'] = [label.name for label in shard.labels.all()]
2162
2163 return serialized_shards
2164
2165
2166def _assign_board_to_shard_precheck(labels):
2167 """Verify whether board labels are valid to be added to a given shard.
2168
2169 First check whether board label is in correct format. Second, check whether
2170 the board label exist. Third, check whether the board has already been
2171 assigned to shard.
2172
2173 @param labels: Board labels separated by comma.
2174
2175 @raises error.RPCException: If label provided doesn't start with `board:`
2176 or board has been added to shard already.
2177 @raises models.Label.DoesNotExist: If the label specified doesn't exist.
2178
2179 @returns: A list of label models that ready to be added to shard.
2180 """
2181 labels = labels.split(',')
2182 label_models = []
2183 for label in labels:
2184 # Check whether the board label is in correct format.
2185 if not label.startswith('board:'):
2186 raise error.RPCException('Sharding only supports `board:.*` label.')
2187 # Check whether the board label exist. If not, exception will be thrown
2188 # by smart_get function.
2189 label = models.Label.smart_get(label)
2190 # Check whether the board has been sharded already
2191 try:
2192 shard = models.Shard.objects.get(labels=label)
2193 raise error.RPCException(
2194 '%s is already on shard %s' % (label, shard.hostname))
2195 except models.Shard.DoesNotExist:
2196 # board is not on any shard, so it's valid.
2197 label_models.append(label)
2198 return label_models
2199
2200
2201def add_shard(hostname, labels):
2202 """Add a shard and start running jobs on it.
2203
2204 @param hostname: The hostname of the shard to be added; needs to be unique.
2205 @param labels: Board labels separated by comma. Jobs of one of the labels
2206 will be assigned to the shard.
2207
2208 @raises error.RPCException: If label provided doesn't start with `board:` or
2209 board has been added to shard already.
2210 @raises model_logic.ValidationError: If a shard with the given hostname
2211 already exist.
2212 @raises models.Label.DoesNotExist: If the label specified doesn't exist.
2213
2214 @returns: The id of the added shard.
2215 """
2216 labels = _assign_board_to_shard_precheck(labels)
2217 shard = models.Shard.add_object(hostname=hostname)
2218 for label in labels:
2219 shard.labels.add(label)
2220 return shard.id
2221
2222
2223def add_board_to_shard(hostname, labels):
2224 """Add boards to a given shard
2225
2226 @param hostname: The hostname of the shard to be changed.
2227 @param labels: Board labels separated by comma.
2228
2229 @raises error.RPCException: If label provided doesn't start with `board:` or
2230 board has been added to shard already.
2231 @raises models.Label.DoesNotExist: If the label specified doesn't exist.
2232
2233 @returns: The id of the changed shard.
2234 """
2235 labels = _assign_board_to_shard_precheck(labels)
2236 shard = models.Shard.objects.get(hostname=hostname)
2237 for label in labels:
2238 shard.labels.add(label)
2239 return shard.id
2240
2241
2242def delete_shard(hostname):
2243 """Delete a shard and reclaim all resources from it.
2244
2245 This claims back all assigned hosts from the shard. To ensure all DUTs are
2246 in a sane state, a Reboot task with highest priority is scheduled for them.
2247 This reboots the DUTs and then all left tasks continue to run in drone of
2248 the master.
2249
2250 The procedure for deleting a shard:
2251 * Lock all unlocked hosts on that shard.
2252 * Remove shard information .
2253 * Assign a reboot task with highest priority to these hosts.
2254 * Unlock these hosts, then, the reboot tasks run in front of all other
2255 tasks.
2256
2257 The status of jobs that haven't been reported to be finished yet, will be
2258 lost. The master scheduler will pick up the jobs and execute them.
2259
2260 @param hostname: Hostname of the shard to delete.
2261 """
2262 shard = rpc_utils.retrieve_shard(shard_hostname=hostname)
2263 hostnames_to_lock = [h.hostname for h in
2264 models.Host.objects.filter(shard=shard, locked=False)]
2265
2266 # TODO(beeps): Power off shard
2267 # For ChromeOS hosts, a reboot test with the highest priority is added to
2268 # the DUT. After a reboot it should be ganranteed that no processes from
2269 # prior tests that were run by a shard are still running on.
2270
2271 # Lock all unlocked hosts.
2272 dicts = {'locked': True, 'lock_time': datetime.datetime.now()}
2273 models.Host.objects.filter(hostname__in=hostnames_to_lock).update(**dicts)
2274
2275 # Remove shard information.
2276 models.Host.objects.filter(shard=shard).update(shard=None)
2277 models.Job.objects.filter(shard=shard).update(shard=None)
2278 shard.labels.clear()
2279 shard.delete()
2280
2281 # Assign a reboot task with highest priority: Super.
2282 t = models.Test.objects.get(name='platform_BootPerfServer:shard')
2283 c = utils.read_file(os.path.join(common.autotest_dir, t.path))
2284 if hostnames_to_lock:
2285 rpc_utils.create_job_common(
2286 'reboot_dut_for_shard_deletion',
2287 priority=priorities.Priority.SUPER,
2288 control_type='Server',
2289 control_file=c, hosts=hostnames_to_lock)
2290
2291 # Unlock these shard-related hosts.
2292 dicts = {'locked': False, 'lock_time': None}
2293 models.Host.objects.filter(hostname__in=hostnames_to_lock).update(**dicts)
2294
2295
2296def get_servers(hostname=None, role=None, status=None):
2297 """Get a list of servers with matching role and status.
2298
2299 @param hostname: FQDN of the server.
2300 @param role: Name of the server role, e.g., drone, scheduler. Default to
2301 None to match any role.
2302 @param status: Status of the server, e.g., primary, backup, repair_required.
2303 Default to None to match any server status.
2304
2305 @raises error.RPCException: If server database is not used.
2306 @return: A list of server names for servers with matching role and status.
2307 """
2308 if not server_manager_utils.use_server_db():
2309 raise error.RPCException('Server database is not enabled. Please try '
2310 'retrieve servers from global config.')
2311 servers = server_manager_utils.get_servers(hostname=hostname, role=role,
2312 status=status)
2313 return [s.get_details() for s in servers]
2314
2315
2316@rpc_utils.route_rpc_to_master
2317def get_stable_version(board=stable_version_utils.DEFAULT, android=False):
2318 """Get stable version for the given board.
2319
2320 @param board: Name of the board.
2321 @param android: If True, the given board is an Android-based device. If
2322 False, assume its a Chrome OS-based device.
2323
2324 @return: Stable version of the given board. Return global configure value
2325 of CROS.stable_cros_version if stable_versinos table does not have
2326 entry of board DEFAULT.
2327 """
2328 return stable_version_utils.get(board=board, android=android)
2329
2330
2331@rpc_utils.route_rpc_to_master
2332def get_all_stable_versions():
2333 """Get stable versions for all boards.
2334
2335 @return: A dictionary of board:version.
2336 """
2337 return stable_version_utils.get_all()
2338
2339
2340@rpc_utils.route_rpc_to_master
2341def set_stable_version(version, board=stable_version_utils.DEFAULT):
2342 """Modify stable version for the given board.
2343
2344 @param version: The new value of stable version for given board.
2345 @param board: Name of the board, default to value `DEFAULT`.
2346 """
2347 stable_version_utils.set(version=version, board=board)
2348
2349
2350@rpc_utils.route_rpc_to_master
2351def delete_stable_version(board):
2352 """Modify stable version for the given board.
2353
2354 Delete a stable version entry in afe_stable_versions table for a given
2355 board, so default stable version will be used.
2356
2357 @param board: Name of the board.
2358 """
2359 stable_version_utils.delete(board=board)
2360
2361
2362def get_tests_by_build(build, ignore_invalid_tests=True):
2363 """Get the tests that are available for the specified build.
2364
2365 @param build: unique name by which to refer to the image.
2366 @param ignore_invalid_tests: flag on if unparsable tests are ignored.
2367
2368 @return: A sorted list of all tests that are in the build specified.
2369 """
2370 # Collect the control files specified in this build
2371 cfile_getter = control_file_lib._initialize_control_file_getter(build)
2372 if SuiteBase.ENABLE_CONTROLS_IN_BATCH:
2373 control_file_info_list = cfile_getter.get_suite_info()
2374 control_file_list = control_file_info_list.keys()
2375 else:
2376 control_file_list = cfile_getter.get_control_file_list()
2377
2378 test_objects = []
2379 _id = 0
2380 for control_file_path in control_file_list:
2381 # Read and parse the control file
2382 if SuiteBase.ENABLE_CONTROLS_IN_BATCH:
2383 control_file = control_file_info_list[control_file_path]
2384 else:
2385 control_file = cfile_getter.get_control_file_contents(
2386 control_file_path)
2387 try:
2388 control_obj = control_data.parse_control_string(control_file)
2389 except:
2390 logging.info('Failed to parse control file: %s', control_file_path)
2391 if not ignore_invalid_tests:
2392 raise
2393
2394 # Extract the values needed for the AFE from the control_obj.
2395 # The keys list represents attributes in the control_obj that
2396 # are required by the AFE
2397 keys = ['author', 'doc', 'name', 'time', 'test_type', 'experimental',
2398 'test_category', 'test_class', 'dependencies', 'run_verify',
2399 'sync_count', 'job_retries', 'retries', 'path']
2400
2401 test_object = {}
2402 for key in keys:
2403 test_object[key] = getattr(control_obj, key) if hasattr(
2404 control_obj, key) else ''
2405
2406 # Unfortunately, the AFE expects different key-names for certain
2407 # values, these must be corrected to avoid the risk of tests
2408 # being omitted by the AFE.
2409 # The 'id' is an additional value used in the AFE.
2410 # The control_data parsing does not reference 'run_reset', but it
2411 # is also used in the AFE and defaults to True.
2412 test_object['id'] = _id
2413 test_object['run_reset'] = True
2414 test_object['description'] = test_object.get('doc', '')
2415 test_object['test_time'] = test_object.get('time', 0)
2416 test_object['test_retry'] = test_object.get('retries', 0)
2417
2418 # Fix the test name to be consistent with the current presentation
2419 # of test names in the AFE.
2420 testpath, subname = os.path.split(control_file_path)
2421 testname = os.path.basename(testpath)
2422 subname = subname.split('.')[1:]
2423 if subname:
2424 testname = '%s:%s' % (testname, ':'.join(subname))
2425
2426 test_object['name'] = testname
2427
2428 # Correct the test path as parse_control_string sets an empty string.
2429 test_object['path'] = control_file_path
2430
2431 _id += 1
2432 test_objects.append(test_object)
2433
2434 test_objects = sorted(test_objects, key=lambda x: x.get('name'))
2435 return rpc_utils.prepare_for_serialization(test_objects)