Merge branch 'master' into origin-2883-job-log-viewer
[arvados.git] / sdk / python / arvados / commands / keepdocker.py
1 #!/usr/bin/env python
2
3 import argparse
4 import errno
5 import json
6 import os
7 import subprocess
8 import sys
9 import tarfile
10 import tempfile
11
12 from collections import namedtuple
13 from stat import *
14
15 import arvados
16 import arvados.commands._util as arv_cmd
17 import arvados.commands.put as arv_put
18
19 STAT_CACHE_ERRORS = (IOError, OSError, ValueError)
20
21 DockerImage = namedtuple('DockerImage',
22                          ['repo', 'tag', 'hash', 'created', 'vsize'])
23
24 opt_parser = argparse.ArgumentParser(add_help=False)
25 opt_parser.add_argument(
26     '-f', '--force', action='store_true', default=False,
27     help="Re-upload the image even if it already exists on the server")
28
29 _group = opt_parser.add_mutually_exclusive_group()
30 _group.add_argument(
31     '--pull', action='store_true', default=True,
32     help="Pull the latest image from Docker repositories first (default)")
33 _group.add_argument(
34     '--no-pull', action='store_false', dest='pull',
35     help="Don't pull images from Docker repositories")
36
37 opt_parser.add_argument(
38     'image',
39     help="Docker image to upload, as a repository name or hash")
40 opt_parser.add_argument(
41     'tag', nargs='?', default='latest',
42     help="Tag of the Docker image to upload (default 'latest')")
43
44 arg_parser = argparse.ArgumentParser(
45         description="Upload a Docker image to Arvados",
46         parents=[opt_parser, arv_put.run_opts])
47
48 class DockerError(Exception):
49     pass
50
51
52 def popen_docker(cmd, *args, **kwargs):
53     manage_stdin = ('stdin' not in kwargs)
54     kwargs.setdefault('stdin', subprocess.PIPE)
55     kwargs.setdefault('stdout', sys.stderr)
56     try:
57         docker_proc = subprocess.Popen(['docker.io'] + cmd, *args, **kwargs)
58     except OSError:  # No docker.io in $PATH
59         docker_proc = subprocess.Popen(['docker'] + cmd, *args, **kwargs)
60     if manage_stdin:
61         docker_proc.stdin.close()
62     return docker_proc
63
64 def check_docker(proc, description):
65     proc.wait()
66     if proc.returncode != 0:
67         raise DockerError("docker {} returned status code {}".
68                           format(description, proc.returncode))
69
70 def docker_images():
71     # Yield a DockerImage tuple for each installed image.
72     list_proc = popen_docker(['images', '--no-trunc'], stdout=subprocess.PIPE)
73     list_output = iter(list_proc.stdout)
74     next(list_output)  # Ignore the header line
75     for line in list_output:
76         words = line.split()
77         size_index = len(words) - 2
78         repo, tag, imageid = words[:3]
79         ctime = ' '.join(words[3:size_index])
80         vsize = ' '.join(words[size_index:])
81         yield DockerImage(repo, tag, imageid, ctime, vsize)
82     list_proc.stdout.close()
83     check_docker(list_proc, "images")
84
85 def find_image_hashes(image_search, image_tag=None):
86     # Given one argument, search for Docker images with matching hashes,
87     # and return their full hashes in a set.
88     # Given two arguments, also search for a Docker image with the
89     # same repository and tag.  If one is found, return its hash in a
90     # set; otherwise, fall back to the one-argument hash search.
91     # Returns None if no match is found, or a hash search is ambiguous.
92     hash_search = image_search.lower()
93     hash_matches = set()
94     for image in docker_images():
95         if (image.repo == image_search) and (image.tag == image_tag):
96             return set([image.hash])
97         elif image.hash.startswith(hash_search):
98             hash_matches.add(image.hash)
99     return hash_matches
100
101 def find_one_image_hash(image_search, image_tag=None):
102     hashes = find_image_hashes(image_search, image_tag)
103     hash_count = len(hashes)
104     if hash_count == 1:
105         return hashes.pop()
106     elif hash_count == 0:
107         raise DockerError("no matching image found")
108     else:
109         raise DockerError("{} images match {}".format(hash_count, image_search))
110
111 def stat_cache_name(image_file):
112     return getattr(image_file, 'name', image_file) + '.stat'
113
114 def pull_image(image_name, image_tag):
115     check_docker(popen_docker(['pull', '-t', image_tag, image_name]), "pull")
116
117 def save_image(image_hash, image_file):
118     # Save the specified Docker image to image_file, then try to save its
119     # stats so we can try to resume after interruption.
120     check_docker(popen_docker(['save', image_hash], stdout=image_file),
121                  "save")
122     image_file.flush()
123     try:
124         with open(stat_cache_name(image_file), 'w') as statfile:
125             json.dump(tuple(os.fstat(image_file.fileno())), statfile)
126     except STAT_CACHE_ERRORS:
127         pass  # We won't resume from this cache.  No big deal.
128
129 def prep_image_file(filename):
130     # Return a file object ready to save a Docker image,
131     # and a boolean indicating whether or not we need to actually save the
132     # image (False if a cached save is available).
133     cache_dir = arv_cmd.make_home_conf_dir(
134         os.path.join('.cache', 'arvados', 'docker'), 0o700)
135     if cache_dir is None:
136         image_file = tempfile.NamedTemporaryFile(suffix='.tar')
137         need_save = True
138     else:
139         file_path = os.path.join(cache_dir, filename)
140         try:
141             with open(stat_cache_name(file_path)) as statfile:
142                 prev_stat = json.load(statfile)
143             now_stat = os.stat(file_path)
144             need_save = any(prev_stat[field] != now_stat[field]
145                             for field in [ST_MTIME, ST_SIZE])
146         except STAT_CACHE_ERRORS + (AttributeError, IndexError):
147             need_save = True  # We couldn't compare against old stats
148         image_file = open(file_path, 'w+b' if need_save else 'rb')
149     return image_file, need_save
150
151 def make_link(link_class, link_name, **link_attrs):
152     link_attrs.update({'link_class': link_class, 'name': link_name})
153     return arvados.api('v1').links().create(body=link_attrs).execute()
154
155 def main(arguments=None):
156     args = arg_parser.parse_args(arguments)
157
158     # Pull the image if requested, unless the image is specified as a hash
159     # that we already have.
160     if args.pull and not find_image_hashes(args.image):
161         pull_image(args.image, args.tag)
162
163     try:
164         image_hash = find_one_image_hash(args.image, args.tag)
165     except DockerError as error:
166         print >>sys.stderr, "arv-keepdocker:", error.message
167         sys.exit(1)
168     if not args.force:
169         # Abort if this image is already in Arvados.
170         existing_links = arvados.api('v1').links().list(
171             filters=[['link_class', '=', 'docker_image_hash'],
172                      ['name', '=', image_hash]]).execute()['items']
173         if existing_links:
174             message = [
175                 "arv-keepdocker: Image {} already stored in collection(s):".
176                 format(image_hash)]
177             message.extend(link['head_uuid'] for link in existing_links)
178             print >>sys.stderr, "\n".join(message)
179             sys.exit(0)
180
181     # Open a file for the saved image, and write it if needed.
182     outfile_name = '{}.tar'.format(image_hash)
183     image_file, need_save = prep_image_file(outfile_name)
184     if need_save:
185         save_image(image_hash, image_file)
186
187     # Call arv-put with switches we inherited from it
188     # (a.k.a., switches that aren't our own).
189     put_args = opt_parser.parse_known_args(arguments)[1]
190     coll_uuid = arv_put.main(
191         put_args + ['--filename', outfile_name, image_file.name]).strip()
192
193     # Read the image metadata and make Arvados links from it.
194     image_file.seek(0)
195     image_tar = tarfile.open(fileobj=image_file)
196     json_file = image_tar.extractfile(image_tar.getmember(image_hash + '/json'))
197     image_metadata = json.load(json_file)
198     json_file.close()
199     image_tar.close()
200     link_base = {'head_uuid': coll_uuid, 'properties': {}}
201     if 'created' in image_metadata:
202         link_base['properties']['image_timestamp'] = image_metadata['created']
203
204     make_link('docker_image_hash', image_hash, **link_base)
205     if not image_hash.startswith(args.image.lower()):
206         make_link('docker_image_repository', args.image, **link_base)
207         make_link('docker_image_repo+tag', '{}:{}'.format(args.image, args.tag),
208                   **link_base)
209
210     # Clean up.
211     image_file.close()
212     for filename in [stat_cache_name(image_file), image_file.name]:
213         try:
214             os.unlink(filename)
215         except OSError as error:
216             if error.errno != errno.ENOENT:
217                 raise
218
219 if __name__ == '__main__':
220     main()