From mboxrd@z Thu Jan 1 00:00:00 1970 Received: from eggs.gnu.org ([2001:4830:134:3::10]:46858) by lists.gnu.org with esmtp (Exim 4.71) (envelope-from ) id 1ag24t-0003mK-4I for qemu-devel@nongnu.org; Tue, 15 Mar 2016 23:24:56 -0400 Received: from Debian-exim by eggs.gnu.org with spam-scanned (Exim 4.71) (envelope-from ) id 1ag24q-0006UA-CE for qemu-devel@nongnu.org; Tue, 15 Mar 2016 23:24:55 -0400 Received: from mx1.redhat.com ([209.132.183.28]:57264) by eggs.gnu.org with esmtp (Exim 4.71) (envelope-from ) id 1ag24q-0006U4-2C for qemu-devel@nongnu.org; Tue, 15 Mar 2016 23:24:52 -0400 Date: Wed, 16 Mar 2016 11:24:45 +0800 From: Fam Zheng Message-ID: <20160316032445.GA32324@ad.usersys.redhat.com> References: <1457086720-30391-1-git-send-email-famz@redhat.com> <1457086720-30391-2-git-send-email-famz@redhat.com> <87wpp9t5rj.fsf@linaro.org> MIME-Version: 1.0 Content-Type: text/plain; charset=iso-8859-1 Content-Disposition: inline In-Reply-To: <87wpp9t5rj.fsf@linaro.org> Content-Transfer-Encoding: quoted-printable Subject: Re: [Qemu-devel] [PATCH v3 01/13] tests: Add utilities for docker testing List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , To: Alex =?iso-8859-1?Q?Benn=E9e?= Cc: kwolf@redhat.com, peter.maydell@linaro.org, sw@weilnetz.de, qemu-devel@nongnu.org, stefanha@redhat.com, Paolo Bonzini , jsnow@redhat.com, david@gibson.dropbear.id.au On Fri, 03/11 15:04, Alex Benn=E9e wrote: >=20 > Fam Zheng writes: >=20 > > 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 inacti= ve > > 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. >=20 > This commit text needs updating with the actual calling conventions. Will do. >=20 > > > > 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. >=20 > It's worth running pylint over this file. There are a number of > missing newlines/spaces/long lines that aren't PEP friendly. I'll run this through pylint. >=20 > > + > > +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 =3D self._guess_command() > > + self._instances =3D [] > > + atexit.register(self._kill_instances) > > + > > + def _do(self, cmd, quiet=3DTrue, **kwargs): > > + if quiet: > > + kwargs["stdout"] =3D subprocess.PIPE > > + return subprocess.call(self._command + cmd, **kwargs) > > + > > + def _do_kill_instances(self, only_known, only_active=3DTrue): > > + cmd =3D ["ps", "-q"] > > + if not only_active: > > + cmd.append("-a") > > + for i in self._output(cmd).split(): > > + resp =3D self._output(["inspect", i]) > > + labels =3D json.loads(resp)[0]["Config"]["Labels"] > > + active =3D json.loads(resp)[0]["State"]["Running"] > > + if not labels: > > + continue > > + instance_uuid =3D labels.get("com.qemu.instance.uuid", N= one) > > + 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=3Dsubprocess.STDOUT, > > + **kwargs) > > + > > + def _guess_command(self): > > + commands =3D [["docker"], ["sudo", "-n", "docker"]] > > + for cmd in commands: > > + if subprocess.call(cmd + ["images"], > > + stdout=3Dsubprocess.PIPE, > > + stderr=3Dsubprocess.PIPE) =3D=3D 0: > > + return cmd > > + commands_txt =3D "\n".join([" " + " ".join(x) for x in comm= ands]) > > + raise Exception("Cannot find working docker command. Tried:\= n%s" % commands_txt) > > + > > + def get_image_dockerfile_checksum(self, tag): > > + resp =3D self._output(["inspect", tag]) > > + labels =3D 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=3DTrue, argv=3D= []): > > + tmp =3D dockerfile + "\n" + \ > > + "LABEL com.qemu.dockerfile-checksum=3D%s" % self.check= sum(dockerfile) > > + tmp_df =3D df + ".tmp" > > + tmp_file =3D open(tmp_df, "wb") > > + tmp_file.write(tmp) > > + tmp_file.close() > > + self._do(["build", "-t", tag, "-f", tmp_df] + argv + [os.pat= h.dirname(df)], > > + quiet=3Dquiet) > > + os.unlink(tmp_df) >=20 > Use python's tempfile to do this. It handles all the lifetime issues fo= r > you automatically - the file gets removed when the object goes out of s= cope. Okay, will do. >=20 > > + > > + def image_matches_dockerfile(self, tag, dockerfile): > > + try: > > + checksum =3D self.get_image_dockerfile_checksum(tag) > > + except: > > + return False > > + return checksum =3D=3D self.checksum(dockerfile) > > + > > + def run(self, cmd, keep, quiet): > > + label =3D uuid.uuid1().hex > > + if not keep: > > + self._instances.append(label) > > + ret =3D self._do(["run", "--label", "com.qemu.instance.uuid=3D= " + label] + cmd, quiet=3Dquiet) > > + if not keep: > > + self._instances.remove(label) > > + return ret > > + > > +class SubCommand(object): > > + """A SubCommand template base class""" > > + name =3D 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 =3D "run" > > + def args(self, parser): > > + parser.add_argument("--keep", action=3D"store_true", > > + help=3D"Don't remove image when the comm= and completes") > > + parser.add_argument("--quiet", action=3D"store_true", > > + help=3D"Run quietly unless an error > > occured") >=20 > I suspect --quiet should be a shared global flag. Will change, so the --verbose in build subcommand below will be expressed= in !quiet. >=20 > Also it would be worth adding help text to show the remaining args are > passed "as is" to the docker command line. Yes, good point. >=20 > > + def run(self, args, argv): > > + return Docker().run(argv, args.keep, quiet=3Dargs.quiet) > > + > > +class BuildCommand(SubCommand): > > + """ Build docker image out of a dockerfile""" > > + name =3D "build" > > + def args(self, parser): > > + parser.add_argument("tag", > > + help=3D"Image Tag") > > + parser.add_argument("dockerfile", > > + help=3D"Dockerfile name") > > + parser.add_argument("--verbose", "-v", action=3D"store_true"= , > > + help=3D"Print verbose information") >=20 > I suspect --verbose should be a shared global flag. >=20 > > + > > + def run(self, args, argv): > > + dockerfile =3D open(args.dockerfile, "rb").read() > > + tag =3D args.tag > > + > > + dkr =3D Docker() > > + if dkr.image_matches_dockerfile(tag, dockerfile): > > + if args.verbose: > > + print "Image is up to date." > > + return 0 > > + > > + quiet =3D not args.verbose > > + dkr.build_image(tag, dockerfile, args.dockerfile, quiet=3Dqu= iet, argv=3Dargv) > > + return 0 >=20 > I've seen this hang. Do builds always succeed? It does "{apt-get,yum,dnf} install", which could block due to network iss= ues. >=20 > > + > > +class CleanCommand(SubCommand): > > + """Clean up docker instances""" > > + name =3D "clean" > > + def run(self, args, argv): > > + Docker().clean() > > + return 0 > > + > > +def main(): > > + parser =3D argparse.ArgumentParser() > > + subparsers =3D parser.add_subparsers() > > + for cls in SubCommand.__subclasses__(): > > + cmd =3D cls() > > + subp =3D subparsers.add_parser(cmd.name, help=3Dcmd.__doc__) > > + cmd.args(subp) > > + subp.set_defaults(cmdobj=3Dcmd) > > + args, argv =3D parser.parse_known_args() > > + return args.cmdobj.run(args, argv) >=20 > There are some niggles with help: >=20 > 14:40 alex@zen/x86_64 [qemu.git/review/docker-v3]>./tests/docker/docke= r.py --help > usage: docker.py [-h] {run,build,clean} ... >=20 > positional arguments: > {run,build,clean} >=20 > Positional? Really. You can only have one command at a time. That's the default output of Python's argparse module. >=20 > run Invoke docker run and take care of cleaning up > build Build docker image out of a dockerfile > clean Clean up docker instances >=20 > optional arguments: > -h, --help show this help message and exit >=20 > OK that's useful, but do we have args for build? >=20 > 14:43 alex@zen/x86_64 [qemu.git/review/docker-v3]>./tests/docker/docke= r.py --help build > usage: docker.py [-h] {run,build,clean} ... >=20 > positional arguments: > {run,build,clean} > run Invoke docker run and take care of cleaning up > build Build docker image out of a dockerfile > clean Clean up docker instances >=20 > optional arguments: > -h, --help show this help message and exit >=20 > Hmm same result. We have to call like this: >=20 > 14:43 alex@zen/x86_64 [qemu.git/review/docker-v3] >./tests/docker/doc= ker.py build --help > usage: docker.py build [-h] [--verbose] tag dockerfile >=20 > positional arguments: > tag Image Tag > dockerfile Dockerfile name >=20 > optional arguments: > -h, --help show this help message and exit > --verbose, -v Print verbose information >=20 > Maybe there is someway to make this clearer. I'll try. Thanks for your input! Fam >=20 > > + > > +if __name__ =3D=3D "__main__": > > + sys.exit(main()) >=20 >=20 > -- > Alex Benn=E9e