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 | |
Mike Frysinger | 383367e | 2014-09-16 15:06:17 -0400 | [diff] [blame] | 16 | from __future__ import print_function |
| 17 | |
David Pursell | f1c27c1 | 2015-03-18 09:51:38 -0700 | [diff] [blame] | 18 | import glob |
| 19 | import os |
| 20 | |
Ralph Nathan | 74e864d | 2015-05-11 12:13:53 -0700 | [diff] [blame] | 21 | from chromite.cbuildbot import constants |
Bertrand SIMONNET | 2b1ed05 | 2015-03-02 11:17:40 -0800 | [diff] [blame] | 22 | from chromite.lib import brick_lib |
David Pursell | f80b8c5 | 2015-04-03 12:46:45 -0700 | [diff] [blame] | 23 | from chromite.lib import commandline |
| 24 | from chromite.lib import cros_build_lib |
David Pursell | f1c27c1 | 2015-03-18 09:51:38 -0700 | [diff] [blame] | 25 | from chromite.lib import cros_import |
Ralph Nathan | 6993125 | 2015-04-14 16:49:21 -0700 | [diff] [blame] | 26 | from chromite.lib import cros_logging as logging |
Ralph Nathan | 74e864d | 2015-05-11 12:13:53 -0700 | [diff] [blame] | 27 | from chromite.lib import osutils |
| 28 | from chromite.lib import workspace_lib |
David Pursell | f1c27c1 | 2015-03-18 09:51:38 -0700 | [diff] [blame] | 29 | |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 30 | |
David Pursell | c7ba784 | 2015-07-08 10:48:41 -0700 | [diff] [blame^] | 31 | # Paths for finding and importing subcommand modules. |
| 32 | _SUBCOMMAND_MODULE_DIRECTORY = os.path.join(os.path.dirname(__file__), 'cros') |
| 33 | _SUBCOMMAND_MODULE_PREFIX = 'cros_' |
| 34 | |
| 35 | |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 36 | _commands = dict() |
| 37 | |
| 38 | |
Ralph Nathan | 74e864d | 2015-05-11 12:13:53 -0700 | [diff] [blame] | 39 | def SetupFileLogger(filename='brillo.log', log_level=logging.DEBUG): |
| 40 | """Store log messages to a file. |
| 41 | |
| 42 | In case of an error, this file can be made visible to the user. |
| 43 | """ |
| 44 | workspace_path = workspace_lib.WorkspacePath() |
| 45 | if workspace_path is None: |
| 46 | return |
Ralph Nathan | 7a0bae2 | 2015-05-13 10:49:54 -0700 | [diff] [blame] | 47 | path = os.path.join(workspace_path, workspace_lib.WORKSPACE_LOGS_DIR, |
| 48 | filename) |
Ralph Nathan | 74e864d | 2015-05-11 12:13:53 -0700 | [diff] [blame] | 49 | osutils.Touch(path, makedirs=True) |
| 50 | logger = logging.getLogger() |
| 51 | fh = logging.FileHandler(path, mode='w') |
| 52 | fh.setLevel(log_level) |
| 53 | fh.setFormatter( |
| 54 | logging.Formatter(fmt=constants.LOGGER_FMT, |
| 55 | datefmt=constants.LOGGER_DATE_FMT)) |
| 56 | logger.addHandler(fh) |
| 57 | |
| 58 | |
Ralph Nathan | 6993125 | 2015-04-14 16:49:21 -0700 | [diff] [blame] | 59 | def UseProgressBar(): |
| 60 | """Determine whether the progress bar is to be used or not. |
| 61 | |
| 62 | We only want the progress bar to display for the brillo commands which operate |
| 63 | at logging level NOTICE. If the user wants to see the noisy output, then they |
| 64 | can execute the command at logging level INFO or DEBUG. |
| 65 | """ |
| 66 | return logging.getLogger().getEffectiveLevel() == logging.NOTICE |
| 67 | |
| 68 | |
David Pursell | c7ba784 | 2015-07-08 10:48:41 -0700 | [diff] [blame^] | 69 | def _FindModules(subdir_path): |
| 70 | """Returns a list of subcommand python modules in |subdir_path|. |
David Pursell | ffb9004 | 2015-03-23 09:21:41 -0700 | [diff] [blame] | 71 | |
| 72 | Args: |
| 73 | subdir_path: directory (string) to search for modules in. |
David Pursell | ffb9004 | 2015-03-23 09:21:41 -0700 | [diff] [blame] | 74 | |
| 75 | Returns: |
| 76 | List of filenames (strings). |
| 77 | """ |
David Pursell | f1c27c1 | 2015-03-18 09:51:38 -0700 | [diff] [blame] | 78 | modules = [] |
David Pursell | c7ba784 | 2015-07-08 10:48:41 -0700 | [diff] [blame^] | 79 | glob_path = os.path.join(subdir_path, '%s*.py' % _SUBCOMMAND_MODULE_PREFIX) |
| 80 | for file_path in glob.glob(glob_path): |
David Pursell | f1c27c1 | 2015-03-18 09:51:38 -0700 | [diff] [blame] | 81 | if not file_path.endswith('_unittest.py'): |
| 82 | modules.append(file_path) |
David Pursell | f1c27c1 | 2015-03-18 09:51:38 -0700 | [diff] [blame] | 83 | return modules |
| 84 | |
| 85 | |
David Pursell | c7ba784 | 2015-07-08 10:48:41 -0700 | [diff] [blame^] | 86 | def _ImportCommands(): |
| 87 | """Directly imports all subcommand python modules. |
David Pursell | f1c27c1 | 2015-03-18 09:51:38 -0700 | [diff] [blame] | 88 | |
David Pursell | c7ba784 | 2015-07-08 10:48:41 -0700 | [diff] [blame^] | 89 | This method imports the modules which may contain subcommands. When |
| 90 | these modules are loaded, declared commands (those that use |
David Pursell | ffb9004 | 2015-03-23 09:21:41 -0700 | [diff] [blame] | 91 | CommandDecorator) will automatically get added to |_commands|. |
David Pursell | f1c27c1 | 2015-03-18 09:51:38 -0700 | [diff] [blame] | 92 | """ |
David Pursell | c7ba784 | 2015-07-08 10:48:41 -0700 | [diff] [blame^] | 93 | for file_path in _FindModules(_SUBCOMMAND_MODULE_DIRECTORY): |
| 94 | module_path = os.path.splitext(file_path)[0] |
| 95 | import_path = os.path.relpath(os.path.realpath(module_path), |
| 96 | os.path.dirname(constants.CHROMITE_DIR)) |
| 97 | cros_import.ImportModule(import_path.split(os.path.sep)) |
David Pursell | f1c27c1 | 2015-03-18 09:51:38 -0700 | [diff] [blame] | 98 | |
| 99 | |
David Pursell | c7ba784 | 2015-07-08 10:48:41 -0700 | [diff] [blame^] | 100 | def ListCommands(): |
David Pursell | ffb9004 | 2015-03-23 09:21:41 -0700 | [diff] [blame] | 101 | """Return a dictionary mapping command names to classes. |
| 102 | |
David Pursell | ffb9004 | 2015-03-23 09:21:41 -0700 | [diff] [blame] | 103 | Returns: |
| 104 | A dictionary mapping names (strings) to commands (classes). |
| 105 | """ |
David Pursell | c7ba784 | 2015-07-08 10:48:41 -0700 | [diff] [blame^] | 106 | _ImportCommands() |
David Pursell | f1c27c1 | 2015-03-18 09:51:38 -0700 | [diff] [blame] | 107 | return _commands.copy() |
| 108 | |
| 109 | |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 110 | class InvalidCommandError(Exception): |
| 111 | """Error that occurs when command class fails sanity checks.""" |
| 112 | pass |
| 113 | |
| 114 | |
| 115 | def CommandDecorator(command_name): |
| 116 | """Decorator that sanity checks and adds class to list of usable commands.""" |
| 117 | |
| 118 | def InnerCommandDecorator(original_class): |
| 119 | """"Inner Decorator that actually wraps the class.""" |
| 120 | if not hasattr(original_class, '__doc__'): |
| 121 | raise InvalidCommandError('All handlers must have docstrings: %s' % |
| 122 | original_class) |
| 123 | |
David Pursell | ffb9004 | 2015-03-23 09:21:41 -0700 | [diff] [blame] | 124 | if not issubclass(original_class, CliCommand): |
| 125 | raise InvalidCommandError('All Commands must derive from CliCommand: %s' % |
| 126 | original_class) |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 127 | |
| 128 | _commands[command_name] = original_class |
Ryan Cui | 47f80e4 | 2013-04-01 19:01:54 -0700 | [diff] [blame] | 129 | original_class.command_name = command_name |
| 130 | |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 131 | return original_class |
| 132 | |
| 133 | return InnerCommandDecorator |
| 134 | |
| 135 | |
David Pursell | ffb9004 | 2015-03-23 09:21:41 -0700 | [diff] [blame] | 136 | class CliCommand(object): |
| 137 | """All CLI commands must derive from this class. |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 138 | |
David Pursell | ffb9004 | 2015-03-23 09:21:41 -0700 | [diff] [blame] | 139 | This class provides the abstract interface for all CLI commands. When |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 140 | designing a new command, you must sub-class from this class and use the |
| 141 | CommandDecorator decorator. You must specify a class docstring as that will be |
| 142 | used as the usage for the sub-command. |
| 143 | |
| 144 | In addition your command should implement AddParser which is passed in a |
| 145 | parser that you can add your own custom arguments. See argparse for more |
| 146 | information. |
| 147 | """ |
Ryan Cui | 47f80e4 | 2013-04-01 19:01:54 -0700 | [diff] [blame] | 148 | # Indicates whether command stats should be uploaded for this command. |
| 149 | # Override to enable command stats uploading. |
| 150 | upload_stats = False |
| 151 | # We set the default timeout to 1 second, to prevent overly long waits for |
| 152 | # commands to complete. From manual tests, stat uploads usually take |
| 153 | # between 0.35s-0.45s in MTV. |
| 154 | upload_stats_timeout = 1 |
| 155 | |
Ryo Hashimoto | 8bc997b | 2014-01-22 18:46:17 +0900 | [diff] [blame] | 156 | # Indicates whether command uses cache related commandline options. |
| 157 | use_caching_options = False |
| 158 | |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 159 | def __init__(self, options): |
| 160 | self.options = options |
Bertrand SIMONNET | 2b1ed05 | 2015-03-02 11:17:40 -0800 | [diff] [blame] | 161 | brick = brick_lib.FindBrickInPath() |
Bertrand SIMONNET | 79e077d | 2015-03-12 18:31:12 -0700 | [diff] [blame] | 162 | self.curr_brick_locator = brick.brick_locator if brick else None |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 163 | |
| 164 | @classmethod |
| 165 | def AddParser(cls, parser): |
| 166 | """Add arguments for this command to the parser.""" |
David Pursell | ffb9004 | 2015-03-23 09:21:41 -0700 | [diff] [blame] | 167 | parser.set_defaults(command_class=cls) |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 168 | |
David Pursell | f80b8c5 | 2015-04-03 12:46:45 -0700 | [diff] [blame] | 169 | @classmethod |
David Pursell | c7ba784 | 2015-07-08 10:48:41 -0700 | [diff] [blame^] | 170 | def AddDeviceArgument(cls, parser, schemes=commandline.DEVICE_SCHEME_SSH): |
David Pursell | f80b8c5 | 2015-04-03 12:46:45 -0700 | [diff] [blame] | 171 | """Add a device argument to the parser. |
| 172 | |
David Pursell | c7ba784 | 2015-07-08 10:48:41 -0700 | [diff] [blame^] | 173 | This standardizes the help message across all subcommands. |
David Pursell | f80b8c5 | 2015-04-03 12:46:45 -0700 | [diff] [blame] | 174 | |
| 175 | Args: |
| 176 | parser: The parser to add the device argument to. |
| 177 | schemes: List of device schemes or single scheme to allow. |
David Pursell | f80b8c5 | 2015-04-03 12:46:45 -0700 | [diff] [blame] | 178 | """ |
David Pursell | f80b8c5 | 2015-04-03 12:46:45 -0700 | [diff] [blame] | 179 | help_strings = [] |
| 180 | schemes = list(cros_build_lib.iflatten_instance(schemes)) |
| 181 | if commandline.DEVICE_SCHEME_SSH in schemes: |
| 182 | help_strings.append('Target a device with [user@]hostname[:port].') |
| 183 | if commandline.DEVICE_SCHEME_USB in schemes: |
| 184 | help_strings.append('Target removable media with usb://[path].') |
| 185 | if commandline.DEVICE_SCHEME_FILE in schemes: |
| 186 | help_strings.append('Target a local file with file://path.') |
David Pursell | c7ba784 | 2015-07-08 10:48:41 -0700 | [diff] [blame^] | 187 | parser.add_argument('device', |
David Pursell | f80b8c5 | 2015-04-03 12:46:45 -0700 | [diff] [blame] | 188 | type=commandline.DeviceParser(schemes), |
| 189 | help=' '.join(help_strings)) |
| 190 | |
Brian Harring | 984988f | 2012-10-10 22:53:30 -0700 | [diff] [blame] | 191 | def Run(self): |
| 192 | """The command to run.""" |
| 193 | raise NotImplementedError() |