blob: 927ec594354790a93fbc22c418c1af17fda29daf [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
14import sys
15import tempfile
16import time
17import urllib
18
19from utils import file_path
20from utils import fs
21from utils import net
22from utils import subprocess42
23from utils import tools
24import isolated_format
25import isolateserver
26
27
28# .exe on Windows.
29EXECUTABLE_SUFFIX = '.exe' if sys.platform == 'win32' else ''
30
31
iannucci4d7792a2017-03-10 10:30:56 -080032if sys.platform == 'win32':
33 def _ensure_batfile(client_path):
34 base, _ = os.path.splitext(client_path)
35 with open(base+".bat", 'w') as f:
36 f.write('\n'.join([ # python turns \n into CRLF
37 '@set CIPD="%~dp0cipd.exe"',
38 '@shift',
39 '@%CIPD% %*'
40 ]))
41else:
42 def _ensure_batfile(_client_path):
43 pass
44
45
nodirbe642ff2016-06-09 15:51:51 -070046class Error(Exception):
47 """Raised on CIPD errors."""
48
49
50def add_cipd_options(parser):
51 group = optparse.OptionGroup(parser, 'CIPD')
52 group.add_option(
vadimsh902948e2017-01-20 15:57:32 -080053 '--cipd-enabled',
54 help='Enable CIPD client bootstrap. Implied by --cipd-package.',
55 action='store_true',
56 default=False)
57 group.add_option(
nodirbe642ff2016-06-09 15:51:51 -070058 '--cipd-server',
vadimsh902948e2017-01-20 15:57:32 -080059 help='URL of the CIPD server. '
60 'Only relevant with --cipd-enabled or --cipd-package.')
nodirbe642ff2016-06-09 15:51:51 -070061 group.add_option(
62 '--cipd-client-package',
nodir90bc8dc2016-06-15 13:35:21 -070063 help='Package name of CIPD client with optional parameters described in '
nodirff531b42016-06-23 13:05:06 -070064 '--cipd-package help. '
vadimsh902948e2017-01-20 15:57:32 -080065 'Only relevant with --cipd-enabled or --cipd-package. '
nodirbe642ff2016-06-09 15:51:51 -070066 'Default: "%default"',
nodir90bc8dc2016-06-15 13:35:21 -070067 default='infra/tools/cipd/${platform}')
nodirbe642ff2016-06-09 15:51:51 -070068 group.add_option(
nodir90bc8dc2016-06-15 13:35:21 -070069 '--cipd-client-version',
70 help='Version of CIPD client. '
vadimsh902948e2017-01-20 15:57:32 -080071 'Only relevant with --cipd-enabled or --cipd-package. '
nodir90bc8dc2016-06-15 13:35:21 -070072 'Default: "%default"',
73 default='latest')
74 group.add_option(
nodirff531b42016-06-23 13:05:06 -070075 '--cipd-package',
76 dest='cipd_packages',
77 help='A CIPD package to install. '
78 'Format is "<path>:<package_name>:<version>". '
79 '"path" is installation directory relative to run_dir, '
80 'defaults to ".". '
nodir90bc8dc2016-06-15 13:35:21 -070081 '"package_name" may have ${platform} and/or ${os_ver} parameters. '
nodirbe642ff2016-06-09 15:51:51 -070082 '${platform} will be expanded to "<os>-<architecture>" and '
83 '${os_ver} will be expanded to OS version name. '
nodirff531b42016-06-23 13:05:06 -070084 'The option can be specified multiple times.',
85 action='append',
86 default=[])
nodirbe642ff2016-06-09 15:51:51 -070087 group.add_option(
88 '--cipd-cache',
89 help='CIPD cache directory, separate from isolate cache. '
vadimsh902948e2017-01-20 15:57:32 -080090 'Only relevant with --cipd-enabled or --cipd-package. '
nodirbe642ff2016-06-09 15:51:51 -070091 'Default: "%default".',
92 default='')
93 parser.add_option_group(group)
94
95
96def validate_cipd_options(parser, options):
97 """Calls parser.error on first found error among cipd options."""
vadimsh902948e2017-01-20 15:57:32 -080098 if options.cipd_packages:
99 options.cipd_enabled = True
100
101 if not options.cipd_enabled:
nodirbe642ff2016-06-09 15:51:51 -0700102 return
nodirff531b42016-06-23 13:05:06 -0700103
104 for pkg in options.cipd_packages:
105 parts = pkg.split(':', 2)
106 if len(parts) != 3:
107 parser.error('invalid package "%s": must have at least 2 colons' % pkg)
108 _path, name, version = parts
109 if not name:
110 parser.error('invalid package "%s": package name is not specified' % pkg)
111 if not version:
112 parser.error('invalid package "%s": version is not specified' % pkg)
113
nodirbe642ff2016-06-09 15:51:51 -0700114 if not options.cipd_server:
vadimsh902948e2017-01-20 15:57:32 -0800115 parser.error('cipd is enabled, --cipd-server is required')
nodirbe642ff2016-06-09 15:51:51 -0700116
117 if not options.cipd_client_package:
nodirbe642ff2016-06-09 15:51:51 -0700118 parser.error(
vadimsh902948e2017-01-20 15:57:32 -0800119 'cipd is enabled, --cipd-client-package is required')
nodir90bc8dc2016-06-15 13:35:21 -0700120 if not options.cipd_client_version:
121 parser.error(
vadimsh902948e2017-01-20 15:57:32 -0800122 'cipd is enabled, --cipd-client-version is required')
nodirbe642ff2016-06-09 15:51:51 -0700123
124
125class CipdClient(object):
126 """Installs packages."""
127
iannucci96fcccc2016-08-30 15:52:22 -0700128 def __init__(self, binary_path, package_name, instance_id, service_url):
nodirbe642ff2016-06-09 15:51:51 -0700129 """Initializes CipdClient.
130
131 Args:
132 binary_path (str): path to the CIPD client binary.
iannucci96fcccc2016-08-30 15:52:22 -0700133 package_name (str): the CIPD package name for the client itself.
134 instance_id (str): the CIPD instance_id for the client itself.
nodirbe642ff2016-06-09 15:51:51 -0700135 service_url (str): if not None, URL of the CIPD backend that overrides
136 the default one.
137 """
138 self.binary_path = binary_path
iannucci96fcccc2016-08-30 15:52:22 -0700139 self.package_name = package_name
140 self.instance_id = instance_id
nodirbe642ff2016-06-09 15:51:51 -0700141 self.service_url = service_url
142
143 def ensure(
144 self, site_root, packages, cache_dir=None, tmp_dir=None, timeout=None):
145 """Ensures that packages installed in |site_root| equals |packages| set.
146
147 Blocking call.
148
149 Args:
150 site_root (str): where to install packages.
iannuccib58d10d2017-03-18 02:00:25 -0700151 packages: dict of subdir -> list of (package_template, version) tuples.
nodirbe642ff2016-06-09 15:51:51 -0700152 cache_dir (str): if set, cache dir for cipd binary own cache.
153 Typically contains packages and tags.
154 tmp_dir (str): if not None, dir for temp files.
155 timeout (int): if not None, timeout in seconds for this function to run.
156
iannucci96fcccc2016-08-30 15:52:22 -0700157 Returns:
iannuccib58d10d2017-03-18 02:00:25 -0700158 Pinned packages in the form of {subdir: [(package_name, package_id)]},
159 which correspond 1:1 with the input packages argument.
iannucci96fcccc2016-08-30 15:52:22 -0700160
nodirbe642ff2016-06-09 15:51:51 -0700161 Raises:
162 Error if could not install packages or timed out.
163 """
164 timeoutfn = tools.sliding_timeout(timeout)
165 logging.info('Installing packages %r into %s', packages, site_root)
166
iannuccib58d10d2017-03-18 02:00:25 -0700167 ensure_file_handle, ensure_file_path = tempfile.mkstemp(
168 dir=tmp_dir, prefix=u'cipd-ensure-file-', suffix='.txt')
iannucci96fcccc2016-08-30 15:52:22 -0700169 json_out_file_handle, json_file_path = tempfile.mkstemp(
170 dir=tmp_dir, prefix=u'cipd-ensure-result-', suffix='.json')
171 os.close(json_out_file_handle)
172
nodirbe642ff2016-06-09 15:51:51 -0700173 try:
174 try:
iannuccib58d10d2017-03-18 02:00:25 -0700175 for subdir, pkgs in sorted(packages.iteritems()):
176 if '\n' in subdir:
177 raise Error(
178 'Could not install packages; subdir %r contains newline' % subdir)
179 os.write(ensure_file_handle, '@Subdir %s\n' % (subdir,))
180 for pkg, version in pkgs:
181 pkg = render_package_name_template(pkg)
182 os.write(ensure_file_handle, '%s %s\n' % (pkg, version))
nodirbe642ff2016-06-09 15:51:51 -0700183 finally:
iannuccib58d10d2017-03-18 02:00:25 -0700184 os.close(ensure_file_handle)
nodirbe642ff2016-06-09 15:51:51 -0700185
186 cmd = [
187 self.binary_path, 'ensure',
188 '-root', site_root,
iannuccib58d10d2017-03-18 02:00:25 -0700189 '-ensure-file', ensure_file_path,
nodirbe642ff2016-06-09 15:51:51 -0700190 '-verbose', # this is safe because cipd-ensure does not print a lot
iannucci96fcccc2016-08-30 15:52:22 -0700191 '-json-output', json_file_path,
nodirbe642ff2016-06-09 15:51:51 -0700192 ]
193 if cache_dir:
194 cmd += ['-cache-dir', cache_dir]
195 if self.service_url:
196 cmd += ['-service-url', self.service_url]
197
198 logging.debug('Running %r', cmd)
199 process = subprocess42.Popen(
200 cmd, stdout=subprocess42.PIPE, stderr=subprocess42.PIPE)
201 output = []
202 for pipe_name, line in process.yield_any_line(timeout=0.1):
203 to = timeoutfn()
204 if to is not None and to <= 0:
205 raise Error(
206 'Could not install packages; took more than %d seconds' % timeout)
207 if not pipe_name:
208 # stdout or stderr was closed, but yield_any_line still may have
209 # something to yield.
210 continue
211 output.append(line)
212 if pipe_name == 'stderr':
213 logging.debug('cipd client: %s', line)
214 else:
215 logging.info('cipd client: %s', line)
216
217 exit_code = process.wait(timeout=timeoutfn())
218 if exit_code != 0:
219 raise Error(
220 'Could not install packages; exit code %d\noutput:%s' % (
221 exit_code, '\n'.join(output)))
iannucci96fcccc2016-08-30 15:52:22 -0700222 with open(json_file_path) as jfile:
223 result_json = json.load(jfile)
iannuccib58d10d2017-03-18 02:00:25 -0700224 return {
225 subdir: [(x['package'], x['instance_id']) for x in pins]
226 for subdir, pins in result_json['result'].iteritems()
227 }
nodirbe642ff2016-06-09 15:51:51 -0700228 finally:
iannuccib58d10d2017-03-18 02:00:25 -0700229 fs.remove(ensure_file_path)
iannucci96fcccc2016-08-30 15:52:22 -0700230 fs.remove(json_file_path)
nodirbe642ff2016-06-09 15:51:51 -0700231
232
233def get_platform():
234 """Returns ${platform} parameter value.
235
236 Borrowed from
237 https://chromium.googlesource.com/infra/infra/+/aaf9586/build/build.py#204
238 """
239 # linux, mac or windows.
240 platform_variant = {
241 'darwin': 'mac',
242 'linux2': 'linux',
243 'win32': 'windows',
244 }.get(sys.platform)
245 if not platform_variant:
246 raise Error('Unknown OS: %s' % sys.platform)
247
248 # amd64, 386, etc.
249 machine = platform.machine().lower()
250 platform_arch = {
251 'amd64': 'amd64',
252 'i386': '386',
253 'i686': '386',
254 'x86': '386',
255 'x86_64': 'amd64',
256 }.get(machine)
257 if not platform_arch:
258 if machine.startswith('arm'):
259 platform_arch = 'armv6l'
260 else:
261 platform_arch = 'amd64' if sys.maxsize > 2**32 else '386'
262 return '%s-%s' % (platform_variant, platform_arch)
263
264
265def get_os_ver():
266 """Returns ${os_ver} parameter value.
267
268 Examples: 'ubuntu14_04' or 'mac10_9' or 'win6_1'.
269
270 Borrowed from
271 https://chromium.googlesource.com/infra/infra/+/aaf9586/build/build.py#204
272 """
273 if sys.platform == 'darwin':
274 # platform.mac_ver()[0] is '10.9.5'.
275 dist = platform.mac_ver()[0].split('.')
276 return 'mac%s_%s' % (dist[0], dist[1])
277
278 if sys.platform == 'linux2':
279 # platform.linux_distribution() is ('Ubuntu', '14.04', ...).
280 dist = platform.linux_distribution()
281 return '%s%s' % (dist[0].lower(), dist[1].replace('.', '_'))
282
283 if sys.platform == 'win32':
284 # platform.version() is '6.1.7601'.
285 dist = platform.version().split('.')
286 return 'win%s_%s' % (dist[0], dist[1])
287 raise Error('Unknown OS: %s' % sys.platform)
288
289
290def render_package_name_template(template):
291 """Expands template variables in a CIPD package name template."""
292 return (template
293 .lower() # Package names are always lower case
294 .replace('${platform}', get_platform())
295 .replace('${os_ver}', get_os_ver()))
296
297
nodirbe642ff2016-06-09 15:51:51 -0700298def _check_response(res, fmt, *args):
299 """Raises Error if response is bad."""
300 if not res:
301 raise Error('%s: no response' % (fmt % args))
302
303 if res.get('status') != 'SUCCESS':
304 raise Error('%s: %s' % (
305 fmt % args,
306 res.get('error_message') or 'status is %s' % res.get('status')))
307
308
309def resolve_version(cipd_server, package_name, version, timeout=None):
310 """Resolves a package instance version (e.g. a tag) to an instance id."""
311 url = '%s/_ah/api/repo/v1/instance/resolve?%s' % (
312 cipd_server,
313 urllib.urlencode({
314 'package_name': package_name,
315 'version': version,
316 }))
317 res = net.url_read_json(url, timeout=timeout)
318 _check_response(res, 'Could not resolve version %s:%s', package_name, version)
319 instance_id = res.get('instance_id')
320 if not instance_id:
321 raise Error('Invalid resolveVersion response: no instance id')
322 return instance_id
323
324
325def get_client_fetch_url(service_url, package_name, instance_id, timeout=None):
326 """Returns a fetch URL of CIPD client binary contents.
327
328 Raises:
329 Error if cannot retrieve fetch URL.
330 """
331 # Fetch the URL of the binary from CIPD backend.
332 package_name = render_package_name_template(package_name)
333 url = '%s/_ah/api/repo/v1/client?%s' % (service_url, urllib.urlencode({
334 'package_name': package_name,
335 'instance_id': instance_id,
336 }))
337 res = net.url_read_json(url, timeout=timeout)
338 _check_response(
339 res, 'Could not fetch CIPD client %s:%s',package_name, instance_id)
340 fetch_url = res.get('client_binary', {}).get('fetch_url')
341 if not fetch_url:
342 raise Error('Invalid fetchClientBinary response: no fetch_url')
343 return fetch_url
344
345
346def _fetch_cipd_client(disk_cache, instance_id, fetch_url, timeoutfn):
347 """Fetches cipd binary to |disk_cache|.
348
349 Retries requests with exponential back-off.
350
351 Raises:
352 Error if could not fetch content.
353 """
354 sleep_time = 1
355 for attempt in xrange(5):
356 if attempt > 0:
357 if timeoutfn() is not None and timeoutfn() < sleep_time:
358 raise Error('Could not fetch CIPD client: timeout')
359 logging.warning('Will retry to fetch CIPD client in %ds', sleep_time)
360 time.sleep(sleep_time)
361 sleep_time *= 2
362
363 try:
364 res = net.url_open(fetch_url, timeout=timeoutfn())
365 if res:
366 disk_cache.write(instance_id, res.iter_content(64 * 1024))
367 return
368 except net.TimeoutError as ex:
369 raise Error('Could not fetch CIPD client: %s', ex)
370 except net.NetError as ex:
371 logging.warning(
372 'Could not fetch CIPD client on attempt #%d: %s', attempt + 1, ex)
373
374 raise Error('Could not fetch CIPD client after 5 retries')
375
376
377@contextlib.contextmanager
vadimsh232f5a82017-01-20 19:23:44 -0800378def get_client(service_url, package_name, version, cache_dir, timeout=None):
nodirbe642ff2016-06-09 15:51:51 -0700379 """Returns a context manager that yields a CipdClient. A blocking call.
380
vadimsh232f5a82017-01-20 19:23:44 -0800381 Upon exit from the context manager, the client binary may be deleted
382 (if the internal cache is full).
383
nodirbe642ff2016-06-09 15:51:51 -0700384 Args:
vadimsh232f5a82017-01-20 19:23:44 -0800385 service_url (str): URL of the CIPD backend.
386 package_name (str): package name template of the CIPD client.
387 version (str): version of CIPD client package.
388 cache_dir: directory to store instance cache, version cache
389 and a hardlink to the client binary.
390 timeout (int): if not None, timeout in seconds for this function.
nodirbe642ff2016-06-09 15:51:51 -0700391
392 Yields:
393 CipdClient.
394
395 Raises:
396 Error if CIPD client version cannot be resolved or client cannot be fetched.
397 """
398 timeoutfn = tools.sliding_timeout(timeout)
399
400 package_name = render_package_name_template(package_name)
401
402 # Resolve version to instance id.
403 # Is it an instance id already? They look like HEX SHA1.
404 if isolated_format.is_valid_hash(version, hashlib.sha1):
405 instance_id = version
iannucci6fd57d22016-08-30 17:02:20 -0700406 elif ':' in version: # it's an immutable tag
nodirbe642ff2016-06-09 15:51:51 -0700407 # version_cache is {version_digest -> instance id} mapping.
408 # It does not take a lot of disk space.
409 version_cache = isolateserver.DiskCache(
410 unicode(os.path.join(cache_dir, 'versions')),
411 isolateserver.CachePolicies(0, 0, 300),
412 hashlib.sha1)
413 with version_cache:
maruel2e8d0f52016-07-16 07:51:29 -0700414 version_cache.cleanup()
nodirbe642ff2016-06-09 15:51:51 -0700415 # Convert |version| to a string that may be used as a filename in disk
416 # cache by hashing it.
417 version_digest = hashlib.sha1(version).hexdigest()
418 try:
tansell9e04a8d2016-07-28 09:31:59 -0700419 with version_cache.getfileobj(version_digest) as f:
420 instance_id = f.read()
nodirbe642ff2016-06-09 15:51:51 -0700421 except isolateserver.CacheMiss:
422 instance_id = resolve_version(
423 service_url, package_name, version, timeout=timeoutfn())
424 version_cache.write(version_digest, instance_id)
iannucci6fd57d22016-08-30 17:02:20 -0700425 else: # it's a ref
426 instance_id = resolve_version(
427 service_url, package_name, version, timeout=timeoutfn())
nodirbe642ff2016-06-09 15:51:51 -0700428
429 # instance_cache is {instance_id -> client binary} mapping.
430 # It is bounded by 5 client versions.
431 instance_cache = isolateserver.DiskCache(
432 unicode(os.path.join(cache_dir, 'clients')),
433 isolateserver.CachePolicies(0, 0, 5),
434 hashlib.sha1)
435 with instance_cache:
maruel2e8d0f52016-07-16 07:51:29 -0700436 instance_cache.cleanup()
nodirbe642ff2016-06-09 15:51:51 -0700437 if instance_id not in instance_cache:
438 logging.info('Fetching CIPD client %s:%s', package_name, instance_id)
439 fetch_url = get_client_fetch_url(
440 service_url, package_name, instance_id, timeout=timeoutfn())
441 _fetch_cipd_client(instance_cache, instance_id, fetch_url, timeoutfn)
442
443 # A single host can run multiple swarming bots, but ATM they do not share
444 # same root bot directory. Thus, it is safe to use the same name for the
445 # binary.
vadimsh232f5a82017-01-20 19:23:44 -0800446 cipd_bin_dir = unicode(os.path.join(cache_dir, 'bin'))
447 binary_path = os.path.join(cipd_bin_dir, 'cipd' + EXECUTABLE_SUFFIX)
nodirbe642ff2016-06-09 15:51:51 -0700448 if fs.isfile(binary_path):
nodir6dfdb2d2016-06-14 20:14:08 -0700449 file_path.remove(binary_path)
vadimsh232f5a82017-01-20 19:23:44 -0800450 else:
451 file_path.ensure_tree(cipd_bin_dir)
tansell9e04a8d2016-07-28 09:31:59 -0700452
453 with instance_cache.getfileobj(instance_id) as f:
454 isolateserver.putfile(f, binary_path, 0511) # -r-x--x--x
nodirbe642ff2016-06-09 15:51:51 -0700455
iannucci4d7792a2017-03-10 10:30:56 -0800456 _ensure_batfile(binary_path)
457
vadimsh232f5a82017-01-20 19:23:44 -0800458 yield CipdClient(
459 binary_path,
460 package_name=package_name,
461 instance_id=instance_id,
462 service_url=service_url)
nodir90bc8dc2016-06-15 13:35:21 -0700463
464
nodirff531b42016-06-23 13:05:06 -0700465def parse_package_args(packages):
466 """Parses --cipd-package arguments.
nodir90bc8dc2016-06-15 13:35:21 -0700467
nodirff531b42016-06-23 13:05:06 -0700468 Assumes |packages| were validated by validate_cipd_options.
469
470 Returns:
iannucci96fcccc2016-08-30 15:52:22 -0700471 A list of [(path, package_name, version), ...]
nodir90bc8dc2016-06-15 13:35:21 -0700472 """
iannucci96fcccc2016-08-30 15:52:22 -0700473 result = []
nodirff531b42016-06-23 13:05:06 -0700474 for pkg in packages:
475 path, name, version = pkg.split(':', 2)
nodir90bc8dc2016-06-15 13:35:21 -0700476 if not name:
nodirff531b42016-06-23 13:05:06 -0700477 raise Error('Invalid package "%s": package name is not specified' % pkg)
nodir90bc8dc2016-06-15 13:35:21 -0700478 if not version:
nodirff531b42016-06-23 13:05:06 -0700479 raise Error('Invalid package "%s": version is not specified' % pkg)
iannucci96fcccc2016-08-30 15:52:22 -0700480 result.append((path, name, version))
nodirff531b42016-06-23 13:05:06 -0700481 return result