blob: e68d28f5ab564d80920c561b6a30c12878924e81 [file] [log] [blame]
nodirbe642ff2016-06-09 15:51:51 -07001# Copyright 2016 The LUCI Authors. All rights reserved.
2# Use of this source code is governed under the Apache License, Version 2.0
3# that can be found in the LICENSE file.
4
5"""Fetches CIPD client and installs packages."""
6
nodirbe642ff2016-06-09 15:51:51 -07007import contextlib
8import hashlib
iannucci96fcccc2016-08-30 15:52:22 -07009import json
nodirbe642ff2016-06-09 15:51:51 -070010import logging
11import optparse
12import os
13import platform
Takuto Ikuta62cdb322021-11-17 00:47:55 +000014import re
15import shutil
nodirbe642ff2016-06-09 15:51:51 -070016import sys
17import tempfile
18import time
Junji Watanabe7a677e92022-01-13 06:07:31 +000019import urllib.parse
nodirbe642ff2016-06-09 15:51:51 -070020
21from utils import file_path
22from utils import fs
23from utils import net
24from utils import subprocess42
25from utils import tools
Marc-Antoine Ruel34f5f282018-05-16 16:04:31 -040026
Justin Luong97eda6f2022-08-23 01:29:16 +000027import errors
Marc-Antoine Ruel34f5f282018-05-16 16:04:31 -040028import local_caching
nodirbe642ff2016-06-09 15:51:51 -070029
30
31# .exe on Windows.
32EXECUTABLE_SUFFIX = '.exe' if sys.platform == 'win32' else ''
33
Junji Watanabe4b890ef2020-09-16 01:43:27 +000034_DEFAULT_CIPD_SERVER = 'https://chrome-infra-packages.appspot.com'
35
36_DEFAULT_CIPD_CLIENT_PACKAGE = 'infra/tools/cipd/${platform}'
37
38_DEFAULT_CIPD_CLIENT_VERSION = 'latest'
nodirbe642ff2016-06-09 15:51:51 -070039
iannucci4d7792a2017-03-10 10:30:56 -080040if sys.platform == 'win32':
Junji Watanabe38b28b02020-04-23 10:23:30 +000041
iannucci4d7792a2017-03-10 10:30:56 -080042 def _ensure_batfile(client_path):
43 base, _ = os.path.splitext(client_path)
Junji Watanabe38b28b02020-04-23 10:23:30 +000044 with open(base + ".bat", 'w') as f:
iannucci4d7792a2017-03-10 10:30:56 -080045 f.write('\n'.join([ # python turns \n into CRLF
Junji Watanabe38b28b02020-04-23 10:23:30 +000046 '@set CIPD="%~dp0cipd.exe"', '@shift', '@%CIPD% %*'
iannucci4d7792a2017-03-10 10:30:56 -080047 ]))
48else:
49 def _ensure_batfile(_client_path):
50 pass
51
52
nodirbe642ff2016-06-09 15:51:51 -070053class Error(Exception):
54 """Raised on CIPD errors."""
55
56
57def add_cipd_options(parser):
58 group = optparse.OptionGroup(parser, 'CIPD')
59 group.add_option(
vadimsh902948e2017-01-20 15:57:32 -080060 '--cipd-enabled',
Ye Kuangfff1e502020-07-13 13:21:57 +000061 help='Enable CIPD client bootstrap. Implied by --cipd-package. Cannot '
62 'turn this off while specifying --cipd-package',
63 default=True)
vadimsh902948e2017-01-20 15:57:32 -080064 group.add_option(
nodirbe642ff2016-06-09 15:51:51 -070065 '--cipd-server',
vadimsh902948e2017-01-20 15:57:32 -080066 help='URL of the CIPD server. '
Ye Kuang0a128a82020-06-26 08:57:31 +000067 'Only relevant with --cipd-enabled or --cipd-package.',
Junji Watanabe4b890ef2020-09-16 01:43:27 +000068 default=_DEFAULT_CIPD_SERVER)
nodirbe642ff2016-06-09 15:51:51 -070069 group.add_option(
70 '--cipd-client-package',
nodir90bc8dc2016-06-15 13:35:21 -070071 help='Package name of CIPD client with optional parameters described in '
Junji Watanabe38b28b02020-04-23 10:23:30 +000072 '--cipd-package help. '
73 'Only relevant with --cipd-enabled or --cipd-package. '
74 'Default: "%default"',
Junji Watanabe4b890ef2020-09-16 01:43:27 +000075 default=_DEFAULT_CIPD_CLIENT_PACKAGE)
nodirbe642ff2016-06-09 15:51:51 -070076 group.add_option(
nodir90bc8dc2016-06-15 13:35:21 -070077 '--cipd-client-version',
78 help='Version of CIPD client. '
Junji Watanabe38b28b02020-04-23 10:23:30 +000079 'Only relevant with --cipd-enabled or --cipd-package. '
80 'Default: "%default"',
Junji Watanabe4b890ef2020-09-16 01:43:27 +000081 default=_DEFAULT_CIPD_CLIENT_VERSION)
nodir90bc8dc2016-06-15 13:35:21 -070082 group.add_option(
nodirff531b42016-06-23 13:05:06 -070083 '--cipd-package',
84 dest='cipd_packages',
85 help='A CIPD package to install. '
Junji Watanabe38b28b02020-04-23 10:23:30 +000086 'Format is "<path>:<package_name>:<version>". '
87 '"path" is installation directory relative to run_dir, '
88 'defaults to ".". '
89 '"package_name" may have ${platform} parameter: it will be '
90 'expanded to "<os>-<architecture>". '
91 'The option can be specified multiple times.',
nodirff531b42016-06-23 13:05:06 -070092 action='append',
93 default=[])
nodirbe642ff2016-06-09 15:51:51 -070094 group.add_option(
95 '--cipd-cache',
96 help='CIPD cache directory, separate from isolate cache. '
Junji Watanabe38b28b02020-04-23 10:23:30 +000097 'Only relevant with --cipd-enabled or --cipd-package. '
Vadim Shtayura087aab72023-01-13 00:38:11 +000098 'Default: "%default".',
nodirbe642ff2016-06-09 15:51:51 -070099 default='')
100 parser.add_option_group(group)
101
102
103def validate_cipd_options(parser, options):
104 """Calls parser.error on first found error among cipd options."""
vadimsh902948e2017-01-20 15:57:32 -0800105 if not options.cipd_enabled:
Ye Kuangfff1e502020-07-13 13:21:57 +0000106 if options.cipd_packages:
107 parser.error('Cannot install CIPD packages when --cipd-enable=false')
nodirbe642ff2016-06-09 15:51:51 -0700108 return
nodirff531b42016-06-23 13:05:06 -0700109
110 for pkg in options.cipd_packages:
111 parts = pkg.split(':', 2)
112 if len(parts) != 3:
113 parser.error('invalid package "%s": must have at least 2 colons' % pkg)
114 _path, name, version = parts
115 if not name:
116 parser.error('invalid package "%s": package name is not specified' % pkg)
117 if not version:
118 parser.error('invalid package "%s": version is not specified' % pkg)
119
nodirbe642ff2016-06-09 15:51:51 -0700120 if not options.cipd_server:
vadimsh902948e2017-01-20 15:57:32 -0800121 parser.error('cipd is enabled, --cipd-server is required')
nodirbe642ff2016-06-09 15:51:51 -0700122
123 if not options.cipd_client_package:
nodirbe642ff2016-06-09 15:51:51 -0700124 parser.error(
vadimsh902948e2017-01-20 15:57:32 -0800125 'cipd is enabled, --cipd-client-package is required')
nodir90bc8dc2016-06-15 13:35:21 -0700126 if not options.cipd_client_version:
127 parser.error(
vadimsh902948e2017-01-20 15:57:32 -0800128 'cipd is enabled, --cipd-client-version is required')
nodirbe642ff2016-06-09 15:51:51 -0700129
130
Junji Watanabeab2102a2022-01-12 01:44:04 +0000131class CipdClient:
nodirbe642ff2016-06-09 15:51:51 -0700132 """Installs packages."""
133
iannucci96fcccc2016-08-30 15:52:22 -0700134 def __init__(self, binary_path, package_name, instance_id, service_url):
nodirbe642ff2016-06-09 15:51:51 -0700135 """Initializes CipdClient.
136
137 Args:
138 binary_path (str): path to the CIPD client binary.
iannucci96fcccc2016-08-30 15:52:22 -0700139 package_name (str): the CIPD package name for the client itself.
140 instance_id (str): the CIPD instance_id for the client itself.
nodirbe642ff2016-06-09 15:51:51 -0700141 service_url (str): if not None, URL of the CIPD backend that overrides
142 the default one.
143 """
144 self.binary_path = binary_path
iannucci96fcccc2016-08-30 15:52:22 -0700145 self.package_name = package_name
146 self.instance_id = instance_id
nodirbe642ff2016-06-09 15:51:51 -0700147 self.service_url = service_url
148
Junji Watanabe38b28b02020-04-23 10:23:30 +0000149 def ensure(self,
150 site_root,
151 packages,
152 cache_dir=None,
153 tmp_dir=None,
154 timeout=None):
nodirbe642ff2016-06-09 15:51:51 -0700155 """Ensures that packages installed in |site_root| equals |packages| set.
156
157 Blocking call.
158
159 Args:
160 site_root (str): where to install packages.
iannuccib58d10d2017-03-18 02:00:25 -0700161 packages: dict of subdir -> list of (package_template, version) tuples.
nodirbe642ff2016-06-09 15:51:51 -0700162 cache_dir (str): if set, cache dir for cipd binary own cache.
163 Typically contains packages and tags.
164 tmp_dir (str): if not None, dir for temp files.
165 timeout (int): if not None, timeout in seconds for this function to run.
166
iannucci96fcccc2016-08-30 15:52:22 -0700167 Returns:
iannuccib58d10d2017-03-18 02:00:25 -0700168 Pinned packages in the form of {subdir: [(package_name, package_id)]},
169 which correspond 1:1 with the input packages argument.
iannucci96fcccc2016-08-30 15:52:22 -0700170
nodirbe642ff2016-06-09 15:51:51 -0700171 Raises:
172 Error if could not install packages or timed out.
173 """
174 timeoutfn = tools.sliding_timeout(timeout)
175 logging.info('Installing packages %r into %s', packages, site_root)
176
iannuccib58d10d2017-03-18 02:00:25 -0700177 ensure_file_handle, ensure_file_path = tempfile.mkstemp(
Junji Watanabe53d31882022-01-13 07:58:00 +0000178 dir=tmp_dir, prefix='cipd-ensure-file-', suffix='.txt')
iannucci96fcccc2016-08-30 15:52:22 -0700179 json_out_file_handle, json_file_path = tempfile.mkstemp(
Junji Watanabe53d31882022-01-13 07:58:00 +0000180 dir=tmp_dir, prefix='cipd-ensure-result-', suffix='.json')
iannucci96fcccc2016-08-30 15:52:22 -0700181 os.close(json_out_file_handle)
182
nodirbe642ff2016-06-09 15:51:51 -0700183 try:
184 try:
Marc-Antoine Ruel04903a32019-10-09 21:09:25 +0000185 for subdir, pkgs in sorted(packages.items()):
iannuccib58d10d2017-03-18 02:00:25 -0700186 if '\n' in subdir:
Junji Watanabe38b28b02020-04-23 10:23:30 +0000187 raise Error('Could not install packages; subdir %r contains newline'
188 % subdir)
tikutaddc3ccb2020-07-07 12:36:39 +0000189 os.write(ensure_file_handle, ('@Subdir %s\n' % (subdir,)).encode())
iannuccib58d10d2017-03-18 02:00:25 -0700190 for pkg, version in pkgs:
tikutaddc3ccb2020-07-07 12:36:39 +0000191 os.write(ensure_file_handle, ('%s %s\n' % (pkg, version)).encode())
nodirbe642ff2016-06-09 15:51:51 -0700192 finally:
iannuccib58d10d2017-03-18 02:00:25 -0700193 os.close(ensure_file_handle)
nodirbe642ff2016-06-09 15:51:51 -0700194
195 cmd = [
Junji Watanabe38b28b02020-04-23 10:23:30 +0000196 self.binary_path,
197 'ensure',
198 '-root',
199 site_root,
200 '-ensure-file',
201 ensure_file_path,
202 '-verbose', # this is safe because cipd-ensure does not print a lot
203 '-json-output',
204 json_file_path,
nodirbe642ff2016-06-09 15:51:51 -0700205 ]
206 if cache_dir:
207 cmd += ['-cache-dir', cache_dir]
208 if self.service_url:
209 cmd += ['-service-url', self.service_url]
210
211 logging.debug('Running %r', cmd)
Junji Watanabe88647c62021-05-11 03:41:10 +0000212 kwargs = {}
Junji Watanabe7a677e92022-01-13 06:07:31 +0000213 kwargs['encoding'] = 'utf-8'
214 kwargs['errors'] = 'backslashreplace'
nodirbe642ff2016-06-09 15:51:51 -0700215 process = subprocess42.Popen(
Junji Watanabebc5a7b62021-04-23 08:40:11 +0000216 cmd,
217 stdout=subprocess42.PIPE,
218 stderr=subprocess42.PIPE,
Junji Watanabe88647c62021-05-11 03:41:10 +0000219 universal_newlines=True,
220 **kwargs)
nodirbe642ff2016-06-09 15:51:51 -0700221 output = []
222 for pipe_name, line in process.yield_any_line(timeout=0.1):
223 to = timeoutfn()
224 if to is not None and to <= 0:
225 raise Error(
226 'Could not install packages; took more than %d seconds' % timeout)
227 if not pipe_name:
228 # stdout or stderr was closed, but yield_any_line still may have
229 # something to yield.
230 continue
231 output.append(line)
232 if pipe_name == 'stderr':
233 logging.debug('cipd client: %s', line)
234 else:
235 logging.info('cipd client: %s', line)
236
237 exit_code = process.wait(timeout=timeoutfn())
Justin Luong97eda6f2022-08-23 01:29:16 +0000238
239 ensure_result = {}
240 if os.path.exists(json_file_path):
241 with open(json_file_path) as jfile:
242 result_json = json.load(jfile)
243 ensure_result = result_json['result']
244 status = result_json.get('error_code')
245 if status in ('auth_error', 'bad_argument_error',
246 'invalid_version_error', 'stale_error',
247 'hash_mismatch_error'):
248 details = result_json.get('error_details')
249 cipd_package = cipd_version = cipd_subdir = None
250 if details:
251 cipd_package = details.get('package')
252 cipd_version = details.get('version')
253 cipd_subdir = details.get('subdir')
254 raise errors.NonRecoverableCipdException(status, cipd_package,
255 cipd_subdir, cipd_version)
256
nodirbe642ff2016-06-09 15:51:51 -0700257 if exit_code != 0:
258 raise Error(
259 'Could not install packages; exit code %d\noutput:%s' % (
260 exit_code, '\n'.join(output)))
iannuccib58d10d2017-03-18 02:00:25 -0700261 return {
Justin Luong97eda6f2022-08-23 01:29:16 +0000262 subdir: [(x['package'], x['instance_id']) for x in pins]
263 for subdir, pins in ensure_result.items()
iannuccib58d10d2017-03-18 02:00:25 -0700264 }
nodirbe642ff2016-06-09 15:51:51 -0700265 finally:
iannuccib58d10d2017-03-18 02:00:25 -0700266 fs.remove(ensure_file_path)
iannucci96fcccc2016-08-30 15:52:22 -0700267 fs.remove(json_file_path)
nodirbe642ff2016-06-09 15:51:51 -0700268
269
270def get_platform():
271 """Returns ${platform} parameter value.
272
Vadim Shtayura8f863a42017-10-18 19:23:15 -0700273 The logic is similar to
274 https://chromium.googlesource.com/chromium/tools/build/+/6c5c7e9c/scripts/slave/infra_platform.py
nodirbe642ff2016-06-09 15:51:51 -0700275 """
276 # linux, mac or windows.
Vadim Shtayura8f863a42017-10-18 19:23:15 -0700277 os_name = {
Takuto Ikuta41504032019-10-29 12:23:57 +0000278 'darwin': 'mac',
Takuto Ikuta41504032019-10-29 12:23:57 +0000279 'linux': 'linux',
280 'win32': 'windows',
nodirbe642ff2016-06-09 15:51:51 -0700281 }.get(sys.platform)
Vadim Shtayura8f863a42017-10-18 19:23:15 -0700282 if not os_name:
nodirbe642ff2016-06-09 15:51:51 -0700283 raise Error('Unknown OS: %s' % sys.platform)
284
Vadim Shtayura8f863a42017-10-18 19:23:15 -0700285 # Normalize machine architecture. Some architectures are identical or
286 # compatible with others. We collapse them into one.
287 arch = platform.machine().lower()
Junji Watanabe7b0cb6c2021-10-28 08:42:31 +0000288 if arch in ('arm64', 'aarch64'):
Vadim Shtayura8f863a42017-10-18 19:23:15 -0700289 arch = 'arm64'
290 elif arch.startswith('armv') and arch.endswith('l'):
291 # 32-bit ARM: Standardize on ARM v6 baseline.
292 arch = 'armv6l'
293 elif arch in ('amd64', 'x86_64'):
294 arch = 'amd64'
Vadim Shtayura5059a052017-10-19 13:04:50 -0700295 elif arch in ('i386', 'i686', 'x86'):
Vadim Shtayura8f863a42017-10-18 19:23:15 -0700296 arch = '386'
Junji Watanabe41a770c2021-07-26 23:44:54 +0000297 elif not arch and os_name == 'windows':
298 # On some 32bit Windows7, platform.machine() returns None.
299 # Fallback to 386 in that case.
300 logging.warning('platform.machine() returns None. '
301 'Use \'386\' as CPU architecture.')
302 arch = '386'
nodirbe642ff2016-06-09 15:51:51 -0700303
Vadim Shtayura8f863a42017-10-18 19:23:15 -0700304 # If using a 32-bit python on x86_64 kernel on Linux, "downgrade" the arch to
305 # 32-bit too (this is the bitness of the userland).
306 python_bits = 64 if sys.maxsize > 2**32 else 32
307 if os_name == 'linux' and arch == 'amd64' and python_bits == 32:
308 arch = '386'
nodirbe642ff2016-06-09 15:51:51 -0700309
Vadim Shtayura8f863a42017-10-18 19:23:15 -0700310 return '%s-%s' % (os_name, arch)
nodirbe642ff2016-06-09 15:51:51 -0700311
312
nodirbe642ff2016-06-09 15:51:51 -0700313def _check_response(res, fmt, *args):
314 """Raises Error if response is bad."""
315 if not res:
316 raise Error('%s: no response' % (fmt % args))
317
318 if res.get('status') != 'SUCCESS':
Junji Watanabe38b28b02020-04-23 10:23:30 +0000319 raise Error('%s: %s' % (fmt % args, res.get('error_message') or
320 'status is %s' % res.get('status')))
nodirbe642ff2016-06-09 15:51:51 -0700321
322
323def resolve_version(cipd_server, package_name, version, timeout=None):
324 """Resolves a package instance version (e.g. a tag) to an instance id."""
325 url = '%s/_ah/api/repo/v1/instance/resolve?%s' % (
326 cipd_server,
Marc-Antoine Ruelad8cabe2019-10-10 23:24:26 +0000327 urllib.parse.urlencode({
328 'package_name': package_name,
329 'version': version,
nodirbe642ff2016-06-09 15:51:51 -0700330 }))
331 res = net.url_read_json(url, timeout=timeout)
332 _check_response(res, 'Could not resolve version %s:%s', package_name, version)
333 instance_id = res.get('instance_id')
334 if not instance_id:
335 raise Error('Invalid resolveVersion response: no instance id')
336 return instance_id
337
338
339def get_client_fetch_url(service_url, package_name, instance_id, timeout=None):
340 """Returns a fetch URL of CIPD client binary contents.
341
342 Raises:
343 Error if cannot retrieve fetch URL.
344 """
345 # Fetch the URL of the binary from CIPD backend.
Marc-Antoine Ruelad8cabe2019-10-10 23:24:26 +0000346 url = '%s/_ah/api/repo/v1/client?%s' % (service_url,
347 urllib.parse.urlencode({
348 'package_name': package_name,
349 'instance_id': instance_id,
350 }))
nodirbe642ff2016-06-09 15:51:51 -0700351 res = net.url_read_json(url, timeout=timeout)
Junji Watanabe38b28b02020-04-23 10:23:30 +0000352 _check_response(res, 'Could not fetch CIPD client %s:%s', package_name,
353 instance_id)
nodirbe642ff2016-06-09 15:51:51 -0700354 fetch_url = res.get('client_binary', {}).get('fetch_url')
355 if not fetch_url:
356 raise Error('Invalid fetchClientBinary response: no fetch_url')
357 return fetch_url
358
359
360def _fetch_cipd_client(disk_cache, instance_id, fetch_url, timeoutfn):
361 """Fetches cipd binary to |disk_cache|.
362
363 Retries requests with exponential back-off.
364
365 Raises:
366 Error if could not fetch content.
367 """
368 sleep_time = 1
Marc-Antoine Ruel0fdee222019-10-10 14:42:40 +0000369 for attempt in range(5):
nodirbe642ff2016-06-09 15:51:51 -0700370 if attempt > 0:
371 if timeoutfn() is not None and timeoutfn() < sleep_time:
372 raise Error('Could not fetch CIPD client: timeout')
373 logging.warning('Will retry to fetch CIPD client in %ds', sleep_time)
374 time.sleep(sleep_time)
375 sleep_time *= 2
376
377 try:
378 res = net.url_open(fetch_url, timeout=timeoutfn())
379 if res:
380 disk_cache.write(instance_id, res.iter_content(64 * 1024))
381 return
382 except net.TimeoutError as ex:
Junji Watanabeab2102a2022-01-12 01:44:04 +0000383 raise Error('Could not fetch CIPD client: %s' % ex)
nodirbe642ff2016-06-09 15:51:51 -0700384 except net.NetError as ex:
Junji Watanabe38b28b02020-04-23 10:23:30 +0000385 logging.warning('Could not fetch CIPD client on attempt #%d: %s',
386 attempt + 1, ex)
nodirbe642ff2016-06-09 15:51:51 -0700387
388 raise Error('Could not fetch CIPD client after 5 retries')
389
390
Takuto Ikuta62cdb322021-11-17 00:47:55 +0000391def _is_valid_hash(value):
392 """Returns if the value is a valid hash for the corresponding algorithm."""
393 size = 2 * hashlib.sha1().digest_size
394 return bool(re.match(r'^[a-fA-F0-9]{%d}$' % size, value))
395
396
nodirbe642ff2016-06-09 15:51:51 -0700397@contextlib.contextmanager
Junji Watanabe4b890ef2020-09-16 01:43:27 +0000398def get_client(cache_dir,
399 service_url=_DEFAULT_CIPD_SERVER,
400 package_template=_DEFAULT_CIPD_CLIENT_PACKAGE,
401 version=_DEFAULT_CIPD_CLIENT_VERSION,
402 timeout=None):
nodirbe642ff2016-06-09 15:51:51 -0700403 """Returns a context manager that yields a CipdClient. A blocking call.
404
vadimsh232f5a82017-01-20 19:23:44 -0800405 Upon exit from the context manager, the client binary may be deleted
406 (if the internal cache is full).
407
nodirbe642ff2016-06-09 15:51:51 -0700408 Args:
vadimsh232f5a82017-01-20 19:23:44 -0800409 service_url (str): URL of the CIPD backend.
Marc-Antoine Ruel6f348a22017-12-06 12:47:37 -0500410 package_template (str): package name template of the CIPD client.
vadimsh232f5a82017-01-20 19:23:44 -0800411 version (str): version of CIPD client package.
412 cache_dir: directory to store instance cache, version cache
413 and a hardlink to the client binary.
414 timeout (int): if not None, timeout in seconds for this function.
nodirbe642ff2016-06-09 15:51:51 -0700415
416 Yields:
417 CipdClient.
418
419 Raises:
420 Error if CIPD client version cannot be resolved or client cannot be fetched.
421 """
422 timeoutfn = tools.sliding_timeout(timeout)
423
Marc-Antoine Ruel6f348a22017-12-06 12:47:37 -0500424 # Package names are always lower case.
425 # TODO(maruel): Assert instead?
426 package_name = package_template.lower().replace('${platform}', get_platform())
nodirbe642ff2016-06-09 15:51:51 -0700427
428 # Resolve version to instance id.
429 # Is it an instance id already? They look like HEX SHA1.
Takuto Ikuta62cdb322021-11-17 00:47:55 +0000430 if _is_valid_hash(version):
nodirbe642ff2016-06-09 15:51:51 -0700431 instance_id = version
Vadim Shtayuraaaecc1c2017-10-19 11:36:42 -0700432 elif ':' in version: # it's an immutable tag, cache the resolved version
433 # version_cache is {hash(package_name, tag) -> instance id} mapping.
nodirbe642ff2016-06-09 15:51:51 -0700434 # It does not take a lot of disk space.
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400435 version_cache = local_caching.DiskContentAddressedCache(
Junji Watanabe7a677e92022-01-13 06:07:31 +0000436 os.path.join(cache_dir, 'versions'),
Marc-Antoine Ruel34f5f282018-05-16 16:04:31 -0400437 local_caching.CachePolicies(
Marc-Antoine Ruel77d93782018-05-24 16:13:55 -0400438 # 1GiB.
Takuto Ikuta6e2ff962019-10-29 12:35:27 +0000439 max_cache_size=1024 * 1024 * 1024,
Marc-Antoine Ruel34f5f282018-05-16 16:04:31 -0400440 min_free_space=0,
441 max_items=300,
442 # 3 weeks.
Takuto Ikuta6e2ff962019-10-29 12:35:27 +0000443 max_age_secs=21 * 24 * 60 * 60),
maruele6fc9382017-05-04 09:03:48 -0700444 trim=True)
Marc-Antoine Ruele79ddbf2018-06-13 18:33:07 +0000445 # Convert (package_name, version) to a string that may be used as a
446 # filename in disk cache by hashing it.
Takuto Ikuta922c8642021-11-18 07:42:16 +0000447 version_digest = hashlib.sha256(
Junji Watanabe7a677e92022-01-13 06:07:31 +0000448 ('%s\n%s' % (package_name, version)).encode()).hexdigest()
Marc-Antoine Ruele79ddbf2018-06-13 18:33:07 +0000449 try:
450 with version_cache.getfileobj(version_digest) as f:
Junji Watanabe7a677e92022-01-13 06:07:31 +0000451 instance_id = f.read().decode()
Takuto Ikutab70dd7f2021-09-06 09:42:53 +0000452 logging.info("instance_id %s", instance_id)
Marc-Antoine Ruele79ddbf2018-06-13 18:33:07 +0000453 except local_caching.CacheMiss:
Takuto Ikutab70dd7f2021-09-06 09:42:53 +0000454 logging.info("version_cache miss for %s", version_digest)
455 instance_id = ''
456
457 if not instance_id:
Marc-Antoine Ruele79ddbf2018-06-13 18:33:07 +0000458 instance_id = resolve_version(
459 service_url, package_name, version, timeout=timeoutfn())
Junji Watanabe7a677e92022-01-13 06:07:31 +0000460 version_cache.write(version_digest, [instance_id.encode()])
Marc-Antoine Ruele79ddbf2018-06-13 18:33:07 +0000461 version_cache.trim()
Vadim Shtayuraaaecc1c2017-10-19 11:36:42 -0700462 else: # it's a ref, hit the backend
iannucci6fd57d22016-08-30 17:02:20 -0700463 instance_id = resolve_version(
464 service_url, package_name, version, timeout=timeoutfn())
nodirbe642ff2016-06-09 15:51:51 -0700465
466 # instance_cache is {instance_id -> client binary} mapping.
467 # It is bounded by 5 client versions.
Marc-Antoine Ruel2666d9c2018-05-18 13:52:02 -0400468 instance_cache = local_caching.DiskContentAddressedCache(
Junji Watanabe7a677e92022-01-13 06:07:31 +0000469 os.path.join(cache_dir, 'clients'),
Takuto Ikuta6e2ff962019-10-29 12:35:27 +0000470 local_caching.CachePolicies(
471 # 1GiB.
472 max_cache_size=1024 * 1024 * 1024,
473 min_free_space=0,
474 max_items=10,
475 # 3 weeks.
476 max_age_secs=21 * 24 * 60 * 60),
maruele6fc9382017-05-04 09:03:48 -0700477 trim=True)
Marc-Antoine Ruele79ddbf2018-06-13 18:33:07 +0000478 if instance_id not in instance_cache:
479 logging.info('Fetching CIPD client %s:%s', package_name, instance_id)
480 fetch_url = get_client_fetch_url(
481 service_url, package_name, instance_id, timeout=timeoutfn())
482 _fetch_cipd_client(instance_cache, instance_id, fetch_url, timeoutfn)
nodirbe642ff2016-06-09 15:51:51 -0700483
Marc-Antoine Ruele79ddbf2018-06-13 18:33:07 +0000484 # A single host can run multiple swarming bots, but they cannot share same
485 # root bot directory. Thus, it is safe to use the same name for the binary.
Junji Watanabe7a677e92022-01-13 06:07:31 +0000486 cipd_bin_dir = os.path.join(cache_dir, 'bin')
Marc-Antoine Ruele79ddbf2018-06-13 18:33:07 +0000487 binary_path = os.path.join(cipd_bin_dir, 'cipd' + EXECUTABLE_SUFFIX)
488 if fs.isfile(binary_path):
489 # TODO(maruel): Do not unconditionally remove the binary.
Takuto Ikuta296ed052019-11-29 01:47:20 +0000490 try:
491 file_path.remove(binary_path)
492 except WindowsError: # pylint: disable=undefined-variable
493 # See whether cipd.exe is running for crbug.com/1028781
494 ret = subprocess42.call(['tasklist.exe'])
495 if ret:
496 logging.error('tasklist returns non-zero: %d', ret)
497 raise
Marc-Antoine Ruele79ddbf2018-06-13 18:33:07 +0000498 else:
499 file_path.ensure_tree(cipd_bin_dir)
tansell9e04a8d2016-07-28 09:31:59 -0700500
Takuto Ikuta62cdb322021-11-17 00:47:55 +0000501 with instance_cache.getfileobj(instance_id) as f, fs.open(binary_path,
502 'wb') as dest:
503 shutil.copyfileobj(f, dest)
504 fs.chmod(binary_path, 0o511) # -r-x--x--x
nodirbe642ff2016-06-09 15:51:51 -0700505
Marc-Antoine Ruele79ddbf2018-06-13 18:33:07 +0000506 _ensure_batfile(binary_path)
iannucci4d7792a2017-03-10 10:30:56 -0800507
Marc-Antoine Ruele79ddbf2018-06-13 18:33:07 +0000508 yield CipdClient(
509 binary_path,
510 package_name=package_name,
511 instance_id=instance_id,
512 service_url=service_url)
513 instance_cache.trim()
nodir90bc8dc2016-06-15 13:35:21 -0700514
515
nodirff531b42016-06-23 13:05:06 -0700516def parse_package_args(packages):
517 """Parses --cipd-package arguments.
nodir90bc8dc2016-06-15 13:35:21 -0700518
nodirff531b42016-06-23 13:05:06 -0700519 Assumes |packages| were validated by validate_cipd_options.
520
521 Returns:
iannucci96fcccc2016-08-30 15:52:22 -0700522 A list of [(path, package_name, version), ...]
nodir90bc8dc2016-06-15 13:35:21 -0700523 """
iannucci96fcccc2016-08-30 15:52:22 -0700524 result = []
nodirff531b42016-06-23 13:05:06 -0700525 for pkg in packages:
526 path, name, version = pkg.split(':', 2)
nodir90bc8dc2016-06-15 13:35:21 -0700527 if not name:
nodirff531b42016-06-23 13:05:06 -0700528 raise Error('Invalid package "%s": package name is not specified' % pkg)
nodir90bc8dc2016-06-15 13:35:21 -0700529 if not version:
nodirff531b42016-06-23 13:05:06 -0700530 raise Error('Invalid package "%s": version is not specified' % pkg)
iannucci96fcccc2016-08-30 15:52:22 -0700531 result.append((path, name, version))
nodirff531b42016-06-23 13:05:06 -0700532 return result