blob: 2dff3a33156751d7484ec94519d7a2cb8c1dd695 [file] [log] [blame]
Keun Soo Yimb293fdb2016-09-21 16:03:44 -07001#!/usr/bin/env python
2#
3# Copyright 2016 - The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
Sam Chiu42ac7c52018-10-22 12:27:34 +080016r"""
17Welcome to
18 ___ _______ ____ __ _____
19 / _ |/ ___/ / / __ \/ / / / _ \
20 / __ / /__/ /__/ /_/ / /_/ / // /
21/_/ |_\___/____/\____/\____/____/
Keun Soo Yimb293fdb2016-09-21 16:03:44 -070022
Sam Chiu42ac7c52018-10-22 12:27:34 +080023
24This a tool to create Android Virtual Devices locally/remotely.
Keun Soo Yimb293fdb2016-09-21 16:03:44 -070025
26- Prerequisites:
Sam Chiu42ac7c52018-10-22 12:27:34 +080027 The manual will be available at
28 https://android.googlesource.com/platform/tools/acloud/+/master/README.md
Keun Soo Yimb293fdb2016-09-21 16:03:44 -070029
Sam Chiu42ac7c52018-10-22 12:27:34 +080030- To get started:
31 - Create instances:
32 1) To create a remote cuttlefish instance with the local built image.
33 Example:
chojoyce1c4ecc92018-12-06 14:16:44 +080034 $ acloud create --local-image
35 Or specify built image dir:
36 $ acloud create --local-image /tmp/image_dir
Sam Chiu42ac7c52018-10-22 12:27:34 +080037 2) To create a local cuttlefish instance using the image which has been
38 built out in your workspace.
39 Example:
40 $ acloud create --local-instance --local-image
Keun Soo Yimb293fdb2016-09-21 16:03:44 -070041
Sam Chiu42ac7c52018-10-22 12:27:34 +080042 - Delete instances:
43 $ acloud delete
Keun Soo Yimb293fdb2016-09-21 16:03:44 -070044
Sam Chiu42ac7c52018-10-22 12:27:34 +080045Try $acloud [cmd] --help for further details.
Keun Soo Yimb293fdb2016-09-21 16:03:44 -070046
Keun Soo Yimb293fdb2016-09-21 16:03:44 -070047"""
Kevin Cheng1ea015f2019-01-08 09:10:58 -080048
49from __future__ import print_function
Keun Soo Yimb293fdb2016-09-21 16:03:44 -070050import argparse
Keun Soo Yimb293fdb2016-09-21 16:03:44 -070051import logging
Kevin Cheng1ea015f2019-01-08 09:10:58 -080052import platform
Keun Soo Yimb293fdb2016-09-21 16:03:44 -070053import sys
54
Kevin Cheng1ea015f2019-01-08 09:10:58 -080055# TODO: Remove this once we switch over to embedded launcher.
56# Exit out if python version is < 2.7.13 due to b/120883119.
57if (sys.version_info.major == 2
58 and sys.version_info.minor == 7
59 and sys.version_info.micro < 13):
60 print("Acloud requires python version 2.7.13+ (currently @ %d.%d.%d)" %
61 (sys.version_info.major, sys.version_info.minor,
62 sys.version_info.micro))
63 print("Update your 2.7 python with:")
64 # pylint: disable=invalid-name
65 os_type = platform.system().lower()
66 if os_type == "linux":
67 print(" apt-get install python2.7")
68 elif os_type == "darwin":
69 print(" brew install python@2 (and then follow instructions at "
70 "https://docs.python-guide.org/starting/install/osx/)")
71 print(" - or -")
72 print(" POSIXLY_CORRECT=1 port -N install python27")
73 sys.exit(1)
74
Kevin Chengf4137c62018-05-22 16:06:58 -070075# Needed to silence oauth2client.
Sam Chiu29d858f2018-08-14 20:06:25 +080076# This is a workaround to get rid of below warning message:
77# 'No handlers could be found for logger "oauth2client.contrib.multistore_file'
78# TODO(b/112803893): Remove this code once bug is fixed.
79OAUTH2_LOGGER = logging.getLogger('oauth2client.contrib.multistore_file')
80OAUTH2_LOGGER.setLevel(logging.CRITICAL)
81OAUTH2_LOGGER.addHandler(logging.FileHandler("/dev/null"))
Kevin Chengb5963882018-05-09 00:06:27 -070082
Kevin Chengf4137c62018-05-22 16:06:58 -070083# pylint: disable=wrong-import-position
Sam Chiu7de3b232018-12-06 19:45:52 +080084from acloud import errors
Kevin Cheng6001db32018-10-23 12:34:20 -070085from acloud.create import create
86from acloud.create import create_args
87from acloud.delete import delete
88from acloud.delete import delete_args
cylan4569dca2018-11-02 12:12:53 +080089from acloud.reconnect import reconnect
90from acloud.reconnect import reconnect_args
Sam Chiu56c58892018-10-25 09:53:19 +080091from acloud.list import list as list_instances
92from acloud.list import list_args
Kevin Cheng6001db32018-10-23 12:34:20 -070093from acloud.metrics import metrics
Keun Soo Yimb293fdb2016-09-21 16:03:44 -070094from acloud.public import acloud_common
95from acloud.public import config
96from acloud.public import device_driver
Kevin Chengb5963882018-05-09 00:06:27 -070097from acloud.public.actions import create_cuttlefish_action
98from acloud.public.actions import create_goldfish_action
Kevin Chengee6030f2018-06-26 10:55:30 -070099from acloud.setup import setup
100from acloud.setup import setup_args
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700101
Sam Chiu445941f2018-10-04 11:54:40 +0800102LOGGING_FMT = "%(asctime)s |%(levelname)s| %(module)s:%(lineno)s| %(message)s"
Sam Chiu29d858f2018-08-14 20:06:25 +0800103ACLOUD_LOGGER = "acloud"
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700104
105# Commands
Kevin Chengb5963882018-05-09 00:06:27 -0700106CMD_CREATE_CUTTLEFISH = "create_cf"
107CMD_CREATE_GOLDFISH = "create_gf"
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700108CMD_CLEANUP = "cleanup"
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700109
110
Kevin Cheng3031f8a2018-05-16 13:21:51 -0700111# pylint: disable=too-many-statements
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700112def _ParseArgs(args):
113 """Parse args.
114
115 Args:
116 args: Argument list passed from main.
117
118 Returns:
119 Parsed args.
120 """
Kevin Cheng3031f8a2018-05-16 13:21:51 -0700121 usage = ",".join([
Sam Chiue669ef72018-10-16 16:23:37 +0800122 setup_args.CMD_SETUP,
123 create_args.CMD_CREATE,
Sam Chiu56c58892018-10-25 09:53:19 +0800124 list_args.CMD_LIST,
Kevin Chengeb85e862018-10-09 15:35:13 -0700125 delete_args.CMD_DELETE,
cylan4569dca2018-11-02 12:12:53 +0800126 reconnect_args.CMD_RECONNECT,
Kevin Cheng3031f8a2018-05-16 13:21:51 -0700127 ])
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700128 parser = argparse.ArgumentParser(
129 description=__doc__,
130 formatter_class=argparse.RawDescriptionHelpFormatter,
Sam Chiu42ac7c52018-10-22 12:27:34 +0800131 usage="acloud {" + usage + "} ...")
Kevin Cheng6bd8d132019-02-25 23:00:38 -0800132 subparsers = parser.add_subparsers(metavar="{" + usage + "}")
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700133 subparser_list = []
134
Kevin Chengb5963882018-05-09 00:06:27 -0700135 # Command "create_cf", create cuttlefish instances
136 create_cf_parser = subparsers.add_parser(CMD_CREATE_CUTTLEFISH)
137 create_cf_parser.required = False
138 create_cf_parser.set_defaults(which=CMD_CREATE_CUTTLEFISH)
139 create_cf_parser.add_argument(
Kevin Chengb5963882018-05-09 00:06:27 -0700140 "--branch",
141 type=str,
142 dest="branch",
143 help="Android branch, e.g. git_master")
144 create_cf_parser.add_argument(
Kevin Chengb5963882018-05-09 00:06:27 -0700145 "--kernel_build_id",
Kevin Chengcf5bbf52019-05-09 16:17:08 -0700146 "--kernel-build-id",
Kevin Chengb5963882018-05-09 00:06:27 -0700147 type=str,
148 dest="kernel_build_id",
149 required=False,
150 help="Android kernel build id, e.g. 4586590. This is to test a new"
Kevin Chengcf5bbf52019-05-09 16:17:08 -0700151 " kernel build with a particular Android build (--build_id). If neither"
152 " kernel_branch nor kernel_build_id are specified, the kernel that's"
153 " bundled with the Android build would be used.")
154 create_cf_parser.add_argument(
155 "--kernel_branch",
156 "--kernel-branch",
157 type=str,
158 dest="kernel_branch",
159 required=False,
160 help="Android kernel build branch name, e.g."
161 " kernel-common-android-4.14. This is to test a new kernel build with a"
162 " particular Android build (--build-id). If specified without"
163 " specifying kernel_build_id, the last green build in the branch will"
164 " be used. If neither kernel_branch nor kernel_build_id are specified,"
165 " the kernel that's bundled with the Android build would be used.")
Kevin Chengb5963882018-05-09 00:06:27 -0700166
Kevin Cheng3087af52018-08-13 13:26:50 -0700167 create_args.AddCommonCreateArgs(create_cf_parser)
Kevin Chengb5963882018-05-09 00:06:27 -0700168 subparser_list.append(create_cf_parser)
169
170 # Command "create_gf", create goldfish instances
171 # In order to create a goldfish device we need the following parameters:
172 # 1. The emulator build we wish to use, this is the binary that emulates
173 # an android device. See go/emu-dev for more
174 # 2. A system-image. This is the android release we wish to run on the
175 # emulated hardware.
176 create_gf_parser = subparsers.add_parser(CMD_CREATE_GOLDFISH)
177 create_gf_parser.required = False
178 create_gf_parser.set_defaults(which=CMD_CREATE_GOLDFISH)
179 create_gf_parser.add_argument(
Kevin Chengb5963882018-05-09 00:06:27 -0700180 "--branch",
181 type=str,
182 dest="branch",
183 help="Android branch, e.g. git_master")
184 create_gf_parser.add_argument(
Kevin Chengb5963882018-05-09 00:06:27 -0700185 "--emulator_build_id",
186 type=str,
187 dest="emulator_build_id",
188 required=False,
189 help="Emulator build used to run the images. e.g. 4669466.")
190 create_gf_parser.add_argument(
191 "--gpu",
192 type=str,
193 dest="gpu",
194 required=False,
195 default=None,
196 help="GPU accelerator to use if any."
197 " e.g. nvidia-tesla-k80, omit to use swiftshader")
198 create_gf_parser.add_argument(
Kevin Chengbced4af2018-06-26 10:35:01 -0700199 "--base_image",
200 type=str,
201 dest="base_image",
202 required=False,
203 help="Name of the goldfish base image to be used to create the instance. "
204 "This will override stable_goldfish_host_image_name from config. "
205 "e.g. emu-dev-cts-061118")
Kevin Chengb5963882018-05-09 00:06:27 -0700206
Kevin Cheng3087af52018-08-13 13:26:50 -0700207 create_args.AddCommonCreateArgs(create_gf_parser)
Kevin Chengb5963882018-05-09 00:06:27 -0700208 subparser_list.append(create_gf_parser)
209
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700210 # Command "cleanup"
211 cleanup_parser = subparsers.add_parser(CMD_CLEANUP)
212 cleanup_parser.required = False
213 cleanup_parser.set_defaults(which=CMD_CLEANUP)
214 cleanup_parser.add_argument(
215 "--expiration_mins",
216 type=int,
217 dest="expiration_mins",
218 required=True,
219 help="Garbage collect all gce instances, gce images, cached disk "
220 "images that are older than |expiration_mins|.")
221 subparser_list.append(cleanup_parser)
222
Kevin Chengeb85e862018-10-09 15:35:13 -0700223 # Command "create"
224 subparser_list.append(create_args.GetCreateArgParser(subparsers))
225
Kevin Chengee6030f2018-06-26 10:55:30 -0700226 # Command "setup"
227 subparser_list.append(setup_args.GetSetupArgParser(subparsers))
228
Sam Chiu56c58892018-10-25 09:53:19 +0800229 # Command "delete"
Kevin Chengeb85e862018-10-09 15:35:13 -0700230 subparser_list.append(delete_args.GetDeleteArgParser(subparsers))
231
Sam Chiu56c58892018-10-25 09:53:19 +0800232 # Command "list"
233 subparser_list.append(list_args.GetListArgParser(subparsers))
234
cylan4569dca2018-11-02 12:12:53 +0800235 # Command "Reconnect"
236 subparser_list.append(reconnect_args.GetReconnectArgParser(subparsers))
237
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700238 # Add common arguments.
Kevin Chengb21d7712018-05-24 14:54:55 -0700239 for subparser in subparser_list:
240 acloud_common.AddCommonArguments(subparser)
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700241
242 return parser.parse_args(args)
243
244
herbertxue2625b042018-08-16 23:28:20 +0800245# pylint: disable=too-many-branches
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700246def _VerifyArgs(parsed_args):
247 """Verify args.
248
249 Args:
250 parsed_args: Parsed args.
251
252 Raises:
253 errors.CommandArgError: If args are invalid.
254 """
herbertxue2625b042018-08-16 23:28:20 +0800255 if parsed_args.which == create_args.CMD_CREATE:
256 create_args.VerifyArgs(parsed_args)
Kevin Cheng84d3eed2018-08-16 15:16:00 -0700257 if parsed_args.which == CMD_CREATE_CUTTLEFISH:
Kevin Chengb5963882018-05-09 00:06:27 -0700258 if not parsed_args.build_id or not parsed_args.build_target:
Kevin Cheng3031f8a2018-05-16 13:21:51 -0700259 raise errors.CommandArgError(
260 "Must specify --build_id and --build_target")
Kevin Chengb5963882018-05-09 00:06:27 -0700261 if parsed_args.which == CMD_CREATE_GOLDFISH:
Kevin Cheng84d3eed2018-08-16 15:16:00 -0700262 if not parsed_args.emulator_build_id and not parsed_args.build_id:
263 raise errors.CommandArgError("Must specify either "
264 "--emulator_build_id or --build_id")
265 if not parsed_args.build_target:
266 raise errors.CommandArgError("Must specify --build_target")
Kevin Chengb5963882018-05-09 00:06:27 -0700267
268 if parsed_args.which in [
Kevin Cheng3087af52018-08-13 13:26:50 -0700269 create_args.CMD_CREATE, CMD_CREATE_CUTTLEFISH, CMD_CREATE_GOLDFISH
Kevin Chengb5963882018-05-09 00:06:27 -0700270 ]:
Kevin Cheng3031f8a2018-05-16 13:21:51 -0700271 if (parsed_args.serial_log_file
272 and not parsed_args.serial_log_file.endswith(".tar.gz")):
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700273 raise errors.CommandArgError(
274 "--serial_log_file must ends with .tar.gz")
Kevin Cheng3031f8a2018-05-16 13:21:51 -0700275 if (parsed_args.logcat_file
276 and not parsed_args.logcat_file.endswith(".tar.gz")):
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700277 raise errors.CommandArgError(
278 "--logcat_file must ends with .tar.gz")
279
280
Sam Chiu29d858f2018-08-14 20:06:25 +0800281def _SetupLogging(log_file, verbose):
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700282 """Setup logging.
283
Sam Chiu29d858f2018-08-14 20:06:25 +0800284 This function define the logging policy in below manners.
285 - without -v , -vv ,--log_file:
286 Only display critical log and print() message on screen.
287
288 - with -v:
289 Display INFO log and set StreamHandler to acloud parent logger to turn on
290 ONLY acloud modules logging.(silence all 3p libraries)
291
292 - with -vv:
293 Display INFO/DEBUG log and set StreamHandler to root logger to turn on all
294 acloud modules and 3p libraries logging.
295
296 - with --log_file.
297 Dump logs to FileHandler with DEBUG level.
298
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700299 Args:
Sam Chiu29d858f2018-08-14 20:06:25 +0800300 log_file: String, if not None, dump the log to log file.
301 verbose: Int, if verbose = 1(-v), log at INFO level and turn on
302 logging on libraries to a StreamHandler.
303 If verbose = 2(-vv), log at DEBUG level and turn on logging on
304 all libraries and 3rd party libraries to a StreamHandler.
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700305 """
Sam Chiu29d858f2018-08-14 20:06:25 +0800306 # Define logging level and hierarchy by verbosity.
307 shandler_level = None
308 logger = None
309 if verbose == 0:
310 shandler_level = logging.CRITICAL
311 logger = logging.getLogger(ACLOUD_LOGGER)
312 elif verbose == 1:
313 shandler_level = logging.INFO
314 logger = logging.getLogger(ACLOUD_LOGGER)
315 elif verbose > 1:
316 shandler_level = logging.DEBUG
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700317 logger = logging.getLogger()
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700318
Sam Chiu29d858f2018-08-14 20:06:25 +0800319 # Add StreamHandler by default.
320 shandler = logging.StreamHandler()
321 shandler.setFormatter(logging.Formatter(LOGGING_FMT))
322 shandler.setLevel(shandler_level)
323 logger.addHandler(shandler)
324 # Set the default level to DEBUG, the other handlers will handle
325 # their own levels via the args supplied (-v and --log_file).
326 logger.setLevel(logging.DEBUG)
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700327
Sam Chiu29d858f2018-08-14 20:06:25 +0800328 # Add FileHandler if log_file is provided.
Sam Chiufde41e92018-08-07 18:37:02 +0800329 if log_file:
Sam Chiu29d858f2018-08-14 20:06:25 +0800330 fhandler = logging.FileHandler(filename=log_file)
331 fhandler.setFormatter(logging.Formatter(LOGGING_FMT))
332 fhandler.setLevel(logging.DEBUG)
333 logger.addHandler(fhandler)
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700334
335
Erwin Jansen95559242018-11-08 15:38:18 -0800336def main(argv=None):
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700337 """Main entry.
338
339 Args:
340 argv: A list of system arguments.
341
342 Returns:
343 0 if success. None-zero if fails.
344 """
Erwin Jansen95559242018-11-08 15:38:18 -0800345 if argv is None:
346 argv = sys.argv[1:]
347
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700348 args = _ParseArgs(argv)
Sam Chiu29d858f2018-08-14 20:06:25 +0800349 _SetupLogging(args.log_file, args.verbose)
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700350 _VerifyArgs(args)
351
Sam Chiuc64f3432018-08-17 11:19:06 +0800352 cfg = config.GetAcloudConfig(args)
Kevin Cheng3087af52018-08-13 13:26:50 -0700353 # TODO: Move this check into the functions it is actually needed.
Fang Dengcef4b112017-03-02 11:20:17 -0800354 # Check access.
Kevin Cheng3087af52018-08-13 13:26:50 -0700355 # device_driver.CheckAccess(cfg)
Fang Dengcef4b112017-03-02 11:20:17 -0800356
Kevin Cheng6001db32018-10-23 12:34:20 -0700357 metrics.LogUsage()
Kevin Chengee6030f2018-06-26 10:55:30 -0700358 report = None
chojoyce7a361732018-11-26 16:26:13 +0800359 if args.which == create_args.CMD_CREATE:
Kevin Chengc3d0d5e2018-08-14 14:22:44 -0700360 create.Run(args)
Kevin Chengb5963882018-05-09 00:06:27 -0700361 elif args.which == CMD_CREATE_CUTTLEFISH:
362 report = create_cuttlefish_action.CreateDevices(
363 cfg=cfg,
364 build_target=args.build_target,
365 build_id=args.build_id,
366 kernel_build_id=args.kernel_build_id,
Kevin Chengcf5bbf52019-05-09 16:17:08 -0700367 kernel_branch=args.kernel_branch,
Kevin Chengb5963882018-05-09 00:06:27 -0700368 num=args.num,
369 serial_log_file=args.serial_log_file,
370 logcat_file=args.logcat_file,
Kevin Cheng86d43c72018-08-30 10:59:14 -0700371 autoconnect=args.autoconnect,
372 report_internal_ip=args.report_internal_ip)
Kevin Chengb5963882018-05-09 00:06:27 -0700373 elif args.which == CMD_CREATE_GOLDFISH:
374 report = create_goldfish_action.CreateDevices(
375 cfg=cfg,
376 build_target=args.build_target,
377 build_id=args.build_id,
378 emulator_build_id=args.emulator_build_id,
379 gpu=args.gpu,
380 num=args.num,
381 serial_log_file=args.serial_log_file,
382 logcat_file=args.logcat_file,
Kevin Cheng84d3eed2018-08-16 15:16:00 -0700383 autoconnect=args.autoconnect,
Kevin Cheng86d43c72018-08-30 10:59:14 -0700384 branch=args.branch,
385 report_internal_ip=args.report_internal_ip)
Sam Chiu56c58892018-10-25 09:53:19 +0800386 elif args.which == delete_args.CMD_DELETE:
Kevin Chengeb85e862018-10-09 15:35:13 -0700387 report = delete.Run(args)
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700388 elif args.which == CMD_CLEANUP:
389 report = device_driver.Cleanup(cfg, args.expiration_mins)
Sam Chiu56c58892018-10-25 09:53:19 +0800390 elif args.which == list_args.CMD_LIST:
391 list_instances.Run(args)
cylan4569dca2018-11-02 12:12:53 +0800392 elif args.which == reconnect_args.CMD_RECONNECT:
393 reconnect.Run(args)
Kevin Chengee6030f2018-06-26 10:55:30 -0700394 elif args.which == setup_args.CMD_SETUP:
herbertxue34776bb2018-07-03 21:57:48 +0800395 setup.Run(args)
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700396 else:
397 sys.stderr.write("Invalid command %s" % args.which)
398 return 2
399
herbertxue07293a32018-11-05 20:40:11 +0800400 if report and args.report_file:
Kevin Chengee6030f2018-06-26 10:55:30 -0700401 report.Dump(args.report_file)
402 if report.errors:
403 msg = "\n".join(report.errors)
404 sys.stderr.write("Encountered the following errors:\n%s\n" % msg)
405 return 1
Keun Soo Yimb293fdb2016-09-21 16:03:44 -0700406 return 0
Tri Vo8e292532016-10-01 16:55:51 -0700407
408
409if __name__ == "__main__":
410 main(sys.argv[1:])