blob: f4d8e73c7b26f555a7b31431aeb0dbcbf12cd6e5 [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
Kuang-che Wu25723422020-09-24 22:20:26 +080024models_to_avoid = {
25 # model: reason
26 'kasumi': 'b/160458394 stateful partition is too small',
27 'mimrock': 'b/160458394 stateful partition is too small',
28 'vorticon': 'b/160458394 stateful partition is too small',
29}
30
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080031
32def cmd_version_info(opts):
33 info = cros_util.version_info(opts.board, opts.version)
34 if opts.name:
35 if opts.name not in info:
36 logger.error('unknown name=%s', opts.name)
37 print(info[opts.name])
38 else:
39 print(json.dumps(info, sort_keys=True, indent=4))
40
41
42def cmd_query_dut_board(opts):
43 assert cros_util.is_dut(opts.dut)
44 print(cros_util.query_dut_board(opts.dut))
45
46
47def cmd_reboot(opts):
48 assert cros_util.is_dut(opts.dut)
Kuang-che Wu2ac9a922020-09-03 16:50:12 +080049 cros_util.reboot(
50 opts.dut, force_reboot_callback=cros_lab_util.reboot_via_servo)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +080051
52
Kuang-che Wuc45cfa42019-01-15 00:15:01 +080053def _get_label_by_prefix(info, prefix):
54 for label in info['Labels']:
55 if label.startswith(prefix + ':'):
56 return label
57 return None
58
59
Kuang-che Wuca456462019-11-04 17:32:55 +080060def cmd_lease_dut(opts):
Kuang-che Wu5157dee2020-07-18 01:13:41 +080061 if opts.duration is not None and opts.duration < 60:
62 raise errors.ArgumentError('--duration', 'must be at least 60 seconds')
Kuang-che Wu22aa9d42019-01-25 10:35:33 +080063 host = cros_lab_util.dut_host_name(opts.dut)
Kuang-che Wu220cc162019-10-31 00:29:37 +080064 logger.info('trying to lease %s', host)
65 if cros_lab_util.skylab_lease_dut(host, opts.duration):
Kuang-che Wuca456462019-11-04 17:32:55 +080066 logger.info('leased %s', host)
Kuang-che Wu22aa9d42019-01-25 10:35:33 +080067 else:
Kuang-che Wuca456462019-11-04 17:32:55 +080068 raise Exception('unable to lease %s' % host)
Kuang-che Wu22aa9d42019-01-25 10:35:33 +080069
70
Kuang-che Wuca456462019-11-04 17:32:55 +080071def cmd_release_dut(opts):
Kuang-che Wu22aa9d42019-01-25 10:35:33 +080072 host = cros_lab_util.dut_host_name(opts.dut)
Kuang-che Wu220cc162019-10-31 00:29:37 +080073 cros_lab_util.skylab_release_dut(host)
Kuang-che Wuca456462019-11-04 17:32:55 +080074 logger.info('%s released', host)
Kuang-che Wu22aa9d42019-01-25 10:35:33 +080075
76
Kuang-che Wu1e56ce22020-06-29 11:21:51 +080077def verify_dimensions_by_lab(dimensions):
78 result = []
79 bots_dimensions = cros_lab_util.swarming_bots_dimensions()
80 for dimension in dimensions:
81 key, value = dimension.split(':', 1)
82 if value in bots_dimensions.get(key, []):
83 result.append(dimension)
84 else:
85 logger.warning('dimension=%s is unknown in the lab, typo? ignored',
86 dimension)
87 return result
88
89
Kuang-che Wu5157dee2020-07-18 01:13:41 +080090def select_available_bots_randomly(dimensions, variants, num=1, is_busy=None):
Kuang-che Wu1e56ce22020-06-29 11:21:51 +080091 bots = []
92 for variant in variants:
93 # There might be thousand bots available, set 'limit' to reduce swarming
94 # API cost. This is not uniform random, but should be good enough.
95 bots += cros_lab_util.swarming_bots_list(
96 dimensions + [variant], is_busy=is_busy, limit=10)
97 if not bots:
98 return None
Kuang-che Wu25723422020-09-24 22:20:26 +080099
100 known_bad = set()
101 good_bots = []
102 for bot in bots:
103 model = bot['dimensions']['label-model'][0]
104 if model in models_to_avoid:
105 if model not in known_bad:
106 logger.warning('model=%s is bad (reason:%s), ignore', model,
107 models_to_avoid[model])
108 known_bad.add(model)
109 continue
110 good_bots.append(bot)
111
112 return random.sample(good_bots, min(num, len(good_bots)))
Kuang-che Wu5157dee2020-07-18 01:13:41 +0800113
114
Kuang-che Wub529d2d2020-09-10 12:26:56 +0800115def filter_dimensions_by_board(boards_with_prebuilt, dimensions):
116 result = []
117 for dimension in dimensions:
118 bots = cros_lab_util.swarming_bots_list([dimension], is_busy=None, limit=1)
119 if not bots:
120 continue
121 board = bots[0]['dimensions']['label-board'][0]
122 if board not in boards_with_prebuilt:
123 logger.warning(
124 'dimension=%s (board=%s) does not have corresponding '
125 'prebuilt image, ignore', dimension, board)
126 continue
127 result.append(dimension)
128 return result
129
130
Kuang-che Wu04619772020-10-22 18:57:07 +0800131def filter_bots_by_board(boards_with_prebuilt, bots):
132 # Sometimes swarming database has inconsistent records. For example,
133 # label-model=kefka + label-board=strago are incorrect (should be
134 # label-board=kefka). It is probably human errors (strago is kefka's
135 # reference board).
136 # This function discards such bots.
137 result = []
138 for bot in bots:
139 board = bot['dimensions']['label-board'][0]
140 if board not in boards_with_prebuilt:
141 logger.warning('%s has unexpected board=%s ignore',
142 bot['dimensions']['dut_name'][0], board)
143 continue
144 result.append(bot)
145 return result
146
147
Kuang-che Wu5157dee2020-07-18 01:13:41 +0800148async def lease_dut_parallelly(duration, bots, timeout=None):
149 tasks = []
150 hosts = []
151 for bot in bots:
152 host = bot['dimensions']['dut_name'][0]
153 hosts.append(host)
154 tasks.append(
155 asyncio.create_task(cros_lab_util.async_lease(host, duration=duration)))
156
157 try:
158 logger.info('trying to lease %d DUTs: %s', len(hosts), hosts)
159 for coro in asyncio.as_completed(tasks, timeout=timeout):
160 host = await coro
161 if host:
162 logger.info('leased %s', host)
Kuang-che Wub529d2d2020-09-10 12:26:56 +0800163 # Unfinished lease tasks will be cancelled when asyncio.run is
164 # finishing.
Kuang-che Wu5157dee2020-07-18 01:13:41 +0800165 return host
166 return None
167 except asyncio.TimeoutError:
168 return None
Kuang-che Wu1e56ce22020-06-29 11:21:51 +0800169
170
Kuang-che Wu22aa9d42019-01-25 10:35:33 +0800171def do_allocate_dut(opts):
172 """Helper of cmd_allocate_dut.
173
174 Returns:
Kuang-che Wub529d2d2020-09-10 12:26:56 +0800175 (todo, host, board_to_build)
Kuang-che Wu22aa9d42019-01-25 10:35:33 +0800176 todo: 'ready' or 'wait'
Kuang-che Wuca456462019-11-04 17:32:55 +0800177 host: leased host name
Kuang-che Wub529d2d2020-09-10 12:26:56 +0800178 board_to_build: board name for building image
Kuang-che Wu22aa9d42019-01-25 10:35:33 +0800179 """
Kuang-che Wu1e56ce22020-06-29 11:21:51 +0800180 if not opts.dut_name and not opts.pool:
181 raise errors.ArgumentError('--pool',
182 'need to be specified if not --dut_name')
Kuang-che Wu7e8abe62020-07-02 09:42:27 +0800183 if opts.version_hint:
184 for v in opts.version_hint.split(','):
185 if cros_util.is_cros_version(v) or cros_util.is_cros_snapshot_version(v):
186 continue
187 raise errors.ArgumentError(
188 '--version_hint',
189 'should be Chrome OS version numbers, separated by comma')
Kuang-che Wu5157dee2020-07-18 01:13:41 +0800190 if opts.duration is not None and opts.duration < 60:
191 raise errors.ArgumentError('--duration', 'must be at least 60 seconds')
Kuang-che Wu22aa9d42019-01-25 10:35:33 +0800192
Kuang-che Wuc26dcdf2019-11-01 16:30:06 +0800193 t0 = time.time()
Zheng-Jie Chang17f36c82020-06-16 05:21:59 +0800194 dimensions = ['dut_state:ready']
Kuang-che Wu1e56ce22020-06-29 11:21:51 +0800195 if not opts.dut_name:
Zheng-Jie Chang17f36c82020-06-16 05:21:59 +0800196 dimensions.append('label-pool:' + opts.pool)
197
Kuang-che Wu1e56ce22020-06-29 11:21:51 +0800198 variants = []
199 if opts.board:
200 for board in opts.board.split(','):
Kuang-che Wu1e56ce22020-06-29 11:21:51 +0800201 variants.append('label-board:' +
202 cros_lab_util.normalize_board_name(board))
Kuang-che Wu0c9b7942019-10-30 16:55:39 +0800203 if opts.model:
Kuang-che Wu1e56ce22020-06-29 11:21:51 +0800204 for model in opts.model.split(','):
Kuang-che Wu25723422020-09-24 22:20:26 +0800205 if model in models_to_avoid:
206 logger.warning('model=%s is bad (reason:%s), ignore', model,
207 models_to_avoid[model])
208 continue
Kuang-che Wu1e56ce22020-06-29 11:21:51 +0800209 variants.append('label-model:' + model)
Kuang-che Wu25723422020-09-24 22:20:26 +0800210 if not variants:
211 raise errors.ArgumentError('--model',
212 'all specified models are not supported')
Kuang-che Wu0c9b7942019-10-30 16:55:39 +0800213 if opts.sku:
Kuang-che Wu1e56ce22020-06-29 11:21:51 +0800214 for sku in opts.sku.split(','):
215 variants.append('label-hwid_sku:' + cros_lab_util.normalize_sku_name(sku))
216 if opts.dut_name:
217 for dut_name in opts.dut_name.split(','):
218 variants.append('dut_name:' + dut_name)
219
Kuang-che Wub529d2d2020-09-10 12:26:56 +0800220 variants = verify_dimensions_by_lab(variants)
221 variants = sorted(set(variants)) # dedup
222 if not variants:
223 raise errors.NoDutAvailable(
224 'Invalid constraints: %s;%s;%s;%s' %
225 (opts.board, opts.model, opts.sku, opts.dut_name))
226
227 # Filter variants by prebuilt images.
228 if opts.version_hint:
229 if not opts.builder_hint:
230 opts.builder_hint = opts.board
231 if not opts.builder_hint:
232 raise errors.ArgumentError('--builder_hint',
233 'must be specified along with --version_hint')
234 boards_with_prebuilt = []
235 versions = opts.version_hint.split(',')
236 for builder in opts.builder_hint.split(','):
237 if not all(cros_util.has_test_image(builder, v) for v in versions):
238 logger.warning(
239 'builder=%s does not have prebuilt test image for %s, ignore',
240 builder, opts.version_hint)
241 continue
242 boards_with_prebuilt.append(cros_lab_util.normalize_board_name(builder))
243 logger.info('boards with prebuilt: %s', boards_with_prebuilt)
244 if not boards_with_prebuilt:
245 raise errors.ArgumentError(
246 '--version_hint',
247 'given builders have no prebuilt for %s' % opts.version_hint)
248 variants = filter_dimensions_by_board(boards_with_prebuilt, variants)
249 if not variants:
250 raise errors.NoDutAvailable(
251 'Devices with specified constraints have no prebuilt. '
252 'Wrong version number?')
Kuang-che Wu0c9b7942019-10-30 16:55:39 +0800253
Kuang-che Wuc26dcdf2019-11-01 16:30:06 +0800254 while True:
Kuang-che Wu5157dee2020-07-18 01:13:41 +0800255 # Query every time because each iteration takes a few minutes
256 bots = select_available_bots_randomly(
257 dimensions, variants, num=opts.parallel, is_busy=False)
258 if not bots:
259 bots = select_available_bots_randomly(
260 dimensions, variants, num=opts.parallel, is_busy=True)
Kuang-che Wu04619772020-10-22 18:57:07 +0800261 bots = filter_bots_by_board(boards_with_prebuilt, bots)
Kuang-che Wu5157dee2020-07-18 01:13:41 +0800262 if not bots:
Kuang-che Wu0c9b7942019-10-30 16:55:39 +0800263 raise errors.NoDutAvailable(
Kuang-che Wu1e56ce22020-06-29 11:21:51 +0800264 'no bots satisfy constraints; all are in maintenance state?')
Kuang-che Wu0c9b7942019-10-30 16:55:39 +0800265
Kuang-che Wuc26dcdf2019-11-01 16:30:06 +0800266 remaining_time = opts.time_limit - (time.time() - t0)
267 if remaining_time <= 0:
268 break
Kuang-che Wu5157dee2020-07-18 01:13:41 +0800269 timeout = min(120, remaining_time)
270 host = asyncio.run(lease_dut_parallelly(opts.duration, bots, timeout))
271 if host:
Kuang-che Wub529d2d2020-09-10 12:26:56 +0800272 # Resolve what board we should build during bisection.
273 board_to_build = None
274 bots = cros_lab_util.swarming_bots_list(['dut_name:' + host])
275 host_board = bots[0]['dimensions']['label-board'][0]
276 if opts.builder_hint:
277 for builder in opts.builder_hint.split(','):
278 if cros_lab_util.normalize_board_name(builder) == host_board:
279 board_to_build = builder
280 break
Kuang-che Wu04619772020-10-22 18:57:07 +0800281 else:
282 raise errors.DutLeaseException('DUT with unexpected board:%s' %
283 host_board)
Kuang-che Wub529d2d2020-09-10 12:26:56 +0800284 else:
285 board_to_build = host_board
286
287 return 'ready', host, board_to_build
Kuang-che Wuc26dcdf2019-11-01 16:30:06 +0800288 time.sleep(1)
Kuang-che Wu0c9b7942019-10-30 16:55:39 +0800289
Kuang-che Wuc26dcdf2019-11-01 16:30:06 +0800290 logger.warning('unable to lease DUT in time limit')
Kuang-che Wub529d2d2020-09-10 12:26:56 +0800291 return 'wait', None, None
Kuang-che Wu0c9b7942019-10-30 16:55:39 +0800292
293
Kuang-che Wu22aa9d42019-01-25 10:35:33 +0800294def cmd_allocate_dut(opts):
Kuang-che Wuca456462019-11-04 17:32:55 +0800295 leased_dut = None
Kuang-che Wu22aa9d42019-01-25 10:35:33 +0800296 try:
Kuang-che Wub529d2d2020-09-10 12:26:56 +0800297 todo, host, board = do_allocate_dut(opts)
Kuang-che Wu5157dee2020-07-18 01:13:41 +0800298 leased_dut = cros_lab_util.dut_name_to_address(host) if host else None
Kuang-che Wub529d2d2020-09-10 12:26:56 +0800299 result = {'result': todo, 'leased_dut': leased_dut, 'board': board}
Kuang-che Wu22aa9d42019-01-25 10:35:33 +0800300 print(json.dumps(result))
301 except Exception as e:
302 logger.exception('cmd_allocate_dut failed')
303 exception_name = e.__class__.__name__
304 result = {
305 'result': 'failed',
306 'exception': exception_name,
307 'text': str(e),
308 }
309 print(json.dumps(result))
Kuang-che Wu22aa9d42019-01-25 10:35:33 +0800310
311
Kuang-che Wua8c3c3e2019-08-28 18:49:28 +0800312def cmd_repair_dut(opts):
313 cros_lab_util.repair(opts.dut)
314
315
Kuang-che Wufe1e88a2019-09-10 21:52:25 +0800316@cli.fatal_error_handler
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800317def main():
318 common.init()
319 parser = argparse.ArgumentParser()
Kuang-che Wufe1e88a2019-09-10 21:52:25 +0800320 cli.patching_argparser_exit(parser)
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800321 common.add_common_arguments(parser)
322 subparsers = parser.add_subparsers(
323 dest='command', title='commands', metavar='<command>')
324
325 parser_version_info = subparsers.add_parser(
326 'version_info',
327 help='Query version info of given chromeos build',
328 description='Given chromeos `board` and `version`, '
329 'print version information of components.')
330 parser_version_info.add_argument(
331 'board', help='ChromeOS board name, like "samus".')
332 parser_version_info.add_argument(
333 'version',
334 type=cros_util.argtype_cros_version,
335 help='ChromeOS version, like "9876.0.0" or "R62-9876.0.0"')
336 parser_version_info.add_argument(
337 'name',
338 nargs='?',
339 help='Component name. If specified, output its version string. '
340 'Otherwise output all version info as dict in json format.')
341 parser_version_info.set_defaults(func=cmd_version_info)
342
343 parser_query_dut_board = subparsers.add_parser(
344 'query_dut_board', help='Query board name of given DUT')
345 parser_query_dut_board.add_argument('dut')
346 parser_query_dut_board.set_defaults(func=cmd_query_dut_board)
347
348 parser_reboot = subparsers.add_parser(
349 'reboot',
350 help='Reboot a DUT',
351 description='Reboot a DUT and verify the reboot is successful.')
352 parser_reboot.add_argument('dut')
353 parser_reboot.set_defaults(func=cmd_reboot)
354
Kuang-che Wuca456462019-11-04 17:32:55 +0800355 parser_lease_dut = subparsers.add_parser(
356 'lease_dut',
357 help='Lease a DUT in the lab',
358 description='Lease a DUT in the lab. '
359 'This is implemented by `skylab lease-dut` with additional checking.')
360 # "skylab lease-dut" doesn't take reason, so this is not required=True.
361 parser_lease_dut.add_argument('--session', help='session name')
362 parser_lease_dut.add_argument('dut')
363 parser_lease_dut.add_argument(
364 '--duration',
365 type=float,
366 help='duration in seconds; will be round to minutes')
367 parser_lease_dut.set_defaults(func=cmd_lease_dut)
368
369 parser_release_dut = subparsers.add_parser(
370 'release_dut',
371 help='Release a DUT in the lab',
372 description='Release a DUT in the lab. '
373 'This is implemented by `skylab release-dut` with additional checking.')
374 parser_release_dut.add_argument('--session', help='session name')
375 parser_release_dut.add_argument('dut')
376 parser_release_dut.set_defaults(func=cmd_release_dut)
377
Kuang-che Wu22aa9d42019-01-25 10:35:33 +0800378 parser_allocate_dut = subparsers.add_parser(
379 'allocate_dut',
380 help='Allocate a DUT in the lab',
Kuang-che Wuca456462019-11-04 17:32:55 +0800381 description='Allocate a DUT in the lab. It will lease a DUT in the lab '
382 'for bisecting. The caller (bisect-kit runner) of this command should '
383 'retry this command again later if no DUT available now.')
Kuang-che Wu22aa9d42019-01-25 10:35:33 +0800384 parser_allocate_dut.add_argument(
385 '--session', required=True, help='session name')
386 parser_allocate_dut.add_argument(
Kuang-che Wub529d2d2020-09-10 12:26:56 +0800387 '--pool',
388 help='Pool to search DUT (default: %(default)s)',
389 default=DEFAULT_DUT_POOL)
Kuang-che Wu1e56ce22020-06-29 11:21:51 +0800390 group = parser_allocate_dut.add_mutually_exclusive_group(required=True)
391 group.add_argument('--board', help='allocation criteria; comma separated')
392 group.add_argument('--model', help='allocation criteria; comma separated')
393 group.add_argument('--sku', help='allocation criteria; comma separated')
394 group.add_argument('--dut_name', help='allocation criteria; comma separated')
Kuang-che Wu22aa9d42019-01-25 10:35:33 +0800395 parser_allocate_dut.add_argument(
Kuang-che Wu1e56ce22020-06-29 11:21:51 +0800396 '--version_hint', help='chromeos version; comma separated')
Kuang-che Wub529d2d2020-09-10 12:26:56 +0800397 parser_allocate_dut.add_argument(
398 '--builder_hint', help='chromeos builder; comma separated')
Kuang-che Wuc26dcdf2019-11-01 16:30:06 +0800399 # Pubsub ack deadline is 10 minutes (b/143663659). Default 9 minutes with 1
400 # minute buffer.
Kuang-che Wu22aa9d42019-01-25 10:35:33 +0800401 parser_allocate_dut.add_argument(
Kuang-che Wu0c9b7942019-10-30 16:55:39 +0800402 '--time_limit',
403 type=int,
Kuang-che Wuc26dcdf2019-11-01 16:30:06 +0800404 default=9 * 60,
Kuang-che Wu0c9b7942019-10-30 16:55:39 +0800405 help='Time limit to attempt lease in seconds (default: %(default)s)')
406 parser_allocate_dut.add_argument(
407 '--duration',
408 type=float,
409 help='lease duration in seconds; will be round to minutes')
Kuang-che Wu5157dee2020-07-18 01:13:41 +0800410 parser_allocate_dut.add_argument(
411 '--parallel',
412 type=int,
413 default=1,
414 help='Submit multiple lease tasks to speed up (default: %(default)d)')
Kuang-che Wu22aa9d42019-01-25 10:35:33 +0800415 parser_allocate_dut.set_defaults(func=cmd_allocate_dut)
416
Kuang-che Wua8c3c3e2019-08-28 18:49:28 +0800417 parser_repair_dut = subparsers.add_parser(
418 'repair_dut',
419 help='Repair a DUT in the lab',
420 description='Repair a DUT in the lab. '
421 'This is simply wrapper of "deploy repair" with additional checking.')
422 parser_repair_dut.add_argument('dut')
423 parser_repair_dut.set_defaults(func=cmd_repair_dut)
424
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800425 opts = parser.parse_args()
426 common.config_logging(opts)
Kuang-che Wud3a4e842019-12-11 12:15:23 +0800427
428 # It's optional by default since python3.
429 if not opts.command:
430 parser.error('command is missing')
Kuang-che Wu2ea804f2017-11-28 17:11:41 +0800431 opts.func(opts)
432
433
434if __name__ == '__main__':
435 main()