1#!/usr/bin/env python3 2# Copyright 2022 The Chromium Authors 3# Use of this source code is governed by a BSD-style license that can be 4# found in the LICENSE file. 5"""Check out the Fuchsia SDK from a given GCS path. Should be used in a 6'hooks_os' entry so that it only runs when .gclient's custom_vars includes 7'fuchsia'.""" 8 9import argparse 10import json 11import logging 12import os 13import platform 14import subprocess 15import sys 16from typing import Optional 17 18from gcs_download import DownloadAndUnpackFromCloudStorage 19 20sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 21 'test'))) 22 23from common import SDK_ROOT, get_host_os, make_clean_directory 24 25_VERSION_FILE = os.path.join(SDK_ROOT, 'meta', 'manifest.json') 26 27 28def _GetHostArch(): 29 host_arch = platform.machine() 30 # platform.machine() returns AMD64 on 64-bit Windows. 31 if host_arch in ['x86_64', 'AMD64']: 32 return 'amd64' 33 elif host_arch == 'aarch64': 34 return 'arm64' 35 raise Exception('Unsupported host architecture: %s' % host_arch) 36 37 38def GetSDKOverrideGCSPath() -> Optional[str]: 39 """Fetches the sdk override path from a file or an environment variable. 40 41 Returns: 42 The override sdk location, stripped of white space. 43 Example: gs://fuchsia-artifacts/development/some-id/sdk 44 """ 45 if os.getenv('FUCHSIA_SDK_OVERRIDE'): 46 return os.environ['FUCHSIA_SDK_OVERRIDE'].strip() 47 48 path = os.path.join(os.path.dirname(__file__), 'sdk_override.txt') 49 50 if os.path.isfile(path): 51 with open(path, 'r') as f: 52 return f.read().strip() 53 54 return None 55 56 57def _GetCurrentVersionFromManifest() -> Optional[str]: 58 if not os.path.exists(_VERSION_FILE): 59 return None 60 with open(_VERSION_FILE) as f: 61 return json.load(f)['id'] 62 63 64def main(): 65 parser = argparse.ArgumentParser() 66 parser.add_argument('--cipd-prefix', help='CIPD base directory for the SDK.') 67 parser.add_argument('--version', help='Specifies the SDK version.') 68 parser.add_argument('--verbose', 69 '-v', 70 action='store_true', 71 help='Enable debug-level logging.') 72 parser.add_argument( 73 '--file', 74 help='Specifies the sdk tar.gz file name without .tar.gz suffix', 75 default='core') 76 args = parser.parse_args() 77 78 logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO) 79 80 # Exit if there's no SDK support for this platform. 81 try: 82 host_plat = get_host_os() 83 except: 84 logging.warning('Fuchsia SDK is not supported on this platform.') 85 return 0 86 87 # TODO(crbug.com/326004432): Remove this once DEPS have been fixed not to 88 # include the "version:" prefix. 89 if args.version.startswith('version:'): 90 args.version = args.version[len('version:'):] 91 92 gcs_tarball_prefix = GetSDKOverrideGCSPath() 93 if not gcs_tarball_prefix: 94 # sdk_override contains the full path but not only the version id. But since 95 # the scenario is limited to dry-run, it's not worth complexity to extract 96 # the version id. 97 if args.version == _GetCurrentVersionFromManifest(): 98 return 0 99 100 make_clean_directory(SDK_ROOT) 101 102 # Download from CIPD if there is no override file. 103 if not gcs_tarball_prefix: 104 if not args.cipd_prefix: 105 parser.exit(1, '--cipd-prefix must be specified.') 106 if not args.version: 107 parser.exit(2, '--version must be specified.') 108 logging.info('Downloading SDK from CIPD...') 109 ensure_file = '%s%s-%s version:%s' % (args.cipd_prefix, host_plat, 110 _GetHostArch(), args.version) 111 subprocess.run(('cipd', 'ensure', '-ensure-file', '-', '-root', SDK_ROOT, 112 '-log-level', 'warning'), 113 check=True, 114 text=True, 115 input=ensure_file) 116 117 # Verify that the downloaded version matches the expected one. 118 downloaded_version = _GetCurrentVersionFromManifest() 119 if downloaded_version != args.version: 120 logging.error( 121 'SDK version after download does not match expected (downloaded:%s ' 122 'vs expected:%s)', downloaded_version, args.version) 123 return 3 124 else: 125 logging.info('Downloading SDK from GCS...') 126 DownloadAndUnpackFromCloudStorage( 127 f'{gcs_tarball_prefix}/{get_host_os()}-{_GetHostArch()}/' 128 f'{args.file}.tar.gz', SDK_ROOT) 129 130 # Build rules (e.g. fidl_library()) depend on updates to the top-level 131 # manifest to spot when to rebuild for an SDK update. Ensure that ninja 132 # sees that the SDK manifest has changed, regardless of the mtime set by 133 # the download & unpack steps above, by setting mtime to now. 134 # See crbug.com/1457463 135 os.utime(os.path.join(SDK_ROOT, 'meta', 'manifest.json'), None) 136 137 root_dir = os.path.dirname(os.path.realpath(__file__)) 138 build_def_cmd = [ 139 os.path.join(root_dir, 'gen_build_defs.py'), 140 ] 141 subprocess.run(build_def_cmd, check=True) 142 143 return 0 144 145 146if __name__ == '__main__': 147 sys.exit(main()) 148