File: command_line.py

package info (click to toggle)
chromium 139.0.7258.138-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,120,676 kB
  • sloc: cpp: 35,100,869; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (242 lines) | stat: -rw-r--r-- 9,733 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# Copyright 2019 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Implements the interface of the results_processor module.

Provides functions to parse command line arguments and process options.
"""

import argparse
import datetime
import logging
import os
import sys

from py_utils import cloud_storage

from core.results_processor import formatters
from core.results_processor import util


def ArgumentParser(standalone=False):
  """Create an ArgumentParser defining options required by the processor."""
  all_output_formats = list(formatters.FORMATTERS.keys())
  if not standalone:
    all_output_formats.append('none')
  parser, group = _CreateTopLevelParser(standalone)
  parser.add_argument(
      '-v', '--verbose', action='count', dest='verbosity', default=0,
      help='Increase verbosity level (repeat as needed)')
  parser.add_argument('-q',
                      '--quiet',
                      action='count',
                      default=0,
                      help='Decrease verbosity level (repeat as needed)')
  group.add_argument(
      '--output-format',
      action='append',
      dest='output_formats',
      metavar='FORMAT',
      choices=all_output_formats,
      required=standalone,
      help=Sentences('Output format to produce.',
                     'May be used multiple times to produce multiple outputs.',
                     'Avaliable formats: %(choices)s.',
                     '' if standalone else 'Defaults to: html.'))
  group.add_argument(
      '--intermediate-dir',
      metavar='DIR_PATH',
      required=standalone,
      help=Sentences(
          'Path to a directory where intermediate results are stored.',
          '' if standalone else 'If not provided, the default is to create a '
          'new directory within "{output_dir}/artifacts/".'))
  group.add_argument(
      '--output-dir', default=_DefaultOutputDir(), metavar='DIR_PATH',
      help=Sentences(
          'Path to a directory where to write final results.',
          'Default: %(default)s.'))
  group.add_argument(
      '--max-values-per-test-case', type=int, metavar='NUM',
      help=Sentences(
          'Fail a test run if it produces more than this number of values.'
          'This includes both ad hoc and metric generated measurements.'))
  group.add_argument(
      '--reset-results', action='store_true',
      help=Sentences(
          'Overwrite any previous output files in the output directory.',
          'The default is to append to existing results.'))
  group.add_argument(
      '--results-label', metavar='LABEL',
      help='Label to identify the results generated by this run.')
  group.add_argument(
      '--test-path-format', metavar='FORMAT',
      choices=[util.TELEMETRY_TEST_PATH_FORMAT, util.GTEST_TEST_PATH_FORMAT],
      default=util.TELEMETRY_TEST_PATH_FORMAT,
      help=Sentences(
          'How to interpret the testPath attribute.',
          'Available options: %(choices)s. Default: %(default)s.'))
  group.add_argument(
      '--trace-processor-path',
      help=Sentences('Path to trace processor shell.',
                     'Default: download a pre-built version from the cloud.'))
  group.add_argument(
      '--upload-results', action='store_true',
      help='Upload generated artifacts to cloud storage.')
  group.add_argument(
      '--upload-bucket', default='output', metavar='BUCKET',
      help=Sentences(
          'Storage bucket to use for uploading artifacts.',
          'Supported values are: %s; or a valid cloud storage bucket name.'
          % ', '.join(sorted(cloud_storage.BUCKET_ALIASES)),
          'Defaults to: %(default)s.'))
  group.add_argument(
      '--experimental-tbmv3-metrics', action='store_true',
      help='Enable running experimental TBMv3 metrics.')
  group.add_argument(
      '--fetch-power-profile',
      action='store_true',
      help=('Specify this if you want to run proxy power metrics that use '
            'device power profiles.'))
  group.add_argument(
      '--extra-metric', action='append', dest='extra_metrics', metavar='METRIC',
      help=('Compute an extra metric on the test results. Metric should have '
            'the form "version:name", e.g. "tbmv3:power_rails_metric". '
            'Can be used multiple times.'))
  group.add_argument(
      '--is-unittest',
      action='store_true',
      help='Is running inside a unittest.')

  # Separate group for fetching device data
  device_group = parser.add_argument_group(title='Device fetching options')
  device_group.add_argument(
      '--fetch-device-data',
      action='store_true',
      help=('Argument to enable fetching data from a device.'))
  device_group.add_argument(
      '--fetch-device-data-on-success',
      action='store_true',
      help=('When --fetch-device-data is enabled, this switch ensures that '
            'data is only pulled after a successful run (exited with 0)'))
  device_group.add_argument(
      '--fetch-device-data-platform',
      dest='fetch_data_platform',
      choices=['android', 'chromeos'],
      help='Platform associated with device type to pull data from. Only '
      'supports --fetch-device-data.')
  device_group.add_argument(
      '--fetch-data-path-device',
      dest='device_data_path',
      help=('Use this to specify the path on device to pull data from. Should '
            'be used with --fetch-device-data.'))
  device_group.add_argument(
      '--fetch-data-path-local',
      dest='local_data_path',
      default=os.environ.get('ISOLATED_OUTDIR', os.getcwd()),
      help=('Use this to override the local copy path. Defaults to '
            'ISOLATED_OUTDIR environment variable or cwd if ISOLATED_OUTDIR is '
            'not set. To be used in conjuction with --fetch-device-data.'))
  return parser


def ProcessOptions(options):
  """Adjust result processing options as needed before running benchmarks.

  Note: The intended scope of this function is limited to only adjust options
  defined by the ArgumentParser above. One should not attempt to read or modify
  any other attributes that the options object may have.

  Currently the main job of this function is to tease out and separate output
  formats to be handled by the results processor, from those that should fall
  back to the legacy output formatters in Telemetry.

  Args:
    options: An options object with values parsed from the command line.
  """
  log_verbosity = options.verbosity - options.quiet
  if log_verbosity >= 2:
    logging.getLogger().setLevel(logging.DEBUG)
  elif log_verbosity == 1:
    logging.getLogger().setLevel(logging.INFO)
  elif log_verbosity <= -2:
    logging.getLogger().setLevel(logging.CRITICAL)
  elif log_verbosity == -1:
    logging.getLogger().setLevel(logging.ERROR)
  else:
    logging.getLogger().setLevel(logging.WARNING)

  # The output_dir option is None or missing if the selected Telemetry command
  # does not involve output generation, e.g. "run_benchmark list", and the
  # argument parser defined above was not invoked.
  if getattr(options, 'output_dir', None) is None:
    return

  def resolve_dir(path):
    return os.path.realpath(os.path.expanduser(path))

  options.output_dir = resolve_dir(options.output_dir)

  if options.intermediate_dir:
    options.intermediate_dir = resolve_dir(options.intermediate_dir)
  else:
    start_time = datetime.datetime.utcnow().strftime('%Y%m%dT%H%M%SZ')
    options.intermediate_dir = os.path.join(options.output_dir, 'artifacts',
                                            'run_%s' % start_time)

  if options.upload_results:
    options.upload_bucket = cloud_storage.BUCKET_ALIASES.get(
        options.upload_bucket, options.upload_bucket)
  else:
    options.upload_bucket = None

  if not options.output_formats:
    options.output_formats = ['html']
  else:
    options.output_formats = sorted(set(options.output_formats))
  if 'none' in options.output_formats:
    options.output_formats.remove('none')

  if options.fetch_device_data:
    if not options.fetch_data_platform:
      raise argparse.ArgumentError(options.fetch_data_platform,
                                   ('--fetch-device-data-platform must be set '
                                    'with --fetch-device-data'))
    if not options.device_data_path:
      raise argparse.ArgumentError(options.device_data_path,
                                   ('--fetch-data-path-device must be set '
                                    'with --fetch-device-data'))
  if options.fetch_device_data_on_success:
    if not options.fetch_device_data:
      raise argparse.ArgumentError(options.fetch_device_data_on_success,
                                   ('--fetch-device-data must be set '
                                    'with --fetch-device-data-on-success'))


def _CreateTopLevelParser(standalone):
  """Create top level parser, and group for result options."""
  if standalone:
    parser = argparse.ArgumentParser(
        description='Standalone command line interface to results_processor.')
    # In standalone mode, both the parser and group are the same thing.
    return parser, parser
  parser = argparse.ArgumentParser(add_help=False)
  group = parser.add_argument_group(title='Result processor options')
  return parser, group


def _DefaultOutputDir():
  """Default output directory.

  Points to the directory of the benchmark runner script, if found, or the
  current working directory otherwise.
  """
  main_module = sys.modules['__main__']
  if hasattr(main_module, '__file__'):
    return os.path.realpath(os.path.dirname(main_module.__file__))
  return os.getcwd()


def Sentences(*args):
  return ' '.join(s for s in args if s)