blob: 4a7e61b3c4e3be785803b675d5658b04935f8f2d [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
siddharthshukla0589e532016-07-07 16:08:01 +020032from __future__ import print_function
33
Jan Tattermusch91ad0182015-10-01 09:22:03 -070034import jobset
35import tempfile
36import time
37import uuid
38import os
39import subprocess
40
41_DEVNULL = open(os.devnull, 'w')
42
Jan Tattermusche2686282015-10-08 16:27:07 -070043
44def random_name(base_name):
45 """Randomizes given base name."""
46 return '%s_%s' % (base_name, uuid.uuid4())
47
48
49def docker_kill(cid):
50 """Kills a docker container. Returns True if successful."""
Jan Tattermuschcc6a2b82015-10-09 14:53:51 -070051 return subprocess.call(['docker','kill', str(cid)],
Carl Mastrangelo2d248a22015-11-19 13:09:52 -080052 stdin=subprocess.PIPE,
Jan Tattermuschcc6a2b82015-10-09 14:53:51 -070053 stdout=_DEVNULL,
54 stderr=subprocess.STDOUT) == 0
Jan Tattermusch91ad0182015-10-01 09:22:03 -070055
56
Jan Tattermusch98c0be52015-10-09 14:33:34 -070057def docker_mapped_port(cid, port, timeout_seconds=15):
Jan Tattermusch91ad0182015-10-01 09:22:03 -070058 """Get port mapped to internal given internal port for given container."""
Jan Tattermusch98c0be52015-10-09 14:33:34 -070059 started = time.time()
60 while time.time() - started < timeout_seconds:
61 try:
62 output = subprocess.check_output('docker port %s %s' % (cid, port),
Jan Tattermuschab5bc722015-10-09 14:46:29 -070063 stderr=_DEVNULL,
Jan Tattermusch98c0be52015-10-09 14:33:34 -070064 shell=True)
65 return int(output.split(':', 2)[1])
66 except subprocess.CalledProcessError as e:
67 pass
68 raise Exception('Failed to get exposed port %s for container %s.' %
69 (port, cid))
Jan Tattermusch91ad0182015-10-01 09:22:03 -070070
71
72def finish_jobs(jobs):
73 """Kills given docker containers and waits for corresponding jobs to finish"""
74 for job in jobs:
75 job.kill(suppress_failure=True)
76
77 while any(job.is_running() for job in jobs):
78 time.sleep(1)
79
80
81def image_exists(image):
82 """Returns True if given docker image exists."""
83 return subprocess.call(['docker','inspect', image],
Carl Mastrangelo2d248a22015-11-19 13:09:52 -080084 stdin=subprocess.PIPE,
Jan Tattermusch91ad0182015-10-01 09:22:03 -070085 stdout=_DEVNULL,
Jan Tattermusch98c0be52015-10-09 14:33:34 -070086 stderr=subprocess.STDOUT) == 0
Jan Tattermusch91ad0182015-10-01 09:22:03 -070087
88
89def remove_image(image, skip_nonexistent=False, max_retries=10):
90 """Attempts to remove docker image with retries."""
91 if skip_nonexistent and not image_exists(image):
92 return True
93 for attempt in range(0, max_retries):
Jan Tattermuschab5bc722015-10-09 14:46:29 -070094 if subprocess.call(['docker','rmi', '-f', image],
Carl Mastrangelo2d248a22015-11-19 13:09:52 -080095 stdin=subprocess.PIPE,
Jan Tattermuschab5bc722015-10-09 14:46:29 -070096 stdout=_DEVNULL,
97 stderr=subprocess.STDOUT) == 0:
Jan Tattermusch91ad0182015-10-01 09:22:03 -070098 return True
99 time.sleep(2)
siddharthshukla0589e532016-07-07 16:08:01 +0200100 print('Failed to remove docker image %s' % image)
Jan Tattermusch91ad0182015-10-01 09:22:03 -0700101 return False
102
103
104class DockerJob:
105 """Encapsulates a job"""
106
107 def __init__(self, spec):
108 self._spec = spec
Craig Tiller2e1a1fe2016-06-23 16:18:31 -0700109 self._job = jobset.Job(spec, newline_on_success=True, travis=True, add_env={})
Jan Tattermusche2686282015-10-08 16:27:07 -0700110 self._container_name = spec.container_name
Jan Tattermusch91ad0182015-10-01 09:22:03 -0700111
112 def mapped_port(self, port):
Jan Tattermusche2686282015-10-08 16:27:07 -0700113 return docker_mapped_port(self._container_name, port)
Jan Tattermusch91ad0182015-10-01 09:22:03 -0700114
115 def kill(self, suppress_failure=False):
116 """Sends kill signal to the container."""
117 if suppress_failure:
118 self._job.suppress_failure_message()
Jan Tattermusche2686282015-10-08 16:27:07 -0700119 return docker_kill(self._container_name)
Jan Tattermusch91ad0182015-10-01 09:22:03 -0700120
121 def is_running(self):
122 """Polls a job and returns True if given job is still running."""
Craig Tiller2e1a1fe2016-06-23 16:18:31 -0700123 return self._job.state() == jobset._RUNNING