12 from collections import namedtuple
16 import arvados.commands._util as arv_cmd
17 import arvados.commands.put as arv_put
19 STAT_CACHE_ERRORS = (IOError, OSError, ValueError)
21 DockerImage = namedtuple('DockerImage',
22 ['repo', 'tag', 'hash', 'created', 'vsize'])
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")
29 _group = opt_parser.add_mutually_exclusive_group()
31 '--pull', action='store_true', default=True,
32 help="Pull the latest image from Docker repositories first (default)")
34 '--no-pull', action='store_false', dest='pull',
35 help="Don't pull images from Docker repositories")
37 opt_parser.add_argument(
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')")
44 arg_parser = argparse.ArgumentParser(
45 description="Upload a Docker image to Arvados",
46 parents=[opt_parser, arv_put.run_opts])
48 class DockerError(Exception):
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)
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)
61 docker_proc.stdin.close()
64 def check_docker(proc, description):
66 if proc.returncode != 0:
67 raise DockerError("docker {} returned status code {}".
68 format(description, proc.returncode))
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:
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")
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()
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)
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)
106 elif hash_count == 0:
107 raise DockerError("no matching image found")
109 raise DockerError("{} images match {}".format(hash_count, image_search))
111 def stat_cache_name(image_file):
112 return getattr(image_file, 'name', image_file) + '.stat'
114 def pull_image(image_name, image_tag):
115 check_docker(popen_docker(['pull', '-t', image_tag, image_name]), "pull")
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),
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.
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')
139 file_path = os.path.join(cache_dir, filename)
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
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()
155 def main(arguments=None):
156 args = arg_parser.parse_args(arguments)
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)
164 image_hash = find_one_image_hash(args.image, args.tag)
165 except DockerError as error:
166 print >>sys.stderr, "arv-keepdocker:", error.message
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']
175 "arv-keepdocker: Image {} already stored in collection(s):".
177 message.extend(link['head_uuid'] for link in existing_links)
178 print >>sys.stderr, "\n".join(message)
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)
185 save_image(image_hash, image_file)
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()
193 # Read the image metadata and make Arvados links from it.
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)
200 link_base = {'head_uuid': coll_uuid, 'properties': {}}
201 if 'created' in image_metadata:
202 link_base['properties']['image_timestamp'] = image_metadata['created']
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),
212 for filename in [stat_cache_name(image_file), image_file.name]:
215 except OSError as error:
216 if error.errno != errno.ENOENT:
219 if __name__ == '__main__':