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.
16 sys
.path
.append(os
.path
.join(os
.path
.dirname(__file__
),
17 '..', '..', 'scripts'))
27 from tarfile
import TarFile
, TarInfo
28 from StringIO
import StringIO
29 from shutil
import copy
, rmtree
30 from pwd
import getpwuid
33 FILTERED_ENV_NAMES
= ['ftp_proxy', 'http_proxy', 'https_proxy']
36 DEVNULL
= open(os
.devnull
, 'wb')
39 def _text_checksum(text
):
40 """Calculate a digest string unique to the text content"""
41 return hashlib
.sha1(text
).hexdigest()
43 def _file_checksum(filename
):
44 return _text_checksum(open(filename
, 'rb').read())
46 def _guess_docker_command():
47 """ Guess a working docker command or raise exception if not found"""
48 commands
= [["docker"], ["sudo", "-n", "docker"]]
51 if subprocess
.call(cmd
+ ["images"],
52 stdout
=DEVNULL
, stderr
=DEVNULL
) == 0:
56 commands_txt
= "\n".join([" " + " ".join(x
) for x
in commands
])
57 raise Exception("Cannot find working docker command. Tried:\n%s" % \
60 def _copy_with_mkdir(src
, root_dir
, sub_path
='.'):
61 """Copy src into root_dir, creating sub_path as needed."""
62 dest_dir
= os
.path
.normpath("%s/%s" % (root_dir
, sub_path
))
66 # we can safely ignore already created directories
69 dest_file
= "%s/%s" % (dest_dir
, os
.path
.basename(src
))
73 def _get_so_libs(executable
):
74 """Return a list of libraries associated with an executable.
76 The paths may be symbolic links which would need to be resolved to
77 ensure theright data is copied."""
80 ldd_re
= re
.compile(r
"(/.*/)(\S*)")
82 ldd_output
= subprocess
.check_output(["ldd", executable
])
83 for line
in ldd_output
.split("\n"):
84 search
= ldd_re
.search(line
)
85 if search
and len(search
.groups()) == 2:
86 so_path
= search
.groups()[0]
87 so_lib
= search
.groups()[1]
88 libs
.append("%s/%s" % (so_path
, so_lib
))
89 except subprocess
.CalledProcessError
:
90 print "%s had no associated libraries (static build?)" % (executable
)
94 def _copy_binary_with_libs(src
, dest_dir
):
95 """Copy a binary executable and all its dependant libraries.
97 This does rely on the host file-system being fairly multi-arch
98 aware so the file don't clash with the guests layout."""
100 _copy_with_mkdir(src
, dest_dir
, "/usr/bin")
102 libs
= _get_so_libs(src
)
105 so_path
= os
.path
.dirname(l
)
106 _copy_with_mkdir(l
, dest_dir
, so_path
)
108 def _read_qemu_dockerfile(img_name
):
109 df
= os
.path
.join(os
.path
.dirname(__file__
), "dockerfiles",
110 img_name
+ ".docker")
111 return open(df
, "r").read()
113 def _dockerfile_preprocess(df
):
115 for l
in df
.splitlines():
116 if len(l
.strip()) == 0 or l
.startswith("#"):
118 from_pref
= "FROM qemu:"
119 if l
.startswith(from_pref
):
120 # TODO: Alternatively we could replace this line with "FROM $ID"
121 # where $ID is the image's hex id obtained with
122 # $ docker images $IMAGE --format="{{.Id}}"
123 # but unfortunately that's not supported by RHEL 7.
124 inlining
= _read_qemu_dockerfile(l
[len(from_pref
):])
125 out
+= _dockerfile_preprocess(inlining
)
130 class Docker(object):
131 """ Running Docker commands """
133 self
._command
= _guess_docker_command()
135 atexit
.register(self
._kill
_instances
)
136 signal
.signal(signal
.SIGTERM
, self
._kill
_instances
)
137 signal
.signal(signal
.SIGHUP
, self
._kill
_instances
)
139 def _do(self
, cmd
, quiet
=True, **kwargs
):
141 kwargs
["stdout"] = DEVNULL
142 return subprocess
.call(self
._command
+ cmd
, **kwargs
)
144 def _do_check(self
, cmd
, quiet
=True, **kwargs
):
146 kwargs
["stdout"] = DEVNULL
147 return subprocess
.check_call(self
._command
+ cmd
, **kwargs
)
149 def _do_kill_instances(self
, only_known
, only_active
=True):
153 for i
in self
._output
(cmd
).split():
154 resp
= self
._output
(["inspect", i
])
155 labels
= json
.loads(resp
)[0]["Config"]["Labels"]
156 active
= json
.loads(resp
)[0]["State"]["Running"]
159 instance_uuid
= labels
.get("com.qemu.instance.uuid", None)
160 if not instance_uuid
:
162 if only_known
and instance_uuid
not in self
._instances
:
164 print "Terminating", i
166 self
._do
(["kill", i
])
170 self
._do
_kill
_instances
(False, False)
173 def _kill_instances(self
, *args
, **kwargs
):
174 return self
._do
_kill
_instances
(True)
176 def _output(self
, cmd
, **kwargs
):
177 return subprocess
.check_output(self
._command
+ cmd
,
178 stderr
=subprocess
.STDOUT
,
181 def get_image_dockerfile_checksum(self
, tag
):
182 resp
= self
._output
(["inspect", tag
])
183 labels
= json
.loads(resp
)[0]["Config"].get("Labels", {})
184 return labels
.get("com.qemu.dockerfile-checksum", "")
186 def build_image(self
, tag
, docker_dir
, dockerfile
,
187 quiet
=True, user
=False, argv
=None, extra_files_cksum
=[]):
191 tmp_df
= tempfile
.NamedTemporaryFile(dir=docker_dir
, suffix
=".docker")
192 tmp_df
.write(dockerfile
)
196 uname
= getpwuid(uid
).pw_name
198 tmp_df
.write("RUN id %s 2>/dev/null || useradd -u %d -U %s" %
202 tmp_df
.write("LABEL com.qemu.dockerfile-checksum=%s" %
203 _text_checksum("\n".join([dockerfile
] +
207 self
._do
_check
(["build", "-t", tag
, "-f", tmp_df
.name
] + argv
+ \
211 def update_image(self
, tag
, tarball
, quiet
=True):
212 "Update a tagged image using "
214 self
._do
_check
(["build", "-t", tag
, "-"], quiet
=quiet
, stdin
=tarball
)
216 def image_matches_dockerfile(self
, tag
, dockerfile
):
218 checksum
= self
.get_image_dockerfile_checksum(tag
)
221 return checksum
== _text_checksum(_dockerfile_preprocess(dockerfile
))
223 def run(self
, cmd
, keep
, quiet
):
224 label
= uuid
.uuid1().hex
226 self
._instances
.append(label
)
227 ret
= self
._do
_check
(["run", "--label",
228 "com.qemu.instance.uuid=" + label
] + cmd
,
231 self
._instances
.remove(label
)
234 def command(self
, cmd
, argv
, quiet
):
235 return self
._do
([cmd
] + argv
, quiet
=quiet
)
237 class SubCommand(object):
238 """A SubCommand template base class"""
239 name
= None # Subcommand name
240 def shared_args(self
, parser
):
241 parser
.add_argument("--quiet", action
="store_true",
242 help="Run quietly unless an error occured")
244 def args(self
, parser
):
245 """Setup argument parser"""
247 def run(self
, args
, argv
):
249 args: parsed argument by argument parser.
250 argv: remaining arguments from sys.argv.
254 class RunCommand(SubCommand
):
255 """Invoke docker run and take care of cleaning up"""
257 def args(self
, parser
):
258 parser
.add_argument("--keep", action
="store_true",
259 help="Don't remove image when command completes")
260 def run(self
, args
, argv
):
261 return Docker().run(argv
, args
.keep
, quiet
=args
.quiet
)
263 class BuildCommand(SubCommand
):
264 """ Build docker image out of a dockerfile. Arguments: <tag> <dockerfile>"""
266 def args(self
, parser
):
267 parser
.add_argument("--include-executable", "-e",
268 help="""Specify a binary that will be copied to the
269 container together with all its dependent
271 parser
.add_argument("--extra-files", "-f", nargs
='*',
272 help="""Specify files that will be copied in the
273 Docker image, fulfilling the ADD directive from the
275 parser
.add_argument("--add-current-user", "-u", dest
="user",
277 help="Add the current user to image's passwd")
278 parser
.add_argument("tag",
280 parser
.add_argument("dockerfile",
281 help="Dockerfile name")
283 def run(self
, args
, argv
):
284 dockerfile
= open(args
.dockerfile
, "rb").read()
288 if "--no-cache" not in argv
and \
289 dkr
.image_matches_dockerfile(tag
, dockerfile
):
291 print "Image is up to date."
293 # Create a docker context directory for the build
294 docker_dir
= tempfile
.mkdtemp(prefix
="docker_build")
296 # Is there a .pre file to run in the build context?
297 docker_pre
= os
.path
.splitext(args
.dockerfile
)[0]+".pre"
298 if os
.path
.exists(docker_pre
):
299 stdout
= DEVNULL
if args
.quiet
else None
300 rc
= subprocess
.call(os
.path
.realpath(docker_pre
),
301 cwd
=docker_dir
, stdout
=stdout
)
306 print "%s exited with code %d" % (docker_pre
, rc
)
309 # Copy any extra files into the Docker context. These can be
310 # included by the use of the ADD directive in the Dockerfile.
312 if args
.include_executable
:
313 # FIXME: there is no checksum of this executable and the linked
314 # libraries, once the image built any change of this executable
315 # or any library won't trigger another build.
316 _copy_binary_with_libs(args
.include_executable
, docker_dir
)
317 for filename
in args
.extra_files
or []:
318 _copy_with_mkdir(filename
, docker_dir
)
319 cksum
+= [_file_checksum(filename
)]
321 argv
+= ["--build-arg=" + k
.lower() + "=" + v
322 for k
, v
in os
.environ
.iteritems()
323 if k
.lower() in FILTERED_ENV_NAMES
]
324 dkr
.build_image(tag
, docker_dir
, dockerfile
,
325 quiet
=args
.quiet
, user
=args
.user
, argv
=argv
,
326 extra_files_cksum
=cksum
)
332 class UpdateCommand(SubCommand
):
333 """ Update a docker image with new executables. Arguments: <tag> <executable>"""
335 def args(self
, parser
):
336 parser
.add_argument("tag",
338 parser
.add_argument("executable",
339 help="Executable to copy")
341 def run(self
, args
, argv
):
342 # Create a temporary tarball with our whole build context and
343 # dockerfile for the update
344 tmp
= tempfile
.NamedTemporaryFile(suffix
="dckr.tar.gz")
345 tmp_tar
= TarFile(fileobj
=tmp
, mode
='w')
347 # Add the executable to the tarball
348 bn
= os
.path
.basename(args
.executable
)
349 ff
= "/usr/bin/%s" % bn
350 tmp_tar
.add(args
.executable
, arcname
=ff
)
352 # Add any associated libraries
353 libs
= _get_so_libs(args
.executable
)
356 tmp_tar
.add(os
.path
.realpath(l
), arcname
=l
)
358 # Create a Docker buildfile
360 df
.write("FROM %s\n" % args
.tag
)
361 df
.write("ADD . /\n")
364 df_tar
= TarInfo(name
="Dockerfile")
365 df_tar
.size
= len(df
.buf
)
366 tmp_tar
.addfile(df_tar
, fileobj
=df
)
370 # reset the file pointers
374 # Run the build with our tarball context
376 dkr
.update_image(args
.tag
, tmp
, quiet
=args
.quiet
)
380 class CleanCommand(SubCommand
):
381 """Clean up docker instances"""
383 def run(self
, args
, argv
):
387 class ImagesCommand(SubCommand
):
388 """Run "docker images" command"""
390 def run(self
, args
, argv
):
391 return Docker().command("images", argv
, args
.quiet
)
394 parser
= argparse
.ArgumentParser(description
="A Docker helper",
395 usage
="%s <subcommand> ..." % os
.path
.basename(sys
.argv
[0]))
396 subparsers
= parser
.add_subparsers(title
="subcommands", help=None)
397 for cls
in SubCommand
.__subclasses
__():
399 subp
= subparsers
.add_parser(cmd
.name
, help=cmd
.__doc
__)
400 cmd
.shared_args(subp
)
402 subp
.set_defaults(cmdobj
=cmd
)
403 args
, argv
= parser
.parse_known_args()
404 return args
.cmdobj
.run(args
, argv
)
406 if __name__
== "__main__":