From patchwork Fri Mar 4 10:18:28 2016 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: Fam Zheng X-Patchwork-Id: 8501811 Return-Path: X-Original-To: patchwork-qemu-devel@patchwork.kernel.org Delivered-To: patchwork-parsemail@patchwork1.web.kernel.org Received: from mail.kernel.org (mail.kernel.org [198.145.29.136]) by patchwork1.web.kernel.org (Postfix) with ESMTP id 14E019F659 for ; Fri, 4 Mar 2016 10:19:25 +0000 (UTC) Received: from mail.kernel.org (localhost [127.0.0.1]) by mail.kernel.org (Postfix) with ESMTP id 3DD3B201CE for ; Fri, 4 Mar 2016 10:19:24 +0000 (UTC) Received: from lists.gnu.org (lists.gnu.org [208.118.235.17]) (using TLSv1 with cipher AES256-SHA (256/256 bits)) (No client certificate requested) by mail.kernel.org (Postfix) with ESMTPS id 3A9A2201C8 for ; Fri, 4 Mar 2016 10:19:23 +0000 (UTC) Received: from localhost ([::1]:40011 helo=lists.gnu.org) by lists.gnu.org with esmtp (Exim 4.71) (envelope-from ) id 1abmpO-0005KV-IZ for patchwork-qemu-devel@patchwork.kernel.org; Fri, 04 Mar 2016 05:19:22 -0500 Received: from eggs.gnu.org ([2001:4830:134:3::10]:48661) by lists.gnu.org with esmtp (Exim 4.71) (envelope-from ) id 1abmp9-0005Af-DK for qemu-devel@nongnu.org; Fri, 04 Mar 2016 05:19:12 -0500 Received: from Debian-exim by eggs.gnu.org with spam-scanned (Exim 4.71) (envelope-from ) id 1abmp8-0005XC-4z for qemu-devel@nongnu.org; Fri, 04 Mar 2016 05:19:07 -0500 Received: from mx1.redhat.com ([209.132.183.28]:33731) by eggs.gnu.org with esmtp (Exim 4.71) (envelope-from ) id 1abmp7-0005X8-RY for qemu-devel@nongnu.org; Fri, 04 Mar 2016 05:19:06 -0500 Received: from int-mx09.intmail.prod.int.phx2.redhat.com (int-mx09.intmail.prod.int.phx2.redhat.com [10.5.11.22]) by mx1.redhat.com (Postfix) with ESMTPS id 82B6D3CA172; Fri, 4 Mar 2016 10:19:05 +0000 (UTC) Received: from fam-t430.redhat.com (vpn1-5-204.pek2.redhat.com [10.72.5.204]) by int-mx09.intmail.prod.int.phx2.redhat.com (8.14.4/8.14.4) with ESMTP id u24AIfN5001604; Fri, 4 Mar 2016 05:18:56 -0500 From: Fam Zheng To: qemu-devel@nongnu.org Date: Fri, 4 Mar 2016 18:18:28 +0800 Message-Id: <1457086720-30391-2-git-send-email-famz@redhat.com> In-Reply-To: <1457086720-30391-1-git-send-email-famz@redhat.com> References: <1457086720-30391-1-git-send-email-famz@redhat.com> X-Scanned-By: MIMEDefang 2.68 on 10.5.11.22 X-detected-operating-system: by eggs.gnu.org: GNU/Linux 3.x X-Received-From: 209.132.183.28 Cc: kwolf@redhat.com, peter.maydell@linaro.org, jsnow@redhat.com, stefanha@redhat.com, sw@weilnetz.de, Paolo Bonzini , =?UTF-8?q?Alex=20Benn=C3=A9e?= , david@gibson.dropbear.id.au Subject: [Qemu-devel] [PATCH v3 01/13] tests: Add utilities for docker testing X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.14 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: qemu-devel-bounces+patchwork-qemu-devel=patchwork.kernel.org@nongnu.org Sender: qemu-devel-bounces+patchwork-qemu-devel=patchwork.kernel.org@nongnu.org X-Spam-Status: No, score=-6.9 required=5.0 tests=BAYES_00, RCVD_IN_DNSWL_HI, UNPARSEABLE_RELAY autolearn=unavailable version=3.3.1 X-Spam-Checker-Version: SpamAssassin 3.3.1 (2010-03-16) on mail.kernel.org X-Virus-Scanned: ClamAV using ClamSMTP docker_run: A wrapper for "docker run" (or "sudo -n docker run" if necessary), which takes care of killing and removing the running container at SIGINT. docker_clean: A tool to tear down all the containers including inactive ones that are started by docker_run. docker_build: A tool to compare an image from given dockerfile and rebuild it if they're different. Signed-off-by: Fam Zheng --- tests/docker/docker.py | 180 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 180 insertions(+) create mode 100755 tests/docker/docker.py diff --git a/tests/docker/docker.py b/tests/docker/docker.py new file mode 100755 index 0000000..22f537c --- /dev/null +++ b/tests/docker/docker.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python2 +# +# Docker controlling module +# +# Copyright (c) 2016 Red Hat Inc. +# +# Authors: +# Fam Zheng +# +# This work is licensed under the terms of the GNU GPL, version 2 +# or (at your option) any later version. See the COPYING file in +# the top-level directory. + +import os +import sys +import subprocess +import json +import hashlib +import atexit +import uuid +import argparse + +class Docker(object): + """ Running Docker commands """ + def __init__(self): + self._command = self._guess_command() + self._instances = [] + atexit.register(self._kill_instances) + + def _do(self, cmd, quiet=True, **kwargs): + if quiet: + kwargs["stdout"] = subprocess.PIPE + return subprocess.call(self._command + cmd, **kwargs) + + def _do_kill_instances(self, only_known, only_active=True): + cmd = ["ps", "-q"] + if not only_active: + cmd.append("-a") + for i in self._output(cmd).split(): + resp = self._output(["inspect", i]) + labels = json.loads(resp)[0]["Config"]["Labels"] + active = json.loads(resp)[0]["State"]["Running"] + if not labels: + continue + instance_uuid = labels.get("com.qemu.instance.uuid", None) + if not instance_uuid: + continue + if only_known and instance_uuid not in self._instances: + continue + print "Terminating", i + if active: + self._do(["kill", i]) + self._do(["rm", i]) + + def clean(self): + self._do_kill_instances(False, False) + return 0 + + def _kill_instances(self): + return self._do_kill_instances(True) + + def _output(self, cmd, **kwargs): + return subprocess.check_output(self._command + cmd, + stderr=subprocess.STDOUT, + **kwargs) + + def _guess_command(self): + commands = [["docker"], ["sudo", "-n", "docker"]] + for cmd in commands: + if subprocess.call(cmd + ["images"], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) == 0: + return cmd + commands_txt = "\n".join([" " + " ".join(x) for x in commands]) + raise Exception("Cannot find working docker command. Tried:\n%s" % commands_txt) + + def get_image_dockerfile_checksum(self, tag): + resp = self._output(["inspect", tag]) + labels = json.loads(resp)[0]["Config"].get("Labels", {}) + return labels.get("com.qemu.dockerfile-checksum", "") + + def checksum(self, text): + return hashlib.sha1(text).hexdigest() + + def build_image(self, tag, dockerfile, df, quiet=True, argv=[]): + tmp = dockerfile + "\n" + \ + "LABEL com.qemu.dockerfile-checksum=%s" % self.checksum(dockerfile) + tmp_df = df + ".tmp" + tmp_file = open(tmp_df, "wb") + tmp_file.write(tmp) + tmp_file.close() + self._do(["build", "-t", tag, "-f", tmp_df] + argv + [os.path.dirname(df)], + quiet=quiet) + os.unlink(tmp_df) + + def image_matches_dockerfile(self, tag, dockerfile): + try: + checksum = self.get_image_dockerfile_checksum(tag) + except: + return False + return checksum == self.checksum(dockerfile) + + def run(self, cmd, keep, quiet): + label = uuid.uuid1().hex + if not keep: + self._instances.append(label) + ret = self._do(["run", "--label", "com.qemu.instance.uuid=" + label] + cmd, quiet=quiet) + if not keep: + self._instances.remove(label) + return ret + +class SubCommand(object): + """A SubCommand template base class""" + name = None # Subcommand name + def args(self, parser): + """Setup argument parser""" + pass + def run(self, args, argv): + """Run command. + args: parsed argument by argument parser. + argv: remaining arguments from sys.argv. + """ + pass + +class RunCommand(SubCommand): + """Invoke docker run and take care of cleaning up""" + name = "run" + def args(self, parser): + parser.add_argument("--keep", action="store_true", + help="Don't remove image when the command completes") + parser.add_argument("--quiet", action="store_true", + help="Run quietly unless an error occured") + def run(self, args, argv): + return Docker().run(argv, args.keep, quiet=args.quiet) + +class BuildCommand(SubCommand): + """ Build docker image out of a dockerfile""" + name = "build" + def args(self, parser): + parser.add_argument("tag", + help="Image Tag") + parser.add_argument("dockerfile", + help="Dockerfile name") + parser.add_argument("--verbose", "-v", action="store_true", + help="Print verbose information") + + def run(self, args, argv): + dockerfile = open(args.dockerfile, "rb").read() + tag = args.tag + + dkr = Docker() + if dkr.image_matches_dockerfile(tag, dockerfile): + if args.verbose: + print "Image is up to date." + return 0 + + quiet = not args.verbose + dkr.build_image(tag, dockerfile, args.dockerfile, quiet=quiet, argv=argv) + return 0 + +class CleanCommand(SubCommand): + """Clean up docker instances""" + name = "clean" + def run(self, args, argv): + Docker().clean() + return 0 + +def main(): + parser = argparse.ArgumentParser() + subparsers = parser.add_subparsers() + for cls in SubCommand.__subclasses__(): + cmd = cls() + subp = subparsers.add_parser(cmd.name, help=cmd.__doc__) + cmd.args(subp) + subp.set_defaults(cmdobj=cmd) + args, argv = parser.parse_known_args() + return args.cmdobj.run(args, argv) + +if __name__ == "__main__": + sys.exit(main())