3 # Docker controlling module
5 # Copyright (c) 2016 Red Hat Inc.
8 # Fam Zheng <famz@redhat.com>
10 # This work is licensed under the terms of the GNU GPL, version 2
11 # or (at your option) any later version. See the COPYING file in
12 # the top-level directory.
25 from tarfile
import TarFile
, TarInfo
26 from StringIO
import StringIO
27 from shutil
import copy
, rmtree
28 from pwd
import getpwuid
31 FILTERED_ENV_NAMES
= ['ftp_proxy', 'http_proxy', 'https_proxy']
34 DEVNULL
= open(os
.devnull
, 'wb')
37 def _text_checksum(text
):
38 """Calculate a digest string unique to the text content"""
39 return hashlib
.sha1(text
).hexdigest()
41 def _file_checksum(filename
):
42 return _text_checksum(open(filename
, 'rb').read())
44 def _guess_docker_command():
45 """ Guess a working docker command or raise exception if not found"""
46 commands
= [["docker"], ["sudo", "-n", "docker"]]
49 if subprocess
.call(cmd
+ ["images"],
50 stdout
=DEVNULL
, stderr
=DEVNULL
) == 0:
54 commands_txt
= "\n".join([" " + " ".join(x
) for x
in commands
])
55 raise Exception("Cannot find working docker command. Tried:\n%s" % \
58 def _copy_with_mkdir(src
, root_dir
, sub_path
='.'):
59 """Copy src into root_dir, creating sub_path as needed."""
60 dest_dir
= os
.path
.normpath("%s/%s" % (root_dir
, sub_path
))
64 # we can safely ignore already created directories
67 dest_file
= "%s/%s" % (dest_dir
, os
.path
.basename(src
))
71 def _get_so_libs(executable
):
72 """Return a list of libraries associated with an executable.
74 The paths may be symbolic links which would need to be resolved to
75 ensure theright data is copied."""
78 ldd_re
= re
.compile(r
"(/.*/)(\S*)")
80 ldd_output
= subprocess
.check_output(["ldd", executable
])
81 for line
in ldd_output
.split("\n"):
82 search
= ldd_re
.search(line
)
83 if search
and len(search
.groups()) == 2:
84 so_path
= search
.groups()[0]
85 so_lib
= search
.groups()[1]
86 libs
.append("%s/%s" % (so_path
, so_lib
))
87 except subprocess
.CalledProcessError
:
88 print "%s had no associated libraries (static build?)" % (executable
)
92 def _copy_binary_with_libs(src
, dest_dir
):
93 """Copy a binary executable and all its dependant libraries.
95 This does rely on the host file-system being fairly multi-arch
96 aware so the file don't clash with the guests layout."""
98 _copy_with_mkdir(src
, dest_dir
, "/usr/bin")
100 libs
= _get_so_libs(src
)
103 so_path
= os
.path
.dirname(l
)
104 _copy_with_mkdir(l
, dest_dir
, so_path
)
106 class Docker(object):
107 """ Running Docker commands """
109 self
._command
= _guess_docker_command()
111 atexit
.register(self
._kill
_instances
)
112 signal
.signal(signal
.SIGTERM
, self
._kill
_instances
)
113 signal
.signal(signal
.SIGHUP
, self
._kill
_instances
)
115 def _do(self
, cmd
, quiet
=True, **kwargs
):
117 kwargs
["stdout"] = DEVNULL
118 return subprocess
.call(self
._command
+ cmd
, **kwargs
)
120 def _do_check(self
, cmd
, quiet
=True, **kwargs
):
122 kwargs
["stdout"] = DEVNULL
123 return subprocess
.check_call(self
._command
+ cmd
, **kwargs
)
125 def _do_kill_instances(self
, only_known
, only_active
=True):
129 for i
in self
._output
(cmd
).split():
130 resp
= self
._output
(["inspect", i
])
131 labels
= json
.loads(resp
)[0]["Config"]["Labels"]
132 active
= json
.loads(resp
)[0]["State"]["Running"]
135 instance_uuid
= labels
.get("com.qemu.instance.uuid", None)
136 if not instance_uuid
:
138 if only_known
and instance_uuid
not in self
._instances
:
140 print "Terminating", i
142 self
._do
(["kill", i
])
146 self
._do
_kill
_instances
(False, False)
149 def _kill_instances(self
, *args
, **kwargs
):
150 return self
._do
_kill
_instances
(True)
152 def _output(self
, cmd
, **kwargs
):
153 return subprocess
.check_output(self
._command
+ cmd
,
154 stderr
=subprocess
.STDOUT
,
157 def get_image_dockerfile_checksum(self
, tag
):
158 resp
= self
._output
(["inspect", tag
])
159 labels
= json
.loads(resp
)[0]["Config"].get("Labels", {})
160 return labels
.get("com.qemu.dockerfile-checksum", "")
162 def build_image(self
, tag
, docker_dir
, dockerfile
,
163 quiet
=True, user
=False, argv
=None, extra_files_cksum
=[]):
167 tmp_df
= tempfile
.NamedTemporaryFile(dir=docker_dir
, suffix
=".docker")
168 tmp_df
.write(dockerfile
)
172 uname
= getpwuid(uid
).pw_name
174 tmp_df
.write("RUN id %s 2>/dev/null || useradd -u %d -U %s" %
178 tmp_df
.write("LABEL com.qemu.dockerfile-checksum=%s" %
179 _text_checksum("\n".join([dockerfile
] +
183 self
._do
_check
(["build", "-t", tag
, "-f", tmp_df
.name
] + argv
+ \
187 def update_image(self
, tag
, tarball
, quiet
=True):
188 "Update a tagged image using "
190 self
._do
_check
(["build", "-t", tag
, "-"], quiet
=quiet
, stdin
=tarball
)
192 def image_matches_dockerfile(self
, tag
, dockerfile
):
194 checksum
= self
.get_image_dockerfile_checksum(tag
)
197 return checksum
== _text_checksum(dockerfile
)
199 def run(self
, cmd
, keep
, quiet
):
200 label
= uuid
.uuid1().hex
202 self
._instances
.append(label
)
203 ret
= self
._do
_check
(["run", "--label",
204 "com.qemu.instance.uuid=" + label
] + cmd
,
207 self
._instances
.remove(label
)
210 def command(self
, cmd
, argv
, quiet
):
211 return self
._do
([cmd
] + argv
, quiet
=quiet
)
213 class SubCommand(object):
214 """A SubCommand template base class"""
215 name
= None # Subcommand name
216 def shared_args(self
, parser
):
217 parser
.add_argument("--quiet", action
="store_true",
218 help="Run quietly unless an error occured")
220 def args(self
, parser
):
221 """Setup argument parser"""
223 def run(self
, args
, argv
):
225 args: parsed argument by argument parser.
226 argv: remaining arguments from sys.argv.
230 class RunCommand(SubCommand
):
231 """Invoke docker run and take care of cleaning up"""
233 def args(self
, parser
):
234 parser
.add_argument("--keep", action
="store_true",
235 help="Don't remove image when command completes")
236 def run(self
, args
, argv
):
237 return Docker().run(argv
, args
.keep
, quiet
=args
.quiet
)
239 class BuildCommand(SubCommand
):
240 """ Build docker image out of a dockerfile. Arguments: <tag> <dockerfile>"""
242 def args(self
, parser
):
243 parser
.add_argument("--include-executable", "-e",
244 help="""Specify a binary that will be copied to the
245 container together with all its dependent
247 parser
.add_argument("--extra-files", "-f", nargs
='*',
248 help="""Specify files that will be copied in the
249 Docker image, fulfilling the ADD directive from the
251 parser
.add_argument("--add-current-user", "-u", dest
="user",
253 help="Add the current user to image's passwd")
254 parser
.add_argument("tag",
256 parser
.add_argument("dockerfile",
257 help="Dockerfile name")
259 def run(self
, args
, argv
):
260 dockerfile
= open(args
.dockerfile
, "rb").read()
264 if dkr
.image_matches_dockerfile(tag
, dockerfile
):
266 print "Image is up to date."
268 # Create a docker context directory for the build
269 docker_dir
= tempfile
.mkdtemp(prefix
="docker_build")
271 # Is there a .pre file to run in the build context?
272 docker_pre
= os
.path
.splitext(args
.dockerfile
)[0]+".pre"
273 if os
.path
.exists(docker_pre
):
274 stdout
= DEVNULL
if args
.quiet
else None
275 rc
= subprocess
.call(os
.path
.realpath(docker_pre
),
276 cwd
=docker_dir
, stdout
=stdout
)
281 print "%s exited with code %d" % (docker_pre
, rc
)
284 # Copy any extra files into the Docker context. These can be
285 # included by the use of the ADD directive in the Dockerfile.
287 if args
.include_executable
:
288 # FIXME: there is no checksum of this executable and the linked
289 # libraries, once the image built any change of this executable
290 # or any library won't trigger another build.
291 _copy_binary_with_libs(args
.include_executable
, docker_dir
)
292 for filename
in args
.extra_files
or []:
293 _copy_with_mkdir(filename
, docker_dir
)
294 cksum
+= [_file_checksum(filename
)]
296 argv
+= ["--build-arg=" + k
.lower() + "=" + v
297 for k
, v
in os
.environ
.iteritems()
298 if k
.lower() in FILTERED_ENV_NAMES
]
299 dkr
.build_image(tag
, docker_dir
, dockerfile
,
300 quiet
=args
.quiet
, user
=args
.user
, argv
=argv
,
301 extra_files_cksum
=cksum
)
307 class UpdateCommand(SubCommand
):
308 """ Update a docker image with new executables. Arguments: <tag> <executable>"""
310 def args(self
, parser
):
311 parser
.add_argument("tag",
313 parser
.add_argument("executable",
314 help="Executable to copy")
316 def run(self
, args
, argv
):
317 # Create a temporary tarball with our whole build context and
318 # dockerfile for the update
319 tmp
= tempfile
.NamedTemporaryFile(suffix
="dckr.tar.gz")
320 tmp_tar
= TarFile(fileobj
=tmp
, mode
='w')
322 # Add the executable to the tarball
323 bn
= os
.path
.basename(args
.executable
)
324 ff
= "/usr/bin/%s" % bn
325 tmp_tar
.add(args
.executable
, arcname
=ff
)
327 # Add any associated libraries
328 libs
= _get_so_libs(args
.executable
)
331 tmp_tar
.add(os
.path
.realpath(l
), arcname
=l
)
333 # Create a Docker buildfile
335 df
.write("FROM %s\n" % args
.tag
)
336 df
.write("ADD . /\n")
339 df_tar
= TarInfo(name
="Dockerfile")
340 df_tar
.size
= len(df
.buf
)
341 tmp_tar
.addfile(df_tar
, fileobj
=df
)
345 # reset the file pointers
349 # Run the build with our tarball context
351 dkr
.update_image(args
.tag
, tmp
, quiet
=args
.quiet
)
355 class CleanCommand(SubCommand
):
356 """Clean up docker instances"""
358 def run(self
, args
, argv
):
362 class ImagesCommand(SubCommand
):
363 """Run "docker images" command"""
365 def run(self
, args
, argv
):
366 return Docker().command("images", argv
, args
.quiet
)
369 parser
= argparse
.ArgumentParser(description
="A Docker helper",
370 usage
="%s <subcommand> ..." % os
.path
.basename(sys
.argv
[0]))
371 subparsers
= parser
.add_subparsers(title
="subcommands", help=None)
372 for cls
in SubCommand
.__subclasses
__():
374 subp
= subparsers
.add_parser(cmd
.name
, help=cmd
.__doc
__)
375 cmd
.shared_args(subp
)
377 subp
.set_defaults(cmdobj
=cmd
)
378 args
, argv
= parser
.parse_known_args()
379 return args
.cmdobj
.run(args
, argv
)
381 if __name__
== "__main__":