| # Copyright 2018 The Chromium Authors. All rights reserved. | |
| # Use of this source code is governed by a BSD-style license that can be | |
| # found in the LICENSE file. | |
| from recipe_engine import recipe_api | |
| from recipe_modules.swarming.api import TaskResult | |
| from collections import OrderedDict | |
| from functools import total_ordering | |
| import datetime, json, re | |
| from .common import (ARCHITECTURES, CPUS, DEFAULT_CPU, MODES, RUNTIMES, | |
| SANITIZERS, SYSTEMS) | |
| from .retry_shards import RetriedShards | |
| PATH_FILTERS = [ | |
| r'(out|xcodebuild)[/\\](Release|Debug|Product)\w*[/\\]' + | |
| r'(clang_\w*[/\\])?(generated_compilations|generated_tests|obj)[/\\]', | |
| r'tools[/\\]sdks', | |
| r'xcodebuild[/\\](Release|Debug|Product)\w*[/\\]sdk[/\\]xcode_links', | |
| ] | |
| def path_filter(checkout): | |
| # The 'isolate' script with the RBE-CAS backend applies the path filter to | |
| # absolute paths, so we compute the complete paths using the regular | |
| # expressions in PATH_FILTERS. | |
| root = checkout.replace('\\', r'[/\\]') | |
| return '|'.join( | |
| r'(^%s[/\\]%s)' % (root, path_expr) for path_expr in PATH_FILTERS) | |
| BQUPLOAD_PACKAGE = 'infra/tools/bqupload/${platform}' | |
| ISOLATE_PACKAGE = 'infra/tools/luci/isolate/${platform}' | |
| ISOLATE_VERSION = 'git_revision:c048e241c7f91df54d608528842315e16429a3b9' | |
| CAS_INSTANCE = 'chromium-swarm' | |
| TEST_PY_PATH = 'tools/test.py' | |
| BUILD_PY_PATH = 'tools/build.py' | |
| GN_PY_PATH = 'tools/gn.py' | |
| _chrome_prefix = '--chrome=third_party/browsers/chrome/' | |
| CHROME_PATH_ARGUMENT = { | |
| 'linux': _chrome_prefix + 'chrome/google-chrome', | |
| 'mac': _chrome_prefix + 'Google Chrome.app/Contents/MacOS/Google Chrome', | |
| 'win': _chrome_prefix + 'Chrome/Application/chrome.exe' | |
| } | |
| _firefox_prefix = '--firefox=third_party/browsers/firefox/' | |
| FIREFOX_PATH_ARGUMENT = { | |
| 'linux': _firefox_prefix + 'firefox/firefox', | |
| 'mac': _firefox_prefix + 'Firefox.app/Contents/MacOS/firefox', | |
| 'win': _firefox_prefix + 'firefox/firefox.exe' | |
| } | |
| CO19_PACKAGE = 'dart/third_party/co19' | |
| CHROME_PACKAGE = 'dart/browsers/chrome/${platform}' | |
| FIREFOX_PACKAGE = 'dart/browsers/firefox/${platform}' | |
| SDK_PACKAGE = 'dart/dart-sdk/${platform}' | |
| CIPD_SERVER_URL = 'https://chrome-infra-packages.appspot.com' | |
| SEMANTIC_VERSION_PATTERN = r'^(?P<major>0|[1-9]\d*)\.(?P<minor>0|[1-9]\d*)\.(?P<patch>0|[1-9]\d*)(?:-(?P<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?P<buildmetadata>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$' | |
| SDK_PATTERN = r'''^\s+sdk:\s+[\"\']?(>=|\^)?(?P<sdk>[0-9]+\.[0-9]+\.[0-9]+[\w.\-\+]*)''' | |
| def _to_lines(list): | |
| """Convert a list to a string containing one item on each line, terminated | |
| by a newline, or the empty string for an empty list.""" | |
| return '\n'.join(list + ['']) | |
| class DartApi(recipe_api.RecipeApi): | |
| """Recipe module for code commonly used in dart recipes. | |
| Shouldn't be used elsewhere.""" | |
| def __init__(self, *args, **kwargs): | |
| super(DartApi, self).__init__(*args, **kwargs) | |
| self._bqupload_client = None | |
| self._isolate_client = None | |
| self.results = Results() | |
| self._checkout_dir = None | |
| @property | |
| def _gclient_working_dir(self): | |
| """Directory where gclient commands should be run. | |
| Using this directory ensures that gclient uses up the correct .gclient file. | |
| """ | |
| return self.m.path.cache_dir / 'builder' | |
| def _clobber(self): | |
| out = 'xcodebuild' if self.m.platform.name == 'mac' else 'out' | |
| out_path = self._checkout_dir / out | |
| if self.m.path.exists(out_path): | |
| os = self.m.platform.name | |
| cmd = (['cmd.exe', '/C', 'rmdir', '/Q', '/S'] | |
| if os == 'win' else ['rm', '-rf']) | |
| self.m.step('clobber', cmd + [out_path]) | |
| def checkout(self, clobber=False, custom_vars={}): | |
| """Checks out the dart code and prepares it for building.""" | |
| self.m.gclient.set_config('dart') | |
| self.m.gclient.c.solutions[0].custom_vars = custom_vars | |
| with self.m.context(cwd=self._gclient_working_dir): | |
| self._checkout_dir = self.m.bot_update.ensure_checkout( | |
| timeout=25 * 60).source_root.path | |
| with self.m.context(cwd=self._checkout_dir): | |
| if clobber: | |
| self._clobber() | |
| self.m.gclient.runhooks() | |
| return self._checkout_dir | |
| def get_secret(self, | |
| name, | |
| bucket='dart-ci-credentials', | |
| keyring='projects/dart-ci/locations/' | |
| 'us-central1/keyRings/dart-ci/cryptoKeys/dart-ci', | |
| object_path=None, | |
| encrypted_path=None, | |
| decrypted_path=None, | |
| extension='.key'): | |
| """Decrypts the specified secret and returns the location of the result""" | |
| cloudkms_dir = self.m.path.start_dir / 'cloudkms' | |
| cloudkms_package = 'infra/tools/luci/cloudkms/${platform}' | |
| self.m.cipd.ensure( | |
| cloudkms_dir, | |
| self.m.cipd.EnsureFile().add_package(cloudkms_package, 'latest')) | |
| with self.m.context(cwd=self.m.path.cleanup_dir): | |
| if encrypted_path == None: | |
| encrypted_path = '%s.encrypted' % name | |
| if object_path == None: | |
| object_path = encrypted_path | |
| if decrypted_path == None: | |
| decrypted_path = self.m.path.cleanup_dir / f'{name}{extension}' | |
| self.m.gsutil.download(bucket, object_path, encrypted_path) | |
| cloudkms = self._executable(cloudkms_dir, 'cloudkms') | |
| self.m.step(f'cloudkms get key {name}', [ | |
| cloudkms, 'decrypt', '-input', encrypted_path, '-output', | |
| decrypted_path, keyring | |
| ]) | |
| return decrypted_path | |
| def kill_tasks(self, ok_ret='any'): | |
| """Kills leftover tasks from previous runs or steps.""" | |
| self.m.step( | |
| 'kill processes', [ | |
| 'python3', '-u', self._checkout_dir / 'tools/task_kill.py', | |
| '--kill_browsers=True', '--kill_vsbuild=True' | |
| ], | |
| ok_ret=ok_ret) | |
| def _executable(self, path, cmd): | |
| """Returns the path to the checked-in SDK dart executable.""" | |
| return path / ('%s.exe' % cmd if self.m.platform.name == 'win' else cmd) | |
| def dart_executable(self): | |
| """Returns the path to the checked-in SDK dart executable.""" | |
| return self._executable(self._checkout_dir / 'tools/sdks/dart-sdk/bin', | |
| 'dart') | |
| def _commit_id(self): | |
| """The commit hash of a CI build or the patch set of a CQ build""" | |
| return str(self.m.buildbucket.gitiles_commit.id or 'refs/changes/%s/%s' % | |
| (self.m.buildbucket.build.input.gerrit_changes[0].change, | |
| self.m.buildbucket.build.input.gerrit_changes[0].patchset)) | |
| def upload_isolate(self, isolate_fileset): | |
| """Builds an isolate""" | |
| if not self._isolate_client: | |
| ensure_file = self.m.cipd.EnsureFile().add_package( | |
| ISOLATE_PACKAGE, ISOLATE_VERSION) | |
| isolate_cache = self.m.path.cache_dir / 'isolate' | |
| self.m.cipd.ensure(isolate_cache, ensure_file) | |
| self._isolate_client = isolate_cache / 'isolate' | |
| fileset_path = self._checkout_dir / isolate_fileset | |
| @self.m.time.exponential_retry(2, datetime.timedelta(seconds=5)) | |
| def _upload(): | |
| return self.m.step( | |
| 'upload testing fileset %s' % isolate_fileset, | |
| [ | |
| self._isolate_client, | |
| 'archive', | |
| # TODO(https://github.com/dart-lang/sdk/issues/41982): | |
| # We currently don't have build targets that produce exactly the | |
| # files needed for sharding. Instead, we have catch-all filesets | |
| # in the test matrix that include at least the files the shards | |
| # need. These filesets are not build outputs and don't know what | |
| # files the build actually produced, so they include many files | |
| # and directories that will be there in some builds, but not all. | |
| # Without -allow-missing-file-dir, these extra files/directories | |
| # cause the isolate command to fail. | |
| '-allow-missing-file-dir', | |
| '-ignored-path-filter-re=%s' % | |
| path_filter(str(self._checkout_dir)), | |
| '-isolate=%s' % fileset_path, | |
| '-cas-instance=%s' % CAS_INSTANCE, | |
| ], | |
| stdout=self.m.raw_io.output_text('out')) | |
| step_result = _upload() | |
| output = step_result.stdout.strip() | |
| # The output of the tool is of the form "uploaded digest: <hash>/<length>", | |
| # where <hash>/<length> is used to address the content. | |
| if not re.match('uploaded digest.*: .*/.*', output): | |
| raise self.m.step.InfraFailure( | |
| 'isolate tool did not produce expected output, got: "%s"' % output) | |
| isolate_hash = output.split()[-1] | |
| step_result.presentation.step_text = 'fileset hash: %s' % isolate_hash | |
| return isolate_hash | |
| def shard(self, | |
| name, | |
| isolate_hash, | |
| test_args, | |
| os, | |
| cpu, | |
| num_shards=0, | |
| last_shard_is_local=False, | |
| cipd_ensure_file=None, | |
| ignore_failure=False): | |
| """Runs test.py in the given isolate, sharded over several swarming tasks. | |
| Returns the created tasks, which can be collected with collect_all(). | |
| """ | |
| assert(num_shards > 0) | |
| if not cipd_ensure_file: # pragma: no cover | |
| cipd_ensure_file = self.m.cipd.EnsureFile() | |
| cipd_ensure_file.add_package( | |
| 'infra/tools/luci/vpython3/${platform}', | |
| 'git_revision:54edd25b784c750239eaaf07a21ed1e548dec39e', | |
| 'cipd_bin_packages') | |
| cipd_ensure_file.add_package('infra/3pp/tools/cpython3/${platform}', | |
| 'version:3@3.11.9.chromium.36', | |
| 'cipd_bin_packages/cpython3') | |
| path_prefixes = [ | |
| 'cipd_bin_packages', | |
| 'cipd_bin_packages/bin', | |
| 'cipd_bin_packages/cpython3', | |
| 'cipd_bin_packages/cpython3/bin', | |
| ] | |
| tasks = [] | |
| # TODO(athom) use built-in sharding to remove for loop | |
| for shard in range(num_shards): | |
| if last_shard_is_local and shard == num_shards - 1: | |
| break | |
| cmd = ((test_args or []) + [ | |
| '--shards=%s' % num_shards, | |
| '--shard=%s' % (shard + 1), | |
| '--output-directory=${ISOLATED_OUTDIR}', | |
| ]) | |
| if self.balance_shards: | |
| cmd.append('--previous-results=LATEST/results.json') | |
| # Inherit dimensions from the parent task for the test shards. In | |
| # particular, if the builder is picky about which OS or browser version | |
| # it wants, its test shards should also get the same version. Don't | |
| # inherit everything because some dimensions like 'caches' are only | |
| # meaningful for the parent and the sudden addition of new dimensions | |
| # like this might result in all shards having no matching matches to run | |
| # on. | |
| parent_dimensions = { | |
| d.key: d.value for d in self.m.buildbucket.backend_task_dimensions | |
| } | |
| inherited_dimensions = ['cpu', 'host_class', 'kvm', 'os', 'safari'] | |
| dimensions = { | |
| k: v | |
| for k, v in parent_dimensions.items() | |
| if k in inherited_dimensions | |
| } | |
| # Route test shards to a separate pool. This prevents a starvation | |
| # scenario where all machines are busy with parent tasks and child tasks | |
| # can't get scheduled. | |
| dimensions['pool'] = 'dart.tests' | |
| # There are no Windows ARM64 machines in Dart's pools, so we use Flutter's. | |
| if os == 'win' and cpu == 'arm64': | |
| dimensions['pool'] = parent_dimensions['pool'] | |
| # Android is the edge case where the parent task only does building on a | |
| # powerful cloud machine and the test shards should be routed to weaker | |
| # machines with phones attached. | |
| if os == 'android': | |
| dimensions['os'] = 'Android' | |
| dimensions['host_class'] = 'android' | |
| dimensions['cpu'] = cpu # I.e., cpu of the phone from the builder name. | |
| task_request = ( | |
| self.m.swarming.task_request().with_name( | |
| '%s_shard_%s' % (name, (shard + 1))). | |
| # Set a priority lower than any builder, to prioritize shards. | |
| with_priority(25)) | |
| if ignore_failure: | |
| task_request = task_request.with_tags({'optional': ['true']}) | |
| task_slice = task_request[0] \ | |
| .with_cipd_ensure_file(cipd_ensure_file) \ | |
| .with_command(cmd) \ | |
| .with_containment_type('AUTO') \ | |
| .with_dimensions(**dimensions) \ | |
| .with_env_prefixes(PATH=path_prefixes) \ | |
| .with_env_vars(VPYTHON_VIRTUALENV_ROOT='cache/vpython') \ | |
| .with_execution_timeout_secs(3600) \ | |
| .with_expiration_secs(3600) \ | |
| .with_cas_input_root(isolate_hash) \ | |
| .with_io_timeout_secs(1200) \ | |
| .with_named_caches({ 'vpython' : 'cache/vpython' }) | |
| if 'shard_timeout' in self.m.properties: | |
| task_slice = (task_slice.with_execution_timeout_secs( | |
| int(self.m.properties['shard_timeout']))) | |
| task_request = task_request.with_slice(0, task_slice) | |
| tasks.append(task_request) | |
| return self.m.swarming.trigger('trigger shards for %s' % name, tasks) | |
| @property | |
| def _is_experimental(self): | |
| return self.m.runtime.is_experimental or self._channel() == 'experimental' | |
| def _channel(self): | |
| channel = self.m.buildbucket.builder_name.split('-')[-1] | |
| if channel in ['beta', 'dev', 'experimental', 'stable', 'try']: | |
| return channel | |
| return 'main' | |
| def _release_builder(self): | |
| """Boolean that reports whether the builder is on the | |
| beta, dev, experimental or stable channels. Some steps are only | |
| run on the be and try builders.""" | |
| return self._channel() in ['beta', 'dev', 'experimental', 'stable'] | |
| def _try_builder(self): | |
| """Boolean that reports whether this a try builder. | |
| Some steps are not run on the try builders.""" | |
| return self._channel() == 'try' | |
| def _branch_builder(self): | |
| """Returns True if this builder is setup to build a branch (other | |
| than the branches associated with release channels; see | |
| _release_builder).""" | |
| return (self.m.buildbucket.gitiles_commit.ref not in ("refs/heads/master", | |
| "refs/heads/main") and | |
| not self._release_builder() and not self._try_builder()) | |
| def _supports_result_database(self): | |
| """Returns True if this builder can send its test results to the test result | |
| system.""" | |
| # This additional check ensures that builders with names indicating a | |
| # release builder but that are on the master branch don't send data to the | |
| # results database. | |
| # TODO(karlklose): verify in the beginning of the recipe that the builder | |
| # name and the commit ref are consistent. | |
| if self._release_builder(): | |
| return False | |
| if self._try_builder(): | |
| return self.m.tryserver.gerrit_change_target_ref == 'refs/heads/main' | |
| else: | |
| return self.m.buildbucket.gitiles_commit.ref in [ | |
| "refs/heads/main", | |
| "refs/heads/master", | |
| "refs/heads/ci-test-data", | |
| ] | |
| def _is_bisecting(self): | |
| return self.m.bisect_build.is_bisecting() | |
| def collect_all(self, steps, retry_shards: bool): | |
| """Collects the results of a sharded test run.""" | |
| # Defer results in case one of the shards has a non-zero exit code. | |
| if any(step.tasks for step in steps): | |
| num_retried_shards = 0 | |
| if retry_shards: | |
| num_retried_shards = int(self.m.properties.get("max_retried_shards", 3)) | |
| retried_shards = RetriedShards(self, num_retried_shards) | |
| with self.m.step.nest('collect shards'): | |
| futures = [] | |
| for step in steps: | |
| tasks = step.tasks | |
| step.tasks = [] | |
| for shard in tasks: | |
| futures.append( | |
| self.m.futures.spawn(self._collect, step, shard, | |
| retried_shards)) | |
| with self.m.futures.iwait(futures) as completed_stream: | |
| for future in completed_stream: | |
| try: | |
| future.result() | |
| except self.m.step.InfraFailure: | |
| for future in futures: | |
| future.cancel() | |
| raise | |
| if any(step.results.failed for step in steps): | |
| raise self.m.step.StepFailure('Sharded test steps failed') | |
| if retried_shards: | |
| self.collect_all(steps, retry_shards=False) | |
| def _collect(self, step, task, retried_shards: RetriedShards): | |
| output_dir = self.m.path.mkdtemp() | |
| # Every shard is only a single task in swarming | |
| task_result = self.m.swarming.collect(task.name, [task], output_dir)[0] | |
| # Swarming uses the task's id as a subdirectory name | |
| output_dir = output_dir / task.id | |
| try: | |
| task_result.analyze() | |
| except self.m.step.InfraFailure as failure: | |
| if (task_result.state == self.m.swarming.TaskState.COMPLETED and | |
| not step.is_test_step): | |
| self.m.step.active_result.presentation.status = 'FAILURE' | |
| step.results.failed = True | |
| else: | |
| if self.m.step.active_result.presentation.status != 'CANCELED': | |
| self.m.step.active_result.presentation.status = 'EXCEPTION' | |
| if retried_shards.should_retry(task_result): | |
| retried_shards.retry( | |
| step, | |
| self.m.swarming.show_request('fetch failing shard request', | |
| task_result.id)) | |
| return | |
| raise | |
| except self.m.step.StepFailure as failure: | |
| assert (task_result.state == self.m.swarming.TaskState.TIMED_OUT) | |
| self.m.step.active_result.presentation.status = 'EXCEPTION' | |
| raise self.m.step.InfraFailure(failure.reason) | |
| if step.is_test_step: | |
| bot_name = task_result.bot_id | |
| task_name = task_result.name | |
| self._add_results_and_links(output_dir, bot_name, task_name, step.results) | |
| def _add_results_and_links(self, output_dir, bot_name, task_name, results): | |
| filenames = ('logs.json', 'results.json') | |
| for filename in filenames: | |
| file_path = output_dir / filename | |
| self.m.path.mock_add_paths(file_path) | |
| if self.m.path.exists(file_path): | |
| contents = self.m.file.read_raw( | |
| 'read %s for %s' % (filename, task_name), | |
| file_path, | |
| test_data='{"configuration":"mock_configuration"}\n').decode('utf8') | |
| if filename == 'results.json': | |
| results.add_results(bot_name, contents) | |
| if filename == 'logs.json': | |
| results.logs += contents | |
| def _get_latest_tested_commit(self): | |
| builder_path = self._get_builder_results_path() | |
| latest_result = self.m.gsutil.download( | |
| 'dart-test-results', | |
| '%s/latest' % builder_path, | |
| self.m.raw_io.output_text(name='latest', add_output_log=True), | |
| name='find latest build', | |
| ok_ret='any') # TODO(athom): succeed only if file does not exist | |
| latest = latest_result.raw_io.output_texts.get('latest') | |
| revision = None | |
| if latest: | |
| latest = latest.strip() | |
| revision_result = self.m.gsutil.download( | |
| 'dart-test-results', | |
| '%s/%s/revision' % (builder_path, latest), | |
| self.m.raw_io.output_text(name='revision', add_output_log=True), | |
| name='get revision for latest build', | |
| ok_ret='any') # TODO(athom): succeed only if file does not exist | |
| revision = revision_result.raw_io.output_texts.get('revision') | |
| return (latest, revision) | |
| def _get_builder_dir(self): | |
| builder = self.m.buildbucket.builder_name | |
| if builder.endswith('-try'): | |
| builder = builder[:-4] | |
| target = self.m.tryserver.gerrit_change_target_ref.split('/')[-1] | |
| if target not in ('main', 'master'): | |
| builder = '%s-%s' % (builder, target) | |
| return str(builder) | |
| def _get_builder_results_path(self, latest=None): | |
| builder = self._get_builder_dir() | |
| path = 'builders/%s' % builder | |
| if latest: | |
| path = '%s/%s' % (path, latest) | |
| if self._is_experimental: | |
| path = 'experimental/%s' % path | |
| return path | |
| def _download_results(self, latest): | |
| filenames = ['results.json', 'flaky.json'] | |
| results_path = self._checkout_dir / 'LATEST' | |
| self.m.file.ensure_directory('ensure LATEST dir', results_path) | |
| for filename in filenames: | |
| self.m.file.write_text('ensure %s exists' % filename, | |
| results_path / filename, '') | |
| if latest: | |
| path = '%s/*.json' % (self._get_builder_results_path(latest)) | |
| self.m.gsutil.download( | |
| 'dart-test-results', | |
| path, | |
| results_path, | |
| name='download previous results') | |
| def _deflake_results(self, step, defer): | |
| step.deflake_list = self.m.step( | |
| 'list tests to deflake (%s)' % step.name, [ | |
| self.dart_executable(), | |
| self._bot_script('compare_results.dart'), | |
| '--flakiness-data=LATEST/flaky.json', | |
| '--changed', | |
| '--failing', | |
| '--count=50', | |
| 'LATEST/results.json', | |
| self.m.raw_io.input_text(step.results.results), | |
| ], | |
| stdout=self.m.raw_io.output_text(add_output_log=True)).stdout | |
| if step.deflake_list: | |
| self._run_step(step, defer) | |
| def _update_flakiness_information(self, results_str): | |
| command_args = [ | |
| '-i', 'LATEST/flaky.json', '-o', | |
| self.m.raw_io.output_text(name='flaky.json', add_output_log=True), | |
| '--build-id', self.m.buildbucket.build.id, '--commit', | |
| self.m.buildbucket.gitiles_commit.id, | |
| self.m.raw_io.input_text(results_str, name='results.json') | |
| ] | |
| if self._try_builder(): | |
| command_args.append('--no-forgive') | |
| flaky_json = self.m.step( | |
| 'update flakiness information', | |
| [self.dart_executable(), | |
| self._bot_script('update_flakiness.dart')] + command_args) | |
| return flaky_json.raw_io.output_texts.get('flaky.json') | |
| def _upload_configurations_to_cloud(self): | |
| results = self.results | |
| logs = _split_by_configuration(results.logs) | |
| flaky = _split_by_configuration(results.flaky_json) | |
| for configuration in results.results_by_configuration: | |
| self._upload_results_to_cloud( | |
| _to_lines(flaky.get(configuration, [])), | |
| _to_lines(logs.get(configuration, [])), | |
| _to_lines(results.results_by_configuration[configuration]), | |
| configuration) | |
| def _upload_results_to_cloud(self, flaky_json_str, logs_str, results_str, | |
| configuration): | |
| builder = self._get_builder_dir() | |
| build_revision = self.m.buildbucket.gitiles_commit.id | |
| build_number = str(self.m.buildbucket.build.number) | |
| if configuration: | |
| path = 'configuration/%s/%s' % (self._channel(), configuration) | |
| if self._is_experimental: | |
| path = 'experimental/%s' % path | |
| else: | |
| path = self._get_builder_results_path() | |
| self._upload_result(path, build_number, 'revision', build_revision) | |
| self._upload_result(path, build_number, 'logs.json', logs_str) | |
| self._upload_result(path, build_number, 'results.json', results_str) | |
| self._upload_result(path, build_number, 'flaky.json', flaky_json_str) | |
| if (not self._release_builder() and not configuration and | |
| not self._is_experimental): | |
| self._upload_result('builders/current_flakiness', 'single_directory', | |
| 'flaky_current_%s.json' % builder, flaky_json_str) | |
| # Update "latest" file, if this is not a bisection build (bisection builds | |
| # have higher build numbers although they test older commits) | |
| if not self._is_bisecting(): | |
| new_latest = self.m.raw_io.input_text(build_number, name='latest') | |
| args = [ | |
| new_latest, | |
| 'dart-test-results', | |
| '%s/%s' % (path, 'latest'), | |
| ] | |
| self.m.gsutil.upload(*args, name='update "latest" reference') | |
| def _upload_result(self, path, build_number, filename, result_str): | |
| args = [ | |
| self.m.raw_io.input_text(str(result_str), name=filename), | |
| 'dart-test-results', | |
| '%s/%s/%s' % (path, build_number, filename), | |
| ] | |
| self.m.gsutil.upload(*args, name='upload %s' % filename) | |
| def _update_blamelist(self): | |
| if not self._supports_result_database() or self._is_experimental: | |
| return | |
| access_token = self.m.service_account.default().get_access_token( | |
| ['https://www.googleapis.com/auth/cloud-platform']) | |
| results_by_configuration = self.results.results_by_configuration | |
| for configuration in results_by_configuration: | |
| results_str = _to_lines(results_by_configuration[configuration]) | |
| command = [ | |
| self.dart_executable(), | |
| self._bot_script('update_blamelists.dart'), '--results', | |
| self.m.raw_io.input_text(results_str), '--auth-token', | |
| self.m.raw_io.input_text(access_token) | |
| ] | |
| if self._branch_builder(): | |
| # Write to the staging database (for testing). | |
| command.append('-s') | |
| self.m.step( | |
| 'update blamelists for configuration "%s"' % configuration, | |
| command, | |
| ok_ret='any') | |
| def _bot_script(self, script_name): | |
| return self._checkout_dir / f'tools/bots/{script_name}' | |
| def _update_results_database(self): | |
| if (self._is_bisecting() or not self._supports_result_database() or | |
| self._is_experimental): # pragma: no cover | |
| return | |
| with self.m.step.nest('update results database'): | |
| package_name = 'dart/ci/builder_scripts/${platform}' | |
| ensure_file = self.m.cipd.EnsureFile().add_package(package_name, 'latest') | |
| ci_scripts_path = self.m.path.start_dir / 'dart-ci-scripts' | |
| self.m.cipd.ensure(ci_scripts_path, ensure_file, | |
| 'install dart_ci scripts') | |
| base_revision = self.m.bot_update.last_returned_properties.get( | |
| 'got_revision', 'got_revision property not found') | |
| command = [ | |
| self._executable(ci_scripts_path, 'upload_results_to_database'), | |
| '--results', | |
| self.m.raw_io.input_text(self.results.results), | |
| '--project', | |
| 'dart-ci', | |
| '--buildbucket_id', | |
| self.m.buildbucket.build.id, | |
| '--base_revision', | |
| base_revision, | |
| ] | |
| self.m.step('run update script', command) | |
| def _extend_results_records(self, results_str, prior_results_path, | |
| flaky_json_str, prior_flaky_path, builder_name, | |
| build_number, commit_time, commit_id): | |
| new_results_str = self.m.step('add fields to result records', [ | |
| self.dart_executable(), | |
| self._bot_script('extend_results.dart'), | |
| self.m.raw_io.input_text(results_str, | |
| name='results.json'), prior_results_path, | |
| self.m.raw_io.input_text(flaky_json_str, name='flaky.json'), | |
| prior_flaky_path, builder_name, build_number, commit_time, commit_id, | |
| self.m.raw_io.output_text() | |
| ]).raw_io.output_text | |
| self.m.step.active_result.presentation.logs['results.json'] = [ | |
| new_results_str | |
| ] | |
| return new_results_str | |
| def _present_results(self): | |
| # Construct the links and data to add to the results step. | |
| logs_str = self.results.logs | |
| results_str = self.results.results | |
| flaky_json_str = self.results.flaky_json | |
| args = [ | |
| self.dart_executable(), | |
| self._bot_script('compare_results.dart'), | |
| '--flakiness-data', | |
| self.m.raw_io.input_text(flaky_json_str, name='flaky.json'), | |
| '--human', | |
| '--verbose', | |
| self._checkout_dir / 'LATEST/results.json', | |
| self.m.raw_io.input_text(results_str), | |
| ] | |
| args_logs = ["--logs", | |
| self.m.raw_io.input_text(logs_str, name='logs.json'), | |
| "--logs-only"] | |
| links = OrderedDict() | |
| judgement_args = list(args) | |
| judgement_args.append('--judgement') | |
| links["new test failures"] = self.m.step( | |
| 'find new test failures', | |
| args + ["--changed", "--failing"], | |
| stdout=self.m.raw_io.output_text(add_output_log=True)).stdout | |
| links["new test failures (logs)"] = self.m.step( | |
| 'find new test failures (logs)', | |
| args + args_logs + ["--changed", "--failing"], | |
| stdout=self.m.raw_io.output_text(add_output_log=True)).stdout | |
| links["tests that began passing"] = self.m.step( | |
| 'find tests that began passing', | |
| args + ["--changed", "--passing"], | |
| stdout=self.m.raw_io.output_text(add_output_log=True)).stdout | |
| links["ignored flaky test failure logs"] = self.m.step( | |
| 'find ignored flaky test failure logs', | |
| args + args_logs + ["--flaky"], | |
| stdout=self.m.raw_io.output_text(add_output_log=True)).stdout | |
| judgement_args += ["--changed", "--failing"] | |
| if self._try_builder(): # pragma: no cover | |
| judgement_args += ["--passing"] | |
| # Run the results step that determines the status of the build. | |
| if not self._supports_result_database() or self._is_bisecting(): | |
| test_results = self.m.step( | |
| 'test results', judgement_args, raise_on_failure=False) | |
| else: | |
| access_token = self.m.service_account.default().get_access_token( | |
| ['https://www.googleapis.com/auth/cloud-platform']) | |
| command = [ | |
| self.dart_executable(), | |
| self._bot_script('get_builder_status.dart'), '-b', | |
| self.m.buildbucket.builder_name, '-n', | |
| self.m.buildbucket.build.number, '-a', | |
| self.m.raw_io.input_text(access_token) | |
| ] | |
| if self._branch_builder(): | |
| # Get the status from the staging database (for testing). | |
| command.append('-s') | |
| test_results = self.m.step( | |
| 'test results', command, raise_on_failure=False) | |
| # Add the links and logs to the results step | |
| if self._try_builder(): | |
| patchset = self._commit_id().replace('refs/changes/', '') | |
| log_url = 'https://dart-ci.firebaseapp.com/cl/%s' % patchset | |
| else: | |
| log_url = self._results_feed_url(results_str) | |
| self.m.step.active_result.presentation.links['Test Results'] = log_url | |
| doc_url = 'https://goto.google.com/dart-status-file-free-workflow' | |
| self.m.step.active_result.presentation.links['Documentation'] = doc_url | |
| # Show only the links with non-empty output (something happened). | |
| for link, contents in links.items(): | |
| if contents != '': # pragma: no cover | |
| self.m.step.active_result.presentation.logs[link] = [contents] | |
| if test_results.retcode == 0: | |
| return | |
| elif test_results.retcode == 1: | |
| test_results.presentation.status = 'FAILURE' | |
| raise recipe_api.StepFailure('failing tests') | |
| else: | |
| # Return codes other than 1 are infra failures. | |
| # A real infra failure has retcode None, and is also handled here. | |
| test_results.presentation.status = 'EXCEPTION' | |
| raise self.m.step.InfraFailure('failed to get test results') | |
| def _results_feed_url(self, results_str): | |
| configurations = { | |
| json.loads(line)['configuration'] | |
| for line in (results_str or '').splitlines() | |
| } | |
| results_feed_url = 'https://dart-ci.firebaseapp.com/' | |
| return '%s#showLatestFailures=true&configurations=%s' % ( | |
| results_feed_url, ','.join(sorted(configurations))) | |
| def read_debug_log(self): | |
| """Reads the debug log file""" | |
| if self.m.platform.name == 'win': | |
| self.m.step('debug log', | |
| ['cmd.exe', '/c', 'type', '.debug.log'], | |
| ok_ret='any') | |
| else: | |
| self.m.step('debug log', | |
| ['cat', '.debug.log'], | |
| ok_ret='any') | |
| def delete_debug_log(self): | |
| """Deletes the debug log file""" | |
| self.m.file.remove('delete debug log', self._checkout_dir / '.debug.log') | |
| def test(self, test_data): | |
| """Reads the test-matrix.json file in the checkout and runs each step listed | |
| in the file. | |
| """ | |
| with self.m.context(infra_steps=True): | |
| test_matrix_path = self._checkout_dir / 'tools/bots/test_matrix.json' | |
| test_matrix = self.m.file.read_json( | |
| 'read test-matrix.json', test_matrix_path, test_data=test_data) | |
| builder = str(self.m.buildbucket.builder_name) | |
| if builder.endswith( | |
| ('-beta', '-dev', 'experimental', '-main', '-stable', '-try')): | |
| builder = builder[0:builder.rfind('-')] | |
| config = self._read_config(test_matrix, builder) | |
| self.delete_debug_log() | |
| self._write_file_sets(test_matrix['filesets']) | |
| steps = self._get_steps(config, builder) | |
| test_steps = [ | |
| step for step in steps if not step.is_trigger and step.is_test_step | |
| ] | |
| # TODO(sortie): Inline and do this unconditionally when we no longer need | |
| # to release Dart 3.1 patch releases. | |
| shard_dart_path = self._checkout_dir / 'pkg/test_runner/lib/src/shard.dart' | |
| self.m.path.mock_add_file(shard_dart_path) | |
| self.balance_shards = self.m.path.exists(shard_dart_path) | |
| if test_steps: | |
| with self.m.step.nest('download previous results'): | |
| if self._is_bisecting(): | |
| # With the new bbagent infrastructure, this value is returned | |
| # as a floating-point value, not an int. | |
| latest = int(self.m.bisect_build.get_base_build()) | |
| else: | |
| latest, _ = self._get_latest_tested_commit() | |
| self._download_results(latest) | |
| with self.m.defer.context(collect_step_name=None) as defer: | |
| defer(self._run_steps, steps, config, defer) | |
| defer(self._collect_shards, steps) | |
| if test_steps: | |
| with self.m.context(cwd=self._checkout_dir): | |
| self._collect_test_results(test_steps) | |
| self._process_test_results() | |
| self._upload_test_results() | |
| self._present_results() | |
| def _read_config(self, test_matrix, builder): | |
| try: | |
| return next(config for config in test_matrix['builder_configurations'] | |
| if builder in config['builders']) | |
| except StopIteration: | |
| raise self.m.step.InfraFailure( | |
| 'Error, could not find builder by name %s in test-matrix' % builder) | |
| def _write_file_sets(self, filesets): | |
| """Writes the fileset to the root of the sdk to allow for swarming to pick | |
| up the files and isolate the files. | |
| Args: | |
| * filesets - Filesets from the test-matrix | |
| """ | |
| for fileset, files in filesets.items(): | |
| isolate_fileset = { 'variables': { 'files': files } } | |
| destination_path = self._checkout_dir / fileset | |
| self.m.file.write_text('write fileset %s to sdk root' % fileset, | |
| destination_path, str(isolate_fileset)) | |
| def _build_isolates(self, config, isolate_hashes): | |
| """Isolate filesets from all steps in config and populates a dictionary | |
| with a mapping from fileset to isolate_hash. | |
| Args: | |
| * config (dict) - Configuration of the builder, including the steps | |
| * isolate_hashes (dict) - A dict that will contain a mapping from | |
| fileset name to isolate hash upon completion of this method. | |
| """ | |
| for step in config['steps']: | |
| if 'fileset' in step and step['fileset'] not in isolate_hashes: | |
| isolate_hash = self.upload_isolate(step['fileset']) | |
| isolate_hashes[step['fileset']] = isolate_hash | |
| def _get_option(self, builder_fragments, options, default_value): | |
| """Gets an option from builder_fragments in options, or returns the default | |
| value.""" | |
| intersection = set(builder_fragments) & set(options) | |
| if len(intersection) == 1: | |
| return intersection.pop() | |
| return default_value | |
| def _get_specific_argument(self, arguments, options): | |
| for arg in arguments: | |
| if isinstance(arg, str): | |
| for option in options: | |
| if arg.startswith(option): | |
| specific_argument = arg[len(option):].strip() | |
| if specific_argument.startswith('='): | |
| specific_argument = specific_argument[1:].strip() | |
| return specific_argument | |
| return None | |
| def _has_specific_argument(self, arguments, options): | |
| return self._get_specific_argument(arguments, options) is not None | |
| def _environment(self, builder_name): | |
| # Find information from the builder name. It should be in the form | |
| # <info>-<os>-<mode>-<arch>-<runtime> or <info>-<os>-<mode>-<arch>. | |
| builder_fragments = builder_name.split('-') | |
| system = self._get_option(builder_fragments, SYSTEMS, 'linux') | |
| mode = self._get_option(builder_fragments, MODES, 'release') | |
| arch = self._get_option(builder_fragments, ARCHITECTURES, 'x64') | |
| cpu = CPUS.get(arch, DEFAULT_CPU) | |
| sanitizer = self._get_option(builder_fragments, SANITIZERS, 'none') | |
| runtime = self._get_option(builder_fragments, RUNTIMES, None) | |
| co19_filter = '--filter=%s/%s' % (CIPD_SERVER_URL, CO19_PACKAGE) | |
| checked_in_sdk_filter = '--filter=%s/%s' % (CIPD_SERVER_URL, SDK_PACKAGE) | |
| chrome_filter = '--filter=%s/%s' % (CIPD_SERVER_URL, CHROME_PACKAGE) | |
| firefox_filter = '--filter=%s/%s' % (CIPD_SERVER_URL, FIREFOX_PACKAGE) | |
| with self.m.context(cwd=self._gclient_working_dir): | |
| result = self.m.gclient( | |
| 'get package versions', [ | |
| 'revinfo', | |
| '--output-json', | |
| self.m.json.output(name='revinfo'), | |
| co19_filter, | |
| checked_in_sdk_filter, | |
| chrome_filter, | |
| firefox_filter, | |
| ], | |
| step_test_data=self._canned_revinfo) | |
| revinfo = result.json.outputs.get('revinfo') | |
| if not revinfo: | |
| raise recipe_api.InfraFailure('failed to get package versions') | |
| packages = {} | |
| for k, v in revinfo.items(): | |
| path, name = k.split(':') | |
| path = path[4:] # Remove "sdk/" prefix | |
| version = v['rev'] | |
| packages[name] = (name, version, path) | |
| assert SDK_PACKAGE in packages | |
| assert CO19_PACKAGE in packages | |
| out = 'xcodebuild' if self.m.platform.name == 'mac' else 'out' | |
| build_root = out + '/' + mode.capitalize() + arch.upper() | |
| environment = { | |
| 'system': system, | |
| 'mode': mode, | |
| 'arch': arch, | |
| 'cpu': cpu, | |
| 'sanitizer': sanitizer, | |
| 'build_root': build_root, | |
| 'copy-coredumps': False, | |
| 'packages': packages, | |
| 'runtime': runtime, | |
| 'out': out | |
| } | |
| # Linux and vm-*-win builders should use copy-coredumps | |
| environment['copy-coredumps'] = (system == 'linux' or system == 'mac' or | |
| (system.startswith('win') and builder_name.startswith('vm-'))) | |
| return environment | |
| def _get_steps(self, config, builder_name): | |
| """Fetches the steps from a json test-matrix builder entry""" | |
| environment = self._environment(builder_name) | |
| return [ | |
| self.TestMatrixStep(self.m, builder_name, config, step_json, | |
| environment, index) | |
| for index, step_json in enumerate(config['steps']) | |
| ] | |
| def _run_steps(self, steps, config, defer): | |
| isolate_hashes = {} | |
| for step in steps: | |
| if step.fileset: | |
| # We don't upload the isolates until the first step with a fileset. | |
| # We need to wait for earlier build steps to complete. | |
| self._build_isolates(config, isolate_hashes) | |
| step.isolate_hash = isolate_hashes[step.fileset] | |
| self._run_step(step, defer) | |
| def _collect_shards(self, steps): | |
| sharded_steps = [ | |
| step for step in steps | |
| if step.isolate_hash # and not (step.local_shard and step.shards < 2) | |
| ] | |
| self.collect_all(sharded_steps, retry_shards=True) | |
| def _run_step(self, step, defer): | |
| with self.m.depot_tools.on_path(), self.m.context( | |
| cwd=self._checkout_dir, env=step.environment_variables): | |
| if step.is_gn_step: | |
| with self.m.context(infra_steps=False): | |
| self._run_gn(step) | |
| elif step.is_build_step: | |
| self._run_build(step) | |
| elif step.is_trigger: | |
| defer(self._run_trigger, step) | |
| elif step.is_test_py_step: | |
| defer(self._run_test_py, step) | |
| else: | |
| with self.m.context(infra_steps=step.is_test_step): | |
| defer(self._run_script, step) | |
| def _run_gn(self, step): | |
| mode = step.environment['mode'] | |
| arch = step.environment['arch'] | |
| sanitizer = step.environment['sanitizer'] | |
| args = step.args | |
| if not self._has_specific_argument(args, ['-m', '--mode']): | |
| args = ['-m%s' % mode] + args | |
| if not self._has_specific_argument(args, ['-a', '--arch']): | |
| args = ['-a%s' % arch] + args | |
| if not self._has_specific_argument(args, ['--sanitizer']): | |
| args = ['--sanitizer=%s' % sanitizer] + args | |
| self.m.build.gn(self._checkout_dir, name=step.name, args=args) | |
| def _run_build(self, step): | |
| mode = step.environment['mode'] | |
| arch = step.environment['arch'] | |
| sanitizer = step.environment['sanitizer'] | |
| args = step.args | |
| if not self._has_specific_argument(args, ['-m', '--mode']): | |
| args = ['-m%s' % mode] + args | |
| if not self._has_specific_argument(args, ['-a', '--arch']): | |
| args = ['-a%s' % arch] + args | |
| if not self._has_specific_argument(args, ['--sanitizer']): | |
| args = ['--sanitizer=%s' % sanitizer] + args | |
| args = ['--check-clean'] + args | |
| self.kill_tasks() | |
| self.m.build.build(self._checkout_dir, name=step.name, args=args) | |
| def _collect_test_results(self, steps): | |
| with self.m.step.nest('deflaking'): | |
| with self.m.defer.context(collect_step_name=None) as defer: | |
| for step in steps: | |
| if step.is_test_py_step: | |
| defer(self._deflake_results, step, defer) | |
| defer(self.collect_all, steps, retry_shards=False) | |
| self.results.results = ''.join((step.results.results for step in steps)) | |
| if not self.results.results: | |
| raise recipe_api.InfraFailure( | |
| 'results.json is empty. No results returned from any test step') | |
| self.results.logs = ''.join((step.results.logs for step in steps)) | |
| def _process_test_results(self): | |
| results = self.results | |
| results.flaky_json = self._update_flakiness_information(results.results) | |
| results.results = self._extend_results_records( | |
| results.results, self._checkout_dir / 'LATEST/results.json', | |
| results.flaky_json, self._checkout_dir / 'LATEST/flaky.json', | |
| self.m.buildbucket.builder_name, self.m.buildbucket.build.number, | |
| self.m.git.get_timestamp(test_data='1234567'), self._commit_id()) | |
| results.results_by_configuration = _split_by_configuration(results.results) | |
| def _upload_test_results(self): | |
| with self.m.step.nest('upload new results'): | |
| if not self._try_builder(): | |
| self._upload_results_to_cloud(self.results.flaky_json, | |
| self.results.logs, self.results.results, | |
| None) | |
| self._upload_configurations_to_cloud() | |
| if self.results.results: | |
| self._update_results_database() | |
| if not self._try_builder(): | |
| self._upload_results_to_bq() | |
| if self._is_bisecting(): | |
| self._update_blamelist() | |
| def _upload_results_to_bq(self): | |
| results_str = self.results.results | |
| if self._is_bisecting(): | |
| return # pragma: no cover | |
| assert(results_str[-1] == '\n') | |
| if not self._bqupload_client: | |
| ensure_file = self.m.cipd.EnsureFile().add_package( | |
| BQUPLOAD_PACKAGE, 'latest') | |
| bqupload_cache = self.m.path.cache_dir / 'bqupload' | |
| self.m.cipd.ensure(bqupload_cache, ensure_file) | |
| self._bqupload_client = bqupload_cache / 'bqupload' | |
| cmd = [self._bqupload_client, 'dart-ci.results.results'] | |
| with self.m.step.nest('upload test results to big query'): | |
| # Upload at most 1000 lines at once | |
| for match in re.finditer(r'(?:.*\n){1,1000}', results_str): | |
| chunk = match.group(0) | |
| if not self._is_experimental: | |
| self.m.step( | |
| 'upload results chunk to big query', | |
| cmd, | |
| stdin=self.m.raw_io.input_text(chunk), | |
| raise_on_failure=False) | |
| def _run_trigger(self, step): | |
| trigger_props = {} | |
| trigger_props['revision'] = self.m.buildbucket.gitiles_commit.id | |
| trigger_props['parent_buildername'] = self.m.buildbucket.builder_name | |
| trigger_props['parent_build_id'] = str(self.m.buildbucket.build.id) | |
| if step.isolate_hash: | |
| trigger_props['parent_fileset'] = step.isolate_hash | |
| trigger_props['parent_fileset_name'] = step.fileset | |
| build_requests = [ | |
| self.m.buildbucket.schedule_request( | |
| builder=builder_name, | |
| properties=trigger_props, | |
| ) for builder_name in step.triggered_builders | |
| ] | |
| self.m.buildbucket.schedule(build_requests, step_name=step.name) | |
| def _run_test_py(self, step): | |
| """Runs test.py with default arguments, based on configuration from. | |
| Args: | |
| * step (TestMatrixStep) - The test-matrix step. | |
| """ | |
| environment = step.environment | |
| args = step.args | |
| arch = self._get_specific_argument(args, ['-a', '--arch']) | |
| if arch: | |
| environment = environment.copy() | |
| environment['cpu'] = CPUS[arch] | |
| step.environment = environment | |
| shards = step.shards | |
| if step.deflake_list: | |
| args = args + ['--repeat=5', '--tests', step.deflake_list] | |
| shards = min(shards, 1) | |
| else: | |
| args = args + ['--silent-failures'] | |
| test_args = [ | |
| '--progress=status', '--report', '--time', '--write-results', | |
| '--write-logs', '--clean-exit' | |
| ] | |
| args = test_args + args | |
| if environment['copy-coredumps']: | |
| args.append('--copy-coredumps') | |
| system = environment['system'] | |
| if system == 'win': | |
| args.append('--cleanup-dart-processes') | |
| ensure_file = self.m.cipd.EnsureFile() | |
| def _add_package(name, browser_arg): | |
| if browser_arg and environment['packages'].get(name): | |
| ensure_file.add_package(*environment['packages'][name]) | |
| args.append(browser_arg) | |
| # The --chrome or --firefox option is added here if the builder is | |
| # configured to use the CIPD package for chrome or firefox respectively. | |
| # The relevant browser package is also added to the ensure file for shards. | |
| _add_package(CHROME_PACKAGE, CHROME_PATH_ARGUMENT.get(system)) | |
| _add_package(FIREFOX_PACKAGE, FIREFOX_PATH_ARGUMENT.get(system)) | |
| self._run_script( | |
| step, | |
| args, | |
| cipd_ensure_file=ensure_file, | |
| ignore_failure=step.deflake_list, | |
| shards=shards) | |
| def _run_script(self, | |
| step, | |
| args=None, | |
| cipd_ensure_file=None, | |
| ignore_failure=False, | |
| shards=None): | |
| """Runs a specific script with current working directory to be checkout. If | |
| the system is linux and a --<browser> argument is in the argument list or | |
| the runtime (passed in environment) is a browser, xvfb is used. If an | |
| isolate_hash is passed in, it will shard the command. | |
| Args: | |
| * step (TestMatrixStep) - The test-matrix step. | |
| * args ([str]) - Overrides the arguments specified in the step. | |
| * cipd_ensure_file ([EnsureFile]) - specifies cipd package dependencies. | |
| * ignore_failure ([bool]) - Do not turn step red if this script fails. | |
| * shards ([int]) - Overrides the number of shards specified in the step. | |
| """ | |
| environment = step.environment | |
| if not args: | |
| args = step.args | |
| if not cipd_ensure_file: # pragma: no cover | |
| cipd_ensure_file = self.m.cipd.EnsureFile() | |
| def _add_package(name): | |
| cipd_ensure_file.add_package(*environment['packages'][name]) | |
| _add_package(SDK_PACKAGE) | |
| if any(arg.startswith('co19/') or arg == 'co19' for arg in args): | |
| _add_package(CO19_PACKAGE) | |
| ok_ret = 'any' if ignore_failure else {0} | |
| runtime = environment.get('runtime', None) | |
| use_xvfb = ( | |
| environment['system'] == 'linux' and | |
| (runtime in ['chrome', 'firefox'] or | |
| self._has_specific_argument(args, ['--chrome', '--firefox']))) | |
| script = step.script | |
| is_python = str(script).endswith('.py') | |
| cmd_prefix = [] | |
| if use_xvfb: | |
| cmd_prefix = [ | |
| '/usr/bin/xvfb-run', '-a', '--server-args=-screen 0 1024x768x24' | |
| ] | |
| if is_python: | |
| cmd_prefix += ['python3', '-u'] | |
| step_name = step.name | |
| shards = shards or step.shards | |
| if step.isolate_hash and not (step.local_shard and shards < 2): | |
| with self.m.step.nest('trigger shards for %s' % step_name): | |
| step.tasks += self.shard( | |
| step_name, | |
| step.isolate_hash, | |
| cmd_prefix + [script] + args, | |
| num_shards=shards, | |
| last_shard_is_local=step.local_shard, | |
| cipd_ensure_file=cipd_ensure_file, | |
| ignore_failure=ignore_failure, | |
| cpu=environment['cpu'], | |
| os=environment['system']) | |
| if step.local_shard: | |
| args = args + [ | |
| '--shards=%s' % shards, | |
| '--shard=%s' % shards, | |
| ] | |
| if self.balance_shards: | |
| args.append('--previous-results=LATEST/results.json') | |
| step_name = '%s_shard_%s' % (step_name, shards) | |
| else: | |
| return # Shards have been triggered, no local shard to run. | |
| output_dir = None | |
| if step.is_test_step: | |
| output_dir = self.m.path.mkdtemp() | |
| args = args + [ | |
| '--output-directory', | |
| output_dir, | |
| ] | |
| cmd = self._checkout_dir / script | |
| self.m.step(step_name, cmd_prefix + [cmd] + args, ok_ret=ok_ret) | |
| if output_dir: | |
| self._add_results_and_links(output_dir, self.m.properties.get('bot_id'), | |
| step_name, step.results) | |
| def _canned_revinfo(self): | |
| revinfo = {} | |
| def _add_package(path, package, version): | |
| revinfo['%s:%s' % (path, package)] = { | |
| 'url': '%s/%s' % (CIPD_SERVER_URL, package), | |
| 'rev': version, | |
| } | |
| _add_package('sdk/tests/co19/src', CO19_PACKAGE, 'git_revision:co19_hash') | |
| _add_package('sdk/tools/sdks', SDK_PACKAGE, 'version:2.9.0-18.0.dev') | |
| if 'download_chrome' in self.m.properties.get('custom_vars', {}): | |
| _add_package('sdk/third_party/browsers/chrome', CHROME_PACKAGE, | |
| 'version:81') | |
| if 'download_firefox' in self.m.properties.get('custom_vars', {}): | |
| _add_package('sdk/third_party/browsers/firefox', FIREFOX_PACKAGE, | |
| 'version:67') | |
| return self.m.json.test_api.output(name='revinfo', data=revinfo) | |
| class TestMatrixStep: | |
| def __init__(self, m, builder_name, config, step_json, environment, index): | |
| self.m = m | |
| self.name = step_json['name'] | |
| self.results = StepResults(m) | |
| self.deflake_list = [] | |
| self.args = step_json.get('arguments', []) | |
| self.environment = environment | |
| self.tasks = [] | |
| self.is_trigger = 'trigger' in step_json | |
| self.triggered_builders = step_json.get('trigger', []) | |
| # If script is not defined, use test.py. | |
| self.script = step_json.get('script', TEST_PY_PATH) | |
| if self.m.platform.name == 'mac' and self.script.startswith('out/'): | |
| self.script = self.script.replace('out/', 'xcodebuild/', 1) | |
| is_dart = self.script.endswith('/dart') | |
| if is_dart: | |
| executable_suffix = '.exe' if self.m.platform.name == 'win' else '' | |
| self.script += executable_suffix | |
| self.is_build_step = self.script.endswith(BUILD_PY_PATH) | |
| self.is_gn_step = self.script.endswith(GN_PY_PATH) | |
| self.is_test_py_step = self.script.endswith(TEST_PY_PATH) | |
| self.is_test_step = (self.is_test_py_step | |
| or step_json.get('testRunner', False)) | |
| self.isolate_hash = None | |
| self.fileset = step_json.get('fileset') | |
| self.shards = step_json.get('shards', 0) | |
| self.local_shard = (self.shards > 1 and index == len(config['steps']) - 1 | |
| and not environment['system'] == 'android') | |
| self.environment_variables = step_json.get('environment', {}) | |
| channel = m.dart._channel() | |
| self.environment_variables['BUILDBOT_BUILDERNAME'] = ( | |
| builder_name + "-%s" % channel) | |
| if self.m.runtime.is_experimental: | |
| self.environment_variables['DART_EXPERIMENTAL_BUILD'] = '1' | |
| # Enable Crashpad integration if a Windows bot wants to copy coredumps. | |
| if self.environment['copy-coredumps'] and self.m.platform.name == 'win': | |
| self.environment_variables['DART_USE_CRASHPAD'] = '1' | |
| def _expand_environment(arg): | |
| for k, v in environment.items(): | |
| arg = arg.replace('${%s}' % k, str(v)) | |
| return arg | |
| self.script = _expand_environment(self.script) | |
| self.args = [_expand_environment(arg) for arg in self.args] | |
| def platform_to_os(self, platform): | |
| return { | |
| 'mac': 'macos', | |
| 'win': 'windows', | |
| }.get(platform, platform) | |
| def platform_to_cipd_os(self, platform): | |
| return { | |
| 'win': 'windows', | |
| }.get(platform, platform) | |
| def os_to_cipd_os(self, platform): | |
| return { | |
| 'macos': 'mac', | |
| }.get(platform, platform) | |
| def arch_to_cipd_arch(self, arch): | |
| return { | |
| 'ia32': '386', | |
| 'x64': 'amd64', | |
| 'arm': 'armv6l', | |
| }.get(arch, arch) | |
| def is_version(self, version): | |
| return re.match(SEMANTIC_VERSION_PATTERN, version) | |
| @total_ordering | |
| class Version: | |
| MAIN_CHANNELS = ['main', 'be'] | |
| @property | |
| def channel(self): | |
| return self.fields['CHANNEL'] | |
| @property | |
| def major(self): | |
| return self.fields['MAJOR'] | |
| @property | |
| def minor(self): | |
| return self.fields['MINOR'] | |
| @property | |
| def patch(self): | |
| return self.fields['PATCH'] | |
| @property | |
| def prerelease(self): | |
| return self.fields['PRERELEASE'] | |
| @property | |
| def prerelease_patch(self): | |
| return self.fields['PRERELEASE_PATCH'] | |
| def __init__(self, version=None, text=None, git_revision=None): | |
| self.fields = {} | |
| self.text = None | |
| self.git_revision = git_revision | |
| if version: | |
| self.set_version(version) | |
| elif text: | |
| self.set_text(text) | |
| def set_text(self, text): | |
| self.fields = {} | |
| self.text = text | |
| for line in self.text.splitlines(): | |
| if not line or line.startswith('#'): | |
| continue | |
| field, value = line.split(' ') | |
| self.fields[field] = value | |
| def set_version(self, version): | |
| match = re.match(SEMANTIC_VERSION_PATTERN, version) | |
| assert match, '%s must be a valid version' % version | |
| self.fields = { | |
| 'CHANNEL': 'stable', | |
| 'MAJOR': match['major'], | |
| 'MINOR': match['minor'], | |
| 'PATCH': match['patch'], | |
| 'PRERELEASE': '0', | |
| 'PRERELEASE_PATCH': '0' | |
| } | |
| if match['prerelease']: | |
| subversions = match['prerelease'].split('.') | |
| self.fields['PRERELEASE'] = subversions[0] | |
| self.fields['PRERELEASE_PATCH'] = subversions[1] | |
| self.fields['CHANNEL'] = subversions[2] | |
| if self.text != None: | |
| self.update_text() | |
| def update_text(self): | |
| updated_lines = [] | |
| for line in self.text.splitlines(): | |
| if line.startswith('#') or not line: | |
| updated_lines.append(line) | |
| else: | |
| field, _ = line.split(' ') | |
| if field in self.fields: | |
| updated_lines.append('%s %s' % (field, self.fields[field])) | |
| else: | |
| updated_lines.append(line) | |
| self.text = _to_lines(updated_lines) | |
| def __str__(self): | |
| result = f'{self.major}.{self.minor}.{self.patch}' | |
| if self.channel in self.MAIN_CHANNELS: | |
| result += f'-edge.{self.git_revision}' if self.git_revision else '-edge' | |
| elif self.channel != 'stable': | |
| result += f'-{self.prerelease}.{self.prerelease_patch}.{self.channel}' | |
| return result | |
| def __eq__(self, other): | |
| for key in [ | |
| 'MAJOR', 'MINOR', 'PATCH', 'PRERELEASE', 'PRERELEASE_PATCH', 'CHANNEL' | |
| ]: | |
| if self.fields[key] != other.fields[key]: | |
| return False | |
| return True | |
| def __lt__(self, other): | |
| for key in ['MAJOR', 'MINOR', 'PATCH']: | |
| if int(self.fields[key]) < int(other.fields[key]): | |
| return True | |
| if int(self.fields[key]) > int(other.fields[key]): | |
| return False | |
| # The stable channel is ahead of the other channels on the same triplet. | |
| if self.fields['CHANNEL'] != 'stable' and other.fields[ | |
| 'CHANNEL'] == 'stable': | |
| return True | |
| if self.fields[ | |
| 'CHANNEL'] == 'stable' and other.fields['CHANNEL'] != 'stable': | |
| return False | |
| # The main channel is ahead of the other channels on the same triplet. | |
| if self.fields['CHANNEL'] not in self.MAIN_CHANNELS and \ | |
| other.fields['CHANNEL'] in self.MAIN_CHANNELS: | |
| return True | |
| if self.fields['CHANNEL'] in self.MAIN_CHANNELS and \ | |
| other.fields['CHANNEL'] not in self.MAIN_CHANNELS: | |
| return False | |
| for key in ['PRERELEASE', 'PRERELEASE_PATCH']: | |
| if int(self.fields[key]) < int(other.fields[key]): | |
| return True | |
| if int(self.fields[key]) > int(other.fields[key]): | |
| return False | |
| return False | |
| def parse_pubspec_sdk(self, pubspec): | |
| return re.search(SDK_PATTERN, pubspec, flags=re.MULTILINE).group('sdk') | |
| def download_dart_sdk(self, | |
| pubspec_path, | |
| pubspec_name='pubspec.yaml', | |
| cipd_platform='${platform}'): | |
| pubspec = self.m.file.read_text( | |
| f'read {pubspec_name}', pubspec_path, test_data=' sdk: 1.2.3') | |
| version = self.parse_pubspec_sdk(pubspec) | |
| dart_sdk_path = self.m.path.cache_dir / 'dart-sdk' | |
| ensure_file = self.m.cipd.EnsureFile() | |
| ensure_file.add_package(f'dart/dart-sdk/{cipd_platform}', | |
| f'version:{version}') | |
| self.m.cipd.ensure(dart_sdk_path, ensure_file) | |
| return dart_sdk_path / 'bin/dart' | |
| def download_and_verify(self, | |
| name, | |
| bucket, | |
| object, | |
| file, | |
| resource, | |
| host='bcidsoftwareverifier-pa', | |
| provenance_object=None, | |
| provenance_file=None, | |
| dry_run=False, | |
| no_verify=False): | |
| self.m.gsutil.download( | |
| bucket, object, file, name=f'download {name}', dry_run=dry_run) | |
| if provenance_object == None: | |
| provenance_object = f'{object}.intoto.jsonl' | |
| if provenance_file == None: | |
| provenance_file = f'{file}.intoto.jsonl' | |
| if not no_verify: | |
| self.m.gsutil.download( | |
| bucket, | |
| provenance_object, | |
| provenance_file, | |
| name=f'download {name} provenance', | |
| dry_run=dry_run) | |
| if not dry_run: | |
| return self.verify_provenance(name, file, resource, host=host) | |
| def verify_provenance(self, | |
| name, | |
| file, | |
| resource, | |
| host='bcidsoftwareverifier-pa'): | |
| provenance_file = f'{file}.intoto.jsonl' | |
| url = f'https://{host}.googleapis.com' \ | |
| '/v1/software-artifact-verification-requests' | |
| token = self.m.service_account.default().get_access_token([ | |
| 'https://www.googleapis.com/auth/bcid_verify', | |
| 'https://www.googleapis.com/auth/cloud-platform' | |
| ]) | |
| sha256 = self.m.file.file_hash(file) | |
| attestation = self.m.file.read_text(f'read {name} provenance', | |
| provenance_file) | |
| request = json.dumps({ | |
| 'resourceToVerify': resource, | |
| 'artifactInfo': { | |
| 'digests': { | |
| 'sha256': sha256, | |
| }, | |
| 'attestations': [attestation], | |
| }, | |
| }) | |
| authorization_file = self.m.path.cleanup_dir / 'authorization' | |
| request_file = self.m.path.cleanup_dir / 'request' | |
| try: | |
| self.m.file.write_text( | |
| 'write authorization', | |
| authorization_file, | |
| f'Authorization: Bearer {token}\n', | |
| include_log=False) | |
| self.m.file.write_text('write request', request_file, request) | |
| response_text = self.m.step( | |
| f'verify {name} provenance', [ | |
| 'curl', '-H', f'@{authorization_file}', '-H', | |
| 'Content-Type: application/json', '-d', f'@{request_file}', url | |
| ], | |
| stdout=self.m.raw_io.output_text(add_output_log=True)).stdout | |
| try: | |
| response = json.loads(response_text) | |
| if not 'allowed' in response or response['allowed'] != True: | |
| rejection = response['rejectionMessage'] | |
| message = f'{name} provenance rejected: {rejection}' | |
| self.m.step.empty(message, status=self.m.step.FAILURE) | |
| return response | |
| except json.JSONDecodeError: | |
| self.m.step.empty( | |
| 'Provenance verification API failed', | |
| status=self.m.step.INFRA_FAILURE) | |
| finally: | |
| self.m.file.remove('delete authorization', authorization_file) | |
| self.m.file.remove('delete request', request_file) | |
| class StepResults: | |
| def __init__(self, m): | |
| self.logs = '' | |
| self.results = '' | |
| self.failed = False | |
| self.builder_name = str(m.buildbucket.builder_name) # Returned as unicode | |
| self.build_number = str(m.buildbucket.build.number) | |
| def add_results(self, bot_name, results_str): | |
| extra = ',"bot_name":"%s"}\n' % bot_name | |
| all_matches = re.finditer(r'(^{.*)(?:})', results_str, flags=re.MULTILINE) | |
| all_chunks = (chunk for match in all_matches for chunk in ( | |
| match.group(1), extra)) | |
| self.results += ''.join(all_chunks) | |
| class Results: | |
| def __init__(self): | |
| self.results = '' | |
| self.logs = '' | |
| self.flaky_json = '' | |
| self.new_failures = False | |
| self.active_failures = '' | |
| self.results_by_configuration = {} | |
| def _split_by_configuration(records): | |
| split = {} | |
| if records: | |
| for line in records.split('\n'): | |
| if line: | |
| split.setdefault(json.loads(line)['configuration'], []).append(line) | |
| return split |