blob: 5a075c9efa849626ef760308004510b354d2ae26 [file] [log] [blame]
Kuang-che Wu875c89a2020-01-08 14:30:55 +08001#!/usr/bin/env python3
Kuang-che Wu6e4beca2018-06-27 17:45:02 +08002# -*- coding: utf-8 -*-
Kuang-che Wu2ea804f2017-11-28 17:11:41 +08003# Copyright 2017 The Chromium OS Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
Kuang-che Wu68db08a2018-03-30 11:50:34 +08006"""Helper script to manipulate chromeos DUT or query info."""
Kuang-che Wu2ea804f2017-11-28 17:11:41 +08007from __future__ import print_function
Kuang-che Wu5157dee2020-07-18 01:13:41 +08008import asyncio
Kuang-che Wu2ea804f2017-11-28 17:11:41 +08009import argparse
10import json
11import logging
Kuang-che Wu0c9b7942019-10-30 16:55:39 +080012import random
13import time
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080014
Kuang-che Wufe1e88a2019-09-10 21:52:25 +080015from bisect_kit import cli
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080016from bisect_kit import common
Kuang-che Wuc45cfa42019-01-15 00:15:01 +080017from bisect_kit import cros_lab_util
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080018from bisect_kit import cros_util
Kuang-che Wu22aa9d42019-01-25 10:35:33 +080019from bisect_kit import errors
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080020
Zheng-Jie Chang17f36c82020-06-16 05:21:59 +080021DEFAULT_DUT_POOL = 'DUT_POOL_QUOTA'
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080022logger = logging.getLogger(__name__)
23
24
25def cmd_version_info(opts):
26 info = cros_util.version_info(opts.board, opts.version)
27 if opts.name:
28 if opts.name not in info:
29 logger.error('unknown name=%s', opts.name)
30 print(info[opts.name])
31 else:
32 print(json.dumps(info, sort_keys=True, indent=4))
33
34
35def cmd_query_dut_board(opts):
36 assert cros_util.is_dut(opts.dut)
37 print(cros_util.query_dut_board(opts.dut))
38
39
40def cmd_reboot(opts):
41 assert cros_util.is_dut(opts.dut)
42 cros_util.reboot(opts.dut)
43
44
Kuang-che Wuc45cfa42019-01-15 00:15:01 +080045def _get_label_by_prefix(info, prefix):
46 for label in info['Labels']:
47 if label.startswith(prefix + ':'):
48 return label
49 return None
50
51
Kuang-che Wuca456462019-11-04 17:32:55 +080052def cmd_lease_dut(opts):
Kuang-che Wu5157dee2020-07-18 01:13:41 +080053 if opts.duration is not None and opts.duration < 60:
54 raise errors.ArgumentError('--duration', 'must be at least 60 seconds')
Kuang-che Wu22aa9d42019-01-25 10:35:33 +080055 host = cros_lab_util.dut_host_name(opts.dut)
Kuang-che Wu220cc162019-10-31 00:29:37 +080056 logger.info('trying to lease %s', host)
57 if cros_lab_util.skylab_lease_dut(host, opts.duration):
Kuang-che Wuca456462019-11-04 17:32:55 +080058 logger.info('leased %s', host)
Kuang-che Wu22aa9d42019-01-25 10:35:33 +080059 else:
Kuang-che Wuca456462019-11-04 17:32:55 +080060 raise Exception('unable to lease %s' % host)
Kuang-che Wu22aa9d42019-01-25 10:35:33 +080061
62
Kuang-che Wuca456462019-11-04 17:32:55 +080063def cmd_release_dut(opts):
Kuang-che Wu22aa9d42019-01-25 10:35:33 +080064 host = cros_lab_util.dut_host_name(opts.dut)
Kuang-che Wu220cc162019-10-31 00:29:37 +080065 cros_lab_util.skylab_release_dut(host)
Kuang-che Wuca456462019-11-04 17:32:55 +080066 logger.info('%s released', host)
Kuang-che Wu22aa9d42019-01-25 10:35:33 +080067
68
Kuang-che Wu1e56ce22020-06-29 11:21:51 +080069def verify_dimensions_by_lab(dimensions):
70 result = []
71 bots_dimensions = cros_lab_util.swarming_bots_dimensions()
72 for dimension in dimensions:
73 key, value = dimension.split(':', 1)
74 if value in bots_dimensions.get(key, []):
75 result.append(dimension)
76 else:
77 logger.warning('dimension=%s is unknown in the lab, typo? ignored',
78 dimension)
79 return result
80
81
Kuang-che Wu5157dee2020-07-18 01:13:41 +080082def select_available_bots_randomly(dimensions, variants, num=1, is_busy=None):
Kuang-che Wu1e56ce22020-06-29 11:21:51 +080083 bots = []
84 for variant in variants:
85 # There might be thousand bots available, set 'limit' to reduce swarming
86 # API cost. This is not uniform random, but should be good enough.
87 bots += cros_lab_util.swarming_bots_list(
88 dimensions + [variant], is_busy=is_busy, limit=10)
89 if not bots:
90 return None
Kuang-che Wu5157dee2020-07-18 01:13:41 +080091 return random.sample(bots, min(num, len(bots)))
92
93
94async def lease_dut_parallelly(duration, bots, timeout=None):
95 tasks = []
96 hosts = []
97 for bot in bots:
98 host = bot['dimensions']['dut_name'][0]
99 hosts.append(host)
100 tasks.append(
101 asyncio.create_task(cros_lab_util.async_lease(host, duration=duration)))
102
103 try:
104 logger.info('trying to lease %d DUTs: %s', len(hosts), hosts)
105 for coro in asyncio.as_completed(tasks, timeout=timeout):
106 host = await coro
107 if host:
108 logger.info('leased %s', host)
109 # Unfinished lease tasks will be cancelled when asyncio.run is finishing.
110 return host
111 return None
112 except asyncio.TimeoutError:
113 return None
Kuang-che Wu1e56ce22020-06-29 11:21:51 +0800114
115
Kuang-che Wu22aa9d42019-01-25 10:35:33 +0800116def do_allocate_dut(opts):
117 """Helper of cmd_allocate_dut.
118
119 Returns:
120 (todo, host)
121 todo: 'ready' or 'wait'
Kuang-che Wuca456462019-11-04 17:32:55 +0800122 host: leased host name
Kuang-che Wu22aa9d42019-01-25 10:35:33 +0800123 """
Kuang-che Wu1e56ce22020-06-29 11:21:51 +0800124 if not opts.dut_name and not opts.pool:
125 raise errors.ArgumentError('--pool',
126 'need to be specified if not --dut_name')
Kuang-che Wu7e8abe62020-07-02 09:42:27 +0800127 if opts.version_hint:
128 for v in opts.version_hint.split(','):
129 if cros_util.is_cros_version(v) or cros_util.is_cros_snapshot_version(v):
130 continue
131 raise errors.ArgumentError(
132 '--version_hint',
133 'should be Chrome OS version numbers, separated by comma')
Kuang-che Wu5157dee2020-07-18 01:13:41 +0800134 if opts.duration is not None and opts.duration < 60:
135 raise errors.ArgumentError('--duration', 'must be at least 60 seconds')
Kuang-che Wu22aa9d42019-01-25 10:35:33 +0800136
Kuang-che Wuc26dcdf2019-11-01 16:30:06 +0800137 t0 = time.time()
Zheng-Jie Chang17f36c82020-06-16 05:21:59 +0800138 dimensions = ['dut_state:ready']
Kuang-che Wu1e56ce22020-06-29 11:21:51 +0800139 if not opts.dut_name:
Zheng-Jie Chang17f36c82020-06-16 05:21:59 +0800140 dimensions.append('label-pool:' + opts.pool)
141
Kuang-che Wu1e56ce22020-06-29 11:21:51 +0800142 variants = []
143 if opts.board:
144 for board in opts.board.split(','):
145 if opts.version_hint:
146 versions = opts.version_hint.split(',')
147 if not all(cros_util.has_test_image(board, v) for v in versions):
148 logger.warning(
149 'board=%s does not have prebuilt test image for %s, ignore',
150 board, opts.version_hint)
151 continue
152 variants.append('label-board:' +
153 cros_lab_util.normalize_board_name(board))
Kuang-che Wu0c9b7942019-10-30 16:55:39 +0800154 if opts.model:
Kuang-che Wu1e56ce22020-06-29 11:21:51 +0800155 for model in opts.model.split(','):
156 variants.append('label-model:' + model)
Kuang-che Wu0c9b7942019-10-30 16:55:39 +0800157 if opts.sku:
Kuang-che Wu1e56ce22020-06-29 11:21:51 +0800158 for sku in opts.sku.split(','):
159 variants.append('label-hwid_sku:' + cros_lab_util.normalize_sku_name(sku))
160 if opts.dut_name:
161 for dut_name in opts.dut_name.split(','):
162 variants.append('dut_name:' + dut_name)
163
164 verified_variants = verify_dimensions_by_lab(variants)
165 if not verified_variants:
166 raise errors.NoDutAvailable('No valid constraints (%s)' % variants)
167 variants = verified_variants
Kuang-che Wu0c9b7942019-10-30 16:55:39 +0800168
Kuang-che Wuc26dcdf2019-11-01 16:30:06 +0800169 while True:
Kuang-che Wu5157dee2020-07-18 01:13:41 +0800170 # Query every time because each iteration takes a few minutes
171 bots = select_available_bots_randomly(
172 dimensions, variants, num=opts.parallel, is_busy=False)
173 if not bots:
174 bots = select_available_bots_randomly(
175 dimensions, variants, num=opts.parallel, is_busy=True)
176 if not bots:
Kuang-che Wu0c9b7942019-10-30 16:55:39 +0800177 raise errors.NoDutAvailable(
Kuang-che Wu1e56ce22020-06-29 11:21:51 +0800178 'no bots satisfy constraints; all are in maintenance state?')
Kuang-che Wu0c9b7942019-10-30 16:55:39 +0800179
Kuang-che Wuc26dcdf2019-11-01 16:30:06 +0800180 remaining_time = opts.time_limit - (time.time() - t0)
181 if remaining_time <= 0:
182 break
Kuang-che Wu5157dee2020-07-18 01:13:41 +0800183 timeout = min(120, remaining_time)
184 host = asyncio.run(lease_dut_parallelly(opts.duration, bots, timeout))
185 if host:
186 return 'ready', host
Kuang-che Wuc26dcdf2019-11-01 16:30:06 +0800187 time.sleep(1)
Kuang-che Wu0c9b7942019-10-30 16:55:39 +0800188
Kuang-che Wuc26dcdf2019-11-01 16:30:06 +0800189 logger.warning('unable to lease DUT in time limit')
Kuang-che Wu0c9b7942019-10-30 16:55:39 +0800190 return 'wait', None
191
192
Kuang-che Wu22aa9d42019-01-25 10:35:33 +0800193def cmd_allocate_dut(opts):
Kuang-che Wuca456462019-11-04 17:32:55 +0800194 leased_dut = None
Kuang-che Wu22aa9d42019-01-25 10:35:33 +0800195 try:
196 todo, host = do_allocate_dut(opts)
Kuang-che Wu5157dee2020-07-18 01:13:41 +0800197 leased_dut = cros_lab_util.dut_name_to_address(host) if host else None
Kuang-che Wu611939f2020-04-14 19:12:50 +0800198 result = {'result': todo, 'leased_dut': leased_dut}
Kuang-che Wu22aa9d42019-01-25 10:35:33 +0800199 print(json.dumps(result))
200 except Exception as e:
201 logger.exception('cmd_allocate_dut failed')
202 exception_name = e.__class__.__name__
203 result = {
204 'result': 'failed',
205 'exception': exception_name,
206 'text': str(e),
207 }
208 print(json.dumps(result))
Kuang-che Wu22aa9d42019-01-25 10:35:33 +0800209
210
Kuang-che Wua8c3c3e2019-08-28 18:49:28 +0800211def cmd_repair_dut(opts):
212 cros_lab_util.repair(opts.dut)
213
214
Kuang-che Wufe1e88a2019-09-10 21:52:25 +0800215@cli.fatal_error_handler
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800216def main():
217 common.init()
218 parser = argparse.ArgumentParser()
Kuang-che Wufe1e88a2019-09-10 21:52:25 +0800219 cli.patching_argparser_exit(parser)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800220 common.add_common_arguments(parser)
221 subparsers = parser.add_subparsers(
222 dest='command', title='commands', metavar='<command>')
223
224 parser_version_info = subparsers.add_parser(
225 'version_info',
226 help='Query version info of given chromeos build',
227 description='Given chromeos `board` and `version`, '
228 'print version information of components.')
229 parser_version_info.add_argument(
230 'board', help='ChromeOS board name, like "samus".')
231 parser_version_info.add_argument(
232 'version',
233 type=cros_util.argtype_cros_version,
234 help='ChromeOS version, like "9876.0.0" or "R62-9876.0.0"')
235 parser_version_info.add_argument(
236 'name',
237 nargs='?',
238 help='Component name. If specified, output its version string. '
239 'Otherwise output all version info as dict in json format.')
240 parser_version_info.set_defaults(func=cmd_version_info)
241
242 parser_query_dut_board = subparsers.add_parser(
243 'query_dut_board', help='Query board name of given DUT')
244 parser_query_dut_board.add_argument('dut')
245 parser_query_dut_board.set_defaults(func=cmd_query_dut_board)
246
247 parser_reboot = subparsers.add_parser(
248 'reboot',
249 help='Reboot a DUT',
250 description='Reboot a DUT and verify the reboot is successful.')
251 parser_reboot.add_argument('dut')
252 parser_reboot.set_defaults(func=cmd_reboot)
253
Kuang-che Wuca456462019-11-04 17:32:55 +0800254 parser_lease_dut = subparsers.add_parser(
255 'lease_dut',
256 help='Lease a DUT in the lab',
257 description='Lease a DUT in the lab. '
258 'This is implemented by `skylab lease-dut` with additional checking.')
259 # "skylab lease-dut" doesn't take reason, so this is not required=True.
260 parser_lease_dut.add_argument('--session', help='session name')
261 parser_lease_dut.add_argument('dut')
262 parser_lease_dut.add_argument(
263 '--duration',
264 type=float,
265 help='duration in seconds; will be round to minutes')
266 parser_lease_dut.set_defaults(func=cmd_lease_dut)
267
268 parser_release_dut = subparsers.add_parser(
269 'release_dut',
270 help='Release a DUT in the lab',
271 description='Release a DUT in the lab. '
272 'This is implemented by `skylab release-dut` with additional checking.')
273 parser_release_dut.add_argument('--session', help='session name')
274 parser_release_dut.add_argument('dut')
275 parser_release_dut.set_defaults(func=cmd_release_dut)
276
Kuang-che Wu22aa9d42019-01-25 10:35:33 +0800277 parser_allocate_dut = subparsers.add_parser(
278 'allocate_dut',
279 help='Allocate a DUT in the lab',
Kuang-che Wuca456462019-11-04 17:32:55 +0800280 description='Allocate a DUT in the lab. It will lease a DUT in the lab '
281 'for bisecting. The caller (bisect-kit runner) of this command should '
282 'retry this command again later if no DUT available now.')
Kuang-che Wu22aa9d42019-01-25 10:35:33 +0800283 parser_allocate_dut.add_argument(
284 '--session', required=True, help='session name')
285 parser_allocate_dut.add_argument(
Kuang-che Wu1e56ce22020-06-29 11:21:51 +0800286 '--pool', help='Pool to search DUT', default=DEFAULT_DUT_POOL)
287 group = parser_allocate_dut.add_mutually_exclusive_group(required=True)
288 group.add_argument('--board', help='allocation criteria; comma separated')
289 group.add_argument('--model', help='allocation criteria; comma separated')
290 group.add_argument('--sku', help='allocation criteria; comma separated')
291 group.add_argument('--dut_name', help='allocation criteria; comma separated')
Kuang-che Wu22aa9d42019-01-25 10:35:33 +0800292 parser_allocate_dut.add_argument(
Kuang-che Wu1e56ce22020-06-29 11:21:51 +0800293 '--version_hint', help='chromeos version; comma separated')
Kuang-che Wuc26dcdf2019-11-01 16:30:06 +0800294 # Pubsub ack deadline is 10 minutes (b/143663659). Default 9 minutes with 1
295 # minute buffer.
Kuang-che Wu22aa9d42019-01-25 10:35:33 +0800296 parser_allocate_dut.add_argument(
Kuang-che Wu0c9b7942019-10-30 16:55:39 +0800297 '--time_limit',
298 type=int,
Kuang-che Wuc26dcdf2019-11-01 16:30:06 +0800299 default=9 * 60,
Kuang-che Wu0c9b7942019-10-30 16:55:39 +0800300 help='Time limit to attempt lease in seconds (default: %(default)s)')
301 parser_allocate_dut.add_argument(
302 '--duration',
303 type=float,
304 help='lease duration in seconds; will be round to minutes')
Kuang-che Wu5157dee2020-07-18 01:13:41 +0800305 parser_allocate_dut.add_argument(
306 '--parallel',
307 type=int,
308 default=1,
309 help='Submit multiple lease tasks to speed up (default: %(default)d)')
Kuang-che Wu22aa9d42019-01-25 10:35:33 +0800310 parser_allocate_dut.set_defaults(func=cmd_allocate_dut)
311
Kuang-che Wua8c3c3e2019-08-28 18:49:28 +0800312 parser_repair_dut = subparsers.add_parser(
313 'repair_dut',
314 help='Repair a DUT in the lab',
315 description='Repair a DUT in the lab. '
316 'This is simply wrapper of "deploy repair" with additional checking.')
317 parser_repair_dut.add_argument('dut')
318 parser_repair_dut.set_defaults(func=cmd_repair_dut)
319
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800320 opts = parser.parse_args()
321 common.config_logging(opts)
Kuang-che Wud3a4e842019-12-11 12:15:23 +0800322
323 # It's optional by default since python3.
324 if not opts.command:
325 parser.error('command is missing')
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800326 opts.func(opts)
327
328
329if __name__ == '__main__':
330 main()