2014-05-23 18:16:26 +00:00
|
|
|
import logging.config
|
|
|
|
|
|
|
|
logging.config.fileConfig('conf/logging.conf', disable_existing_loggers=False)
|
|
|
|
|
2013-10-24 20:37:03 +00:00
|
|
|
import logging
|
|
|
|
import argparse
|
2013-10-29 23:59:29 +00:00
|
|
|
import os
|
2014-01-24 19:40:36 +00:00
|
|
|
import requests
|
|
|
|
import re
|
|
|
|
import json
|
|
|
|
import shutil
|
2014-03-31 19:40:24 +00:00
|
|
|
import tarfile
|
2013-10-24 20:37:03 +00:00
|
|
|
|
2014-04-30 22:48:36 +00:00
|
|
|
from docker import Client
|
|
|
|
from docker.errors import APIError
|
2014-01-24 19:40:36 +00:00
|
|
|
from tempfile import TemporaryFile, mkdtemp
|
|
|
|
from zipfile import ZipFile
|
2014-02-12 23:58:40 +00:00
|
|
|
from functools import partial
|
2014-04-02 23:32:41 +00:00
|
|
|
from datetime import datetime, timedelta
|
|
|
|
from threading import Event
|
2014-04-14 19:21:05 +00:00
|
|
|
from uuid import uuid4
|
2014-04-30 22:48:36 +00:00
|
|
|
from collections import defaultdict
|
2014-07-30 21:54:58 +00:00
|
|
|
from requests.exceptions import ConnectionError
|
2013-10-24 20:37:03 +00:00
|
|
|
|
|
|
|
from data import model
|
2014-05-06 22:46:19 +00:00
|
|
|
from workers.worker import Worker, WorkerUnhealthyException, JobException
|
2014-05-21 23:50:37 +00:00
|
|
|
from app import userfiles as user_files, build_logs, sentry, dockerfile_build_queue
|
2014-07-18 20:34:52 +00:00
|
|
|
from endpoints.notificationhelper import spawn_notification
|
2014-04-01 17:46:41 +00:00
|
|
|
from util.safetar import safe_extractall
|
2014-04-16 19:45:41 +00:00
|
|
|
from util.dockerfileparse import parse_dockerfile, ParsedDockerfile, serialize_dockerfile
|
2013-10-24 20:37:03 +00:00
|
|
|
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2014-04-02 23:32:41 +00:00
|
|
|
TIMEOUT_PERIOD_MINUTES = 20
|
2014-04-14 19:21:05 +00:00
|
|
|
CACHE_EXPIRATION_PERIOD_HOURS = 24
|
2014-04-30 22:48:36 +00:00
|
|
|
NO_TAGS = ['<none>:<none>']
|
2014-05-06 22:46:19 +00:00
|
|
|
RESERVATION_TIME = (TIMEOUT_PERIOD_MINUTES + 5) * 60
|
2014-04-02 23:32:41 +00:00
|
|
|
|
2014-07-30 21:54:58 +00:00
|
|
|
def matches_system_error(status_str):
|
|
|
|
""" Returns true if the given status string matches a known system error in the
|
|
|
|
Docker builder.
|
|
|
|
"""
|
2014-08-28 20:07:56 +00:00
|
|
|
KNOWN_MATCHES = ['lxc-start: invalid', 'lxc-start: failed to', 'lxc-start: Permission denied']
|
2014-07-30 21:54:58 +00:00
|
|
|
|
|
|
|
for match in KNOWN_MATCHES:
|
2014-08-26 16:41:43 +00:00
|
|
|
# 10 because we might have a Unix control code at the start.
|
|
|
|
found = status_str.find(match[0:len(match) + 10])
|
|
|
|
if found >= 0 and found <= 10:
|
2014-07-30 21:54:58 +00:00
|
|
|
return True
|
|
|
|
|
|
|
|
return False
|
|
|
|
|
2014-02-04 00:08:37 +00:00
|
|
|
|
|
|
|
class StatusWrapper(object):
|
|
|
|
def __init__(self, build_uuid):
|
|
|
|
self._uuid = build_uuid
|
|
|
|
self._status = {
|
|
|
|
'total_commands': None,
|
|
|
|
'current_command': None,
|
|
|
|
'push_completion': 0.0,
|
2014-04-30 22:48:36 +00:00
|
|
|
'pull_completion': 0.0,
|
2014-02-04 00:08:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
self.__exit__(None, None, None)
|
|
|
|
|
|
|
|
def __enter__(self):
|
|
|
|
return self._status
|
|
|
|
|
|
|
|
def __exit__(self, exc_type, value, traceback):
|
|
|
|
build_logs.set_status(self._uuid, self._status)
|
|
|
|
|
2013-10-27 23:06:20 +00:00
|
|
|
|
2014-03-28 21:53:33 +00:00
|
|
|
class _IncompleteJsonError(Exception):
|
|
|
|
def __init__(self, start_from):
|
|
|
|
self.start_from = start_from
|
|
|
|
|
|
|
|
|
|
|
|
class _StreamingJSONDecoder(json.JSONDecoder):
|
|
|
|
FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL
|
|
|
|
WHITESPACE = re.compile(r'[ \t\n\r]*', FLAGS)
|
|
|
|
|
|
|
|
def decode(self, s, _w=WHITESPACE.match):
|
|
|
|
"""Return the Python representation of ``s`` (a ``str`` or ``unicode``
|
|
|
|
instance containing a JSON document)
|
|
|
|
|
|
|
|
"""
|
|
|
|
start_from = 0
|
|
|
|
while start_from < len(s):
|
|
|
|
try:
|
|
|
|
obj, end = self.raw_decode(s[start_from:], idx=_w(s[start_from:], 0).end())
|
|
|
|
except ValueError:
|
|
|
|
raise _IncompleteJsonError(start_from)
|
|
|
|
end = _w(s[start_from:], end).end()
|
|
|
|
start_from += end
|
|
|
|
yield obj
|
|
|
|
|
|
|
|
|
|
|
|
class StreamingDockerClient(Client):
|
|
|
|
def _stream_helper(self, response):
|
|
|
|
"""Generator for data coming from a chunked-encoded HTTP response."""
|
|
|
|
content_buf = ''
|
|
|
|
for content in response.iter_content(chunk_size=256):
|
|
|
|
content_buf += content
|
|
|
|
try:
|
|
|
|
for val in json.loads(content_buf, cls=_StreamingJSONDecoder):
|
|
|
|
yield val
|
|
|
|
content_buf = ''
|
|
|
|
except _IncompleteJsonError as exc:
|
|
|
|
content_buf = content_buf[exc.start_from:]
|
2014-03-05 15:32:24 +00:00
|
|
|
|
|
|
|
|
2014-02-05 16:07:54 +00:00
|
|
|
class DockerfileBuildContext(object):
|
2014-02-24 21:11:23 +00:00
|
|
|
def __init__(self, build_context_dir, dockerfile_subdir, repo, tag_names,
|
2014-04-30 22:48:36 +00:00
|
|
|
push_token, build_uuid, cache_size_gb, pull_credentials=None):
|
2014-02-05 16:07:54 +00:00
|
|
|
self._build_dir = build_context_dir
|
2014-02-24 21:11:23 +00:00
|
|
|
self._dockerfile_subdir = dockerfile_subdir
|
|
|
|
self._repo = repo
|
|
|
|
self._tag_names = tag_names
|
2014-02-05 16:07:54 +00:00
|
|
|
self._push_token = push_token
|
2014-02-12 23:58:40 +00:00
|
|
|
self._status = StatusWrapper(build_uuid)
|
2014-02-13 16:44:39 +00:00
|
|
|
self._build_logger = partial(build_logs.append_log_message, build_uuid)
|
2014-03-27 22:33:13 +00:00
|
|
|
self._pull_credentials = pull_credentials
|
2014-04-30 22:48:36 +00:00
|
|
|
self._cache_size_gb = cache_size_gb
|
2014-03-27 22:33:13 +00:00
|
|
|
|
|
|
|
# Note: We have two different clients here because we (potentially) login
|
|
|
|
# with both, but with different credentials that we do not want shared between
|
|
|
|
# the build and push operations.
|
2014-03-31 22:10:34 +00:00
|
|
|
self._push_cl = StreamingDockerClient(timeout=1200)
|
|
|
|
self._build_cl = StreamingDockerClient(timeout=1200)
|
2013-10-27 23:06:20 +00:00
|
|
|
|
2014-02-24 21:11:23 +00:00
|
|
|
dockerfile_path = os.path.join(self._build_dir, dockerfile_subdir,
|
2014-03-28 21:53:33 +00:00
|
|
|
'Dockerfile')
|
2014-04-30 22:48:36 +00:00
|
|
|
if not os.path.exists(dockerfile_path):
|
|
|
|
raise RuntimeError('Build job did not contain a Dockerfile.')
|
2014-05-06 22:46:19 +00:00
|
|
|
|
2014-04-14 22:54:39 +00:00
|
|
|
# Compute the number of steps
|
|
|
|
with open(dockerfile_path, 'r') as dockerfileobj:
|
|
|
|
self._parsed_dockerfile = parse_dockerfile(dockerfileobj.read())
|
2014-04-16 19:45:41 +00:00
|
|
|
|
|
|
|
self.__inject_quay_repo_env(self._parsed_dockerfile, repo)
|
2014-04-14 22:54:39 +00:00
|
|
|
self._num_steps = len(self._parsed_dockerfile.commands)
|
2014-02-05 16:07:54 +00:00
|
|
|
|
2014-04-16 19:45:41 +00:00
|
|
|
with open(dockerfile_path, 'w') as dockerfileobj:
|
|
|
|
dockerfileobj.write(serialize_dockerfile(self._parsed_dockerfile))
|
|
|
|
|
2014-04-30 22:48:36 +00:00
|
|
|
logger.debug('Will build and push to repo %s with tags named: %s', self._repo,
|
|
|
|
self._tag_names)
|
2014-02-05 16:07:54 +00:00
|
|
|
|
|
|
|
def __enter__(self):
|
2014-05-06 22:46:19 +00:00
|
|
|
try:
|
|
|
|
self.__cleanup_containers()
|
|
|
|
self.__cleanup_images()
|
|
|
|
self.__prune_cache()
|
|
|
|
except APIError:
|
2014-05-19 17:50:45 +00:00
|
|
|
sentry.client.captureException()
|
2014-05-06 22:46:19 +00:00
|
|
|
message = 'Docker installation is no longer healthy.'
|
|
|
|
logger.exception(message)
|
|
|
|
raise WorkerUnhealthyException(message)
|
2014-07-30 21:54:58 +00:00
|
|
|
|
2014-02-05 16:07:54 +00:00
|
|
|
return self
|
|
|
|
|
|
|
|
def __exit__(self, exc_type, value, traceback):
|
|
|
|
shutil.rmtree(self._build_dir)
|
2013-10-27 23:06:20 +00:00
|
|
|
|
2014-07-30 21:54:58 +00:00
|
|
|
try:
|
|
|
|
self.__cleanup_containers()
|
|
|
|
except APIError:
|
|
|
|
sentry.client.captureException()
|
|
|
|
message = 'Docker installation is no longer healthy.'
|
|
|
|
logger.exception(message)
|
|
|
|
raise WorkerUnhealthyException(message)
|
|
|
|
|
2014-04-16 19:45:41 +00:00
|
|
|
@staticmethod
|
|
|
|
def __inject_quay_repo_env(parsed_dockerfile, quay_reponame):
|
|
|
|
env_command = {
|
|
|
|
'command': 'ENV',
|
|
|
|
'parameters': 'QUAY_REPOSITORY %s' % quay_reponame
|
|
|
|
}
|
|
|
|
for index, command in reversed(list(enumerate(parsed_dockerfile.commands))):
|
|
|
|
if command['command'] == 'FROM':
|
|
|
|
new_command_index = index + 1
|
|
|
|
logger.debug('Injecting env command at dockerfile index: %s', new_command_index)
|
|
|
|
parsed_dockerfile.commands.insert(new_command_index, env_command)
|
|
|
|
break
|
|
|
|
|
2014-01-24 19:40:36 +00:00
|
|
|
@staticmethod
|
|
|
|
def __total_completion(statuses, total_images):
|
|
|
|
percentage_with_sizes = float(len(statuses.values()))/total_images
|
2014-04-30 22:48:36 +00:00
|
|
|
sent_bytes = sum([status['current'] for status in statuses.values()])
|
|
|
|
total_bytes = sum([status['total'] for status in statuses.values()])
|
2014-01-24 19:40:36 +00:00
|
|
|
return float(sent_bytes)/total_bytes*percentage_with_sizes
|
|
|
|
|
2014-04-30 22:48:36 +00:00
|
|
|
@staticmethod
|
|
|
|
def __monitor_completion(status_stream, required_message, status_updater, status_completion_key,
|
|
|
|
num_images=0):
|
|
|
|
images = {}
|
|
|
|
for status in status_stream:
|
|
|
|
logger.debug('%s: %s', status_completion_key, status)
|
|
|
|
if 'status' in status:
|
|
|
|
status_msg = status['status']
|
|
|
|
|
|
|
|
if status_msg == required_message:
|
|
|
|
if 'progressDetail' in status and 'id' in status:
|
|
|
|
image_id = status['id']
|
|
|
|
detail = status['progressDetail']
|
|
|
|
|
|
|
|
if 'current' in detail and 'total' in detail:
|
|
|
|
images[image_id] = detail
|
|
|
|
with status_updater as status_update:
|
|
|
|
status_update[status_completion_key] = \
|
|
|
|
DockerfileBuildContext.__total_completion(images, max(len(images), num_images))
|
|
|
|
|
|
|
|
elif 'errorDetail' in status:
|
|
|
|
message = 'Error pushing image.'
|
|
|
|
if 'message' in status['errorDetail']:
|
|
|
|
message = str(status['errorDetail']['message'])
|
|
|
|
|
|
|
|
raise RuntimeError(message)
|
|
|
|
|
|
|
|
def pull(self):
|
2014-03-27 22:33:13 +00:00
|
|
|
# Login with the specified credentials (if any).
|
|
|
|
if self._pull_credentials:
|
2014-04-01 23:00:11 +00:00
|
|
|
logger.debug('Logging in with pull credentials: %s@%s',
|
|
|
|
self._pull_credentials['username'], self._pull_credentials['registry'])
|
2014-03-31 22:10:34 +00:00
|
|
|
self._build_cl.login(self._pull_credentials['username'], self._pull_credentials['password'],
|
2014-03-27 22:33:13 +00:00
|
|
|
registry=self._pull_credentials['registry'], reauth=True)
|
|
|
|
|
2014-04-14 22:54:39 +00:00
|
|
|
# Pull the image, in case it was updated since the last build
|
2014-06-16 18:01:17 +00:00
|
|
|
image_and_tag_tuple = self._parsed_dockerfile.get_image_and_tag()
|
|
|
|
if image_and_tag_tuple is None or image_and_tag_tuple[0] is None:
|
2014-06-13 20:56:48 +00:00
|
|
|
self._build_logger('Missing FROM command in Dockerfile', build_logs.ERROR)
|
|
|
|
raise JobException('Missing FROM command in Dockerfile')
|
|
|
|
|
2014-06-16 18:01:17 +00:00
|
|
|
image_and_tag = ':'.join(image_and_tag_tuple)
|
2014-04-30 22:48:36 +00:00
|
|
|
self._build_logger('Pulling base image: %s' % image_and_tag)
|
|
|
|
pull_status = self._build_cl.pull(image_and_tag, stream=True)
|
|
|
|
|
|
|
|
self.__monitor_completion(pull_status, 'Downloading', self._status, 'pull_completion')
|
2014-04-14 22:54:39 +00:00
|
|
|
|
2014-05-06 22:46:19 +00:00
|
|
|
def build(self, reservation_extension_method):
|
2014-03-27 22:33:13 +00:00
|
|
|
# Start the build itself.
|
2014-02-04 00:08:37 +00:00
|
|
|
logger.debug('Starting build.')
|
2014-01-24 19:40:36 +00:00
|
|
|
|
2014-02-05 16:07:54 +00:00
|
|
|
with self._status as status:
|
|
|
|
status['total_commands'] = self._num_steps
|
2014-02-04 00:08:37 +00:00
|
|
|
|
2014-04-30 22:48:36 +00:00
|
|
|
logger.debug('Building to tags named: %s', self._tag_names)
|
2014-02-24 21:11:23 +00:00
|
|
|
context_path = os.path.join(self._build_dir, self._dockerfile_subdir)
|
|
|
|
|
2014-04-30 22:48:36 +00:00
|
|
|
logger.debug('Final context path: %s exists: %s', context_path,
|
|
|
|
os.path.exists(context_path))
|
2014-02-24 21:11:23 +00:00
|
|
|
|
2014-03-27 22:33:13 +00:00
|
|
|
build_status = self._build_cl.build(path=context_path, stream=True)
|
2014-02-04 00:08:37 +00:00
|
|
|
|
|
|
|
current_step = 0
|
|
|
|
built_image = None
|
2014-03-28 21:53:33 +00:00
|
|
|
for status in build_status:
|
2014-03-07 17:27:30 +00:00
|
|
|
fully_unwrapped = ""
|
|
|
|
if isinstance(status, dict):
|
2014-04-01 17:46:41 +00:00
|
|
|
keys_to_extract = ['error', 'status', 'stream']
|
|
|
|
for key in keys_to_extract:
|
|
|
|
if key in status:
|
|
|
|
fully_unwrapped = status[key]
|
|
|
|
break
|
|
|
|
|
|
|
|
if not fully_unwrapped:
|
|
|
|
logger.debug('Status dict did not have any extractable keys and was: %s', status)
|
2014-03-07 17:27:30 +00:00
|
|
|
elif isinstance(status, basestring):
|
|
|
|
fully_unwrapped = status
|
|
|
|
|
2014-03-05 22:44:22 +00:00
|
|
|
status_str = str(fully_unwrapped.encode('utf-8'))
|
2014-07-30 21:54:58 +00:00
|
|
|
|
|
|
|
# Check for system errors when building.
|
|
|
|
if matches_system_error(status_str):
|
|
|
|
raise WorkerUnhealthyException(status_str)
|
|
|
|
|
2014-02-13 16:44:39 +00:00
|
|
|
logger.debug('Status: %s', status_str)
|
2014-03-05 22:44:22 +00:00
|
|
|
step_increment = re.search(r'Step ([0-9]+) :', status_str)
|
2014-02-04 00:08:37 +00:00
|
|
|
if step_increment:
|
2014-02-13 16:44:39 +00:00
|
|
|
self._build_logger(status_str, build_logs.COMMAND)
|
2014-02-04 00:08:37 +00:00
|
|
|
current_step = int(step_increment.group(1))
|
2014-04-30 22:48:36 +00:00
|
|
|
logger.debug('Step now: %s/%s', current_step, self._num_steps)
|
2014-03-05 22:44:22 +00:00
|
|
|
with self._status as status_update:
|
|
|
|
status_update['current_command'] = current_step
|
2014-05-06 22:46:19 +00:00
|
|
|
|
|
|
|
# Tell the queue that we're making progress every time we advance a step
|
|
|
|
reservation_extension_method(RESERVATION_TIME)
|
2014-02-04 00:08:37 +00:00
|
|
|
continue
|
2014-02-10 20:03:55 +00:00
|
|
|
else:
|
2014-02-13 16:44:39 +00:00
|
|
|
self._build_logger(status_str)
|
2014-02-04 00:08:37 +00:00
|
|
|
|
2014-03-05 22:44:22 +00:00
|
|
|
complete = re.match(r'Successfully built ([a-z0-9]+)$', status_str)
|
2014-02-04 00:08:37 +00:00
|
|
|
if complete:
|
|
|
|
built_image = complete.group(1)
|
2014-04-30 22:48:36 +00:00
|
|
|
logger.debug('Final image ID is: %s', built_image)
|
2014-02-04 00:08:37 +00:00
|
|
|
continue
|
|
|
|
|
|
|
|
# Get the image count
|
|
|
|
if not built_image:
|
|
|
|
return
|
|
|
|
|
|
|
|
return built_image
|
2014-01-24 19:40:36 +00:00
|
|
|
|
2014-02-05 16:07:54 +00:00
|
|
|
def push(self, built_image):
|
2014-02-04 00:08:37 +00:00
|
|
|
# Login to the registry
|
2014-02-24 21:11:23 +00:00
|
|
|
host = re.match(r'([a-z0-9.:]+)/.+/.+$', self._repo)
|
2014-02-04 00:08:37 +00:00
|
|
|
if not host:
|
2014-02-24 21:11:23 +00:00
|
|
|
raise RuntimeError('Invalid repo name: %s' % self._repo)
|
2014-01-24 21:25:25 +00:00
|
|
|
|
2014-02-04 00:08:37 +00:00
|
|
|
for protocol in ['https', 'http']:
|
|
|
|
registry_endpoint = '%s://%s/v1/' % (protocol, host.group(1))
|
2014-04-30 22:48:36 +00:00
|
|
|
logger.debug('Attempting login to registry: %s', registry_endpoint)
|
2014-01-24 21:25:25 +00:00
|
|
|
|
2014-02-04 00:08:37 +00:00
|
|
|
try:
|
2014-03-27 22:33:13 +00:00
|
|
|
self._push_cl.login('$token', self._push_token, registry=registry_endpoint)
|
2014-02-04 00:08:37 +00:00
|
|
|
break
|
|
|
|
except APIError:
|
|
|
|
pass # Probably the wrong protocol
|
2014-01-24 19:40:36 +00:00
|
|
|
|
2014-02-24 21:11:23 +00:00
|
|
|
for tag in self._tag_names:
|
2014-04-30 22:48:36 +00:00
|
|
|
logger.debug('Tagging image %s as %s:%s', built_image, self._repo, tag)
|
2014-03-27 22:33:13 +00:00
|
|
|
self._push_cl.tag(built_image, self._repo, tag)
|
2014-02-24 21:11:23 +00:00
|
|
|
|
2014-03-27 22:33:13 +00:00
|
|
|
history = json.loads(self._push_cl.history(built_image))
|
2014-02-04 00:08:37 +00:00
|
|
|
num_images = len(history)
|
2014-01-24 19:40:36 +00:00
|
|
|
|
2014-04-30 22:48:36 +00:00
|
|
|
logger.debug('Pushing to repo %s', self._repo)
|
2014-03-27 22:33:13 +00:00
|
|
|
resp = self._push_cl.push(self._repo, stream=True)
|
2014-04-30 22:48:36 +00:00
|
|
|
self.__monitor_completion(resp, 'Pushing', self._status, 'push_completion', num_images)
|
2014-04-14 19:21:05 +00:00
|
|
|
|
|
|
|
def __cleanup_containers(self):
|
2014-01-24 19:40:36 +00:00
|
|
|
# First clean up any containers that might be holding the images
|
2014-03-27 22:33:13 +00:00
|
|
|
for running in self._build_cl.containers(quiet=True):
|
2014-04-30 22:48:36 +00:00
|
|
|
logger.debug('Killing container: %s', running['Id'])
|
2014-03-27 22:33:13 +00:00
|
|
|
self._build_cl.kill(running['Id'])
|
2014-01-24 19:40:36 +00:00
|
|
|
|
|
|
|
# Next, remove all of the containers (which should all now be killed)
|
2014-03-27 22:33:13 +00:00
|
|
|
for container in self._build_cl.containers(all=True, quiet=True):
|
2014-04-30 22:48:36 +00:00
|
|
|
logger.debug('Removing container: %s', container['Id'])
|
2014-03-27 22:33:13 +00:00
|
|
|
self._build_cl.remove_container(container['Id'])
|
2014-01-24 19:40:36 +00:00
|
|
|
|
2014-04-30 22:48:36 +00:00
|
|
|
def __cleanup_images(self):
|
|
|
|
""" Remove tags on internal nodes, and remove images older than the expiratino time. """
|
|
|
|
ids_to_images, ids_to_children = self.__compute_image_graph()
|
|
|
|
|
|
|
|
# Untag all internal nodes, which are usually the base images
|
|
|
|
for internal_id in ids_to_children.keys():
|
|
|
|
internal = ids_to_images[internal_id]
|
|
|
|
if internal['RepoTags'] != NO_TAGS:
|
|
|
|
for tag_name in internal['RepoTags']:
|
|
|
|
self._build_cl.remove_image(tag_name)
|
|
|
|
|
|
|
|
# Make sure all of the leaves have gibberish tags, and remove those older than our expiration
|
|
|
|
leaves = set(ids_to_images.keys()) - set(ids_to_children.keys())
|
2014-04-14 19:21:05 +00:00
|
|
|
now = datetime.now()
|
2014-04-30 22:48:36 +00:00
|
|
|
for leaf_id in leaves:
|
|
|
|
leaf = ids_to_images[leaf_id]
|
|
|
|
|
|
|
|
created = datetime.fromtimestamp(leaf['Created'])
|
|
|
|
expiration = created + timedelta(hours=CACHE_EXPIRATION_PERIOD_HOURS)
|
|
|
|
if expiration > now:
|
|
|
|
# Assign a new tag as a uuid to preserve this image
|
|
|
|
new_tag = str(uuid4())
|
|
|
|
self._build_cl.tag(leaf['Id'], new_tag)
|
|
|
|
|
|
|
|
# Remove all of the existing tags
|
|
|
|
if leaf['RepoTags'] != NO_TAGS:
|
|
|
|
for tag_name in leaf['RepoTags']:
|
|
|
|
self._build_cl.remove_image(tag_name)
|
|
|
|
|
|
|
|
def __prune_cache(self):
|
|
|
|
""" Remove the oldest leaf image until the cache size is the desired size. """
|
|
|
|
|
|
|
|
logger.debug('Pruning cache to size(gb): %s', self._cache_size_gb)
|
|
|
|
while self.__compute_cache_size_gb() > self._cache_size_gb:
|
|
|
|
logger.debug('Locating the oldest image in the cache to prune.')
|
|
|
|
# Find the oldest tagged image and remove it
|
|
|
|
oldest_creation_time = datetime.max
|
|
|
|
oldest_image = None
|
|
|
|
for image in self._build_cl.images():
|
|
|
|
created = datetime.fromtimestamp(image['Created'])
|
|
|
|
if created < oldest_creation_time:
|
|
|
|
oldest_creation_time = created
|
|
|
|
oldest_image = image
|
|
|
|
|
|
|
|
logger.debug('Removing oldest image from cache: %s', oldest_image['Id'])
|
|
|
|
# Remove all tags on the oldest image
|
|
|
|
if oldest_image['RepoTags'] == NO_TAGS:
|
|
|
|
# Remove the image id directly since there are no tags
|
|
|
|
self._build_cl.remove_image(oldest_image['Id'])
|
|
|
|
else:
|
|
|
|
# Remove all tags
|
|
|
|
for tag_name in oldest_image['RepoTags']:
|
|
|
|
self._build_cl.remove_image(tag_name)
|
|
|
|
|
|
|
|
def __compute_cache_size_gb(self):
|
|
|
|
all_images = self._build_cl.images(all=True)
|
|
|
|
size_in_bytes = sum([img['Size'] for img in all_images])
|
|
|
|
size_in_gb = float(size_in_bytes)/1024/1024/1024
|
|
|
|
logger.debug('Computed cache size(gb) of: %s', size_in_gb)
|
|
|
|
return size_in_gb
|
|
|
|
|
|
|
|
def __compute_image_graph(self):
|
|
|
|
all_images = self._build_cl.images(all=True)
|
|
|
|
|
|
|
|
ids_to_images = {}
|
|
|
|
ids_to_children = defaultdict(list)
|
|
|
|
for image in all_images:
|
|
|
|
if image['ParentId'] != '':
|
|
|
|
ids_to_children[image['ParentId']].append(image)
|
|
|
|
ids_to_images[image['Id']] = image
|
|
|
|
|
|
|
|
return (ids_to_images, ids_to_children)
|
|
|
|
|
2014-02-05 16:07:54 +00:00
|
|
|
|
|
|
|
class DockerfileBuildWorker(Worker):
|
2014-04-30 22:48:36 +00:00
|
|
|
def __init__(self, cache_size_gb, *vargs, **kwargs):
|
2014-02-05 16:07:54 +00:00
|
|
|
super(DockerfileBuildWorker, self).__init__(*vargs, **kwargs)
|
|
|
|
|
|
|
|
self._mime_processors = {
|
|
|
|
'application/zip': DockerfileBuildWorker.__prepare_zip,
|
2014-03-07 04:40:21 +00:00
|
|
|
'application/x-zip-compressed': DockerfileBuildWorker.__prepare_zip,
|
2014-02-05 16:07:54 +00:00
|
|
|
'text/plain': DockerfileBuildWorker.__prepare_dockerfile,
|
|
|
|
'application/octet-stream': DockerfileBuildWorker.__prepare_dockerfile,
|
2014-03-31 19:40:24 +00:00
|
|
|
'application/x-tar': DockerfileBuildWorker.__prepare_tarball,
|
|
|
|
'application/gzip': DockerfileBuildWorker.__prepare_tarball,
|
2014-04-07 14:58:53 +00:00
|
|
|
'application/x-gzip': DockerfileBuildWorker.__prepare_tarball,
|
2014-02-05 16:07:54 +00:00
|
|
|
}
|
|
|
|
|
2014-04-02 23:32:41 +00:00
|
|
|
self._timeout = Event()
|
2014-04-30 22:48:36 +00:00
|
|
|
self._cache_size_gb = cache_size_gb
|
2014-04-02 23:32:41 +00:00
|
|
|
|
2014-02-05 16:07:54 +00:00
|
|
|
@staticmethod
|
|
|
|
def __prepare_zip(request_file):
|
|
|
|
build_dir = mkdtemp(prefix='docker-build-')
|
|
|
|
|
|
|
|
# Save the zip file to temp somewhere
|
|
|
|
with TemporaryFile() as zip_file:
|
2014-04-04 20:06:41 +00:00
|
|
|
zip_file.write(request_file.content)
|
2014-02-05 16:07:54 +00:00
|
|
|
to_extract = ZipFile(zip_file)
|
|
|
|
to_extract.extractall(build_dir)
|
|
|
|
|
|
|
|
return build_dir
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def __prepare_dockerfile(request_file):
|
|
|
|
build_dir = mkdtemp(prefix='docker-build-')
|
|
|
|
dockerfile_path = os.path.join(build_dir, "Dockerfile")
|
|
|
|
with open(dockerfile_path, 'w') as dockerfile:
|
|
|
|
dockerfile.write(request_file.content)
|
|
|
|
|
|
|
|
return build_dir
|
|
|
|
|
2014-03-31 19:40:24 +00:00
|
|
|
@staticmethod
|
|
|
|
def __prepare_tarball(request_file):
|
|
|
|
build_dir = mkdtemp(prefix='docker-build-')
|
|
|
|
|
|
|
|
# Save the zip file to temp somewhere
|
|
|
|
with tarfile.open(mode='r|*', fileobj=request_file.raw) as tar_stream:
|
2014-04-01 17:46:41 +00:00
|
|
|
safe_extractall(tar_stream, build_dir)
|
2014-03-31 19:40:24 +00:00
|
|
|
|
|
|
|
return build_dir
|
|
|
|
|
2014-04-02 23:32:41 +00:00
|
|
|
def watchdog(self):
|
|
|
|
logger.debug('Running build watchdog code.')
|
|
|
|
|
2014-07-30 21:54:58 +00:00
|
|
|
try:
|
|
|
|
docker_cl = Client()
|
2014-04-02 23:32:41 +00:00
|
|
|
|
2014-07-30 21:54:58 +00:00
|
|
|
# Iterate the running containers and kill ones that have been running more than 20 minutes
|
|
|
|
for container in docker_cl.containers():
|
|
|
|
start_time = datetime.fromtimestamp(container['Created'])
|
|
|
|
running_time = datetime.now() - start_time
|
|
|
|
if running_time > timedelta(minutes=TIMEOUT_PERIOD_MINUTES):
|
|
|
|
logger.warning('Container has been running too long: %s with command: %s',
|
|
|
|
container['Id'], container['Command'])
|
|
|
|
docker_cl.kill(container['Id'])
|
|
|
|
self._timeout.set()
|
2014-08-27 23:02:53 +00:00
|
|
|
|
2014-07-30 21:54:58 +00:00
|
|
|
except ConnectionError as exc:
|
|
|
|
raise WorkerUnhealthyException(exc.message)
|
2014-04-02 23:32:41 +00:00
|
|
|
|
2014-01-24 19:40:36 +00:00
|
|
|
def process_queue_item(self, job_details):
|
2014-04-02 23:32:41 +00:00
|
|
|
self._timeout.clear()
|
|
|
|
|
2014-05-19 17:50:45 +00:00
|
|
|
# Make sure we have more information for debugging problems
|
|
|
|
sentry.client.user_context(job_details)
|
|
|
|
|
2014-02-04 00:08:37 +00:00
|
|
|
repository_build = model.get_repository_build(job_details['namespace'],
|
|
|
|
job_details['repository'],
|
|
|
|
job_details['build_uuid'])
|
2013-10-28 18:49:23 +00:00
|
|
|
|
2014-04-02 01:49:06 +00:00
|
|
|
pull_credentials = job_details.get('pull_credentials', None)
|
|
|
|
|
2014-02-24 21:11:23 +00:00
|
|
|
job_config = json.loads(repository_build.job_config)
|
|
|
|
|
2014-02-25 23:22:02 +00:00
|
|
|
resource_url = user_files.get_file_url(repository_build.resource_key)
|
2014-02-24 21:11:23 +00:00
|
|
|
tag_names = job_config['docker_tags']
|
|
|
|
build_subdir = job_config['build_subdir']
|
|
|
|
repo = job_config['repository']
|
|
|
|
|
2014-01-24 19:40:36 +00:00
|
|
|
access_token = repository_build.access_token.code
|
|
|
|
|
2014-02-12 23:58:40 +00:00
|
|
|
log_appender = partial(build_logs.append_log_message,
|
|
|
|
repository_build.uuid)
|
|
|
|
|
|
|
|
log_appender('initializing', build_logs.PHASE)
|
|
|
|
|
2014-02-24 21:11:23 +00:00
|
|
|
start_msg = ('Starting job with resource url: %s repo: %s' % (resource_url,
|
|
|
|
repo))
|
2014-04-02 23:32:41 +00:00
|
|
|
logger.debug(start_msg)
|
2013-10-24 20:37:03 +00:00
|
|
|
|
2014-03-31 19:40:24 +00:00
|
|
|
docker_resource = requests.get(resource_url, stream=True)
|
2014-01-24 19:40:36 +00:00
|
|
|
c_type = docker_resource.headers['content-type']
|
2013-10-24 20:37:03 +00:00
|
|
|
|
2014-04-11 22:34:47 +00:00
|
|
|
if ';' in c_type:
|
|
|
|
c_type = c_type.split(';')[0]
|
|
|
|
|
2014-02-24 21:11:23 +00:00
|
|
|
filetype_msg = ('Request to build type: %s with repo: %s and tags: %s' %
|
|
|
|
(c_type, repo, tag_names))
|
2014-02-04 00:08:37 +00:00
|
|
|
logger.info(filetype_msg)
|
2014-02-12 23:58:40 +00:00
|
|
|
log_appender(filetype_msg)
|
2013-10-24 20:37:03 +00:00
|
|
|
|
2014-07-18 19:58:18 +00:00
|
|
|
# Spawn a notification that the build has started.
|
|
|
|
event_data = {
|
|
|
|
'build_id': repository_build.uuid,
|
|
|
|
'build_name': repository_build.display_name,
|
|
|
|
'docker_tags': tag_names,
|
|
|
|
'trigger_id': repository_build.trigger.uuid,
|
|
|
|
'trigger_kind': repository_build.trigger.service.name
|
|
|
|
}
|
|
|
|
|
2014-07-18 20:34:52 +00:00
|
|
|
spawn_notification(repository_build.repository, 'build_start', event_data,
|
|
|
|
subpage='build?current=%s' % repository_build.uuid,
|
2014-07-18 19:58:18 +00:00
|
|
|
pathargs=['build', repository_build.uuid])
|
|
|
|
|
2014-08-15 21:58:11 +00:00
|
|
|
|
2014-07-18 19:58:18 +00:00
|
|
|
# Setup a handler for spawning failure messages.
|
|
|
|
def spawn_failure(message, event_data):
|
2014-07-18 20:34:52 +00:00
|
|
|
event_data['error_message'] = message
|
|
|
|
spawn_notification(repository_build.repository, 'build_failure', event_data,
|
|
|
|
subpage='build?current=%s' % repository_build.uuid,
|
2014-07-18 19:58:18 +00:00
|
|
|
pathargs=['build', repository_build.uuid])
|
|
|
|
|
2014-08-15 21:58:11 +00:00
|
|
|
if c_type not in self._mime_processors:
|
|
|
|
log_appender('error', build_logs.PHASE)
|
|
|
|
repository_build.phase = 'error'
|
|
|
|
repository_build.save()
|
|
|
|
message = 'Unknown mime-type: %s' % c_type
|
|
|
|
log_appender(message, build_logs.ERROR)
|
|
|
|
spawn_failure(message, event_data)
|
|
|
|
raise JobException(message)
|
|
|
|
|
|
|
|
# Try to build the build directory package from the buildpack.
|
|
|
|
log_appender('unpacking', build_logs.PHASE)
|
|
|
|
repository_build.phase = 'unpacking'
|
|
|
|
repository_build.save()
|
|
|
|
|
|
|
|
build_dir = None
|
|
|
|
try:
|
|
|
|
build_dir = self._mime_processors[c_type](docker_resource)
|
|
|
|
except Exception as ex:
|
2014-08-15 22:23:43 +00:00
|
|
|
cur_message = ex.message or 'Error while unpacking build package'
|
|
|
|
log_appender(cur_message, build_logs.ERROR)
|
|
|
|
spawn_failure(cur_message, event_data)
|
|
|
|
raise JobException(cur_message)
|
2014-08-15 21:58:11 +00:00
|
|
|
|
2014-07-18 19:58:18 +00:00
|
|
|
# Start the build process.
|
2014-04-30 22:48:36 +00:00
|
|
|
try:
|
|
|
|
with DockerfileBuildContext(build_dir, build_subdir, repo, tag_names, access_token,
|
|
|
|
repository_build.uuid, self._cache_size_gb,
|
|
|
|
pull_credentials) as build_ctxt:
|
|
|
|
log_appender('pulling', build_logs.PHASE)
|
|
|
|
repository_build.phase = 'pulling'
|
|
|
|
repository_build.save()
|
|
|
|
build_ctxt.pull()
|
|
|
|
|
2014-05-06 22:46:19 +00:00
|
|
|
self.extend_processing(RESERVATION_TIME)
|
|
|
|
|
2014-04-30 22:48:36 +00:00
|
|
|
log_appender('building', build_logs.PHASE)
|
|
|
|
repository_build.phase = 'building'
|
|
|
|
repository_build.save()
|
2014-05-06 22:46:19 +00:00
|
|
|
built_image = build_ctxt.build(self.extend_processing)
|
2014-02-04 00:08:37 +00:00
|
|
|
|
2014-02-05 16:07:54 +00:00
|
|
|
if not built_image:
|
2014-02-12 23:58:40 +00:00
|
|
|
log_appender('error', build_logs.PHASE)
|
2014-02-05 16:07:54 +00:00
|
|
|
repository_build.phase = 'error'
|
|
|
|
repository_build.save()
|
2014-05-06 22:46:19 +00:00
|
|
|
|
|
|
|
message = 'Unable to build dockerfile.'
|
2014-04-02 23:32:41 +00:00
|
|
|
if self._timeout.is_set():
|
2014-05-06 22:46:19 +00:00
|
|
|
message = 'Build step was terminated after %s minutes.' % TIMEOUT_PERIOD_MINUTES
|
|
|
|
|
|
|
|
log_appender(message, build_logs.ERROR)
|
|
|
|
raise JobException(message)
|
|
|
|
|
|
|
|
self.extend_processing(RESERVATION_TIME)
|
2014-02-04 00:08:37 +00:00
|
|
|
|
2014-02-12 23:58:40 +00:00
|
|
|
log_appender('pushing', build_logs.PHASE)
|
2014-02-05 16:07:54 +00:00
|
|
|
repository_build.phase = 'pushing'
|
|
|
|
repository_build.save()
|
2014-02-04 00:08:37 +00:00
|
|
|
|
2014-02-05 16:07:54 +00:00
|
|
|
build_ctxt.push(built_image)
|
2013-10-24 20:37:03 +00:00
|
|
|
|
2014-02-12 23:58:40 +00:00
|
|
|
log_appender('complete', build_logs.PHASE)
|
2014-02-05 16:07:54 +00:00
|
|
|
repository_build.phase = 'complete'
|
|
|
|
repository_build.save()
|
2013-10-24 20:37:03 +00:00
|
|
|
|
2014-07-18 19:58:18 +00:00
|
|
|
# Spawn a notification that the build has completed.
|
2014-07-18 20:34:52 +00:00
|
|
|
spawn_notification(repository_build.repository, 'build_success', event_data,
|
|
|
|
subpage='build?current=%s' % repository_build.uuid,
|
2014-07-18 19:58:18 +00:00
|
|
|
pathargs=['build', repository_build.uuid])
|
|
|
|
|
2014-05-06 22:46:19 +00:00
|
|
|
except WorkerUnhealthyException as exc:
|
2014-07-18 19:58:18 +00:00
|
|
|
# Spawn a notification that the build has failed.
|
2014-08-26 16:41:43 +00:00
|
|
|
log_appender('Worker has become unhealthy. Will retry shortly.', build_logs.ERROR)
|
2014-07-18 19:58:18 +00:00
|
|
|
spawn_failure(exc.message, event_data)
|
|
|
|
|
|
|
|
# Raise the exception to the queue.
|
2014-05-06 22:46:19 +00:00
|
|
|
raise exc
|
|
|
|
|
2014-07-11 16:05:52 +00:00
|
|
|
except JobException as exc:
|
2014-07-18 19:58:18 +00:00
|
|
|
# Spawn a notification that the build has failed.
|
|
|
|
spawn_failure(exc.message, event_data)
|
|
|
|
|
|
|
|
# Raise the exception to the queue.
|
2014-07-11 16:05:52 +00:00
|
|
|
raise exc
|
|
|
|
|
2014-07-30 21:54:58 +00:00
|
|
|
except ConnectionError as exc:
|
|
|
|
# A connection exception means the worker has become unhealthy (Docker is down)
|
|
|
|
# so we re-raise as that exception.
|
|
|
|
log_appender('Docker daemon has gone away. Will retry shortly.', build_logs.ERROR)
|
|
|
|
raise WorkerUnhealthyException(exc.message)
|
|
|
|
|
2014-04-30 22:48:36 +00:00
|
|
|
except Exception as exc:
|
2014-07-18 19:58:18 +00:00
|
|
|
# Spawn a notification that the build has failed.
|
|
|
|
spawn_failure(exc.message, event_data)
|
|
|
|
|
|
|
|
# Write the error to the logs.
|
2014-05-19 17:50:45 +00:00
|
|
|
sentry.client.captureException()
|
2014-04-30 22:48:36 +00:00
|
|
|
log_appender('error', build_logs.PHASE)
|
|
|
|
logger.exception('Exception when processing request.')
|
|
|
|
repository_build.phase = 'error'
|
|
|
|
repository_build.save()
|
|
|
|
log_appender(str(exc), build_logs.ERROR)
|
2014-07-18 19:58:18 +00:00
|
|
|
|
|
|
|
# Raise the exception to the queue.
|
2014-05-06 22:46:19 +00:00
|
|
|
raise JobException(str(exc))
|
2013-10-24 20:37:03 +00:00
|
|
|
|
|
|
|
|
|
|
|
desc = 'Worker daemon to monitor dockerfile build'
|
|
|
|
parser = argparse.ArgumentParser(description=desc)
|
2014-04-30 22:48:36 +00:00
|
|
|
parser.add_argument('--cachegb', default=20, type=float,
|
|
|
|
help='Maximum cache size in gigabytes.')
|
2013-10-24 20:37:03 +00:00
|
|
|
args = parser.parse_args()
|
|
|
|
|
2014-05-06 22:46:19 +00:00
|
|
|
worker = DockerfileBuildWorker(args.cachegb, dockerfile_build_queue,
|
|
|
|
reservation_seconds=RESERVATION_TIME)
|
2014-05-18 21:19:14 +00:00
|
|
|
worker.start(start_status_server_port=8000)
|