blob: 326c4faed95629dbc7236eeec4562e0674e769d9 [file] [log] [blame]
Jan Tattermusch91ad0182015-10-01 09:22:03 -07001# Copyright 2015, Google Inc.
2# All rights reserved.
3#
4# Redistribution and use in source and binary forms, with or without
5# modification, are permitted provided that the following conditions are
6# met:
7#
8# * Redistributions of source code must retain the above copyright
9# notice, this list of conditions and the following disclaimer.
10# * Redistributions in binary form must reproduce the above
11# copyright notice, this list of conditions and the following disclaimer
12# in the documentation and/or other materials provided with the
13# distribution.
14# * Neither the name of Google Inc. nor the names of its
15# contributors may be used to endorse or promote products derived from
16# this software without specific prior written permission.
17#
18# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30"""Helpers to run docker instances as jobs."""
31
32import jobset
33import tempfile
34import time
35import uuid
36import os
37import subprocess
38
39_DEVNULL = open(os.devnull, 'w')
40
Jan Tattermusche2686282015-10-08 16:27:07 -070041
42def random_name(base_name):
43 """Randomizes given base name."""
44 return '%s_%s' % (base_name, uuid.uuid4())
45
46
47def docker_kill(cid):
48 """Kills a docker container. Returns True if successful."""
Jan Tattermuschcc6a2b82015-10-09 14:53:51 -070049 return subprocess.call(['docker','kill', str(cid)],
Carl Mastrangelo2d248a22015-11-19 13:09:52 -080050 stdin=subprocess.PIPE,
Jan Tattermuschcc6a2b82015-10-09 14:53:51 -070051 stdout=_DEVNULL,
52 stderr=subprocess.STDOUT) == 0
Jan Tattermusch91ad0182015-10-01 09:22:03 -070053
54
Jan Tattermusch98c0be52015-10-09 14:33:34 -070055def docker_mapped_port(cid, port, timeout_seconds=15):
Jan Tattermusch91ad0182015-10-01 09:22:03 -070056 """Get port mapped to internal given internal port for given container."""
Jan Tattermusch98c0be52015-10-09 14:33:34 -070057 started = time.time()
58 while time.time() - started < timeout_seconds:
59 try:
60 output = subprocess.check_output('docker port %s %s' % (cid, port),
Jan Tattermuschab5bc722015-10-09 14:46:29 -070061 stderr=_DEVNULL,
Jan Tattermusch98c0be52015-10-09 14:33:34 -070062 shell=True)
63 return int(output.split(':', 2)[1])
64 except subprocess.CalledProcessError as e:
65 pass
66 raise Exception('Failed to get exposed port %s for container %s.' %
67 (port, cid))
Jan Tattermusch91ad0182015-10-01 09:22:03 -070068
69
70def finish_jobs(jobs):
71 """Kills given docker containers and waits for corresponding jobs to finish"""
72 for job in jobs:
73 job.kill(suppress_failure=True)
74
75 while any(job.is_running() for job in jobs):
76 time.sleep(1)
77
78
79def image_exists(image):
80 """Returns True if given docker image exists."""
81 return subprocess.call(['docker','inspect', image],
Carl Mastrangelo2d248a22015-11-19 13:09:52 -080082 stdin=subprocess.PIPE,
Jan Tattermusch91ad0182015-10-01 09:22:03 -070083 stdout=_DEVNULL,
Jan Tattermusch98c0be52015-10-09 14:33:34 -070084 stderr=subprocess.STDOUT) == 0
Jan Tattermusch91ad0182015-10-01 09:22:03 -070085
86
87def remove_image(image, skip_nonexistent=False, max_retries=10):
88 """Attempts to remove docker image with retries."""
89 if skip_nonexistent and not image_exists(image):
90 return True
91 for attempt in range(0, max_retries):
Jan Tattermuschab5bc722015-10-09 14:46:29 -070092 if subprocess.call(['docker','rmi', '-f', image],
Carl Mastrangelo2d248a22015-11-19 13:09:52 -080093 stdin=subprocess.PIPE,
Jan Tattermuschab5bc722015-10-09 14:46:29 -070094 stdout=_DEVNULL,
95 stderr=subprocess.STDOUT) == 0:
Jan Tattermusch91ad0182015-10-01 09:22:03 -070096 return True
97 time.sleep(2)
98 print 'Failed to remove docker image %s' % image
99 return False
100
101
102class DockerJob:
103 """Encapsulates a job"""
104
105 def __init__(self, spec):
106 self._spec = spec
Adele Zhou2271ab52015-10-28 13:59:14 -0700107 self._job = jobset.Job(spec, bin_hash=None, newline_on_success=True, travis=True, add_env={})
Jan Tattermusche2686282015-10-08 16:27:07 -0700108 self._container_name = spec.container_name
Jan Tattermusch91ad0182015-10-01 09:22:03 -0700109
110 def mapped_port(self, port):
Jan Tattermusche2686282015-10-08 16:27:07 -0700111 return docker_mapped_port(self._container_name, port)
Jan Tattermusch91ad0182015-10-01 09:22:03 -0700112
113 def kill(self, suppress_failure=False):
114 """Sends kill signal to the container."""
115 if suppress_failure:
116 self._job.suppress_failure_message()
Jan Tattermusche2686282015-10-08 16:27:07 -0700117 return docker_kill(self._container_name)
Jan Tattermusch91ad0182015-10-01 09:22:03 -0700118
119 def is_running(self):
120 """Polls a job and returns True if given job is still running."""
121 return self._job.state(jobset.NoCache()) == jobset._RUNNING