Commit 35d13f92 authored by Cédric Bosdonnat's avatar Cédric Bosdonnat

Convert to python3

Python2 is going to die soon, convert to python3.
parent 368d09f6
...@@ -30,7 +30,6 @@ from gi.repository import GLib ...@@ -30,7 +30,6 @@ from gi.repository import GLib
import gi import gi
import re import re
import os, sys, shutil, errno, stat import os, sys, shutil, errno, stat
import exceptions
import rpm import rpm
from subprocess import Popen, PIPE, STDOUT from subprocess import Popen, PIPE, STDOUT
import gettext import gettext
...@@ -49,7 +48,6 @@ gettext.textdomain("libvirt-sandbox") ...@@ -49,7 +48,6 @@ gettext.textdomain("libvirt-sandbox")
try: try:
gettext.install("libvirt-sandbox", gettext.install("libvirt-sandbox",
localedir="/usr/share/locale", localedir="/usr/share/locale",
unicode=False,
codeset = 'utf-8') codeset = 'utf-8')
except IOError: except IOError:
import __builtin__ import __builtin__
...@@ -235,7 +233,7 @@ class Container: ...@@ -235,7 +233,7 @@ class Container:
path = "%s%s" % (self.dest, f) path = "%s%s" % (self.dest, f)
os.chown(path, s.st_uid, s.st_gid) os.chown(path, s.st_uid, s.st_gid)
os.chmod(path, s.st_mode) os.chmod(path, s.st_mode)
except OSError, e: except OSError as e:
if not e.errno == errno.ENOENT: if not e.errno == errno.ENOENT:
raise raise
...@@ -253,7 +251,7 @@ class Container: ...@@ -253,7 +251,7 @@ class Container:
try: try:
path = "%s%s" % (self.dest, d) path = "%s%s" % (self.dest, d)
os.makedirs(path) os.makedirs(path)
except OSError, e: except OSError as e:
if not e.errno == errno.EEXIST: if not e.errno == errno.EEXIST:
raise raise
...@@ -263,7 +261,7 @@ class Container: ...@@ -263,7 +261,7 @@ class Container:
path = "%s%s" % (self.dest, f) path = "%s%s" % (self.dest, f)
fd=open(path, "w") fd=open(path, "w")
fd.close() fd.close()
except OSError, e: except OSError as e:
if not e.errno == errno.EEXIST: if not e.errno == errno.EEXIST:
raise raise
...@@ -404,10 +402,10 @@ class GenericContainer(Container): ...@@ -404,10 +402,10 @@ class GenericContainer(Container):
def create(self): def create(self):
try: try:
self.create_generic() self.create_generic()
except Exception, e: except Exception as e:
try: try:
self.delete() self.delete()
except Exception, e2: except Exception as e2:
pass pass
raise e raise e
...@@ -581,8 +579,8 @@ WantedBy=multi-user.target ...@@ -581,8 +579,8 @@ WantedBy=multi-user.target
def get_rpm_for_unit(self, unitfile): def get_rpm_for_unit(self, unitfile):
mi = self.ts.dbMatch(rpm.RPMTAG_BASENAMES, unitfile) mi = self.ts.dbMatch(rpm.RPMTAG_BASENAMES, unitfile)
try: try:
h = mi.next(); h = next(mi);
except exceptions.StopIteration: except StopIteration:
return None return None
return h['name'] return h['name']
...@@ -590,8 +588,8 @@ WantedBy=multi-user.target ...@@ -590,8 +588,8 @@ WantedBy=multi-user.target
def extract_rpm(self, rpm_name): def extract_rpm(self, rpm_name):
mi = self.ts.dbMatch('name', rpm_name) mi = self.ts.dbMatch('name', rpm_name)
try: try:
h = mi.next(); h = next(mi);
except exceptions.StopIteration: except StopIteration:
raise ValueError([_("Cannot find package named %s") % rpm_name]) raise ValueError([_("Cannot find package named %s") % rpm_name])
for fentry in h.fiFromHeader(): for fentry in h.fiFromHeader():
...@@ -602,16 +600,16 @@ WantedBy=multi-user.target ...@@ -602,16 +600,16 @@ WantedBy=multi-user.target
if os.path.isfile(fname): if os.path.isfile(fname):
self.add_file(fname) self.add_file(fname)
srcrpm = h[rpm.RPMTAG_SOURCERPM] srcrpm = str(h[rpm.RPMTAG_SOURCERPM], encoding='utf-8')
srcrpmbits = self.split_filename(srcrpm) srcrpmbits = self.split_filename(srcrpm)
if srcrpmbits[0] == h[rpm.RPMTAG_NAME]: if srcrpmbits[0] == str(h[rpm.RPMTAG_NAME], encoding='utf-8'):
return return
mi = self.ts.dbMatch(rpm.RPMTAG_NAME, srcrpmbits[0]) mi = self.ts.dbMatch(rpm.RPMTAG_NAME, srcrpmbits[0])
try: try:
h = mi.next(); h = next(mi);
except exceptions.StopIteration: except StopIteration:
raise ValueError([_("Cannot find base package %s") % srcrpmbits[0]]) raise ValueError([_("Cannot find base package %s") % srcrpmbits[0]])
for fentry in h.fiFromHeader(): for fentry in h.fiFromHeader():
...@@ -771,7 +769,7 @@ PrivateNetwork=false ...@@ -771,7 +769,7 @@ PrivateNetwork=false
fd.write("[Unit]\n") fd.write("[Unit]\n")
fd.write("Description=Sandbox multi-user target\n") fd.write("Description=Sandbox multi-user target\n")
fd.close() fd.close()
except OSError, e: except OSError as e:
if not e.errno == errno.EEXIST: if not e.errno == errno.EEXIST:
raise raise
...@@ -789,7 +787,7 @@ PrivateNetwork=false ...@@ -789,7 +787,7 @@ PrivateNetwork=false
jpath = "/var/log/journal/" + uuid jpath = "/var/log/journal/" + uuid
if os.path.lexists(jpath): if os.path.lexists(jpath):
os.remove(jpath) os.remove(jpath)
except Exception, e: except Exception as e:
sys.stderr.write("%s: %s\n" % (sys.argv[0], e)) sys.stderr.write("%s: %s\n" % (sys.argv[0], e))
sys.stderr.flush() sys.stderr.flush()
...@@ -825,10 +823,10 @@ PrivateNetwork=false ...@@ -825,10 +823,10 @@ PrivateNetwork=false
try: try:
self.create_systemd() self.create_systemd()
except Exception, e: except Exception as e:
try: try:
self.delete() self.delete()
except Exception, e2: except Exception as e2:
sys.stderr.write("Cleanup failed: %s\n" % str(e2)) sys.stderr.write("Cleanup failed: %s\n" % str(e2))
raise raise
...@@ -923,10 +921,10 @@ def connect(args): ...@@ -923,10 +921,10 @@ def connect(args):
execute(args) execute(args)
return return
print """\ print ("""\
Connected to %s. Connected to %s.
Type 'Ctrl + ]' to detach from the console. Type 'Ctrl + ]' to detach from the console.
""" % ( args.name ) """ % ( args.name ))
os.execl("/usr/libexec/virt-sandbox-service-util", os.execl("/usr/libexec/virt-sandbox-service-util",
"virt-sandbox-service-util", "virt-sandbox-service-util",
"-c", args.uri, "-c", args.uri,
...@@ -1014,7 +1012,7 @@ def clone(args): ...@@ -1014,7 +1012,7 @@ def clone(args):
newcontainer.set_security(args.security) newcontainer.set_security(args.security)
newcontainer.set_security_label() newcontainer.set_security_label()
newcontainer.save_config() newcontainer.save_config()
except Exception, e: except Exception as e:
if newcontainer is not None: if newcontainer is not None:
newcontainer.delete() newcontainer.delete()
raise raise
...@@ -1296,23 +1294,21 @@ if __name__ == '__main__': ...@@ -1296,23 +1294,21 @@ if __name__ == '__main__':
sys.exit(1) sys.exit(1)
args.func(args) args.func(args)
sys.exit(0) sys.exit(0)
except KeyboardInterrupt, e: except KeyboardInterrupt as e:
sys.exit(0) sys.exit(0)
except ValueError, e: except ValueError as e:
for line in e: sys.stderr.write("%s: %s\n" % (sys.argv[0], e))
for l in line:
sys.stderr.write("%s: %s\n" % (sys.argv[0], l))
sys.stderr.flush() sys.stderr.flush()
sys.exit(1) sys.exit(1)
except IOError, e: except IOError as e:
sys.stderr.write("%s: %s: %s\n" % (sys.argv[0], e.filename, e.strerror)) sys.stderr.write("%s: %s: %s\n" % (sys.argv[0], e.filename, e.strerror))
sys.stderr.flush() sys.stderr.flush()
sys.exit(1) sys.exit(1)
except OSError, e: except OSError as e:
sys.stderr.write("%s: %s\n" % (sys.argv[0], e)) sys.stderr.write("%s: %s\n" % (sys.argv[0], e))
sys.stderr.flush() sys.stderr.flush()
sys.exit(1) sys.exit(1)
except GLib.GError, e: except GLib.GError as e:
sys.stderr.write("%s: %s\n" % (sys.argv[0], e)) sys.stderr.write("%s: %s\n" % (sys.argv[0], e))
sys.stderr.flush() sys.stderr.flush()
sys.exit(1) sys.exit(1)
...@@ -30,7 +30,6 @@ import os.path ...@@ -30,7 +30,6 @@ import os.path
import re import re
import shutil import shutil
import sys import sys
import urllib2
import subprocess import subprocess
import random import random
import string import string
...@@ -52,7 +51,6 @@ gettext.textdomain("libvirt-sandbox") ...@@ -52,7 +51,6 @@ gettext.textdomain("libvirt-sandbox")
try: try:
gettext.install("libvirt-sandbox", gettext.install("libvirt-sandbox",
localedir="/usr/share/locale", localedir="/usr/share/locale",
unicode=False,
codeset = 'utf-8') codeset = 'utf-8')
except IOError: except IOError:
import __builtin__ import __builtin__
...@@ -149,7 +147,7 @@ def list_cached(args): ...@@ -149,7 +147,7 @@ def list_cached(args):
tmpls.extend(template.Template.get_all(source, tmpls.extend(template.Template.get_all(source,
"%s/%s" % (args.template_dir, source))) "%s/%s" % (args.template_dir, source)))
for tmpl in tmpls: for tmpl in tmpls:
print tmpl print (tmpl)
def requires_template(parser): def requires_template(parser):
parser.add_argument("template", parser.add_argument("template",
...@@ -265,20 +263,20 @@ def main(): ...@@ -265,20 +263,20 @@ def main():
try: try:
args.func(args) args.func(args)
sys.exit(0) sys.exit(0)
except KeyboardInterrupt, e: except KeyboardInterrupt as e:
sys.exit(0) sys.exit(0)
except ValueError, e: except ValueError as e:
sys.stderr.write("%s: %s\n" % (sys.argv[0], e)) sys.stderr.write("%s: %s\n" % (sys.argv[0], e))
sys.stderr.flush() sys.stderr.flush()
sys.exit(1) sys.exit(1)
except IOError, e: except IOError as e:
sys.stderr.write("%s: %s: %s\n" % (sys.argv[0], e.filename, e.reason)) sys.stderr.write("%s: %s\n" % (sys.argv[0], e.filename))
sys.stderr.flush() sys.stderr.flush()
sys.exit(1) sys.exit(1)
except OSError, e: except OSError as e:
sys.stderr.write("%s: %s\n" % (sys.argv[0], e)) sys.stderr.write("%s: %s\n" % (sys.argv[0], e))
sys.stderr.flush() sys.stderr.flush()
sys.exit(1) sys.exit(1)
except Exception, e: except Exception as e:
print e.message print (e)
sys.exit(1) sys.exit(1)
...@@ -21,14 +21,15 @@ ...@@ -21,14 +21,15 @@
# Author: Eren Yagdiran <erenyagdiran@gmail.com> # Author: Eren Yagdiran <erenyagdiran@gmail.com>
# #
import urllib2
import sys import sys
import json import json
import traceback import traceback
import os import os
import subprocess import subprocess
import shutil import shutil
import urlparse import urllib.error
import urllib.parse
import urllib.request
import hashlib import hashlib
from abc import ABCMeta, abstractmethod from abc import ABCMeta, abstractmethod
import copy import copy
...@@ -133,7 +134,7 @@ class DockerAuthBasic(DockerAuth): ...@@ -133,7 +134,7 @@ class DockerAuthBasic(DockerAuth):
req.add_header("X-Docker-Token", "true") req.add_header("X-Docker-Token", "true")
def process_res(self, res): def process_res(self, res):
self.token = res.info().getheader('X-Docker-Token') self.token = res.info().get('X-Docker-Token')
def process_err(self, err): def process_err(self, err):
return False return False
...@@ -194,10 +195,10 @@ class DockerAuthBearer(DockerAuth): ...@@ -194,10 +195,10 @@ class DockerAuthBearer(DockerAuth):
if params != "": if params != "":
url = url + "?" + params url = url + "?" + params
req = urllib2.Request(url=url) req = urllib.request.Request(url=url)
req.add_header("Accept", "application/json") req.add_header("Accept", "application/json")
res = urllib2.urlopen(req) res = urllib.request.urlopen(req)
data = json.loads(res.read()) data = json.loads(res.read())
self.token = data["token"] self.token = data["token"]
return True return True
...@@ -207,7 +208,7 @@ class DockerRegistry(): ...@@ -207,7 +208,7 @@ class DockerRegistry():
def __init__(self, uri_base): def __init__(self, uri_base):
self.uri_base = list(urlparse.urlparse(uri_base)) self.uri_base = list(urllib.parse.urlparse(uri_base))
self.auth_handler = DockerAuthNop() self.auth_handler = DockerAuthNop()
def set_auth_handler(self, auth_handler): def set_auth_handler(self, auth_handler):
...@@ -216,8 +217,8 @@ class DockerRegistry(): ...@@ -216,8 +217,8 @@ class DockerRegistry():
def supports_v2(self): def supports_v2(self):
try: try:
(data, res) = self.get_json("/v2/") (data, res) = self.get_json("/v2/")
ver = res.info().getheader("Docker-Distribution-Api-Version") ver = res.info().get("Docker-Distribution-Api-Version")
except urllib2.HTTPError as e: except urllib.error.HTTPError as e:
ver = e.headers.get("Docker-Distribution-Api-Version", None) ver = e.headers.get("Docker-Distribution-Api-Version", None)
if ver is None: if ver is None:
...@@ -243,17 +244,17 @@ class DockerRegistry(): ...@@ -243,17 +244,17 @@ class DockerRegistry():
else: else:
server = "%s:%s" % (hostname, port) server = "%s:%s" % (hostname, port)
url = urlparse.urlunparse((protocol, server, "", None, None, None)) url = urllib.parse.urlunparse((protocol, server, "", None, None, None))
return cls(url) return cls(url)
def get_url(self, path, headers=None): def get_url(self, path, headers=None):
url_bits = copy.copy(self.uri_base) url_bits = copy.copy(self.uri_base)
url_bits[2] = path url_bits[2] = path
url = urlparse.urlunparse(url_bits) url = urllib.parse.urlunparse(url_bits)
debug("Fetching %s..." % url) debug("Fetching %s..." % url)
req = urllib2.Request(url=url) req = urllib.request.Request(url=url)
if headers is not None: if headers is not None:
for h in headers.keys(): for h in headers.keys():
...@@ -262,16 +263,16 @@ class DockerRegistry(): ...@@ -262,16 +263,16 @@ class DockerRegistry():
self.auth_handler.prepare_req(req) self.auth_handler.prepare_req(req)
try: try:
res = urllib2.urlopen(req) res = urllib.request.urlopen(req)
self.auth_handler.process_res(res) self.auth_handler.process_res(res)
return res return res
except urllib2.HTTPError as e: except urllib.error.HTTPError as e:
if e.code == 401: if e.code == 401:
retry = self.auth_handler.process_err(e) retry = self.auth_handler.process_err(e)
if retry: if retry:
debug("Re-Fetching %s..." % url) debug("Re-Fetching %s..." % url)
self.auth_handler.prepare_req(req) self.auth_handler.prepare_req(req)
res = urllib2.urlopen(req) res = urllib.request.urlopen(req)
self.auth_handler.process_res(res) self.auth_handler.process_res(res)
return res return res
else: else:
...@@ -284,7 +285,7 @@ class DockerRegistry(): ...@@ -284,7 +285,7 @@ class DockerRegistry():
try: try:
res = self.get_url(path) res = self.get_url(path)
datalen = res.info().getheader("Content-Length") datalen = res.info().get("Content-Length")
if datalen is not None: if datalen is not None:
datalen = int(datalen) datalen = int(datalen)
...@@ -296,7 +297,7 @@ class DockerRegistry(): ...@@ -296,7 +297,7 @@ class DockerRegistry():
patternIndex = 0 patternIndex = 0
donelen = 0 donelen = 0
with open(dest, "w") as f: with open(dest, "wb") as f:
while 1: while 1:
buf = res.read(1024*64) buf = res.read(1024*64)
if not buf: if not buf:
...@@ -321,7 +322,7 @@ class DockerRegistry(): ...@@ -321,7 +322,7 @@ class DockerRegistry():
raise IOError("Checksum '%s' for data does not match '%s'" % (csumstr, checksum)) raise IOError("Checksum '%s' for data does not match '%s'" % (csumstr, checksum))
debug("OK\n") debug("OK\n")
return res return res
except Exception, e: except Exception as e:
debug("FAIL %s\n" % str(e)) debug("FAIL %s\n" % str(e))
raise raise
...@@ -333,7 +334,7 @@ class DockerRegistry(): ...@@ -333,7 +334,7 @@ class DockerRegistry():
data = json.loads(res.read()) data = json.loads(res.read())
debug("OK\n") debug("OK\n")
return (data, res) return (data, res)
except Exception, e: except Exception as e:
debug("FAIL %s\n" % str(e)) debug("FAIL %s\n" % str(e))
raise raise
...@@ -426,10 +427,10 @@ class DockerSource(base.Source): ...@@ -426,10 +427,10 @@ class DockerSource(base.Source):
(data, res) = registry.get_json("/v1/repositories/%s/%s/images" % ( (data, res) = registry.get_json("/v1/repositories/%s/%s/images" % (
image.repo, image.name, image.repo, image.name,
)) ))
except urllib2.HTTPError, e: except urllib.error.HTTPError as e:
raise ValueError(["Image '%s' does not exist" % template]) raise ValueError(["Image '%s' does not exist" % template])
registryendpoint = res.info().getheader('X-Docker-Endpoints') registryendpoint = res.info().get('X-Docker-Endpoints')
if basicauth.token is not None: if basicauth.token is not None:
registry.set_auth_handler(DockerAuthToken(basicauth.token)) registry.set_auth_handler(DockerAuthToken(basicauth.token))
......
...@@ -19,7 +19,7 @@ ...@@ -19,7 +19,7 @@
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
# #
import urlparse import urllib.parse
import importlib import importlib
import re import re
...@@ -71,7 +71,7 @@ class Template(object): ...@@ -71,7 +71,7 @@ class Template(object):
classimpl = getattr(mod, classname) classimpl = getattr(mod, classname)
return classimpl() return classimpl()
except Exception as e: except Exception as e:
print e print (e)
raise Exception("Invalid source: '%s'" % source) raise Exception("Invalid source: '%s'" % source)
def get_source_impl(self): def get_source_impl(self):
...@@ -101,12 +101,12 @@ class Template(object): ...@@ -101,12 +101,12 @@ class Template(object):
netloc = None netloc = None
query = "&".join([key + "=" + self.params[key] for key in self.params.keys()]) query = "&".join([key + "=" + self.params[key] for key in self.params.keys()])
ret = urlparse.urlunparse((scheme, netloc, self.path, None, query, None)) ret = urllib.parse.urlunparse((scheme, netloc, self.path, None, query, None))
return ret return ret
@classmethod @classmethod
def from_uri(klass, uri): def from_uri(klass, uri):
o = urlparse.urlparse(uri) o = urllib.parse.urlparse(uri)
idx = o.scheme.find("+") idx = o.scheme.find("+")
if idx == -1: if idx == -1:
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment