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

@@ -12,7 +12,6 @@

  import sys

  import tempfile

  import time

- import traceback

  import distutils.util

  

  IDENTITY = """
@@ -58,11 +57,15 @@

    expire: False

  """

  

- def main(argv):

-     parser = argparse.ArgumentParser(description="Inventory for a QCow2 test image")

+ 

+ def main():

+     parser = argparse.ArgumentParser(description=

+                                      "Inventory for a QCow2 test image")

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

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

-     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:
@@ -72,21 +75,23 @@

              data = list(opts.subjects)

          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):

-     hosts = [ ]

-     variables = { }

+     hosts = []

+     variables = {}

      for subject in subjects:

          if subject.endswith((".qcow2", ".qcow2c")):

              vars = host(subject)

              if vars:

                  hosts.append(subject)

                  variables[subject] = 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 start_qemu(image, cloudinit, log, portrange=(2222, 5555)):
@@ -105,10 +110,12 @@

          raise RuntimeError("unable to find free local port to map SSH to")

  

      return subprocess.Popen(["/usr/bin/qemu-system-x86_64", "-m", "1024", image,

-         "-enable-kvm", "-snapshot", "-cdrom", cloudinit,

-         "-net", "nic,model=virtio", "-net", "user,hostfwd=tcp:127.0.0.3:{0}-:22".format(port),

-         "-device", "isa-serial,chardev=pts2", "-chardev", "file,id=pts2,path=" + log,

-         "-display", "none"], stdout=open(os.devnull, 'w')), port

+                              "-enable-kvm", "-snapshot", "-cdrom", cloudinit,

+                              "-net", "nic,model=virtio", "-net",

+                              "user,hostfwd=tcp:127.0.0.3:{0}-:22".format(port),

+                              "-device", "isa-serial,chardev=pts2", "-chardev",

+                              "file,id=pts2,path=" + log, "-display", "none"],

+                             stdout=open(os.devnull, 'w')), port

  

  

  def host(image):
@@ -138,24 +145,27 @@

      cloudinit = os.path.join(directory, "cloud-init.iso")

      subprocess.check_call(["/usr/bin/genisoimage", "-input-charset", "utf-8",

                             "-volid", "cidata", "-joliet", "-rock", "-quiet",

-                            "-output", cloudinit, userdata, metadata], stdout=null)

+                            "-output", cloudinit, userdata, metadata],

+                           stdout=null)

  

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

+     # Determine if virtual machine should be kept available

+     # for diagnosis after completion

      try:

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

      except ValueError:

          diagnose = 0

  

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

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

  

      # And launch the actual VM

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

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

+                                                               "artifacts"))

      try:

          os.makedirs(artifacts)

      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)))

  

      proc = None  # for failure detection

      cpe = None  # for exception scoping
@@ -168,7 +178,7 @@

              continue

      if proc is None:

          raise RuntimeError("Could not launch VM for qcow2 image"

-                            " '{0}':{1}".format(image, cpe.output))

+                            " '{}':{}".format(image, cpe.output))

  

      for tries in xrange(0, 30):

          try:
@@ -183,7 +193,8 @@

              }

  

              # Write out a handy inventory file, for our use and for debugging

-             args = " ".join([ "{0}='{1}'".format(*item) for item in variables.items() ])

+             args = " ".join(["{}='{}'".format(

+                 *item) for item in variables.items()])

              inventory = os.path.join(directory, "inventory")

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

                  f.write("[subjects]\nlocalhost {1}\n".format(image, args))
@@ -202,13 +213,15 @@

  

              (pid, ret) = os.waitpid(proc.pid, os.WNOHANG)

              if pid != 0:

-                 raise RuntimeError("qemu failed to launch qcow2 image: {0}".format(image))

+                 raise RuntimeError(

+                     "qemu failed to launch qcow2 image: {}".format(image))

              subprocess.check_call(ping, stdout=null, stderr=null)

              break

          except subprocess.CalledProcessError:

              time.sleep(3)

      else:

-         raise RuntimeError("could not access launched qcow2 image: {0}".format(image))

+         raise RuntimeError(

+             "could not access launched qcow2 image: {}".format(image))

  

      # Process of our parent

      ppid = os.getppid()
@@ -238,15 +251,20 @@

              os.kill(ppid, 0)

              os.kill(proc.pid, 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: ssh -p {0} -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null root@{1} # password: {2}\n".format(port, "127.0.0.3", "foobar"))

-         sys.stderr.write("DIAGNOSE: export ANSIBLE_INVENTORY={0}\n".format(inventory))

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

- 

-         def _signal_handler(*args):

+         sys.stderr.write(

+             "DIAGNOSE: ssh -p {} -o StrictHostKeyChecking=no -o "

+             "UserKnownHostsFile=/dev/null root@{} # password: {}\n".format(

+                 port, "127.0.0.3", "foobar"))

+         sys.stderr.write(

+             "DIAGNOSE: export ANSIBLE_INVENTORY={}\n".format(inventory))

+         sys.stderr.write(

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

+ 

+         def _signal_handler():

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

  

          signal.signal(signal.SIGTERM, _signal_handler)
@@ -261,5 +279,6 @@

      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.

Pull-Request has been closed by astepano

6 years ago
Metadata