Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 1 | # Copyright (c) 2012 The Chromium OS Authors. All rights reserved. |
| 2 | # Use of this source code is governed by a BSD-style license that can be |
| 3 | # found in the LICENSE file. |
| 4 | |
David Pursell | ffb9004 | 2015-03-23 09:21:41 -0700 | [diff] [blame] | 5 | """Module that contains meta-logic related to CLI commands. |
| 6 | |
David Pursell | f1c27c1 | 2015-03-18 09:51:38 -0700 | [diff] [blame] | 7 | This module contains two important definitions used by all commands: |
David Pursell | ffb9004 | 2015-03-23 09:21:41 -0700 | [diff] [blame] | 8 | CliCommand: The parent class of all CLI commands. |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 9 | CommandDecorator: Decorator that must be used to ensure that the command shows |
David Pursell | ffb9004 | 2015-03-23 09:21:41 -0700 | [diff] [blame] | 10 | up in |_commands| and is discoverable. |
David Pursell | f1c27c1 | 2015-03-18 09:51:38 -0700 | [diff] [blame] | 11 | |
| 12 | Commands can be either imported directly or looked up using this module's |
| 13 | ListCommands() function. |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 14 | """ |
| 15 | |
Alex Klein | 665aa07 | 2019-12-12 15:13:53 -0700 | [diff] [blame] | 16 | import importlib |
Chris McDonald | 14ac61d | 2021-07-21 11:49:56 -0600 | [diff] [blame] | 17 | import logging |
David Pursell | f1c27c1 | 2015-03-18 09:51:38 -0700 | [diff] [blame] | 18 | import os |
Alex Klein | 3a88327 | 2021-03-19 16:02:43 -0600 | [diff] [blame] | 19 | import sys |
David Pursell | f1c27c1 | 2015-03-18 09:51:38 -0700 | [diff] [blame] | 20 | |
David Pursell | f80b8c5 | 2015-04-03 12:46:45 -0700 | [diff] [blame] | 21 | from chromite.lib import commandline |
Chris McDonald | 14ac61d | 2021-07-21 11:49:56 -0600 | [diff] [blame] | 22 | from chromite.lib import constants |
David Pursell | f80b8c5 | 2015-04-03 12:46:45 -0700 | [diff] [blame] | 23 | from chromite.lib import cros_build_lib |
David Pursell | f1c27c1 | 2015-03-18 09:51:38 -0700 | [diff] [blame] | 24 | |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 25 | |
David Pursell | c7ba784 | 2015-07-08 10:48:41 -0700 | [diff] [blame] | 26 | # Paths for finding and importing subcommand modules. |
| 27 | _SUBCOMMAND_MODULE_DIRECTORY = os.path.join(os.path.dirname(__file__), 'cros') |
| 28 | _SUBCOMMAND_MODULE_PREFIX = 'cros_' |
| 29 | |
| 30 | |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 31 | _commands = dict() |
| 32 | |
| 33 | |
Ralph Nathan | 6993125 | 2015-04-14 16:49:21 -0700 | [diff] [blame] | 34 | def UseProgressBar(): |
| 35 | """Determine whether the progress bar is to be used or not. |
| 36 | |
| 37 | We only want the progress bar to display for the brillo commands which operate |
| 38 | at logging level NOTICE. If the user wants to see the noisy output, then they |
| 39 | can execute the command at logging level INFO or DEBUG. |
| 40 | """ |
| 41 | return logging.getLogger().getEffectiveLevel() == logging.NOTICE |
| 42 | |
| 43 | |
Mike Frysinger | 1a47081 | 2019-11-07 01:19:17 -0500 | [diff] [blame] | 44 | def ImportCommand(name): |
| 45 | """Directly import the specified subcommand. |
| 46 | |
| 47 | This method imports the module which must contain the single subcommand. When |
| 48 | the module is loaded, the declared command (those that use CommandDecorator) |
| 49 | will automatically get added to |_commands|. |
David Pursell | ffb9004 | 2015-03-23 09:21:41 -0700 | [diff] [blame] | 50 | |
| 51 | Args: |
Mike Frysinger | 1a47081 | 2019-11-07 01:19:17 -0500 | [diff] [blame] | 52 | name: The subcommand to load. |
David Pursell | ffb9004 | 2015-03-23 09:21:41 -0700 | [diff] [blame] | 53 | |
| 54 | Returns: |
Mike Frysinger | 1a47081 | 2019-11-07 01:19:17 -0500 | [diff] [blame] | 55 | A reference to the subcommand class. |
David Pursell | ffb9004 | 2015-03-23 09:21:41 -0700 | [diff] [blame] | 56 | """ |
Mike Frysinger | 1a47081 | 2019-11-07 01:19:17 -0500 | [diff] [blame] | 57 | module_path = os.path.join(_SUBCOMMAND_MODULE_DIRECTORY, |
| 58 | 'cros_%s' % (name.replace('-', '_'),)) |
| 59 | import_path = os.path.relpath(os.path.realpath(module_path), |
| 60 | os.path.dirname(constants.CHROMITE_DIR)) |
Alex Klein | 665aa07 | 2019-12-12 15:13:53 -0700 | [diff] [blame] | 61 | module_parts = import_path.split(os.path.sep) |
| 62 | importlib.import_module('.'.join(module_parts)) |
Mike Frysinger | 1a47081 | 2019-11-07 01:19:17 -0500 | [diff] [blame] | 63 | return _commands[name] |
David Pursell | f1c27c1 | 2015-03-18 09:51:38 -0700 | [diff] [blame] | 64 | |
| 65 | |
David Pursell | c7ba784 | 2015-07-08 10:48:41 -0700 | [diff] [blame] | 66 | def ListCommands(): |
Mike Frysinger | 1a47081 | 2019-11-07 01:19:17 -0500 | [diff] [blame] | 67 | """Return the set of available subcommands. |
David Pursell | ffb9004 | 2015-03-23 09:21:41 -0700 | [diff] [blame] | 68 | |
Mike Frysinger | 1a47081 | 2019-11-07 01:19:17 -0500 | [diff] [blame] | 69 | We assume that there is a direct one-to-one relationship between the module |
| 70 | name on disk and the command that module implements. We assume this as a |
| 71 | performance requirement (to avoid importing every subcommand every time even |
| 72 | though we'd only ever run a single one), and to avoid 3rd party module usage |
| 73 | in one subcommand breaking all other subcommands (not a great solution). |
David Pursell | ffb9004 | 2015-03-23 09:21:41 -0700 | [diff] [blame] | 74 | """ |
Mike Frysinger | 1a47081 | 2019-11-07 01:19:17 -0500 | [diff] [blame] | 75 | # Filenames use underscores due to python naming limitations, but subcommands |
| 76 | # use dashes as they're easier for humans to type. |
| 77 | # Strip off the leading "cros_" and the trailing ".py". |
| 78 | return set(x[5:-3].replace('_', '-') |
| 79 | for x in os.listdir(_SUBCOMMAND_MODULE_DIRECTORY) |
| 80 | if (x.startswith(_SUBCOMMAND_MODULE_PREFIX) and x.endswith('.py') |
| 81 | and not x.endswith('_unittest.py'))) |
David Pursell | f1c27c1 | 2015-03-18 09:51:38 -0700 | [diff] [blame] | 82 | |
| 83 | |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 84 | class InvalidCommandError(Exception): |
| 85 | """Error that occurs when command class fails sanity checks.""" |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 86 | |
| 87 | |
| 88 | def CommandDecorator(command_name): |
| 89 | """Decorator that sanity checks and adds class to list of usable commands.""" |
| 90 | |
| 91 | def InnerCommandDecorator(original_class): |
Mike Frysinger | 07475fa | 2019-08-01 14:44:55 -0400 | [diff] [blame] | 92 | """Inner Decorator that actually wraps the class.""" |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 93 | if not hasattr(original_class, '__doc__'): |
| 94 | raise InvalidCommandError('All handlers must have docstrings: %s' % |
| 95 | original_class) |
| 96 | |
David Pursell | ffb9004 | 2015-03-23 09:21:41 -0700 | [diff] [blame] | 97 | if not issubclass(original_class, CliCommand): |
| 98 | raise InvalidCommandError('All Commands must derive from CliCommand: %s' % |
| 99 | original_class) |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 100 | |
| 101 | _commands[command_name] = original_class |
Ryan Cui | 47f80e4 | 2013-04-01 19:01:54 -0700 | [diff] [blame] | 102 | original_class.command_name = command_name |
| 103 | |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 104 | return original_class |
| 105 | |
| 106 | return InnerCommandDecorator |
| 107 | |
| 108 | |
David Pursell | ffb9004 | 2015-03-23 09:21:41 -0700 | [diff] [blame] | 109 | class CliCommand(object): |
| 110 | """All CLI commands must derive from this class. |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 111 | |
David Pursell | ffb9004 | 2015-03-23 09:21:41 -0700 | [diff] [blame] | 112 | This class provides the abstract interface for all CLI commands. When |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 113 | designing a new command, you must sub-class from this class and use the |
| 114 | CommandDecorator decorator. You must specify a class docstring as that will be |
| 115 | used as the usage for the sub-command. |
| 116 | |
| 117 | In addition your command should implement AddParser which is passed in a |
| 118 | parser that you can add your own custom arguments. See argparse for more |
| 119 | information. |
| 120 | """ |
Ryo Hashimoto | 8bc997b | 2014-01-22 18:46:17 +0900 | [diff] [blame] | 121 | # Indicates whether command uses cache related commandline options. |
| 122 | use_caching_options = False |
| 123 | |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 124 | def __init__(self, options): |
| 125 | self.options = options |
| 126 | |
| 127 | @classmethod |
| 128 | def AddParser(cls, parser): |
| 129 | """Add arguments for this command to the parser.""" |
David Pursell | ffb9004 | 2015-03-23 09:21:41 -0700 | [diff] [blame] | 130 | parser.set_defaults(command_class=cls) |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 131 | |
David Pursell | f80b8c5 | 2015-04-03 12:46:45 -0700 | [diff] [blame] | 132 | @classmethod |
Alex Klein | df03034 | 2020-02-14 10:07:38 -0700 | [diff] [blame] | 133 | def AddDeviceArgument(cls, parser, schemes=commandline.DEVICE_SCHEME_SSH, |
| 134 | positional=False): |
David Pursell | f80b8c5 | 2015-04-03 12:46:45 -0700 | [diff] [blame] | 135 | """Add a device argument to the parser. |
| 136 | |
David Pursell | c7ba784 | 2015-07-08 10:48:41 -0700 | [diff] [blame] | 137 | This standardizes the help message across all subcommands. |
David Pursell | f80b8c5 | 2015-04-03 12:46:45 -0700 | [diff] [blame] | 138 | |
| 139 | Args: |
| 140 | parser: The parser to add the device argument to. |
| 141 | schemes: List of device schemes or single scheme to allow. |
Alex Klein | df03034 | 2020-02-14 10:07:38 -0700 | [diff] [blame] | 142 | positional: Whether it should be a positional or named argument. |
David Pursell | f80b8c5 | 2015-04-03 12:46:45 -0700 | [diff] [blame] | 143 | """ |
David Pursell | f80b8c5 | 2015-04-03 12:46:45 -0700 | [diff] [blame] | 144 | help_strings = [] |
| 145 | schemes = list(cros_build_lib.iflatten_instance(schemes)) |
| 146 | if commandline.DEVICE_SCHEME_SSH in schemes: |
Mike Frysinger | 7163c3a | 2018-02-08 16:45:10 -0500 | [diff] [blame] | 147 | help_strings.append('Target a device with [user@]hostname[:port]. ' |
| 148 | 'IPv4/IPv6 addresses are allowed, but IPv6 must ' |
| 149 | 'use brackets (e.g. [::1]).') |
David Pursell | f80b8c5 | 2015-04-03 12:46:45 -0700 | [diff] [blame] | 150 | if commandline.DEVICE_SCHEME_USB in schemes: |
| 151 | help_strings.append('Target removable media with usb://[path].') |
Alex Klein | e83d86c | 2019-12-11 15:17:31 -0700 | [diff] [blame] | 152 | if commandline.DEVICE_SCHEME_SERVO in schemes: |
| 153 | help_strings.append('Target a servo by port or serial number with ' |
| 154 | 'servo:port[:port] or servo:serial:serial-number. ' |
| 155 | 'e.g. servo:port:1234 or servo:serial:C1230024192.') |
David Pursell | f80b8c5 | 2015-04-03 12:46:45 -0700 | [diff] [blame] | 156 | if commandline.DEVICE_SCHEME_FILE in schemes: |
| 157 | help_strings.append('Target a local file with file://path.') |
Alex Klein | df03034 | 2020-02-14 10:07:38 -0700 | [diff] [blame] | 158 | if positional: |
| 159 | parser.add_argument('device', |
| 160 | type=commandline.DeviceParser(schemes), |
| 161 | help=' '.join(help_strings)) |
| 162 | else: |
| 163 | parser.add_argument('-d', '--device', |
| 164 | type=commandline.DeviceParser(schemes), |
| 165 | help=' '.join(help_strings)) |
David Pursell | f80b8c5 | 2015-04-03 12:46:45 -0700 | [diff] [blame] | 166 | |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 167 | def Run(self): |
| 168 | """The command to run.""" |
| 169 | raise NotImplementedError() |
Alex Klein | 3a88327 | 2021-03-19 16:02:43 -0600 | [diff] [blame] | 170 | |
| 171 | def TranslateToChrootArgv(self): |
| 172 | """Hook to get the argv for reexecution inside the chroot. |
| 173 | |
| 174 | By default, return the same args used to execute it in the first place. |
| 175 | Hook allows commands to translate specific arguments, i.e. change paths to |
| 176 | chroot paths. |
| 177 | """ |
| 178 | return sys.argv[:] |