python: PEP8 compatibility

The new version of the pep8 command is detecting more indentation
mistakes than it used to, this fixes them.

Signed-off-by: Stéphane Graber <stgraber@ubuntu.com>
Acked-by: Serge E. Hallyn <serge.hallyn@ubuntu.com>
This commit is contained in:
Stéphane Graber 2012-11-22 15:25:45 -05:00
parent f79d43bbe7
commit bde1853954
4 changed files with 84 additions and 82 deletions

View File

@ -46,16 +46,17 @@ def randomMAC():
import random import random
mac = [0x00, 0x16, 0x3e, mac = [0x00, 0x16, 0x3e,
random.randint(0x00, 0x7f), random.randint(0x00, 0x7f),
random.randint(0x00, 0xff), random.randint(0x00, 0xff),
random.randint(0x00, 0xff)] random.randint(0x00, 0xff)]
return ':'.join(map(lambda x: "%02x" % x, mac)) return ':'.join(map(lambda x: "%02x" % x, mac))
# Begin parsing the command line # Begin parsing the command line
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(description=_(
description=_("LXC: Start an ephemeral container"), "LXC: Start an ephemeral container"),
formatter_class=argparse.RawTextHelpFormatter, epilog=_( formatter_class=argparse.RawTextHelpFormatter,
"""If a COMMAND is given, then the container will run only as long epilog=_("If a COMMAND is given, then the "
"""container will run only as long
as the command runs. as the command runs.
If no COMMAND is given, this command will attach to tty1 and stop the If no COMMAND is given, this command will attach to tty1 and stop the
container when exiting (with ctrl-a-q). container when exiting (with ctrl-a-q).
@ -64,29 +65,31 @@ If no COMMAND is given and -d is used, the name and IP addresses of the
container will be printed to the console.""")) container will be printed to the console."""))
parser.add_argument("--orig", "-o", type=str, required=True, parser.add_argument("--orig", "-o", type=str, required=True,
help=_("name of the original container")) help=_("name of the original container"))
parser.add_argument("--bdir", "-b", type=str, parser.add_argument("--bdir", "-b", type=str,
help=_("directory to bind mount into container")) help=_("directory to bind mount into container"))
parser.add_argument("--user", "-u", type=str, parser.add_argument("--user", "-u", type=str,
help=_("the user to connect to the container as")) help=_("the user to connect to the container as"))
parser.add_argument("--key", "-S", type=str, parser.add_argument("--key", "-S", type=str,
help=_("the path to the SSH key to use to connect")) help=_("the path to the SSH key to use to connect"))
parser.add_argument("--daemon", "-d", action="store_true", parser.add_argument("--daemon", "-d", action="store_true",
help=_("run in the background")) help=_("run in the background"))
parser.add_argument("--union-type", "-U", type=str, default="overlayfs", parser.add_argument("--union-type", "-U", type=str, default="overlayfs",
choices=("overlayfs", "aufs"), choices=("overlayfs", "aufs"),
help=_("type of union (overlayfs or aufs), defaults to overlayfs.")) help=_("type of union (overlayfs or aufs), "
"defaults to overlayfs."))
parser.add_argument("--keep-data", "-k", action="store_true", parser.add_argument("--keep-data", "-k", action="store_true",
help=_("Use a persistent backend instead of tmpfs.")) help=_("Use a persistent backend instead of tmpfs."))
parser.add_argument("command", metavar='CMD', type=str, nargs="*", parser.add_argument("command", metavar='CMD', type=str, nargs="*",
help=_("Run specific command in container (command as argument)")) help=_("Run specific command in container "
"(command as argument)"))
args = parser.parse_args() args = parser.parse_args()
@ -129,7 +132,7 @@ if orig.get_config_item("lxc.mount"):
for line in orig_fd.read().split("\n"): for line in orig_fd.read().split("\n"):
# Start by replacing any reference to the container rootfs # Start by replacing any reference to the container rootfs
line.replace(orig.get_config_item("lxc.rootfs"), line.replace(orig.get_config_item("lxc.rootfs"),
dest.get_config_item("lxc.rootfs")) dest.get_config_item("lxc.rootfs"))
# Skip any line that's not a bind mount # Skip any line that's not a bind mount
fields = line.split() fields = line.split()
@ -143,17 +146,17 @@ if orig.get_config_item("lxc.mount"):
# Process any remaining line # Process any remaining line
dest_mount = os.path.abspath(os.path.join("%s/rootfs/" % ( dest_mount = os.path.abspath(os.path.join("%s/rootfs/" % (
dest_path), fields[1])) dest_path), fields[1]))
if dest_mount == os.path.abspath("%s/rootfs/%s" % ( if dest_mount == os.path.abspath("%s/rootfs/%s" % (
dest_path, args.bdir)): dest_path, args.bdir)):
dest_fd.write("%s\n" % line) dest_fd.write("%s\n" % line)
continue continue
if "%s/rootfs/" % dest_path not in dest_mount: if "%s/rootfs/" % dest_path not in dest_mount:
print(_( print(_("Skipping mount entry '%s' as it's outside "
"Skipping mount entry '%s' as it's outside of the container rootfs.") % line) "of the container rootfs.") % line)
overlay_dirs += [(fields[0], dest_mount)] overlay_dirs += [(fields[0], dest_mount)]
@ -176,27 +179,27 @@ LXC_NAME="%s"
if args.union_type == "overlayfs": if args.union_type == "overlayfs":
fd.write("mount -n -t overlayfs" fd.write("mount -n -t overlayfs"
" -oupperdir=%s,lowerdir=%s none %s\n" % ( " -oupperdir=%s,lowerdir=%s none %s\n" % (
target, target,
entry[0], entry[0],
entry[1])) entry[1]))
elif args.union_type == "aufs": elif args.union_type == "aufs":
fd.write("mount -n -t aufs " fd.write("mount -n -t aufs "
"-o br=${upper}=rw:${lower}=ro,noplink none %s\n" % ( "-o br=${upper}=rw:${lower}=ro,noplink none %s\n" % (
target, target,
entry[0], entry[0],
entry[1])) entry[1]))
count += 1 count += 1
if args.bdir: if args.bdir:
if not os.path.exists(args.bdir): if not os.path.exists(args.bdir):
print(_("Path '%s' doesn't exist, won't be bind-mounted.") % print(_("Path '%s' doesn't exist, won't be bind-mounted.") %
args.bdir) args.bdir)
else: else:
src_path = os.path.abspath(args.bdir) src_path = os.path.abspath(args.bdir)
dst_path = "%s/rootfs/%s" % (dest_path, os.path.abspath(args.bdir)) dst_path = "%s/rootfs/%s" % (dest_path, os.path.abspath(args.bdir))
fd.write("mkdir -p %s\nmount -n --bind %s %s\n" % ( fd.write("mkdir -p %s\nmount -n --bind %s %s\n" % (
dst_path, src_path, dst_path)) dst_path, src_path, dst_path))
fd.write(""" fd.write("""
[ -e $LXC_DIR/configured ] && exit 0 [ -e $LXC_DIR/configured ] && exit 0
@ -210,7 +213,7 @@ touch $LXC_DIR/configured
""") """)
dest.set_config_item("lxc.hook.pre-mount", dest.set_config_item("lxc.hook.pre-mount",
os.path.join(dest_path, "pre-mount")) os.path.join(dest_path, "pre-mount"))
# Generate post-stop script # Generate post-stop script
if not args.keep_data: if not args.keep_data:
@ -221,7 +224,7 @@ if not args.keep_data:
""" % (dest_path, dest_path)) """ % (dest_path, dest_path))
dest.set_config_item("lxc.hook.post-stop", dest.set_config_item("lxc.hook.post-stop",
os.path.join(dest_path, "post-stop")) os.path.join(dest_path, "post-stop"))
dest.save_config() dest.save_config()
@ -248,11 +251,9 @@ if args.daemon:
You can enter it from the command line with: lxc-console -n %s You can enter it from the command line with: lxc-console -n %s
The following IP addresses have be found in the container: The following IP addresses have be found in the container:
%s""") % ( %s""") % (dest.name,
dest.name, "\n".join([" - %s" % entry for entry in ips]
"\n".join([" - %s" % entry for entry in ips] or [" - %s" % _("No address could be found")])))
or [" - %s" % _("No address could be found")])
))
sys.exit(0) sys.exit(0)
# Now deal with the case where we want to run a command in the container # Now deal with the case where we want to run a command in the container
@ -265,8 +266,8 @@ if not ips:
# NOTE: To replace by .attach() once the kernel supports it # NOTE: To replace by .attach() once the kernel supports it
cmd = ["ssh", cmd = ["ssh",
"-o", "StrictHostKeyChecking=no", "-o", "StrictHostKeyChecking=no",
"-o", "UserKnownHostsFile=/dev/null"] "-o", "UserKnownHostsFile=/dev/null"]
if args.user: if args.user:
cmd += ["-l", args.user] cmd += ["-l", args.user]

View File

@ -43,20 +43,20 @@ container = lxc.Container(CONTAINER_NAME)
# A few basic checks of the current state # A few basic checks of the current state
assert(container.config_file_name == "%s/%s/config" % assert(container.config_file_name == "%s/%s/config" %
(LXC_PATH_LIB, CONTAINER_NAME)) (LXC_PATH_LIB, CONTAINER_NAME))
assert(container.defined == False) assert(not container.defined)
assert(container.init_pid == -1) assert(container.init_pid == -1)
assert(container.name == CONTAINER_NAME) assert(container.name == CONTAINER_NAME)
assert(container.running == False) assert(not container.running)
assert(container.state == "STOPPED") assert(container.state == "STOPPED")
## Create a rootfs ## Create a rootfs
print("Creating rootfs using '%s'" % LXC_TEMPLATE) print("Creating rootfs using '%s'" % LXC_TEMPLATE)
container.create(LXC_TEMPLATE) container.create(LXC_TEMPLATE)
assert(container.defined == True) assert(container.defined)
assert(container.name == CONTAINER_NAME assert(container.name == CONTAINER_NAME
== container.get_config_item("lxc.utsname")) == container.get_config_item("lxc.utsname"))
assert(container.name in lxc.list_containers()) assert(container.name in lxc.list_containers())
## Test the config ## Test the config
@ -86,7 +86,7 @@ container.wait("RUNNING", 3)
# A few basic checks of the current state # A few basic checks of the current state
assert(container.init_pid > 1) assert(container.init_pid > 1)
assert(container.running == True) assert(container.running)
assert(container.state == "RUNNING") assert(container.state == "RUNNING")
## Checking IP address ## Checking IP address
@ -104,7 +104,7 @@ container.wait("FROZEN", 3)
# A few basic checks of the current state # A few basic checks of the current state
assert(container.init_pid > 1) assert(container.init_pid > 1)
assert(container.running == True) assert(container.running)
assert(container.state == "FROZEN") assert(container.state == "FROZEN")
## Unfreezing the container ## Unfreezing the container
@ -114,7 +114,7 @@ container.wait("RUNNING", 3)
# A few basic checks of the current state # A few basic checks of the current state
assert(container.init_pid > 1) assert(container.init_pid > 1)
assert(container.running == True) assert(container.running)
assert(container.state == "RUNNING") assert(container.state == "RUNNING")
if len(sys.argv) > 1 and sys.argv[1] == "--with-console": if len(sys.argv) > 1 and sys.argv[1] == "--with-console":
@ -133,7 +133,7 @@ if container.running:
# A few basic checks of the current state # A few basic checks of the current state
assert(container.init_pid == -1) assert(container.init_pid == -1)
assert(container.running == False) assert(not container.running)
assert(container.state == "STOPPED") assert(container.state == "STOPPED")
## Cloning the container ## Cloning the container
@ -148,4 +148,4 @@ clone.destroy()
print("Destroying the container") print("Destroying the container")
container.destroy() container.destroy()
assert(container.defined == False) assert(not container.defined)

View File

@ -56,7 +56,7 @@ class ContainerNetwork():
if key not in self.props: if key not in self.props:
raise AttributeError("'%s' network has no attribute '%s'" % ( raise AttributeError("'%s' network has no attribute '%s'" % (
self.__get_network_item("type"), key)) self.__get_network_item("type"), key))
return self.__clear_network_item(self.props[key]) return self.__clear_network_item(self.props[key])
@ -69,7 +69,7 @@ class ContainerNetwork():
if key not in self.props: if key not in self.props:
raise AttributeError("'%s' network has no attribute '%s'" % ( raise AttributeError("'%s' network has no attribute '%s'" % (
self.__get_network_item("type"), key)) self.__get_network_item("type"), key))
return self.__get_network_item(self.props[key]) return self.__get_network_item(self.props[key])
@ -79,7 +79,7 @@ class ContainerNetwork():
if key not in self.props: if key not in self.props:
raise AttributeError("'%s' network has no attribute '%s'" % ( raise AttributeError("'%s' network has no attribute '%s'" % (
self.__get_network_item("type"), key)) self.__get_network_item("type"), key))
return True return True
@ -93,21 +93,21 @@ class ContainerNetwork():
if key not in self.props: if key not in self.props:
raise AttributeError("'%s' network has no attribute '%s'" % ( raise AttributeError("'%s' network has no attribute '%s'" % (
self.__get_network_item("type"), key)) self.__get_network_item("type"), key))
return self.__set_network_item(self.props[key], value) return self.__set_network_item(self.props[key], value)
def __clear_network_item(self, key): def __clear_network_item(self, key):
return self.container.clear_config_item("lxc.network.%s.%s" % ( return self.container.clear_config_item("lxc.network.%s.%s" % (
self.index, key)) self.index, key))
def __get_network_item(self, key): def __get_network_item(self, key):
return self.container.get_config_item("lxc.network.%s.%s" % ( return self.container.get_config_item("lxc.network.%s.%s" % (
self.index, key)) self.index, key))
def __set_network_item(self, key, value): def __set_network_item(self, key, value):
return self.container.set_config_item("lxc.network.%s.%s" % ( return self.container.set_config_item("lxc.network.%s.%s" % (
self.index, key), value) self.index, key), value)
class ContainerNetworkList(): class ContainerNetworkList():
@ -128,7 +128,7 @@ class ContainerNetworkList():
index = len(self.container.get_config_item("lxc.network")) index = len(self.container.get_config_item("lxc.network"))
return self.container.set_config_item("lxc.network.%s.type" % index, return self.container.set_config_item("lxc.network.%s.type" % index,
network_type) network_type)
def remove(self, index): def remove(self, index):
count = len(self.container.get_config_item("lxc.network")) count = len(self.container.get_config_item("lxc.network"))
@ -272,9 +272,8 @@ class Container(_lxc.Container):
if not source.defined: if not source.defined:
return False return False
if subprocess.call( if subprocess.call(["lxc-clone", "-o", source.name, "-n", self.name],
["lxc-clone", "-o", source.name, "-n", self.name], universal_newlines=True) != 0:
universal_newlines=True) != 0:
return False return False
self.load_config() self.load_config()
@ -288,9 +287,8 @@ class Container(_lxc.Container):
if not self.running: if not self.running:
return False return False
if subprocess.call( if subprocess.call(["lxc-console", "-n", self.name, "-t", "%s" % tty],
["lxc-console", "-n", self.name, "-t", "%s" % tty], universal_newlines=True) != 0:
universal_newlines=True) != 0:
return False return False
return True return True
@ -339,10 +337,11 @@ class Container(_lxc.Container):
ip6_cmd = base_cmd + ["-6", "addr", "show", "scope", "global"] ip6_cmd = base_cmd + ["-6", "addr", "show", "scope", "global"]
if interface: if interface:
ip = subprocess.Popen(ip6_cmd + ["dev", interface], ip = subprocess.Popen(ip6_cmd + ["dev", interface],
stdout=subprocess.PIPE, universal_newlines=True) stdout=subprocess.PIPE,
universal_newlines=True)
else: else:
ip = subprocess.Popen(ip6_cmd, stdout=subprocess.PIPE, ip = subprocess.Popen(ip6_cmd, stdout=subprocess.PIPE,
universal_newlines=True) universal_newlines=True)
ip.wait() ip.wait()
for line in ip.stdout.read().split("\n"): for line in ip.stdout.read().split("\n"):
@ -355,10 +354,11 @@ class Container(_lxc.Container):
ip4_cmd = base_cmd + ["-4", "addr", "show", "scope", "global"] ip4_cmd = base_cmd + ["-4", "addr", "show", "scope", "global"]
if interface: if interface:
ip = subprocess.Popen(ip4_cmd + ["dev", interface], ip = subprocess.Popen(ip4_cmd + ["dev", interface],
stdout=subprocess.PIPE, universal_newlines=True) stdout=subprocess.PIPE,
universal_newlines=True)
else: else:
ip = subprocess.Popen(ip4_cmd, stdout=subprocess.PIPE, ip = subprocess.Popen(ip4_cmd, stdout=subprocess.PIPE,
universal_newlines=True) universal_newlines=True)
ip.wait() ip.wait()
for line in ip.stdout.read().split("\n"): for line in ip.stdout.read().split("\n"):
@ -407,14 +407,14 @@ class Container(_lxc.Container):
set_key(key, value) set_key(key, value)
new_value = self.get_config_item(key) new_value = self.get_config_item(key)
if isinstance(value, str) and isinstance(new_value, str) and \ if (isinstance(value, str) and isinstance(new_value, str) and
value == new_value: value == new_value):
return True return True
elif isinstance(value, list) and isinstance(new_value, list) and \ elif (isinstance(value, list) and isinstance(new_value, list) and
set(value) == set(new_value): set(value) == set(new_value)):
return True return True
elif isinstance(value, str) and isinstance(new_value, list) and \ elif (isinstance(value, str) and isinstance(new_value, list) and
set([value]) == set(new_value): set([value]) == set(new_value)):
return True return True
elif old_value: elif old_value:
set_key(key, old_value) set_key(key, old_value)
@ -423,7 +423,7 @@ class Container(_lxc.Container):
self.clear_config_item(key) self.clear_config_item(key)
return False return False
def wait(self, state, timeout = -1): def wait(self, state, timeout=-1):
""" """
Wait for the container to reach a given state or timeout. Wait for the container to reach a given state or timeout.
""" """
@ -433,6 +433,7 @@ class Container(_lxc.Container):
return _lxc.Container.wait(self, state, timeout) return _lxc.Container.wait(self, state, timeout)
def list_containers(as_object=False): def list_containers(as_object=False):
""" """
List the containers on the system. List the containers on the system.

View File

@ -1,10 +1,10 @@
from distutils.core import setup, Extension from distutils.core import setup, Extension
module = Extension('_lxc', sources = ['lxc.c'], libraries = ['lxc']) module = Extension('_lxc', sources=['lxc.c'], libraries=['lxc'])
setup (name = '_lxc', setup(name='_lxc',
version = '0.1', version='0.1',
description = 'LXC', description='LXC',
packages = ['lxc'], packages=['lxc'],
package_dir = {'lxc':'lxc'}, package_dir={'lxc': 'lxc'},
ext_modules = [module]) ext_modules=[module])