Apply fixers from futurize
[invirt/packages/invirt-images.git] / invirt-images
index ea208a5..93e4f6e 100755 (executable)
@@ -1,5 +1,11 @@
 #!/usr/bin/python
 
+from __future__ import print_function
+from future import standard_library
+standard_library.install_aliases()
+from builtins import map
+from builtins import zip
+from builtins import range
 from invirt import database
 import os
 import sys
@@ -7,7 +13,7 @@ import subprocess
 import random
 import string
 import tempfile
-import urllib
+import urllib.request, urllib.parse, urllib.error
 import math
 import optparse as op
 
@@ -37,23 +43,43 @@ def lvcreate(name, size):
         return 5
     else:
         if verbosity > 0:
-            print stderr
+            print(stderr)
         return 6
 
 def lvrename(dest, src):
-    lvr = subprocess.Popen(['lvrename', 'xenvg', src, dest],
+    lvr = subprocess.Popen(['lvchange', '-an', "xenvg/%s" % (src,)],
                            stderr=subprocess.PIPE,
                            stdout=getOutput()['stdout'])
     ret = lvr.wait()
-    if not ret:
-        return 0
-    stderr = lvr.stderr.read()
-    if 'not found in volume group' in stderr:
-        return 0
-    else:
+
+    if ret:
+       if verbosity > 0:
+           print(lvr.stderr.read())
+       return ret
+
+    lvr = subprocess.Popen(['lvrename', "xenvg/%s" % (src,), "xenvg/%s" % (dest,)],
+                           stderr=subprocess.PIPE,
+                           stdout=getOutput()['stdout'])
+    ret = lvr.wait()
+
+    if ret:
+        stderr = lvr.stderr.read()
+        if not ('not found in volume group' in stderr):
+            if verbosity > 0:
+                print(stderr)
+            return ret
+
+    subprocess.Popen(['lvchange', '-ay', "xenvg/%s" % (dest,)],
+                     stderr=subprocess.PIPE,
+                     stdout=getOutput()['stdout'])
+    ret = lvr.wait()
+
+    if ret:
         if verbosity > 0:
-            print stderr
-        return ret
+           print(lvr.stderr.read())
+
+    return ret
+
 
 def lv_random(func, pattern, *args):
     """
@@ -73,7 +99,7 @@ def lv_random(func, pattern, *args):
     # Keep trying until it works
     while True:
         rand_string = ''.join(random.choice(string.ascii_letters) \
-                                  for i in xrange(6))
+                                  for i in range(6))
         if '%s' in pattern:
             name = pattern % rand_string
         else:
@@ -83,7 +109,7 @@ def lv_random(func, pattern, *args):
             return name
         # 5 is the return code if the destination already exists
         elif '%s' not in pattern or ret != 5:
-            raise InvirtImageException, 'E: Error running %s with args %s' % (func.__name__, args)
+            raise InvirtImageException('E: Error running %s with args %s' % (func.__name__, args))
 
 def lvcreate_random(pattern, size):
     """
@@ -111,16 +137,16 @@ def fetch_image(cdrom):
     full_uri = os.path.join(cdrom.mirror.uri_prefix, cdrom.uri_suffix)
     temp_file = tempfile.mkstemp()[1]
     if verbosity > 0:
-        print >>sys.stderr, "Fetching image %s from %s to %s" % (cdrom.cdrom_id, full_uri, temp_file)
+        print("Fetching image %s from %s to %s" % (cdrom.cdrom_id, full_uri, temp_file), file=sys.stderr)
     try:
         if full_uri.startswith('rsync://'):
             if subprocess.call(['rsync', '--no-motd', '-tLP', full_uri, temp_file],
                                **getOutput()):
-                raise InvirtImageException, "E: Unable to download '%s'" % full_uri
+                raise InvirtImageException("E: Unable to download '%s'" % full_uri)
         else:
             # I'm not going to look for errors here, because I bet it'll
             # throw its own exceptions
-            urllib.urlretrieve(full_uri, temp_file)
+            urllib.request.urlretrieve(full_uri, temp_file)
         return temp_file
     except:
         os.unlink(temp_file)
@@ -132,7 +158,7 @@ def copy_file(src, dest):
     """
     if subprocess.call(['dd', 'if=%s' % src, 'of=%s' % dest, 'bs=1M'],
                        **getOutput()):
-        raise InvirtImageException, 'E: Unable to transfer %s into %s' % (src, dest)
+        raise InvirtImageException('E: Unable to transfer %s into %s' % (src, dest))
 
 def load_image(cdrom):
     """
@@ -144,14 +170,14 @@ def load_image(cdrom):
         return
     try:
         temp_file = fetch_image(cdrom)
-    except InvirtImageException, e:
-        print >>sys.stderr, 'ERROR: %s.  Skipping.' % e
+    except InvirtImageException as e:
+        print('ERROR: %s.  Skipping.' % e, file=sys.stderr)
         return
 
     try:
         st_size = os.stat(temp_file).st_size
         if not st_size:
-            print >>sys.stderr, "Failed to fetch %s" % cdrom.cdrom_id
+            print("Failed to fetch %s" % cdrom.cdrom_id, file=sys.stderr)
             return
         cdrom_size = '%sM' % math.ceil((float(st_size) / (1024 * 1024)))
         new_lv = lvcreate_random('image-new_%s_%%s' % cdrom.cdrom_id, cdrom_size)
@@ -238,11 +264,11 @@ def main():
     (options, args) = parser.parse_args()
     verbosity = options.verbosity
     if options.action is None:
-        print parser.format_help()
+        print(parser.format_help())
     elif options.action == 'add':
         if options.item == 'cdrom':
-            attrs = dict(zip(('cdrom_id', 'description', 'mirror_id', 'uri_suffix'),
-                             args))
+            attrs = dict(list(zip(('cdrom_id', 'description', 'mirror_id', 'uri_suffix'),
+                             args)))
             cdrom = database.CDROM(**attrs)
             database.session.add(cdrom)
             database.session.commit()
@@ -250,8 +276,8 @@ def main():
             load_image(cdrom)
         
         elif options.item == 'mirror':
-            attrs = dict(zip(('mirror_id', 'uri_prefix'),
-                             args))
+            attrs = dict(list(zip(('mirror_id', 'uri_prefix'),
+                             args)))
             mirror = database.Mirror(**attrs)
             database.session.add(mirror)
             database.session.commit()