#77 Stick to the pep8 style docker inventory
Closed 6 years ago by astepano. Opened 6 years ago by sturivny.
Unknown source pep8-docker-inventory  into  master

@@ -7,21 +7,24 @@

  import shutil

  import shlex

  import signal

- import socket

  import subprocess

  import sys

  import tempfile

  import time

- import traceback

  import distutils.util

  

- def main(argv):

-     parser = argparse.ArgumentParser(description="Inventory for a container image in a registry")

+ 

+ def main():

+     parser = argparse.ArgumentParser(

+         description="Inventory for a container image in a registry")

      parser.add_argument("--list", action="store_true", help="Verbose output")

      parser.add_argument('--host', help="Get host variables")

-     parser.add_argument('--docker-extra-args', help="Extra docker arguments for launching container",

+     parser.add_argument('--docker-extra-args',

+                         help="Extra docker arguments for launching container",

                          default=os.environ.get("TEST_DOCKER_EXTRA_ARGS", ""))

-     parser.add_argument("subjects", nargs="*", default=shlex.split(os.environ.get("TEST_SUBJECTS", "")))

+     parser.add_argument("subjects", nargs="*",

+                         default=shlex.split(

+                             os.environ.get("TEST_SUBJECTS", "")))

      opts = parser.parse_args()

  

      try:
@@ -31,14 +34,15 @@

              data = list(opts.subjects, opts.docker_extra_args)

          sys.stdout.write(json.dumps(data, indent=4, separators=(',', ': ')))

      except RuntimeError as ex:

-         sys.stderr.write("{0}: {1}\n".format(os.path.basename(sys.argv[0]), str(ex)))

+         sys.stderr.write("{}: {}\n".format(os.path.basename(sys.argv[0]),

+                                            str(ex)))

          return 1

- 

      return 0

  

+ 

  def list(subjects, docker_extra_args):

-     hosts = [ ]

-     variables = { }

+     hosts = []

+     variables = {}

      for subject in subjects:

          if subject.startswith("docker:"):

              image = subject[7:]
@@ -46,7 +50,9 @@

              if vars:

                  hosts.append(name)

                  variables[name] = vars

-     return { "localhost": { "hosts": hosts, "vars": { } }, "subjects": { "hosts": hosts, "vars": { } }, "_meta": { "hostvars": variables } }

+     return {"localhost": {"hosts": hosts, "vars": {}}, "subjects":

+             {"hosts": hosts, "vars": {}}, "_meta": {"hostvars": variables}}

+ 

  

  def host(image, docker_extra_args):

      null = open(os.devnull, 'w')
@@ -61,39 +67,37 @@

      directory = tempfile.mkdtemp(prefix="inventory-docker")

      cidfile = os.path.join(directory, "cid")

  

-     # Determine if container should be kept available for diagnosis after completion

+     # Determine if container should be kept available for diagnosis after

+     # completion

      try:

          diagnose = distutils.util.strtobool(os.getenv("TEST_DEBUG", "0"))

      except ValueError:

          diagnose = 0

  

-     # Check for any additional arguments to include when starting docker container

+     # Check for any additional arguments to include when starting docker

+     # container

      try:

          extra_arg_list = shlex.split(docker_extra_args)

      except ValueError:

          raise RuntimeError("Could not parse DOCKER_EXTRA_ARGS")

  

-     sys.stderr.write("Launching Docker container for {0}\n".format(image))

+     sys.stderr.write("Launching Docker container for {}\n".format(image))

  

      # Make sure the docker service is running

-     cmd = [

-         "/usr/sbin/service", "docker", "start"

-     ]

+     cmd = ["/usr/sbin/service", "docker", "start"]

      try:

          subprocess.check_call(cmd, stdout=sys.stderr.fileno())

-     except subprocess.CalledProcessError as ex:

+     except subprocess.CalledProcessError:

          raise RuntimeError("Could not start docker service")

  

      # And launch the actual container

-     cmd = [

-         "/usr/bin/docker", "run", "--detach", "--cidfile={0}".format(cidfile),

-     ] + extra_arg_list + [

-         "--entrypoint=/bin/sh", image, "-c", "sleep 1000000"

-     ]

+     cmd = ["/usr/bin/docker", "run", "--detach",

+            "--cidfile={}".format(cidfile)] + extra_arg_list + [

+             "--entrypoint=/bin/sh", image, "-c", "sleep 1000000"]

      try:

          subprocess.check_call(cmd, stdout=sys.stderr.fileno())

-     except subprocess.CalledProcessError as ex:

-         raise RuntimeError("Could not start container image: {0}".format(image))

+     except subprocess.CalledProcessError:

+         raise RuntimeError("Could not start container image: {}".format(image))

  

      # Read out the container environment variable

      for x in range(1, 90):
@@ -101,28 +105,28 @@

              break

          time.sleep(1)

      else:

-         raise RuntimeError("Could not find container file for launched container")

+         raise RuntimeError(

+             "Could not find container file for launched container")

  

      with open(cidfile, "r") as f:

          name = f.read().strip()

  

      # Now install the necessary stuff in the container :S

-     install = [

-         "/usr/bin/docker", "exec", "--user=root", name, "/usr/bin/yum", "-y", "install",

-         "python2", "python2-dnf", "libselinux-python"

-     ]

+     install = ["/usr/bin/docker", "exec", "--user=root", name,

+                "/usr/bin/yum", "-y", "install",

+                "python2", "python2-dnf", "libselinux-python"]

      try:

          subprocess.check_call(install, stdout=sys.stderr.fileno())

-     except subprocess.CalledProcessError as ex:

-         raise RuntimeError("Could not install Ansible dependencies in launched container")

+     except subprocess.CalledProcessError:

+         raise RuntimeError(

+             "Could not install Ansible dependencies in launched container")

  

      # Directory to place artifacts

-     artifacts = os.environ.get("TEST_ARTIFACTS", os.path.join(os.getcwd(), "artifacts"))

+     artifacts = os.environ.get("TEST_ARTIFACTS", os.path.join(os.getcwd(),

+                                                               "artifacts"))

  

      # The variables

-     variables = {

-         "ansible_connection": "docker",

-     }

+     variables = {"ansible_connection": "docker"}

  

      # Process of our parent

      ppid = os.getppid()
@@ -151,14 +155,16 @@

          try:

              os.kill(ppid, 0)

          except OSError:

-             break # Either of the processes no longer exist

+             break  # Either of the processes no longer exist

  

      if diagnose:

          sys.stderr.write("\n")

-         sys.stderr.write("DIAGNOSE: docker exec -it {0} /bin/bash\n".format(name))

-         sys.stderr.write("DIAGNOSE: kill {0} # when finished\n".format(os.getpid()))

+         sys.stderr.write(

+             "DIAGNOSE: docker exec -it {} /bin/bash\n".format(name))

+         sys.stderr.write(

+             "DIAGNOSE: kill {} # when finished\n".format(os.getpid()))

  

-         def _signal_handler(*args):

+         def _signal_handler():

              sys.stderr.write("\nDIAGNOSE ending...\n")

  

          signal.signal(signal.SIGTERM, _signal_handler)
@@ -170,16 +176,17 @@

      except OSError as exc:

          if exc.errno != errno.EEXIST or not os.path.isdir(artifacts):

              raise

-     log = os.path.join(artifacts, "{0}.log".format(os.path.basename(image)))

+     log = os.path.join(artifacts, "{}.log".format(os.path.basename(image)))

  

      # Kill the container

      with open(log, "w") as f:

-         subprocess.call(["/usr/bin/docker", "logs", name ], stdout=f.fileno())

-     subprocess.call(["/usr/bin/docker", "kill", name ], stdout=null.fileno())

-     subprocess.call(["/usr/bin/docker", "rm", "-f", name ], stdout=null)

+         subprocess.call(["/usr/bin/docker", "logs", name], stdout=f.fileno())

+     subprocess.call(["/usr/bin/docker", "kill", name], stdout=null.fileno())

+     subprocess.call(["/usr/bin/docker", "rm", "-f", name], stdout=null)

  

      shutil.rmtree(directory)

      sys.exit(0)

  

+ 

  if __name__ == '__main__':

-     sys.exit(main(sys.argv))

+     sys.exit(main())

Remove unused import.
Groome code to pep8 style.

Formating shout be as follow:

    # Check for any additional arguments to include when starting docker
    # container

in VIM: ctrl-v, gq

Right indentation:

    cmd = ["/usr/bin/docker", "run", "--detach",
           "--cidfile={}".format(cidfile)] + extra_arg_list + [
               "--entrypoint=/bin/sh", image, "-c", "sleep 1000000"]

2 new commits added

  • Stick to the pep8 style docker inventory
  • Stick to the pep7 style docker inventory
6 years ago

rebased onto 15d8749

6 years ago

@astepano Updated PR,
so if you have free time welcome for review =)

What is wrong with {0} ?
{} without 0 it looks simlpy.

Pull-Request has been closed by astepano

6 years ago
Metadata