docker.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. #!/usr/bin/env python2
  2. #
  3. # Docker controlling module
  4. #
  5. # Copyright (c) 2016 Red Hat Inc.
  6. #
  7. # Authors:
  8. # Fam Zheng <famz@redhat.com>
  9. #
  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.
  13. from __future__ import print_function
  14. import os
  15. import sys
  16. import subprocess
  17. import json
  18. import hashlib
  19. import atexit
  20. import uuid
  21. import argparse
  22. import tempfile
  23. import re
  24. import signal
  25. from tarfile import TarFile, TarInfo
  26. try:
  27. from StringIO import StringIO
  28. except ImportError:
  29. from io import StringIO
  30. from shutil import copy, rmtree
  31. from pwd import getpwuid
  32. from datetime import datetime,timedelta
  33. FILTERED_ENV_NAMES = ['ftp_proxy', 'http_proxy', 'https_proxy']
  34. DEVNULL = open(os.devnull, 'wb')
  35. def _text_checksum(text):
  36. """Calculate a digest string unique to the text content"""
  37. return hashlib.sha1(text).hexdigest()
  38. def _file_checksum(filename):
  39. return _text_checksum(open(filename, 'rb').read())
  40. def _guess_docker_command():
  41. """ Guess a working docker command or raise exception if not found"""
  42. commands = [["docker"], ["sudo", "-n", "docker"]]
  43. for cmd in commands:
  44. try:
  45. # docker version will return the client details in stdout
  46. # but still report a status of 1 if it can't contact the daemon
  47. if subprocess.call(cmd + ["version"],
  48. stdout=DEVNULL, stderr=DEVNULL) == 0:
  49. return cmd
  50. except OSError:
  51. pass
  52. commands_txt = "\n".join([" " + " ".join(x) for x in commands])
  53. raise Exception("Cannot find working docker command. Tried:\n%s" % \
  54. commands_txt)
  55. def _copy_with_mkdir(src, root_dir, sub_path='.'):
  56. """Copy src into root_dir, creating sub_path as needed."""
  57. dest_dir = os.path.normpath("%s/%s" % (root_dir, sub_path))
  58. try:
  59. os.makedirs(dest_dir)
  60. except OSError:
  61. # we can safely ignore already created directories
  62. pass
  63. dest_file = "%s/%s" % (dest_dir, os.path.basename(src))
  64. copy(src, dest_file)
  65. def _get_so_libs(executable):
  66. """Return a list of libraries associated with an executable.
  67. The paths may be symbolic links which would need to be resolved to
  68. ensure theright data is copied."""
  69. libs = []
  70. ldd_re = re.compile(r"(/.*/)(\S*)")
  71. try:
  72. ldd_output = subprocess.check_output(["ldd", executable])
  73. for line in ldd_output.split("\n"):
  74. search = ldd_re.search(line)
  75. if search and len(search.groups()) == 2:
  76. so_path = search.groups()[0]
  77. so_lib = search.groups()[1]
  78. libs.append("%s/%s" % (so_path, so_lib))
  79. except subprocess.CalledProcessError:
  80. print("%s had no associated libraries (static build?)" % (executable))
  81. return libs
  82. def _copy_binary_with_libs(src, dest_dir):
  83. """Copy a binary executable and all its dependent libraries.
  84. This does rely on the host file-system being fairly multi-arch
  85. aware so the file don't clash with the guests layout."""
  86. _copy_with_mkdir(src, dest_dir, "/usr/bin")
  87. libs = _get_so_libs(src)
  88. if libs:
  89. for l in libs:
  90. so_path = os.path.dirname(l)
  91. _copy_with_mkdir(l , dest_dir, so_path)
  92. def _check_binfmt_misc(executable):
  93. """Check binfmt_misc has entry for executable in the right place.
  94. The details of setting up binfmt_misc are outside the scope of
  95. this script but we should at least fail early with a useful
  96. message if it won't work."""
  97. binary = os.path.basename(executable)
  98. binfmt_entry = "/proc/sys/fs/binfmt_misc/%s" % (binary)
  99. if not os.path.exists(binfmt_entry):
  100. print ("No binfmt_misc entry for %s" % (binary))
  101. return False
  102. with open(binfmt_entry) as x: entry = x.read()
  103. qpath = "/usr/bin/%s" % (binary)
  104. if not re.search("interpreter %s\n" % (qpath), entry):
  105. print ("binfmt_misc for %s does not point to %s" % (binary, qpath))
  106. return False
  107. return True
  108. def _read_qemu_dockerfile(img_name):
  109. # special case for Debian linux-user images
  110. if img_name.startswith("debian") and img_name.endswith("user"):
  111. img_name = "debian-bootstrap"
  112. df = os.path.join(os.path.dirname(__file__), "dockerfiles",
  113. img_name + ".docker")
  114. return open(df, "r").read()
  115. def _dockerfile_preprocess(df):
  116. out = ""
  117. for l in df.splitlines():
  118. if len(l.strip()) == 0 or l.startswith("#"):
  119. continue
  120. from_pref = "FROM qemu:"
  121. if l.startswith(from_pref):
  122. # TODO: Alternatively we could replace this line with "FROM $ID"
  123. # where $ID is the image's hex id obtained with
  124. # $ docker images $IMAGE --format="{{.Id}}"
  125. # but unfortunately that's not supported by RHEL 7.
  126. inlining = _read_qemu_dockerfile(l[len(from_pref):])
  127. out += _dockerfile_preprocess(inlining)
  128. continue
  129. out += l + "\n"
  130. return out
  131. class Docker(object):
  132. """ Running Docker commands """
  133. def __init__(self):
  134. self._command = _guess_docker_command()
  135. self._instances = []
  136. atexit.register(self._kill_instances)
  137. signal.signal(signal.SIGTERM, self._kill_instances)
  138. signal.signal(signal.SIGHUP, self._kill_instances)
  139. def _do(self, cmd, quiet=True, **kwargs):
  140. if quiet:
  141. kwargs["stdout"] = DEVNULL
  142. return subprocess.call(self._command + cmd, **kwargs)
  143. def _do_check(self, cmd, quiet=True, **kwargs):
  144. if quiet:
  145. kwargs["stdout"] = DEVNULL
  146. return subprocess.check_call(self._command + cmd, **kwargs)
  147. def _do_kill_instances(self, only_known, only_active=True):
  148. cmd = ["ps", "-q"]
  149. if not only_active:
  150. cmd.append("-a")
  151. for i in self._output(cmd).split():
  152. resp = self._output(["inspect", i])
  153. labels = json.loads(resp)[0]["Config"]["Labels"]
  154. active = json.loads(resp)[0]["State"]["Running"]
  155. if not labels:
  156. continue
  157. instance_uuid = labels.get("com.qemu.instance.uuid", None)
  158. if not instance_uuid:
  159. continue
  160. if only_known and instance_uuid not in self._instances:
  161. continue
  162. print("Terminating", i)
  163. if active:
  164. self._do(["kill", i])
  165. self._do(["rm", i])
  166. def clean(self):
  167. self._do_kill_instances(False, False)
  168. return 0
  169. def _kill_instances(self, *args, **kwargs):
  170. return self._do_kill_instances(True)
  171. def _output(self, cmd, **kwargs):
  172. return subprocess.check_output(self._command + cmd,
  173. stderr=subprocess.STDOUT,
  174. **kwargs)
  175. def inspect_tag(self, tag):
  176. try:
  177. return self._output(["inspect", tag])
  178. except subprocess.CalledProcessError:
  179. return None
  180. def get_image_creation_time(self, info):
  181. return json.loads(info)[0]["Created"]
  182. def get_image_dockerfile_checksum(self, tag):
  183. resp = self.inspect_tag(tag)
  184. labels = json.loads(resp)[0]["Config"].get("Labels", {})
  185. 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=[]):
  188. if argv == None:
  189. argv = []
  190. tmp_df = tempfile.NamedTemporaryFile(dir=docker_dir, suffix=".docker")
  191. tmp_df.write(dockerfile)
  192. if user:
  193. uid = os.getuid()
  194. uname = getpwuid(uid).pw_name
  195. tmp_df.write("\n")
  196. tmp_df.write("RUN id %s 2>/dev/null || useradd -u %d -U %s" %
  197. (uname, uid, uname))
  198. tmp_df.write("\n")
  199. tmp_df.write("LABEL com.qemu.dockerfile-checksum=%s" %
  200. _text_checksum(_dockerfile_preprocess(dockerfile)))
  201. for f, c in extra_files_cksum:
  202. tmp_df.write("LABEL com.qemu.%s-checksum=%s" % (f, c))
  203. tmp_df.flush()
  204. self._do_check(["build", "-t", tag, "-f", tmp_df.name] + argv + \
  205. [docker_dir],
  206. quiet=quiet)
  207. def update_image(self, tag, tarball, quiet=True):
  208. "Update a tagged image using "
  209. self._do_check(["build", "-t", tag, "-"], quiet=quiet, stdin=tarball)
  210. def image_matches_dockerfile(self, tag, dockerfile):
  211. try:
  212. checksum = self.get_image_dockerfile_checksum(tag)
  213. except Exception:
  214. return False
  215. return checksum == _text_checksum(_dockerfile_preprocess(dockerfile))
  216. def run(self, cmd, keep, quiet):
  217. label = uuid.uuid1().hex
  218. if not keep:
  219. self._instances.append(label)
  220. ret = self._do_check(["run", "--label",
  221. "com.qemu.instance.uuid=" + label] + cmd,
  222. quiet=quiet)
  223. if not keep:
  224. self._instances.remove(label)
  225. return ret
  226. def command(self, cmd, argv, quiet):
  227. return self._do([cmd] + argv, quiet=quiet)
  228. class SubCommand(object):
  229. """A SubCommand template base class"""
  230. name = None # Subcommand name
  231. def shared_args(self, parser):
  232. parser.add_argument("--quiet", action="store_true",
  233. help="Run quietly unless an error occurred")
  234. def args(self, parser):
  235. """Setup argument parser"""
  236. pass
  237. def run(self, args, argv):
  238. """Run command.
  239. args: parsed argument by argument parser.
  240. argv: remaining arguments from sys.argv.
  241. """
  242. pass
  243. class RunCommand(SubCommand):
  244. """Invoke docker run and take care of cleaning up"""
  245. name = "run"
  246. def args(self, parser):
  247. parser.add_argument("--keep", action="store_true",
  248. help="Don't remove image when command completes")
  249. def run(self, args, argv):
  250. return Docker().run(argv, args.keep, quiet=args.quiet)
  251. class BuildCommand(SubCommand):
  252. """ Build docker image out of a dockerfile. Arguments: <tag> <dockerfile>"""
  253. name = "build"
  254. def args(self, parser):
  255. parser.add_argument("--include-executable", "-e",
  256. help="""Specify a binary that will be copied to the
  257. container together with all its dependent
  258. libraries""")
  259. parser.add_argument("--extra-files", "-f", nargs='*',
  260. help="""Specify files that will be copied in the
  261. Docker image, fulfilling the ADD directive from the
  262. Dockerfile""")
  263. parser.add_argument("--add-current-user", "-u", dest="user",
  264. action="store_true",
  265. help="Add the current user to image's passwd")
  266. parser.add_argument("tag",
  267. help="Image Tag")
  268. parser.add_argument("dockerfile",
  269. help="Dockerfile name")
  270. def run(self, args, argv):
  271. dockerfile = open(args.dockerfile, "rb").read()
  272. tag = args.tag
  273. dkr = Docker()
  274. if "--no-cache" not in argv and \
  275. dkr.image_matches_dockerfile(tag, dockerfile):
  276. if not args.quiet:
  277. print("Image is up to date.")
  278. else:
  279. # Create a docker context directory for the build
  280. docker_dir = tempfile.mkdtemp(prefix="docker_build")
  281. # Validate binfmt_misc will work
  282. if args.include_executable:
  283. if not _check_binfmt_misc(args.include_executable):
  284. return 1
  285. # Is there a .pre file to run in the build context?
  286. docker_pre = os.path.splitext(args.dockerfile)[0]+".pre"
  287. if os.path.exists(docker_pre):
  288. stdout = DEVNULL if args.quiet else None
  289. rc = subprocess.call(os.path.realpath(docker_pre),
  290. cwd=docker_dir, stdout=stdout)
  291. if rc == 3:
  292. print("Skip")
  293. return 0
  294. elif rc != 0:
  295. print("%s exited with code %d" % (docker_pre, rc))
  296. return 1
  297. # Copy any extra files into the Docker context. These can be
  298. # included by the use of the ADD directive in the Dockerfile.
  299. cksum = []
  300. if args.include_executable:
  301. # FIXME: there is no checksum of this executable and the linked
  302. # libraries, once the image built any change of this executable
  303. # or any library won't trigger another build.
  304. _copy_binary_with_libs(args.include_executable, docker_dir)
  305. for filename in args.extra_files or []:
  306. _copy_with_mkdir(filename, docker_dir)
  307. cksum += [(filename, _file_checksum(filename))]
  308. argv += ["--build-arg=" + k.lower() + "=" + v
  309. for k, v in os.environ.iteritems()
  310. if k.lower() in FILTERED_ENV_NAMES]
  311. dkr.build_image(tag, docker_dir, dockerfile,
  312. quiet=args.quiet, user=args.user, argv=argv,
  313. extra_files_cksum=cksum)
  314. rmtree(docker_dir)
  315. return 0
  316. class UpdateCommand(SubCommand):
  317. """ Update a docker image with new executables. Arguments: <tag> <executable>"""
  318. name = "update"
  319. def args(self, parser):
  320. parser.add_argument("tag",
  321. help="Image Tag")
  322. parser.add_argument("executable",
  323. help="Executable to copy")
  324. def run(self, args, argv):
  325. # Create a temporary tarball with our whole build context and
  326. # dockerfile for the update
  327. tmp = tempfile.NamedTemporaryFile(suffix="dckr.tar.gz")
  328. tmp_tar = TarFile(fileobj=tmp, mode='w')
  329. # Add the executable to the tarball
  330. bn = os.path.basename(args.executable)
  331. ff = "/usr/bin/%s" % bn
  332. tmp_tar.add(args.executable, arcname=ff)
  333. # Add any associated libraries
  334. libs = _get_so_libs(args.executable)
  335. if libs:
  336. for l in libs:
  337. tmp_tar.add(os.path.realpath(l), arcname=l)
  338. # Create a Docker buildfile
  339. df = StringIO()
  340. df.write("FROM %s\n" % args.tag)
  341. df.write("ADD . /\n")
  342. df.seek(0)
  343. df_tar = TarInfo(name="Dockerfile")
  344. df_tar.size = len(df.buf)
  345. tmp_tar.addfile(df_tar, fileobj=df)
  346. tmp_tar.close()
  347. # reset the file pointers
  348. tmp.flush()
  349. tmp.seek(0)
  350. # Run the build with our tarball context
  351. dkr = Docker()
  352. dkr.update_image(args.tag, tmp, quiet=args.quiet)
  353. return 0
  354. class CleanCommand(SubCommand):
  355. """Clean up docker instances"""
  356. name = "clean"
  357. def run(self, args, argv):
  358. Docker().clean()
  359. return 0
  360. class ImagesCommand(SubCommand):
  361. """Run "docker images" command"""
  362. name = "images"
  363. def run(self, args, argv):
  364. return Docker().command("images", argv, args.quiet)
  365. class ProbeCommand(SubCommand):
  366. """Probe if we can run docker automatically"""
  367. name = "probe"
  368. def run(self, args, argv):
  369. try:
  370. docker = Docker()
  371. if docker._command[0] == "docker":
  372. print("yes")
  373. elif docker._command[0] == "sudo":
  374. print("sudo")
  375. except Exception:
  376. print("no")
  377. return
  378. class CcCommand(SubCommand):
  379. """Compile sources with cc in images"""
  380. name = "cc"
  381. def args(self, parser):
  382. parser.add_argument("--image", "-i", required=True,
  383. help="The docker image in which to run cc")
  384. parser.add_argument("--cc", default="cc",
  385. help="The compiler executable to call")
  386. parser.add_argument("--user",
  387. help="The user-id to run under")
  388. parser.add_argument("--source-path", "-s", nargs="*", dest="paths",
  389. help="""Extra paths to (ro) mount into container for
  390. reading sources""")
  391. def run(self, args, argv):
  392. if argv and argv[0] == "--":
  393. argv = argv[1:]
  394. cwd = os.getcwd()
  395. cmd = ["--rm", "-w", cwd,
  396. "-v", "%s:%s:rw" % (cwd, cwd)]
  397. if args.paths:
  398. for p in args.paths:
  399. cmd += ["-v", "%s:%s:ro,z" % (p, p)]
  400. if args.user:
  401. cmd += ["-u", args.user]
  402. cmd += [args.image, args.cc]
  403. cmd += argv
  404. return Docker().command("run", cmd, args.quiet)
  405. class CheckCommand(SubCommand):
  406. """Check if we need to re-build a docker image out of a dockerfile.
  407. Arguments: <tag> <dockerfile>"""
  408. name = "check"
  409. def args(self, parser):
  410. parser.add_argument("tag",
  411. help="Image Tag")
  412. parser.add_argument("dockerfile", default=None,
  413. help="Dockerfile name", nargs='?')
  414. parser.add_argument("--checktype", choices=["checksum", "age"],
  415. default="checksum", help="check type")
  416. parser.add_argument("--olderthan", default=60, type=int,
  417. help="number of minutes")
  418. def run(self, args, argv):
  419. tag = args.tag
  420. try:
  421. dkr = Docker()
  422. except:
  423. print("Docker not set up")
  424. return 1
  425. info = dkr.inspect_tag(tag)
  426. if info is None:
  427. print("Image does not exist")
  428. return 1
  429. if args.checktype == "checksum":
  430. if not args.dockerfile:
  431. print("Need a dockerfile for tag:%s" % (tag))
  432. return 1
  433. dockerfile = open(args.dockerfile, "rb").read()
  434. if dkr.image_matches_dockerfile(tag, dockerfile):
  435. if not args.quiet:
  436. print("Image is up to date")
  437. return 0
  438. else:
  439. print("Image needs updating")
  440. return 1
  441. elif args.checktype == "age":
  442. timestr = dkr.get_image_creation_time(info).split(".")[0]
  443. created = datetime.strptime(timestr, "%Y-%m-%dT%H:%M:%S")
  444. past = datetime.now() - timedelta(minutes=args.olderthan)
  445. if created < past:
  446. print ("Image created @ %s more than %d minutes old" %
  447. (timestr, args.olderthan))
  448. return 1
  449. else:
  450. if not args.quiet:
  451. print ("Image less than %d minutes old" % (args.olderthan))
  452. return 0
  453. def main():
  454. parser = argparse.ArgumentParser(description="A Docker helper",
  455. usage="%s <subcommand> ..." % os.path.basename(sys.argv[0]))
  456. subparsers = parser.add_subparsers(title="subcommands", help=None)
  457. for cls in SubCommand.__subclasses__():
  458. cmd = cls()
  459. subp = subparsers.add_parser(cmd.name, help=cmd.__doc__)
  460. cmd.shared_args(subp)
  461. cmd.args(subp)
  462. subp.set_defaults(cmdobj=cmd)
  463. args, argv = parser.parse_known_args()
  464. return args.cmdobj.run(args, argv)
  465. if __name__ == "__main__":
  466. sys.exit(main())