From 0d243983d011dc4eb4af231f0a118ce93eabb526 Mon Sep 17 00:00:00 2001 From: Cole Robinson Date: Sat, 13 Apr 2013 14:34:52 -0400 Subject: [PATCH] Revive pep8 and clean up the code autopep8 is pretty cool :) --- setup.py | 26 +- tests/capabilities.py | 90 +++---- tests/clitest.py | 170 ++++++------- tests/clonetest.py | 11 +- tests/interface.py | 1 + tests/nodedev.py | 1 + tests/pep8.cfg | 14 ++ tests/storage.py | 10 +- tests/support.py | 1 + tests/urltest.py | 57 ++--- tests/utils.py | 33 +++ tests/validation.py | 172 +++++++------- tests/virtconvtest.py | 3 +- tests/xmlconfig.py | 10 +- tests/xmlparse.py | 2 + todo.txt | 1 - virt-clone | 10 + virt-convert | 6 +- virt-image | 8 +- virt-install | 29 ++- virt-manager | 14 +- virt-manager-tui | 2 + virtManager/about.py | 1 + virtManager/asyncjob.py | 6 + virtManager/autodrawer.py | 2 +- virtManager/baseclass.py | 3 +- virtManager/choosecd.py | 1 + virtManager/clone.py | 3 + virtManager/config.py | 16 +- virtManager/connect.py | 4 +- virtManager/connectauth.py | 3 +- virtManager/console.py | 8 +- virtManager/create.py | 2 +- virtManager/createinterface.py | 1 + virtManager/createpool.py | 1 + virtManager/createvol.py | 1 + virtManager/delete.py | 4 + virtManager/details.py | 9 +- virtManager/domain.py | 9 +- virtManager/engine.py | 2 + virtManager/error.py | 1 + virtManager/guidiff.py | 3 + virtManager/halhelper.py | 7 + virtManager/host.py | 4 + virtManager/inspection.py | 19 +- virtManager/interface.py | 1 + virtManager/keyring.py | 2 +- virtManager/libvirtobject.py | 2 + virtManager/mediadev.py | 1 + virtManager/migrate.py | 1 + virtManager/module_trace.py | 5 + virtManager/netdev.py | 1 + virtManager/network.py | 5 +- virtManager/nodedev.py | 1 + virtManager/packageutils.py | 5 + virtManager/preferences.py | 1 + virtManager/remote.py | 1 + virtManager/storagebrowse.py | 1 + virtManager/storagepool.py | 1 + virtManager/storagevol.py | 1 + virtManager/systray.py | 4 +- virtManager/uihelpers.py | 43 ++++ virtManager/util.py | 24 +- virtManagerTui/adddomain.py | 4 +- virtManagerTui/addhost.py | 8 +- virtManagerTui/addnetwork.py | 8 +- virtManagerTui/addpool.py | 8 +- virtManagerTui/addvolume.py | 4 +- virtManagerTui/changehost.py | 6 +- virtManagerTui/createmeter.py | 1 + virtManagerTui/createuser.py | 4 +- virtManagerTui/domainconfig.py | 1 + virtManagerTui/domainlistconfigscreen.py | 3 +- virtManagerTui/hostconnect.py | 2 + virtManagerTui/hostlistconfigscreen.py | 1 + virtManagerTui/hostmenu.py | 4 +- virtManagerTui/libvirtworker.py | 6 +- virtManagerTui/listdomains.py | 4 +- virtManagerTui/listnetworks.py | 3 +- virtManagerTui/listpools.py | 4 +- virtManagerTui/mainmenu.py | 12 +- virtManagerTui/migratedomain.py | 8 +- virtManagerTui/netmenu.py | 14 +- virtManagerTui/networkconfig.py | 1 + virtManagerTui/networklistconfigscreen.py | 1 + virtManagerTui/nodeadmin.py | 1 + virtManagerTui/nodemenu.py | 20 +- virtManagerTui/pausedomain.py | 2 + virtManagerTui/poolconfig.py | 5 +- virtManagerTui/removedomain.py | 10 +- virtManagerTui/removehost.py | 6 +- virtManagerTui/removenetwork.py | 8 +- virtManagerTui/removepool.py | 4 +- virtManagerTui/removevolume.py | 8 +- virtManagerTui/startdomain.py | 2 + virtManagerTui/startnetwork.py | 4 +- virtManagerTui/startpool.py | 4 +- virtManagerTui/stopdomain.py | 2 + virtManagerTui/stopnetwork.py | 4 +- virtManagerTui/stoppool.py | 4 +- virtManagerTui/storagelistconfigscreen.py | 1 + virtManagerTui/storagemenu.py | 18 +- virtManagerTui/userworker.py | 1 + virtManagerTui/vmmconfigscreen.py | 1 + virtManagerTui/volumeconfig.py | 1 + virtcli/cliconfig.py | 2 + virtcli/cliutils.py | 1 + virtconv/__init__.py | 4 +- virtconv/diskcfg.py | 21 +- virtconv/formats.py | 13 +- virtconv/netdevcfg.py | 1 + virtconv/parsers/ovf.py | 17 +- virtconv/parsers/virtimage.py | 13 +- virtconv/parsers/vmx.py | 11 +- virtconv/vmcfg.py | 2 + virtinst/Boot.py | 3 +- virtinst/CPU.py | 2 + virtinst/CapabilitiesParser.py | 15 +- virtinst/Clock.py | 1 + virtinst/CloneManager.py | 13 +- virtinst/DistroInstaller.py | 6 +- virtinst/DomainFeatures.py | 2 + virtinst/DomainNumatune.py | 2 +- virtinst/Guest.py | 24 +- virtinst/ImageFetcher.py | 8 + virtinst/ImageInstaller.py | 3 + virtinst/ImageParser.py | 14 +- virtinst/ImportInstaller.py | 1 + virtinst/Installer.py | 2 +- virtinst/Interface.py | 27 ++- virtinst/LiveCDInstaller.py | 1 + virtinst/NodeDeviceParser.py | 37 ++- virtinst/OSDistro.py | 110 +++++---- virtinst/PXEInstaller.py | 1 + virtinst/Seclabel.py | 5 +- virtinst/Storage.py | 56 +++-- virtinst/User.py | 10 +- virtinst/VirtualAudio.py | 5 +- virtinst/VirtualCharDevice.py | 47 ++-- virtinst/VirtualController.py | 12 +- virtinst/VirtualDevice.py | 2 + virtinst/VirtualDisk.py | 60 +++-- virtinst/VirtualFilesystem.py | 1 + virtinst/VirtualGraphics.py | 12 +- virtinst/VirtualHostDevice.py | 3 +- virtinst/VirtualInputDevice.py | 1 + virtinst/VirtualMemballoon.py | 3 +- virtinst/VirtualNetworkInterface.py | 7 +- virtinst/VirtualRedirDevice.py | 9 +- virtinst/VirtualSmartCardDevice.py | 5 +- virtinst/VirtualVideoDevice.py | 3 +- virtinst/VirtualWatchdog.py | 3 +- virtinst/XMLBuilderDomain.py | 5 + virtinst/cli.py | 108 ++++++++- virtinst/osdict.py | 275 +++++++++++----------- virtinst/support.py | 117 +++++---- virtinst/uriutil.py | 2 +- virtinst/util.py | 57 +++-- 158 files changed, 1469 insertions(+), 790 deletions(-) create mode 100644 tests/pep8.cfg diff --git a/setup.py b/setup.py index 55b2b651..0d2dbaf3 100644 --- a/setup.py +++ b/setup.py @@ -140,7 +140,7 @@ class my_build_icons(build_icons): for size in glob.glob(os.path.join(self.icon_dir, "*")): for category in glob.glob(os.path.join(size, "*")): icons = [] - for icon in glob.glob(os.path.join(category,"*")): + for icon in glob.glob(os.path.join(category, "*")): if not os.path.islink(icon): icons.append(icon) if not icons: @@ -418,17 +418,23 @@ class CheckPylint(Command): cmd += " ".join(files) os.system(cmd + " --rcfile tests/pylint.cfg") + print "running pep8" + cmd = "pep8 " + cmd += "--exclude scriptimports " + cmd += " ".join(files) + os.system(cmd + " --config tests/pep8.cfg") + setup( - name = "virt-manager", - version = cliconfig.__version__, - author = "Cole Robinson", - author_email = "virt-tools-list@redhat.com", - url = "http://virt-manager.org", - license = "GPLv2+", + name="virt-manager", + version=cliconfig.__version__, + author="Cole Robinson", + author_email="virt-tools-list@redhat.com", + url="http://virt-manager.org", + license="GPLv2+", # These wrappers are generated in our custom build command - scripts = ([ + scripts=([ "build/virt-manager", "build/virt-clone", "build/virt-install", @@ -436,7 +442,7 @@ setup( "build/virt-convert"] + (cliconfig.with_tui and ["build/virt-manager-tui"] or [])), - data_files = [ + data_files=[ ("share/virt-manager/", [ "virt-manager", "virt-install", @@ -466,7 +472,7 @@ setup( glob.glob("virtconv/parsers/*.py")), ] + tui_files, - cmdclass = { + cmdclass={ 'build': my_build, 'build_i18n': my_build_i18n, 'build_icons': my_build_icons, diff --git a/tests/capabilities.py b/tests/capabilities.py index 1f113c90..6d36358f 100644 --- a/tests/capabilities.py +++ b/tests/capabilities.py @@ -18,6 +18,7 @@ import os.path import unittest import virtinst.CapabilitiesParser as capabilities + def build_host_feature_dict(feature_list): fdict = {} for f in feature_list: @@ -25,6 +26,7 @@ def build_host_feature_dict(feature_list): return fdict + class TestCapabilities(unittest.TestCase): def _compareGuest(self, (arch, os_type, domains, features), guest): @@ -62,74 +64,74 @@ class TestCapabilities(unittest.TestCase): self._compareGuest(guests[idx], caps.guests[idx]) def testCapabilities1(self): - host = ( 'x86_64', {'vmx': capabilities.FEATURE_ON}) + host = ('x86_64', {'vmx': capabilities.FEATURE_ON}) guests = [ - ( 'x86_64', 'xen', - [['xen', None, []]], {} ), - ( 'i686', 'xen', - [['xen', None, []]], { 'pae': capabilities.FEATURE_ON } ), - ( 'i686', 'hvm', - [['xen', "/usr/lib64/xen/bin/qemu-dm", ['pc', 'isapc']]], { 'pae': capabilities.FEATURE_ON | capabilities.FEATURE_OFF } ), - ( 'x86_64', 'hvm', - [['xen', "/usr/lib64/xen/bin/qemu-dm", ['pc', 'isapc']]], {} ) - ] + ('x86_64', 'xen', + [['xen', None, []]], {}), + ('i686', 'xen', + [['xen', None, []]], {'pae': capabilities.FEATURE_ON}), + ('i686', 'hvm', + [['xen', "/usr/lib64/xen/bin/qemu-dm", ['pc', 'isapc']]], {'pae': capabilities.FEATURE_ON | capabilities.FEATURE_OFF}), + ('x86_64', 'hvm', + [['xen', "/usr/lib64/xen/bin/qemu-dm", ['pc', 'isapc']]], {}) + ] self._testCapabilities("capabilities-xen.xml", host, guests) def testCapabilities2(self): - host = ( 'x86_64', {}) + host = ('x86_64', {}) secmodel = ('selinux', '0') guests = [ - ( 'x86_64', 'hvm', - [['qemu', '/usr/bin/qemu-system-x86_64', ['pc', 'isapc']]], {} ), - ( 'i686', 'hvm', - [['qemu', '/usr/bin/qemu', ['pc', 'isapc']]], {} ), - ( 'mips', 'hvm', - [['qemu', '/usr/bin/qemu-system-mips', ['mips']]], {} ), - ( 'mipsel', 'hvm', - [['qemu', '/usr/bin/qemu-system-mipsel', ['mips']]], {} ), - ( 'sparc', 'hvm', - [['qemu', '/usr/bin/qemu-system-sparc', ['sun4m']]], {} ), - ( 'ppc', 'hvm', + ('x86_64', 'hvm', + [['qemu', '/usr/bin/qemu-system-x86_64', ['pc', 'isapc']]], {}), + ('i686', 'hvm', + [['qemu', '/usr/bin/qemu', ['pc', 'isapc']]], {}), + ('mips', 'hvm', + [['qemu', '/usr/bin/qemu-system-mips', ['mips']]], {}), + ('mipsel', 'hvm', + [['qemu', '/usr/bin/qemu-system-mipsel', ['mips']]], {}), + ('sparc', 'hvm', + [['qemu', '/usr/bin/qemu-system-sparc', ['sun4m']]], {}), + ('ppc', 'hvm', [['qemu', '/usr/bin/qemu-system-ppc', - ['g3bw', 'mac99', 'prep']]], {} ), - ] + ['g3bw', 'mac99', 'prep']]], {}), + ] self._testCapabilities("capabilities-qemu.xml", host, guests, secmodel) def testCapabilities3(self): - host = ( 'i686', {}) + host = ('i686', {}) guests = [ - ( 'i686', 'hvm', + ('i686', 'hvm', [['qemu', '/usr/bin/qemu', ['pc', 'isapc']], - ['kvm', '/usr/bin/qemu-kvm', ['pc', 'isapc']]], {} ), - ( 'x86_64', 'hvm', - [['qemu', '/usr/bin/qemu-system-x86_64', ['pc', 'isapc']]], {} ), - ( 'mips', 'hvm', - [['qemu', '/usr/bin/qemu-system-mips', ['mips']]], {} ), - ( 'mipsel', 'hvm', - [['qemu', '/usr/bin/qemu-system-mipsel', ['mips']]], {} ), - ( 'sparc', 'hvm', - [['qemu', '/usr/bin/qemu-system-sparc', ['sun4m']]], {} ), - ( 'ppc', 'hvm', + ['kvm', '/usr/bin/qemu-kvm', ['pc', 'isapc']]], {}), + ('x86_64', 'hvm', + [['qemu', '/usr/bin/qemu-system-x86_64', ['pc', 'isapc']]], {}), + ('mips', 'hvm', + [['qemu', '/usr/bin/qemu-system-mips', ['mips']]], {}), + ('mipsel', 'hvm', + [['qemu', '/usr/bin/qemu-system-mipsel', ['mips']]], {}), + ('sparc', 'hvm', + [['qemu', '/usr/bin/qemu-system-sparc', ['sun4m']]], {}), + ('ppc', 'hvm', [['qemu', '/usr/bin/qemu-system-ppc', - ['g3bw', 'mac99', 'prep']]], {} ), - ] + ['g3bw', 'mac99', 'prep']]], {}), + ] self._testCapabilities("capabilities-kvm.xml", host, guests) def testCapabilities4(self): - host = ( 'i686', - { 'pae': capabilities.FEATURE_ON | capabilities.FEATURE_OFF }) + host = ('i686', + {'pae': capabilities.FEATURE_ON | capabilities.FEATURE_OFF}) guests = [ - ( 'i686', 'linux', + ('i686', 'linux', [['test', None, []]], - { 'pae': capabilities.FEATURE_ON | capabilities.FEATURE_OFF } ), - ] + {'pae': capabilities.FEATURE_ON | capabilities.FEATURE_OFF}), + ] self._testCapabilities("capabilities-test.xml", host, guests) @@ -137,7 +139,7 @@ class TestCapabilities(unittest.TestCase): guests = [ ("x86_64", "exe", [["lxc", "/usr/libexec/libvirt_lxc", []]], {}), ("i686", "exe", [["lxc", "/usr/libexec/libvirt_lxc", []]], {}), - ] + ] self._testCapabilities("capabilities-lxc.xml", (None, None), guests) diff --git a/tests/clitest.py b/tests/clitest.py index 47e5d92d..4a5ee7e0 100644 --- a/tests/clitest.py +++ b/tests/clitest.py @@ -137,20 +137,20 @@ test_files = { # Format: # # "appname" { -# "categoryfoo" : { Some descriptive test catagory name (e.g. storage) +# "categoryfoo" : {Some descriptive test catagory name (e.g. storage) # # "args" : Args to be applied to all invocations in category # -# "valid" : { # Argument strings that should succeed +# "valid" : {# Argument strings that should succeed # "--option --string --number1" # Some option string to test. The # resulting cmdstr would be: # $ appname globalargs categoryfoo_args --option --string --number1 -# } +# } # -# "invalid" : { # Argument strings that should fail +# "invalid" : {# Argument strings that should fail # "--opt1 --opt2", -# } -# } # End categoryfoo +# } +# } # End categoryfoo # #} @@ -253,7 +253,7 @@ args_dict = { "--disk /dev/hda", # Building 'default' pool "--disk pool=default,size=.00001", - ], + ], "invalid": [ # Nonexisting file, size too big @@ -288,8 +288,8 @@ args_dict = { "--disk %(DIR)s,device=cdrom", # Unknown driver name and type options (as of 1.0.0) "--disk %(EXISTIMG1)s,driver_name=foobar,driver_type=foobaz", - ] - }, # category "storage" + ] + }, # category "storage" "install" : { "args": "--nographics --noautoconsole --nodisks", @@ -331,7 +331,7 @@ args_dict = { "--hvm --pxe --boot cdrom,fd,hd,network,menu=off", # Boot w/o other install option "--hvm --boot network,hd,menu=on", - ], + ], "invalid": [ # Bogus virt-type @@ -352,8 +352,8 @@ args_dict = { "--hvm --cdrom %(EXISTIMG1)s --extra-args console=ttyS0", # initrd-inject with manual kernel/initrd "--hvm --boot kernel=%(TREEDIR)s/pxeboot/vmlinuz,initrd=%(TREEDIR)s/pxeboot/initrd.img --initrd-inject virt-install", - ], - }, # category "install" + ], + }, # category "install" "graphics": { "args": "--noautoconsole --nodisks --pxe", @@ -379,7 +379,7 @@ args_dict = { "--vnc --keymap local", # --keymap none "--vnc --keymap none", - ], + ], "invalid": [ # Invalid keymap @@ -394,9 +394,9 @@ args_dict = { "--graphics vnc,foobar=baz", # mixing old and new "--graphics vnc --vnclisten 1.2.3.4", - ], + ], - }, # category "graphics" + }, # category "graphics" "smartcard": { "args": "--noautoconsole --nodisks --pxe", @@ -411,7 +411,7 @@ args_dict = { # --smartcard mode with type # XXX Requires implementing more opts #"--smartcard passthrough,type=tcp", - ], + ], "invalid": [ # Missing argument @@ -422,9 +422,9 @@ args_dict = { "--smartcard passthrough,type=foo", # --smartcard bogus "--smartcard host,foobar=baz", - ], + ], - }, # category "smartcard" + }, # category "smartcard" "char" : { "args": "--hvm --nographics --noautoconsole --nodisks --pxe", @@ -452,7 +452,7 @@ args_dict = { "--console pty,target_type=virtio", # --console xen "--console pty,target_type=xen", - ], + ], "invalid" : [ # Bogus device type "--parallel foobah", @@ -466,9 +466,9 @@ args_dict = { "--channel pty,target_type=guestfwd", # --console unknown type "--console pty,target_type=abcd", - ], + ], - }, # category 'char' + }, # category 'char' "cpuram" : { "args" : "--hvm --nographics --noautoconsole --nodisks --pxe", @@ -498,7 +498,7 @@ args_dict = { "--cpu foobar,+x2apic,+x2apicagain,-distest,forbid=foo,forbid=bar,disable=distest2,optional=opttest,require=reqtest,match=strict,vendor=meee", # Simple --numatune "--numatune 1,2,3,5-7,^6", - ], + ], "invalid" : [ # Bogus cpuset @@ -517,9 +517,9 @@ args_dict = { "--cpu host", # Non-escaped numatune "--numatune 1-3,4,mode=strict", - ], + ], - }, # category 'cpuram' + }, # category 'cpuram' "misc": { "args": "--nographics --noautoconsole", @@ -571,7 +571,7 @@ args_dict = { "--hvm --nodisks --pxe --memballoon virtio", # --memballoon disabled "--hvm --nodisks --pxe --memballoon none", - ], + ], "invalid": [ # Positional arguments error @@ -592,7 +592,7 @@ args_dict = { "--hvm --nodisks --pxe --print-xml", # Busted --memballoon "--hvm --nodisks --pxe --memballoon foobar", - ], + ], "compare": [ # No arguments @@ -624,9 +624,9 @@ args_dict = { ("--connect %(DEFAULTURI)s --hvm --nodisks --pxe --cpuset auto " "--vcpus 2", "cpuset-auto"), - ], + ], - }, # category "misc" + }, # category "misc" "network": { "args": "--pxe --nographics --noautoconsole --nodisks", @@ -652,7 +652,7 @@ args_dict = { "--network=user,model=e1000", # several networks "--network=network:default,model=e1000 --network=user,model=virtio,mac=22:22:33:44:55:AF", - ], + ], "invalid": [ # Nonexistent network "--network=FOO", @@ -662,9 +662,9 @@ args_dict = { "--network user --bridge foo0", # Colliding macaddr "--mac 22:22:33:12:34:AB", - ], + ], - }, # category "network" + }, # category "network" "controller": { "args": "--noautoconsole --nodisks --pxe", @@ -674,7 +674,7 @@ args_dict = { "--controller usb,model=ich9-ehci1,address=0:0:4.7,index=0", "--controller usb,model=ich9-ehci1,address=0:0:4.7,index=1,master=0", "--controller usb2", - ], + ], "invalid": [ # Missing argument @@ -685,9 +685,9 @@ args_dict = { "--controller usb,model=ich9-ehci1,address=0:0:4.7,index=bar,master=foo", # --bogus "--controller host,foobar=baz", - ], + ], - }, # category "controller" + }, # category "controller" "hostdev" : { "args": "--noautoconsole --nographics --nodisks --pxe", @@ -697,7 +697,7 @@ args_dict = { "--host-device usb_device_781_5151_2004453082054CA1BEEE", # Many hostdev parsing types "--host-device 001.003 --host-device 15:0.1 --host-device 2:15:0.2 --host-device 0:15:0.3 --host-device 0x0781:0x5151 --host-device 1d6b:2", - ], + ], "invalid" : [ # Unsupported hostdev type @@ -706,8 +706,8 @@ args_dict = { "--host-device foobarhostdev", # Parseable hostdev, but unknown digits "--host-device 300:400", - ], - }, # category "hostdev" + ], + }, # category "hostdev" "redirdev" : { "args": "--noautoconsole --nographics --nodisks --pxe", @@ -717,7 +717,7 @@ args_dict = { "--redirdev usb,type=tcp,server=localhost:4000", # Different host server "--redirdev usb,type=tcp,server=127.0.0.1:4002", - ], + ], "invalid" : [ # Missing argument @@ -734,8 +734,8 @@ args_dict = { "--redirdev usb,type=tcp,server=localhost:", # Missing host "--redirdev usb,type=tcp,server=:399", - ], - }, # category "redirdev" + ], + }, # category "redirdev" "remote" : { "args": "--connect %(REMOTEURI)s --nographics --noautoconsole", @@ -751,15 +751,15 @@ args_dict = { "--pxe --disk vol=%(POOL)s/%(VOL)s", # Creating storage on managed pool "--pxe --disk pool=%(POOL)s,size=.04", - ], + ], "invalid": [ # Use of --location "--nodisks --location /tmp", # Trying to use unmanaged storage "--file %(EXISTIMG1)s --pxe", - ], + ], - }, # category "remote" + }, # category "remote" "kvm" : { @@ -770,7 +770,7 @@ args_dict = { "--cdrom %(EXISTIMG2)s --file %(EXISTIMG1)s --os-variant win2k3 --wait 0 --sound", # F14 Directory tree URL install with extra-args "--os-variant fedora14 --file %(EXISTIMG1)s --location %(TREEDIR)s --extra-args console=ttyS0 --sound" - ], + ], "invalid" : [ # Unknown machine type @@ -779,7 +779,7 @@ args_dict = { "--nodisks --boot network --arch mips --virt-type kvm", # Invalid arch/virt combo "--nodisks --boot network --paravirt --arch mips", - ], + ], "compare" : [ # F14 Directory tree URL install with extra-args @@ -803,9 +803,9 @@ args_dict = { # exotic arch + machine type ("--os-variant fedora14 --nodisks --boot fd --graphics sdl --arch sparc --machine SS-20", "qemu-sparc"), - ], + ], -}, # category "kvm" +}, # category "kvm" "xen" : { "args": "--connect %(XENURI)s --noautoconsole", @@ -817,10 +817,10 @@ args_dict = { "--nodisks --boot hd --paravirt", # 32 on 64 xen "--nodisks --boot hd --paravirt --arch i686", - ], + ], "invalid" : [ - ], + ], "compare" : [ # Xen default @@ -836,7 +836,7 @@ args_dict = { ("--connect %(XENIA64URI)s --disk %(EXISTIMG1)s --location %(TREEDIR)s --paravirt", "xen-ia64-pv"), # ia64 hvm ("--connect %(XENIA64URI)s --disk %(EXISTIMG1)s --location %(TREEDIR)s --hvm", "xen-ia64-hvm"), - ], + ], }, @@ -850,11 +850,11 @@ args_dict = { ("", "default"), ("--filesystem /source,/", "fs-default"), ("--init /usr/bin/httpd", "manual-init"), - ], + ], -}, # lxc +}, # lxc -}, # virt-install +}, # virt-install @@ -888,7 +888,7 @@ args_dict = { "--original-xml %(CLONE_NOEXIST_XML)s --file %(EXISTIMG1)s --preserve", # Overwriting existing VM "-o test -n test-many-devices --replace", - ], + ], "invalid": [ # Positional arguments error @@ -913,8 +913,8 @@ args_dict = { "--original-xml %(CLONE_DISK_XML)s --file %(ROIMG)s --file %(ROIMG)s --force", # XML w/ managed storage, specify RO non existent "--original-xml %(CLONE_DISK_XML)s --file %(ROIMG)s --file %(ROIMGNOEXIST)s --force", - ] - }, # category "general" + ] + }, # category "general" "misc" : { "args": "", @@ -928,21 +928,21 @@ args_dict = { "--original-xml %(CLONE_STORAGE_XML)s --auto-clone", # Auto flag, actual VM, skip state check "-o test-for-clone --auto-clone --clone-running", - ], + ], "invalid" : [ # Just the auto flag "--auto-clone" # Auto flag, actual VM, without state skip "-o test-for-clone --auto-clone", - ], + ], "compare" : [ ("--connect %(KVMURI)s -o test-for-clone --auto-clone --clone-running", "clone-auto1"), ("-o test-clone-simple --name newvm --auto-clone --clone-running", "clone-auto2"), - ], - }, # category "misc" + ], + }, # category "misc" "remote" : { "args": "--connect %(REMOTEURI)s", @@ -952,15 +952,15 @@ args_dict = { "-o test --auto-clone", # Auto flag w/ managed storage, "--original-xml %(CLONE_STORAGE_XML)s --auto-clone", - ], + ], "invalid": [ # Auto flag w/ storage, "--original-xml %(CLONE_DISK_XML)s --auto-clone", - ], - }, # categort "remote" + ], + }, # categort "remote" -}, # app 'virt-clone' +}, # app 'virt-clone' @@ -982,13 +982,13 @@ args_dict = { "--name foobar --ram 64 --os-variant winxp", # OS variant 'none' "--name foobar --ram 64 --os-variant none", - ], + ], "invalid": [ # Out of bounds index "--boot 10", - ], - }, # category 'general' + ], + }, # category 'general' "graphics" : { "args" : "--name test-image --boot 0 %(IMAGE_XML)s", @@ -998,10 +998,10 @@ args_dict = { "--sdl", # VNC w/ lots of options "--vnc --keymap ja --vncport 5950 --vnclisten 1.2.3.4", - ], + ], "invalid": [], - }, + }, "misc": { "args" : "", @@ -1009,13 +1009,13 @@ args_dict = { "valid" : [ # Colliding VM name w/ --replace "--name test --replace %(IMAGE_XML)s", - ], + ], "invalid" : [ # No name specified, and no prompt flag "%(IMAGE_XML)s", # Colliding VM name without --replace "--name test %(IMAGE_XML)s", - ], + ], "compare" : [ ("--name foobar --ram 64 --os-variant winxp --boot 0 %(IMAGE_XML)s", @@ -1026,9 +1026,9 @@ args_dict = { ("--name foobar --ram 64 --boot 0 " "%(IMAGE_NOGFX_XML)s", "image-nogfx"), - ] + ] - }, # category 'misc' + }, # category 'misc' "network": { "args": "--name test-image --boot 0 --nographics %(IMAGE_XML)s", @@ -1044,18 +1044,18 @@ args_dict = { "--network=user,model=e1000", # several networks "--network=network:default,model=e1000 --network=user,model=virtio", - ], + ], "invalid": [ # Nonexistent network "--network=FOO", # Invalid mac "--network=network:default --mac 1234", - ], + ], - }, # category "network" + }, # category "network" - }, # app 'virt-image' + }, # app 'virt-image' "virt-convert" : { @@ -1079,25 +1079,27 @@ args_dict = { "%(VMX_IMG1)s -o vmx -D none %(VIRTCONV_OUT)s", # virt-image with exotic formats specified "%(VC_IMG2)s -o vmx -D vmdk %(VIRTCONV_OUT)s" - ], + ], "invalid": [ # virt-image to virt-image with invalid format "%(VC_IMG1)s -o virt-image -D foobarfmt %(VIRTCONV_OUT)s", # virt-image to ovf (has no output formatter) "%(VC_IMG1)s -o ovf %(VIRTCONV_OUT)s", - ], + ], "compare": [ # virt-image to default (virt-image) w/ no convert ("%(VC_IMG1)s %(VIRTCONV_OUT)s", "convert-default"), - ], - }, # category 'misc' + ], + }, # category 'misc' - }, # app 'virt-convert' + }, # app 'virt-convert' } _conns = {} + + def open_conn(uri): #if uri not in _conns: # _conns[uri] = virtinst.cli.getConnection(uri) @@ -1108,6 +1110,7 @@ def open_conn(uri): # Test class helpers # ###################### + class Command(object): """ Instance of a single cli command to test @@ -1380,6 +1383,7 @@ newidx = 0 curtest = 0 old_bridge = virtinst.util.default_bridge + def setup(): """ Create initial test files/dirs @@ -1406,6 +1410,7 @@ def cleanup(): virtinst.util.default_bridge = old_bridge + class CLITests(unittest.TestCase): def __init__(self, *args, **kwargs): unittest.TestCase.__init__(self, *args, **kwargs) @@ -1422,6 +1427,7 @@ class CLITests(unittest.TestCase): if curtest == newidx: cleanup() + def maketest(cmd): def cmdtemplate(self, c): err = c.run() diff --git a/tests/clonetest.py b/tests/clonetest.py index 205c4ce6..65c863c6 100644 --- a/tests/clonetest.py +++ b/tests/clonetest.py @@ -38,13 +38,13 @@ POOL1 = "/default-pool" POOL2 = "/cross-pool" DISKPOOL = "/disk-pool" -local_files = [ FILE1, FILE2] +local_files = [FILE1, FILE2] clonexml_dir = os.path.join(os.getcwd(), "tests/clone-xml") clone_files = [] for tmpf in os.listdir(clonexml_dir): - black_list = [ "managed-storage", "cross-pool", "force", "skip", + black_list = ["managed-storage", "cross-pool", "force", "skip", "fullpool"] if tmpf.endswith("-out.xml"): tmpf = tmpf[0:(len(tmpf) - len("-out.xml"))] @@ -53,6 +53,7 @@ for tmpf in os.listdir(clonexml_dir): conn = utils.open_testdriver() + class TestClone(unittest.TestCase): def setUp(self): @@ -92,7 +93,7 @@ class TestClone(unittest.TestCase): cloneobj.clone_mac = "22:23:45:67:89:00" cloneobj.clone_mac = "22:23:45:67:89:01" - if disks != None: + if disks is not None: for disk in disks: cloneobj.clone_devices = disk else: @@ -149,7 +150,7 @@ class TestClone(unittest.TestCase): def testRemoteNoStorage(self): """Test remote clone where VM has no storage that needs cloning""" useconn = utils.open_test_remote() - for base in [ "nostorage", "noclone-storage" ] : + for base in ["nostorage", "noclone-storage"] : self._clone_helper(base, disks=[], useconn=useconn) def testRemoteWithStorage(self): @@ -158,7 +159,7 @@ class TestClone(unittest.TestCase): since libvirt has no storage clone api. """ useconn = utils.open_test_remote() - for base in [ "general-cfg" ] : + for base in ["general-cfg"] : try: self._clone_helper(base, disks=["%s/1.img" % POOL1, diff --git a/tests/interface.py b/tests/interface.py index a87fae61..4242dc2e 100644 --- a/tests/interface.py +++ b/tests/interface.py @@ -33,6 +33,7 @@ eth_iface2 = conn.interfaceLookupByName("eth1") eth_iface3 = conn.interfaceLookupByName("eth2") br_iface = conn.interfaceLookupByName("brempty") + class TestInterfaces(unittest.TestCase): def setUp(self): diff --git a/tests/nodedev.py b/tests/nodedev.py index 953ab841..18b162f1 100644 --- a/tests/nodedev.py +++ b/tests/nodedev.py @@ -36,6 +36,7 @@ unknown_xml = """ """ + class TestNodeDev(unittest.TestCase): def _nodeDevFromName(self, devname): diff --git a/tests/pep8.cfg b/tests/pep8.cfg new file mode 100644 index 00000000..c02241e1 --- /dev/null +++ b/tests/pep8.cfg @@ -0,0 +1,14 @@ +[pep8] + +format = pylint + +# E12*: # Continuation line indents +# E203: # Space before : in dictionary defs +# E221: # Multiple spaces before operator +# (warngs about column aligning assigments) +# E241: # Space after , column alignment nono +# E301: # 1 blank line between methods +# E303: # Too many blank lines +# E501: # Line too long + +ignore=E121,E122,E123,E124,E125,E126,E127,E128,E203,E221,E241,E301,E303,E501 diff --git a/tests/storage.py b/tests/storage.py index 35d654d1..de530eba 100644 --- a/tests/storage.py +++ b/tests/storage.py @@ -28,6 +28,7 @@ import libvirt basepath = os.path.join(os.getcwd(), "tests", "storage-xml") + def generate_uuid_from_string(msg): res = msg.split("-", 1) @@ -44,6 +45,7 @@ def generate_uuid_from_string(msg): return numstr + def _findFreePoolName(conn, namebase): i = 0 @@ -55,6 +57,7 @@ def _findFreePoolName(conn, namebase): except: return poolname + def createPool(conn, ptype, poolname=None, fmt=None, target_path=None, source_path=None, source_name=None, uuid=None, iqn=None): poolclass = StoragePool.get_pool_class(ptype) @@ -82,6 +85,7 @@ def createPool(conn, ptype, poolname=None, fmt=None, target_path=None, return poolCompare(pool_inst) + def poolCompare(pool_inst): filename = os.path.join(basepath, pool_inst.name + ".xml") out_expect = pool_inst.get_xml_config() @@ -92,10 +96,11 @@ def poolCompare(pool_inst): return pool_inst.install(build=True, meter=None, create=True) + def createVol(poolobj, volname=None, input_vol=None, clone_vol=None): volclass = StorageVolume.get_volume_for_pool(pool_object=poolobj) - if volname == None: + if volname is None: volname = poolobj.name() + "-vol" alloc = 5 * 1024 * 1024 * 1024 @@ -125,6 +130,7 @@ def createVol(poolobj, volname=None, input_vol=None, clone_vol=None): return vol_inst.install(meter=False) + class TestStorage(unittest.TestCase): def setUp(self): @@ -166,7 +172,7 @@ class TestStorage(unittest.TestCase): # Test creating with many devices createPool(self.conn, StoragePool.TYPE_LOGICAL, "pool-logical-manydev", - source_path=[ "/tmp/path1", "/tmp/path2", "/tmp/path3" ], + source_path=["/tmp/path1", "/tmp/path2", "/tmp/path3"], target_path=None) def testDiskPool(self): diff --git a/tests/support.py b/tests/support.py index 1010f924..2f62ff7f 100644 --- a/tests/support.py +++ b/tests/support.py @@ -22,6 +22,7 @@ from tests import utils conn = utils.open_testdriver() + class TestSupport(unittest.TestCase): def testSupportCollide(self): diff --git a/tests/urltest.py b/tests/urltest.py index 49133d5f..a6222275 100644 --- a/tests/urltest.py +++ b/tests/urltest.py @@ -69,6 +69,8 @@ NOBOOTISO_FILTER = ".*opensuse12.*|.*opensuse11.*|.*opensuse10.3.*|.*opensuse10. EXPECT_XEN_FAIL = ".*opensuse10.2.*|.*opensuse10.0.*" # Return the expected Distro class for the passed distro label + + def distroClass(distname): if re.match(r".*fedora.*", distname): return FedoraDistro @@ -93,90 +95,90 @@ urls = { "fedora15" : { 'x86_64': FEDORA_BASEURL % ("15", "x86_64"), 'distro': ("linux", "fedora15") - }, + }, "fedora16" : { 'x86_64': FEDORA_BASEURL % ("16", "x86_64"), 'distro': ("linux", "fedora16") - }, + }, # SUSE Distros "opensuse10.0" : { 'i386' : "http://ftp.hosteurope.de/mirror/ftp.opensuse.org/discontinued/10.0/", 'x86_64': "http://ftp.hosteurope.de/mirror/ftp.opensuse.org/discontinued/10.0/", - }, + }, "opensuse10.2" : { 'x86_64': OLD_OPENSUSE_BASEURL % ("10.2") - }, + }, "opensuse10.3" : { 'x86_64': OLD_OPENSUSE_BASEURL % ("10.3") - }, + }, "opensuse11.4" : { 'i386' : OPENSUSE_BASEURL % ("11.4"), 'x86_64': OPENSUSE_BASEURL % ("11.4") - }, + }, "opensuse12.1" : { 'i386' : OPENSUSE_BASEURL % ("12.1"), 'x86_64': OPENSUSE_BASEURL % ("12.1") - }, + }, # Debian Distros "debian-lenny-64" : { "noxen": True, 'x86_64': DEBIAN_BASEURL % ("lenny", "amd64"), 'distro': ("linux", None) - }, + }, "debian-squeeze" : { 'i386' : DEBIAN_BASEURL % ("squeeze", "i386"), 'x86_64': DEBIAN_BASEURL % ("squeeze", "amd64"), 'distro': ("linux", None) - }, + }, "debian-wheezy" : { 'x86_64': DEBIAN_BASEURL % ("wheezy", "amd64"), 'distro': ("linux", None) - }, + }, "debian-sid" : { 'x86_64': DEBIAN_BASEURL % ("sid", "amd64"), 'distro': ("linux", None) - }, + }, "debian-daily" : { 'i386' : "http://d-i.debian.org/daily-images/amd64/", 'distro': ("linux", None) - }, + }, # CentOS Distros "centos-5-latest" : { 'i386' : CURCENTOS_BASEURL % ("5", "i386"), 'x86_64' : CURCENTOS_BASEURL % ("5", "x86_64"), # No .treeinfo 'distro': ("linux", "rhel5.4") - }, + }, "centos-4.9" : { 'i386' : CURCENTOS_BASEURL % ("4.9", "i386"), 'x86_64' : CURCENTOS_BASEURL % ("4.9", "x86_64"), 'distro': ("linux", None) - }, + }, "centos-5.0" : { 'x86_64' : OLDCENTOS_BASEURL % ("5.0", "x86_64"), 'distro': ("linux", None) - }, + }, "centos-4.0" : { "noxen": True, 'x86_64' : OLDCENTOS_BASEURL % ("4.0", "x86_64"), 'distro': ("linux", None) - }, + }, # Scientific Linux "scientific-5.4" : { 'x86_64': SCIENTIFIC_BASEURL % ("54", "x86_64"), 'distro': ("linux", "rhel5.4") - }, + }, "scientific-5.2" : { 'x86_64': SCIENTIFIC_BASEURL % ("52", "x86_64"), 'distro': ("linux", "rhel5") - }, + }, "scientific-5.0" : { 'x86_64': SCIENTIFIC_BASEURL % ("50", "x86_64"), 'distro': ("linux", None) - }, + }, # Ubuntu "ubuntu-hardy" : { @@ -184,27 +186,27 @@ urls = { 'i386': UBUNTU_BASEURL % ("hardy", "i386"), 'x86_64': UBUNTU_BASEURL % ("hardy", "amd64"), 'distro': ("linux", None) - }, + }, "ubuntu-maverick" : { 'i386': UBUNTU_BASEURL % ("maverick", "i386"), 'x86_64': UBUNTU_BASEURL % ("maverick", "amd64"), 'distro': ("linux", None) - }, + }, "ubuntu-natty" : { 'i386': UBUNTU_BASEURL % ("natty", "i386"), 'x86_64': UBUNTU_BASEURL % ("natty", "amd64"), 'distro': ("linux", None) - }, + }, "ubuntu-oneiric" : { 'i386': UBUNTU_BASEURL % ("oneiric", "i386"), 'x86_64': UBUNTU_BASEURL % ("oneiric", "amd64"), 'distro': ("linux", None) - }, + }, "ubuntu-precise" : { 'i386': UBUNTU_BASEURL % ("precise", "i386"), 'x86_64': UBUNTU_BASEURL % ("precise", "amd64"), 'distro': ("linux", None) - }, + }, # Mandriva "mandriva-2009.1" : { @@ -212,13 +214,13 @@ urls = { 'i586': MANDRIVA_BASEURL % ("2009.1", "i586"), 'x86_64': MANDRIVA_BASEURL % ("2009.1", "x86_64"), 'distro': ("linux", None) - }, + }, "mandriva-2010.2" : { "noxen": True, 'i586': MANDRIVA_BASEURL % ("2010.2", "i586"), 'x86_64': MANDRIVA_BASEURL % ("2010.2", "x86_64"), 'distro': ("linux", None) - }, + }, } @@ -226,6 +228,7 @@ testconn = libvirt.open("test:///default") testguest = virtinst.Guest(conn=testconn, installer=virtinst.DistroInstaller()) + class TestURLFetch(unittest.TestCase): @@ -336,7 +339,7 @@ class TestURLFetch(unittest.TestCase): boot = hvmstore.acquireBootDisk(testguest, fetcher, self.meter) logging.debug("acquireBootDisk: %s", str(boot)) - if boot != True: + if boot is not True: raise RuntimeError("Didn't fetch any boot iso.") except Exception, e: logging.exception("%s-%s: bootdisk fetching: %s", diff --git a/tests/utils.py b/tests/utils.py index 56a38195..957b67b1 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -44,10 +44,12 @@ _plainkvm = "%s,qemu" % _fakeuri _plainxen = "%s,xen" % _fakeuri _kvmuri = "%s,caps=%s" % (_plainkvm, _kvmcaps) + def get_debug(): return ("DEBUG_TESTS" in os.environ and os.environ["DEBUG_TESTS"] == "1") + def _make_uri(base, connver=None, libver=None): if connver: base += ",connver=%s" % connver @@ -55,33 +57,51 @@ def _make_uri(base, connver=None, libver=None): base += ",libver=%s" % libver return base + def open_testdriver(): return virtinst.cli.getConnection(_testuri) + + def open_testkvmdriver(): return virtinst.cli.getConnection(_kvmuri) + + def open_plainkvm(connver=None, libver=None): return virtinst.cli.getConnection(_make_uri(_plainkvm, connver, libver)) + + def open_plainxen(connver=None, libver=None): return virtinst.cli.getConnection(_make_uri(_plainxen, connver, libver)) + + def open_test_remote(): return virtinst.cli.getConnection(_remoteuri) _default_conn = open_testdriver() _conn = None + + def set_conn(newconn): global _conn _conn = newconn + + def reset_conn(): set_conn(_default_conn) + + def get_conn(): return _conn reset_conn() # Register libvirt handler + + def libvirt_callback(ignore, err): logging.warn("libvirt errmsg: %s", err[2]) libvirt.registerErrorHandler(f=libvirt_callback, ctx=None) + def sanitize_xml_for_define(xml): # Libvirt throws errors since we are defining domain # type='xen', when test driver can only handle type='test' @@ -100,6 +120,7 @@ def sanitize_xml_for_define(xml): return xml + def test_create(testconn, xml): xml = sanitize_xml_for_define(xml) @@ -122,6 +143,7 @@ def test_create(testconn, xml): except: pass + def read_file(filename): """Helper function to read a files contents and return them""" f = open(filename, "r") @@ -130,6 +152,7 @@ def read_file(filename): return out + def diff_compare(actual_out, filename=None, expect_out=None): """Compare passed string output to contents of filename""" if not expect_out: @@ -162,6 +185,7 @@ def get_basic_paravirt_guest(installer=None): g.installer._scratchdir = scratch return g + def get_basic_fullyvirt_guest(typ="xen", installer=None): g = virtinst.Guest(conn=_conn, type=typ) g.name = "TestGuest" @@ -181,24 +205,29 @@ def get_basic_fullyvirt_guest(typ="xen", installer=None): g.installer._scratchdir = scratch return g + def make_import_installer(os_type="hvm"): inst = virtinst.ImportInstaller(type="xen", os_type=os_type, conn=_conn) return inst + def make_distro_installer(location="/default-pool/default-vol", gtype="xen"): inst = virtinst.DistroInstaller(type=gtype, os_type="hvm", conn=_conn, location=location) return inst + def make_live_installer(location="/dev/loop0", gtype="xen"): inst = virtinst.LiveCDInstaller(type=gtype, os_type="hvm", conn=_conn, location=location) return inst + def make_pxe_installer(gtype="xen"): inst = virtinst.PXEInstaller(type=gtype, os_type="hvm", conn=_conn) return inst + def build_win_kvm(path=None): g = get_basic_fullyvirt_guest("kvm") g.os_type = "windows" @@ -211,19 +240,23 @@ def build_win_kvm(path=None): return g + def get_floppy(path=None): if not path: path = "/default-pool/testvol1.img" return VirtualDisk(path, conn=_conn, device=VirtualDisk.DEVICE_FLOPPY) + def get_filedisk(path=None): if not path: path = "/tmp/test.img" return VirtualDisk(path, size=.0001, conn=_conn) + def get_blkdisk(path="/dev/loop0"): return VirtualDisk(path, conn=_conn) + def get_virtual_network(): dev = virtinst.VirtualNetworkInterface(conn=_conn) dev.macaddr = "22:22:33:44:55:66" diff --git a/tests/validation.py b/tests/validation.py index 7440f8be..e02bb859 100644 --- a/tests/validation.py +++ b/tests/validation.py @@ -26,11 +26,11 @@ import traceback import os # Template for adding arguments to test -# { 'label' : { \ -# 'VAR' : { \ +# {'label' : {\ +# 'VAR' : {\ # 'invalid' : [param], # 'valid' : [param]}, -# '__init__' : { \ +# '__init__' : {\ # 'invalid' : [{'initparam':val}], # 'valid' : [{'initparam':val}]} # @@ -66,33 +66,33 @@ args = { 'name' : { 'invalid' : ['123456789', 'im_invalid!', '', 0, 'verylongnameverylongnameverylongnamevery' - 'longnameveryvery', "test" # In use, - ], - 'valid' : ['Valid_name.01'] }, + 'longnameveryvery', "test", + ], + 'valid' : ['Valid_name.01']}, 'memory' : { 'invalid' : [-1, 0, ''], - 'valid' : [200, 2000] }, + 'valid' : [200, 2000]}, 'maxmemory' : { 'invalid' : [-1, 0, ''], 'valid' : [200, 2000], }, 'uuid' : { - 'invalid' : [ '', 0, '1234567812345678123456781234567x'], + 'invalid' : ['', 0, '1234567812345678123456781234567x'], 'valid' : ['12345678123456781234567812345678', '12345678-1234-1234-ABCD-ABCDEF123456']}, 'vcpus' : { 'invalid' : [-1, 0, 1000, ''], - 'valid' : [ 1, 32 ] }, + 'valid' : [1, 32]}, 'type' : { 'invalid' : [], - 'valid' : ['sometype'] }, + 'valid' : ['sometype']}, 'cdrom' : { 'invalid' : ['', 0, '/somepath'], 'valid' : ['/dev/loop0'] - }, + }, 'arch' : { 'invalid' : [], 'valid' : ["i386", 'i686', 'x86_64'], - }, + }, 'os_type' : { 'invalid' : ['notpresent', 0, ''], 'valid' : ['other', 'windows', 'unix', 'linux']}, @@ -103,103 +103,102 @@ args = { 'disk' : { - 'init_conns' : [ testconn, None ], + 'init_conns' : [testconn, None], '__init__' : { 'invalid' : [ {'path' : 0}, - { 'path' : '/root' }, - { 'path' : 'valid', 'size' : None }, - { 'path' : "valid", 'size' : 'invalid' }, - { 'path' : 'valid', 'size' : -1}, - { 'path' : None }, - { 'path' : "noexist1", 'size' : 900000, 'sparse' : False }, - { 'path' : "noexist2", 'type' : VirtualDisk.DEVICE_CDROM}, - { 'volName' : ("default-pool", "default-vol")}, - { 'conn' : testconn, 'volName' : ("pool-noexist", "default-vol")}, - { 'conn' : testconn, 'volName' : ("default-pool", "vol-noexist")}, - { 'conn' : testconn, 'volName' : ( 1234, "vol-noexist")}, - { 'path' : 'valid', 'size' : 1, 'driverCache' : 'invalid' }, - { 'conn' : testconn, "path" : "/full-pool/newvol.img", "size" : 1, - 'sparse' : False }, + {'path' : '/root'}, + {'path' : 'valid', 'size' : None}, + {'path' : "valid", 'size' : 'invalid'}, + {'path' : 'valid', 'size' : -1}, + {'path' : None}, + {'path' : "noexist1", 'size' : 900000, 'sparse' : False}, + {'path' : "noexist2", 'type' : VirtualDisk.DEVICE_CDROM}, + {'volName' : ("default-pool", "default-vol")}, + {'conn' : testconn, 'volName' : ("pool-noexist", "default-vol")}, + {'conn' : testconn, 'volName' : ("default-pool", "vol-noexist")}, + {'conn' : testconn, 'volName' : (1234, "vol-noexist")}, + {'path' : 'valid', 'size' : 1, 'driverCache' : 'invalid'}, + {'conn' : testconn, "path" : "/full-pool/newvol.img", "size" : 1, + 'sparse' : False}, # Inactive pool w/ volume - { 'conn' : testconn, "path" : "/inactive-pool/inactive-vol"}, - ], + {'conn' : testconn, "path" : "/inactive-pool/inactive-vol"}, + ], 'valid' : [ - { 'path' : '/dev/loop0' }, - { 'path' : 'nonexist', 'size' : 1 }, - { 'path' :'/dev/null'}, - { 'path' : None, 'device' : VirtualDisk.DEVICE_CDROM}, - { 'path' : None, 'device' : VirtualDisk.DEVICE_FLOPPY}, - { 'conn' : testconn, 'volName' : ("default-pool", "default-vol")}, - { 'conn' : testconn, 'path' : "/default-pool/default-vol" }, - { 'conn' : testconn, 'path' : "/default-pool/vol-noexist", 'size' : 1 }, - { 'conn' : testconn, 'volInstall': volinst}, - { 'path' : 'nonexist', 'size' : 1, 'driverCache' : 'writethrough' }, + {'path' : '/dev/loop0'}, + {'path' : 'nonexist', 'size' : 1}, + {'path' : '/dev/null'}, + {'path' : None, 'device' : VirtualDisk.DEVICE_CDROM}, + {'path' : None, 'device' : VirtualDisk.DEVICE_FLOPPY}, + {'conn' : testconn, 'volName' : ("default-pool", "default-vol")}, + {'conn' : testconn, 'path' : "/default-pool/default-vol"}, + {'conn' : testconn, 'path' : "/default-pool/vol-noexist", 'size' : 1}, + {'conn' : testconn, 'volInstall': volinst}, + {'path' : 'nonexist', 'size' : 1, 'driverCache' : 'writethrough'}, # Full pool, but we are nonsparse - { 'conn' : testconn, "path" : "/full-pool/newvol.img", "size" : 1 }, - ] - }, + {'conn' : testconn, "path" : "/full-pool/newvol.img", "size" : 1}, + ] +}, 'shareable' : { - 'invalid': [ None, 1234 ], - 'valid': [ True, False ] - }, + 'invalid': [None, 1234], + 'valid': [True, False] +}, }, 'installer' : { - 'init_conns' : [ testconn, None ], + 'init_conns' : [testconn, None], 'extraargs' : { 'invalid' : [], 'valid' : ['someargs']}, 'arch' : { 'invalid' : [], 'valid' : ['i686', 'i386', 'x86_64'], - } + } }, 'distroinstaller' : { - 'init_conns' : [ testconn, None ], + 'init_conns' : [testconn, None], 'location' : { 'invalid' : ['nogood', 'http:/nogood', [], None, ("pool-noexist", "default-vol"), ("default-pool", "vol-noexist"), - ], + ], 'valid' : ['/dev/null', 'http://web', 'ftp://ftp', 'nfs:nfsserv', - '/tmp', # For installing from local dir tree - ("default-pool", "default-vol"), - ]} + '/tmp', ("default-pool", "default-vol"), + ]} }, 'livecdinstaller' : { - 'init_conns' : [ testconn, None ], + 'init_conns' : [testconn, None], 'location' : { 'invalid' : ['path-noexist', ("pool-noexist", "default-vol"), ("default-pool", "vol-noexist"), - ], + ], 'valid' : ['/dev/null', ("default-pool", "default-vol"), - ]} + ]} }, 'imageinstaller' : { '__init__' : { - 'invalid' : \ + 'invalid' : [{'image' : virtimage, 'capabilities': testcaps, 'boot_index': 5}, {'image' : virtimage, 'capabilities': "foo"}], - 'valid' : \ + 'valid' : [{'image' : virtimage, 'capabilities': testcaps, 'boot_index': 1}, - {'image' : virtimage }, + {'image' : virtimage}, {'image' : virtimage, 'capabilities': testcaps, 'conn': None}], - } + } }, 'network' : { - 'init_conns' : [ testconn, None ], + 'init_conns' : [testconn, None], '__init__' : { - 'invalid' : [ {'macaddr':0}, {'macaddr':''}, {'macaddr':'$%XD'}, - {'type':'network'} ], + 'invalid' : [{'macaddr' : 0}, {'macaddr' : ''}, {'macaddr' : '$%XD'}, + {'type' : 'network'}], 'valid' : []} }, @@ -207,53 +206,52 @@ args = { 'original_guest' : { 'invalid' : ['idontexist'], 'valid' : ['test']}, - 'clone_name': { 'invalid' : [0, 'test' # Already in use - ], + 'clone_name': {'invalid' : [0, 'test'], 'valid' : ['some.valid-name_9']}, - 'clone_uuid': { 'invalid' : [0], + 'clone_uuid': {'invalid' : [0], 'valid' : ['12345678123456781234567812345678']}, - 'clone_mac' : { 'invalid' : ['badformat'], + 'clone_mac' : {'invalid' : ['badformat'], 'valid' : ['AA:BB:CC:DD:EE:FF']}, - 'clone_bs' : { 'invalid' : [], 'valid' : ['valid']}, + 'clone_bs' : {'invalid' : [], 'valid' : ['valid']}, }, 'inputdev' : { - 'init_conns' : [ testconn ], + 'init_conns' : [testconn], 'type' : { - 'valid' : [ "mouse", "tablet"], - 'invalid' : [ "foobar", 1234]}, + 'valid' : ["mouse", "tablet"], + 'invalid' : ["foobar", 1234]}, 'bus' : { - 'valid' : [ "ps2", "xen", "usb"], - 'invalid' : [ "foobar", 1234]}, + 'valid' : ["ps2", "xen", "usb"], + 'invalid' : ["foobar", 1234]}, }, 'chardev' : { - 'init_conns' : [ testconn ], + 'init_conns' : [testconn], 'source_path': { 'invalid' : [], - 'valid' : [ "/some/path" ]}, + 'valid' : ["/some/path"]}, 'source_mode': { - 'invalid' : [ None ], - 'valid' : virtinst.VirtualCharDevice.char_modes }, + 'invalid' : [None], + 'valid' : virtinst.VirtualCharDevice.char_modes}, 'source_host': { 'invalid' : [], - 'valid' : [ "some.source.host" ]}, + 'valid' : ["some.source.host"]}, 'source_port': { - 'invalid' : [ "foobar"], - 'valid' : [ 1234 ]}, + 'invalid' : ["foobar"], + 'valid' : [1234]}, 'connect_host': { 'invalid' : [], - 'valid' : [ "some.connect.com" ]}, + 'valid' : ["some.connect.com"]}, 'connect_port': { - 'invalid' : [ "foobar"], - 'valid' : [ 1234 ]}, + 'invalid' : ["foobar"], + 'valid' : [1234]}, 'protocol': { - 'invalid' : [ None ], - 'valid' : virtinst.VirtualCharDevice.char_protocols }, + 'invalid' : [None], + 'valid' : virtinst.VirtualCharDevice.char_protocols}, }, 'interface' : { - 'init_conns' : [ testconn ], + 'init_conns' : [testconn], 'name' : { 'invalid' : ["eth0", None, 1234], 'valid' : ["foobar"], }, @@ -341,7 +339,7 @@ args = { } -} # End of validation dict +} # End of validation dict class TestValidation(unittest.TestCase): @@ -409,7 +407,7 @@ class TestValidation(unittest.TestCase): @name String name indexing args""" logging.debug("Testing '%s'", name) testdict = args[name] - if manual_dict != None: + if manual_dict is not None: testdict = manual_dict for paramname in testdict.keys(): diff --git a/tests/virtconvtest.py b/tests/virtconvtest.py index c7b66eff..e226da60 100644 --- a/tests/virtconvtest.py +++ b/tests/virtconvtest.py @@ -30,6 +30,7 @@ virtimage_output = BASE + "/virtimage_output" ovf_input = BASE + "/ovf_input" + class TestVirtConv(unittest.TestCase): def setUp(self): @@ -43,7 +44,7 @@ class TestVirtConv(unittest.TestCase): raise AssertionError("find_parser_by_file for '%s' returned " "wrong parser type.\n" "Expected: %s\n" - "Received: %s\n" % \ + "Received: %s\n" % (infile, in_type, str((not inp) and str(inp) or inp.name))) diff --git a/tests/xmlconfig.py b/tests/xmlconfig.py index bb2101db..088b3b67 100644 --- a/tests/xmlconfig.py +++ b/tests/xmlconfig.py @@ -43,17 +43,21 @@ _kvmconn = utils.open_testkvmdriver() _plainkvm = utils.open_plainkvm() _plainxen = utils.open_plainxen() + def qemu_uri(): return "qemu:///system" + def xen_uri(): return "xen:///" + def build_xmlfile(filebase): if not filebase: return None return os.path.join("tests/xmlconfig-xml", filebase + ".xml") + class TestXMLConfig(unittest.TestCase): def setUp(self): @@ -482,11 +486,11 @@ class TestXMLConfig(unittest.TestCase): def testKVMKeymap(self): conn = utils.open_plainkvm(connver=10000) g = virtinst.VirtualGraphics(conn=conn, type="vnc") - self.assertTrue(g.keymap != None) + self.assertTrue(g.keymap is not None) conn = utils.open_plainkvm(connver=11000) g = virtinst.VirtualGraphics(conn=conn, type="vnc") - self.assertTrue(g.keymap == None) + self.assertTrue(g.keymap is None) def testF11Qemu(self): @@ -785,7 +789,7 @@ class TestXMLConfig(unittest.TestCase): # Check keymap autoconfig gdev1 = virtinst.VirtualGraphics(conn=g.conn, type="vnc") - self.assertTrue(gdev1.keymap != None) + self.assertTrue(gdev1.keymap is not None) gdev1.keymap = "en-us" # Check keymap None diff --git a/tests/xmlparse.py b/tests/xmlparse.py index f5e9b914..65db8a87 100644 --- a/tests/xmlparse.py +++ b/tests/xmlparse.py @@ -25,11 +25,13 @@ from tests import utils conn = utils.open_testdriver() kvmconn = utils.open_testkvmdriver() + def sanitize_file_xml(xml): # s/"/'/g from generated XML, matches what libxml dumps out # This won't work all the time, but should be good enough for testing return xml.replace("'", "\"") + class XMLParseTest(unittest.TestCase): def _roundtrip_compare(self, filename): diff --git a/todo.txt b/todo.txt index d6941835..c10f61a5 100644 --- a/todo.txt +++ b/todo.txt @@ -59,7 +59,6 @@ start a spice guest, shrink the window to smaller than guest resolution, scrollb After virtinst merge ==================== -enable all pep8 bits drop old stuff from both spec files update README virtinst initrd test: drop the big files? just stub em out diff --git a/virt-clone b/virt-clone index 3f7eb669..2b145709 100755 --- a/virt-clone +++ b/virt-clone @@ -44,6 +44,7 @@ def get_clone_name(new_name, auto_clone, design): err_txt = _("A name is required for the new virtual machine.") cli.prompt_loop(prompt_txt, err_txt, new_name, design, "clone_name") + def get_original_guest(guest_name, origfile, design): origxml = None @@ -63,6 +64,7 @@ def get_original_guest(guest_name, origfile, design): cli.prompt_loop(prompt_txt, err_txt, guest_name, design, "original_guest") + def get_clone_macaddr(new_mac, design): if new_mac is None: pass @@ -72,10 +74,12 @@ def get_clone_macaddr(new_mac, design): for i in new_mac: design.clone_mac = i + def get_clone_uuid(new_uuid, design): if new_uuid is not None: design.clone_uuid = new_uuid + def get_clone_diskfile(new_diskfiles, design, conn, preserve=False, auto_clone=False): if new_diskfiles is None: @@ -103,6 +107,7 @@ def get_clone_diskfile(new_diskfiles, design, conn, preserve=False, design.clone_devices = devpath newidx += 1 + def _check_disk(conn, clone_path, orig_path, preserve): prompt_txt = (_("What would you like to use as the cloned disk " @@ -114,9 +119,11 @@ def _check_disk(conn, clone_path, orig_path, preserve): check_size=False, path_to_clone=orig_path) + def get_clone_sparse(sparse, design): design.clone_sparse = sparse + def get_preserve(preserve, design): design.preserve = preserve @@ -125,6 +132,7 @@ def get_force_target(target, design): for i in target or []: design.force_target = i + def parse_args(): parser = cli.setupParser() cli.add_connect_option(parser) @@ -196,6 +204,8 @@ def parse_args(): return options, parseargs ### Let's do it! + + def main(conn=None): cli.earlyLogging() options, parseargs = parse_args() diff --git a/virt-convert b/virt-convert index aa4ca457..1374a146 100755 --- a/virt-convert +++ b/virt-convert @@ -153,6 +153,7 @@ def parse_args(): return options + def cleanup(msg, options, vmdef, paths): """ After failure, clean up anything we created. @@ -177,6 +178,7 @@ def cleanup(msg, options, vmdef, paths): sys.exit(1) + def main(): cli.earlyLogging() options = parse_args() @@ -215,7 +217,7 @@ def main(): logging.debug("Creating directory %s", options.output_dir) if options.nodry: os.mkdir(options.output_dir) - clean += [ options.output_dir ] + clean += [options.output_dir] except OSError, e: if (e.errno != errno.EEXIST): fail("Could not create directory %s: %s" % @@ -272,7 +274,7 @@ def main(): outfile.writelines(output) outfile.close() - clean += [ options.output_file ] + clean += [options.output_file] except ValueError, e: cleanup(_("Couldn't export to file \"%s\": %s") % (options.output_file, e), options, vmdef, clean) diff --git a/virt-image b/virt-image index e0531850..824ae963 100755 --- a/virt-image +++ b/virt-image @@ -44,12 +44,15 @@ def get_networks(domain, guest, options): cli.get_networks(guest, networks, macs) + def get_graphics(image, guest, options): graphics = cli.digest_graphics(guest, options, default_override=bool(image.graphics)) cli.get_graphics(guest, graphics) ### Option parsing + + def parse_args(): usage = "%prog [options] image.xml" parser = cli.setupParser(usage) @@ -109,8 +112,6 @@ def parse_args(): help=optparse.SUPPRESS_HELP) misc.add_option("", "--force", action="store_true", dest="force", default=False, - #help=_("Do not prompt for input. Answers yes where " - # "applicable, terminates for all other prompts"), help=optparse.SUPPRESS_HELP) misc.add_option("-q", "--quiet", action="store_true", dest="quiet", help=_("Suppress non-error output")) @@ -124,6 +125,7 @@ def parse_args(): return options + def main(conn=None): cli.earlyLogging() options = parse_args() @@ -138,7 +140,7 @@ def main(conn=None): try: image = virtinst.ImageParser.parse_file(options.image) except virtinst.ImageParser.ParserException, msg: - fail( "%s '%s': %s" % (_("Cannot parse"), options.image, msg)) + fail("%s '%s': %s" % (_("Cannot parse"), options.image, msg)) if options.boot is not None: nboots = len(image.domain.boots) diff --git a/virt-install b/virt-install index 612594b5..c8371e7f 100755 --- a/virt-install +++ b/virt-install @@ -46,12 +46,14 @@ from virtinst.cli import fail, print_stdout, print_stderr install_methods = "--location URL, --cdrom CD/ISO, --pxe, --import, --boot hd|cdrom|..." install_missing = (_("An install method must be specified\n(%(methods)s)") % - {"methods" : install_methods }) + {"methods" : install_methods}) disk_missing = _("--disk storage must be specified (override with --nodisks)") + def install_specified(location, cdpath, pxe, import_install): return bool(pxe or cdpath or location or import_install) + def cdrom_specified(guest, diskopts=None): disks = guest.get_devices("disk") @@ -67,9 +69,11 @@ def cdrom_specified(guest, diskopts=None): return False + def storage_specified(files, disks, nodisks, filesystems): return bool(files or disks or nodisks or filesystems) + def supports_pxe(guest): """ Return False if we are pretty sure the config doesn't support PXE @@ -115,6 +119,7 @@ def get_graphics(guest, options): graphics = cli.digest_graphics(guest, options) cli.get_graphics(guest, graphics) + def get_chardevs(char_type, opts, guest, cb): for optstr in cli.listify(opts): try: @@ -124,6 +129,7 @@ def get_chardevs(char_type, opts, guest, cb): fail(_("Error in %(chartype)s device parameters: %(err)s") % {"chartype": char_type, "err": str(e)}) + def get_watchdog(watchdogs, guest): for optstr in cli.listify(watchdogs): try: @@ -132,6 +138,7 @@ def get_watchdog(watchdogs, guest): except Exception, e: fail(_("Error in watchdog device parameters: %s") % str(e)) + def get_filesystems(filesystems, guest): for optstr in cli.listify(filesystems): try: @@ -140,6 +147,7 @@ def get_filesystems(filesystems, guest): except Exception, e: fail(_("Error in filesystem device parameters: %s") % str(e)) + def get_disk(diskopts, size, sparse, guest, is_file_path): try: dev = None @@ -159,6 +167,7 @@ def get_disk(diskopts, size, sparse, guest, is_file_path): guest.add_device(d) + def get_disks(guest, file_paths, disk_paths, size, sparse, need_storage): is_file_path = (file_paths or (not disk_paths and cli.is_prompt())) disks = (file_paths or disk_paths) @@ -176,6 +185,7 @@ def get_disks(guest, file_paths, disk_paths, size, sparse, need_storage): for idx in range(len(disklist)): get_disk(disklist[idx], sizelist[idx], sparse, guest, is_file_path) + def get_networks(guest, options): networks, macs = cli.digest_networks(guest, options) cli.get_networks(guest, networks, macs) @@ -238,6 +248,7 @@ def prompt_virt(caps, arch, req_virt_type, req_accel): return (req_virt_type, req_accel) + def get_virt_type(conn, options): # Set up all virt/hypervisor parameters @@ -318,6 +329,7 @@ def get_install_media(guest, location, cdpath, need_install): except ValueError, e: fail(_("Error validating install location: %s" % str(e))) + def media_prompt(guest): if guest.installer.is_hvm(): prompt_txt = _("What is the install CD-ROM/ISO or URL?") @@ -344,6 +356,7 @@ def media_prompt(guest): continue break + def validate_install_media(guest, location, cdpath, cdinstall=False): if cdinstall or cdpath: guest.installer.cdrom = True @@ -389,6 +402,7 @@ def validate_required_options(options, guest): return need_storage, need_install + def check_option_collisions(options, guest): # Disk collisions if options.nodisks and (options.file_paths or @@ -396,7 +410,7 @@ def check_option_collisions(options, guest): options.disksize): fail(_("Cannot specify storage and use --nodisks")) - if ((options.file_paths or options.disksize or options.sparse == False) and + if ((options.file_paths or options.disksize or not options.sparse) and options.diskopts): fail(_("Cannot mix --file, --nonsparse, or --file-size with --disk " "options. Use --disk PATH[,size=SIZE][,sparse=yes|no]")) @@ -474,6 +488,7 @@ def build_installer(options, conn, virt_type, hv_name, arch, machine): return installer + def build_guest_instance(conn, options): capsguest, capsdomain = get_virt_type(conn, options) @@ -568,7 +583,8 @@ def _run_console(args): return child os.execvp(args[0], args) - os._exit(1) # pylint: disable=W0212 + os._exit(1) # pylint: disable=W0212 + def vnc_console(dom, uri): args = ["/usr/bin/virt-viewer", @@ -583,6 +599,7 @@ def vnc_console(dom, uri): return _run_console(args) + def txt_console(dom, uri): args = ["/usr/bin/virsh", "--connect", uri, @@ -590,6 +607,7 @@ def txt_console(dom, uri): return _run_console(args) + def start_install(guest, continue_inst, options): def show_console(dom): gdev = guest.get_devices("graphics") @@ -606,7 +624,7 @@ def start_install(guest, continue_inst, options): else: logging.debug("No viewer to launch for graphics type '%s'", gtype) - return None # SDL needs no viewer app + return None # SDL needs no viewer app # There are two main cases we care about: # @@ -620,7 +638,7 @@ def start_install(guest, continue_inst, options): # wait_on_install = continue_inst wait_time = -1 - if options.wait != None: + if options.wait is not None: wait_on_install = True wait_time = options.wait * 60 @@ -681,6 +699,7 @@ def start_install(guest, continue_inst, options): fail(e, do_exit=False) cli.install_fail(guest) + def check_domain(guest, dom, conscb, wait_for_install, wait_time, start_time): """ Make sure domain ends up in expected state, and wait if for install diff --git a/virt-manager b/virt-manager index 53e2170b..7bf5dfd9 100755 --- a/virt-manager +++ b/virt-manager @@ -65,10 +65,11 @@ def drop_tty(): # tty. This prevents libvirt's SSH tunnels from prompting # for user input if SSH keys/agent aren't configured. if os.fork() != 0: - os._exit(0) # pylint: disable=W0212 + os._exit(0) # pylint: disable=W0212 os.setsid() + def drop_stdio(): # We close STDIN/OUT/ERR since they're generally spewing # junk to console when domains are in process of shutting @@ -85,6 +86,7 @@ def drop_stdio(): os.dup2(0, 1) os.dup2(0, 2) + def parse_commandline(): optParser = optparse.OptionParser(version=cliconfig.__version__, usage="virt-manager [options]") @@ -152,6 +154,7 @@ def launch_specific_window(engine, show, uri, uuid): elif show == 'summary': engine.show_host_summary(uri) + def _conn_state_changed(conn, engine, show, uri, uuid): if conn.state == conn.STATE_DISCONNECTED: return True @@ -162,6 +165,8 @@ def _conn_state_changed(conn, engine, show, uri, uuid): return True # maps --show-* to engine (ie local instance) methods + + def show_engine(engine, show, uri, uuid, no_conn_auto): conn = None @@ -182,6 +187,8 @@ def show_engine(engine, show, uri, uuid, no_conn_auto): engine.autostart_conns() # maps --show-* to remote manager (ie dbus call) methods + + def show_remote(managerObj, show, uri, uuid): # Do this regardless managerObj.show_manager() @@ -189,6 +196,7 @@ def show_remote(managerObj, show, uri, uuid): if show or uri or uuid: launch_specific_window(managerObj, show, uri, uuid) + def dbus_config(engine): """ Setup dbus interface @@ -221,6 +229,8 @@ def dbus_config(engine): # Generic OptionParser callback for all --show-* options # This routine stores UUID to options.uuid for all --show-* options # where is metavar="UUID" and also sets options.show + + def opt_show_cb(option, opt_str, value, parser): if option.metavar == "UUID": setattr(parser.values, "uuid", value) @@ -237,7 +247,7 @@ def main(): origargs = " ".join(sys.argv[:]) try: - from gi.repository import Gtk # pylint: disable=E0611 + from gi.repository import Gtk # pylint: disable=E0611 except: # Don't just let the exception raise here. abrt reports bugs # when users mess up su/sudo and DISPLAY isn't set. Printing diff --git a/virt-manager-tui b/virt-manager-tui index e27f39c8..f7838151 100755 --- a/virt-manager-tui +++ b/virt-manager-tui @@ -40,11 +40,13 @@ def parse_commandline(): return optParser.parse_args() + def _show_startup_error(message, details): errordlg = DialogScreen("Error Starting Virtual Machine Manager", message + "\n\n" + details) errordlg.show() + def main(): cliutils.setup_i18n() diff --git a/virtManager/about.py b/virtManager/about.py index b3a9eb69..7560fcaf 100644 --- a/virtManager/about.py +++ b/virtManager/about.py @@ -22,6 +22,7 @@ import logging from virtManager.baseclass import vmmGObjectUI + class vmmAbout(vmmGObjectUI): def __init__(self): vmmGObjectUI.__init__(self, "vmm-about.ui", "vmm-about") diff --git a/virtManager/asyncjob.py b/virtManager/asyncjob.py index 71c20b89..ce700cbd 100644 --- a/virtManager/asyncjob.py +++ b/virtManager/asyncjob.py @@ -33,6 +33,7 @@ import urlgrabber from virtManager.baseclass import vmmGObjectUI + class vmmCreateMeter(urlgrabber.progress.BaseMeter): def __init__(self, asyncjob): # progress meter has to run asynchronously, so pass in the @@ -94,6 +95,7 @@ class asyncJobWorker(threading.Thread): def run(self): threading.Thread.run(self) + def cb_wrapper(callback, asyncjob, *args, **kwargs): try: callback(asyncjob, *args, **kwargs) @@ -106,6 +108,7 @@ def cb_wrapper(callback, asyncjob, *args, **kwargs): asyncjob.set_error(str(e), "".join(traceback.format_exc())) + def _simple_async(callback, args, title, text, parent, errorintro, show_progress, simplecb, errorcb): """ @@ -134,12 +137,15 @@ def _simple_async(callback, args, title, text, parent, errorintro, parent.err.show_err(error, details=details) + def idle_wrapper(fn): def wrapped(self, *args, **kwargs): return self.idle_add(fn, self, *args, **kwargs) return wrapped # Displays a progress bar while executing the "callback" method. + + class vmmAsyncJob(vmmGObjectUI): @staticmethod diff --git a/virtManager/autodrawer.py b/virtManager/autodrawer.py index 79117592..c9de6c96 100644 --- a/virtManager/autodrawer.py +++ b/virtManager/autodrawer.py @@ -471,7 +471,7 @@ class AutoDrawer(Drawer): if toplevel.get_group(): # XXX: Not in pyGtk. - #grabbed = toplevel.get_group().get_current_grab() + # grabbed = toplevel.get_group().get_current_grab() pass if not grabbed: grabbed = Gtk.grab_get_current() diff --git a/virtManager/baseclass.py b/virtManager/baseclass.py index 4201538c..68ec6a9a 100644 --- a/virtManager/baseclass.py +++ b/virtManager/baseclass.py @@ -164,7 +164,7 @@ class vmmGObject(GObject.GObject): def __del__(self): # XXX - #GObject.GObject.__del__(self) + # GObject.GObject.__del__(self) try: if self.config and self._leak_check: @@ -172,6 +172,7 @@ class vmmGObject(GObject.GObject): except: logging.exception("Error removing %s", self.object_key) + class vmmGObjectUI(vmmGObject): def __init__(self, filename, windowname): vmmGObject.__init__(self) diff --git a/virtManager/choosecd.py b/virtManager/choosecd.py index 16841c9d..aa682521 100644 --- a/virtManager/choosecd.py +++ b/virtManager/choosecd.py @@ -29,6 +29,7 @@ from virtManager.baseclass import vmmGObjectUI from virtManager.mediadev import MEDIA_FLOPPY from virtManager.storagebrowse import vmmStorageBrowser + class vmmChooseCD(vmmGObjectUI): __gsignals__ = { "cdrom-chosen": (GObject.SignalFlags.RUN_FIRST, None, [object, str]) diff --git a/virtManager/clone.py b/virtManager/clone.py index 4dcbc4d9..9f49ff8e 100644 --- a/virtManager/clone.py +++ b/virtManager/clone.py @@ -63,6 +63,7 @@ NETWORK_INFO_NEW_MAC = 2 # XXX: What to do for cleanup if clone fails? # XXX: Disable mouse scroll for combo boxes + def can_we_clone(conn, vol, path): """Is the passed path even clone-able""" ret = True @@ -94,6 +95,7 @@ def can_we_clone(conn, vol, path): return (ret, msg) + def do_we_default(conn, vol, path, ro, shared, devtype): """ Returns (do we clone by default?, info string if not)""" ignore = conn @@ -121,6 +123,7 @@ def do_we_default(conn, vol, path, ro, shared, devtype): return (not info, info) + class vmmCloneVM(vmmGObjectUI): def __init__(self, orig_vm): vmmGObjectUI.__init__(self, "vmm-clone.ui", "vmm-clone") diff --git a/virtManager/config.py b/virtManager/config.py index a00052cf..4e8bf9f7 100644 --- a/virtManager/config.py +++ b/virtManager/config.py @@ -140,10 +140,10 @@ class vmmConfig(object): nv.set_string(v) newValues.append(nv) ignore = path - #XXX: set_list is not available with introspection + # XXX: set_list is not available with introspection # val = GConf.Value() - #val.set_list(newValues) - #self.conf.set(path, val) + # val.set_list(newValues) + # self.conf.set(path, val) def check_inspection(self, support_threading): if not support_threading: @@ -151,20 +151,20 @@ class vmmConfig(object): try: # Check we can open the Python guestfs module. - from guestfs import GuestFS # pylint: disable=F0401 + from guestfs import GuestFS # pylint: disable=F0401 g = GuestFS() # Check for the first version which fixed Python GIL bug. version = g.version() - if version["major"] == 1: # major must be 1 + if version["major"] == 1: # major must be 1 if version["minor"] == 8: - if version["release"] >= 6: # >= 1.8.6 + if version["release"] >= 6: # >= 1.8.6 return True elif version["minor"] == 10: - if version["release"] >= 1: # >= 1.10.1 + if version["release"] >= 1: # >= 1.10.1 return True elif version["minor"] == 11: - if version["release"] >= 2: # >= 1.11.2 + if version["release"] >= 2: # >= 1.11.2 return True elif version["minor"] >= 12: # >= 1.12, 1.13, etc. return True diff --git a/virtManager/connect.py b/virtManager/connect.py index ee6a2291..660befaa 100644 --- a/virtManager/connect.py +++ b/virtManager/connect.py @@ -39,6 +39,7 @@ CONN_SSH = 0 CONN_TCP = 1 CONN_TLS = 2 + def current_user(): try: import getpass @@ -46,6 +47,7 @@ def current_user(): except: return "" + def default_conn_user(conn): if conn == CONN_SSH: return "root" @@ -219,7 +221,7 @@ class vmmConnect(vmmGObjectUI): # Call method to create new browser, and get back an object path for it. interface = -1 # physical interface to use? -1 is unspec protocol = 0 # 0 = IPv4, 1 = IPv6, -1 = Unspecified - service = '_libvirt._tcp' # Service name to poll for + service = '_libvirt._tcp' # Service name to poll for flags = 0 # Extra option flags domain = "" # Domain to browse in. NULL uses default bpath = self.server.ServiceBrowserNew(interface, protocol, service, diff --git a/virtManager/connectauth.py b/virtManager/connectauth.py index 036f2fbc..7f32ef23 100644 --- a/virtManager/connectauth.py +++ b/virtManager/connectauth.py @@ -29,6 +29,7 @@ import time import dbus import libvirt + def do_we_have_session(): pid = os.getpid() try: @@ -126,7 +127,7 @@ def creds_dialog_main(creds): """ Libvirt openAuth callback for username/password credentials """ - from gi.repository import Gtk # pylint: disable=E0611 + from gi.repository import Gtk # pylint: disable=E0611 dialog = Gtk.Dialog("Authentication required", None, 0, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, diff --git a/virtManager/console.py b/virtManager/console.py index 6cc9fce8..dc73d739 100644 --- a/virtManager/console.py +++ b/virtManager/console.py @@ -171,7 +171,7 @@ class Tunnel(object): os.dup(fds[1].fileno()) os.dup(errorfds[1].fileno()) os.execlp(*argv) - os._exit(1) # pylint: disable=W0212 + os._exit(1) # pylint: disable=W0212 else: fds[1].close() errorfds[1].close() @@ -614,7 +614,7 @@ class vmmConsolePages(vmmGObjectUI): # State for disabling modifiers when keyboard is grabbed # XXX - #self.accel_groups = Gtk.accel_groups_from_object(self.topwin) + # self.accel_groups = Gtk.accel_groups_from_object(self.topwin) self.accel_groups = [] self.gtk_settings_accel = None self.gtk_settings_mnemonic = None @@ -917,7 +917,7 @@ class vmmConsolePages(vmmGObjectUI): if self.viewer is None: return - v = self.viewer # close_viewer() can be reentered + v = self.viewer # close_viewer() can be reentered self.viewer = None w = v.display @@ -1265,6 +1265,6 @@ class vmmConsolePages(vmmGObjectUI): desktop_h = int(req.width / desktop_ratio) dy = (req.height - desktop_h) / 2 - #viewer_alloc = (x=dx, y=dy, width=desktop_w, height=desktop_h) + # viewer_alloc = (x=dx, y=dy, width=desktop_w, height=desktop_h) viewer_alloc = (dx, dy, desktop_w, desktop_h) self.viewer.display.size_allocate(viewer_alloc) diff --git a/virtManager/create.py b/virtManager/create.py index 1bfee887..c5ec3f65 100644 --- a/virtManager/create.py +++ b/virtManager/create.py @@ -1157,7 +1157,7 @@ class vmmCreate(vmmGObjectUI): self.widget("install-os-type").hide() self.widget("install-os-version").hide() self.mediaDetected = False - self.detect_media_os() # Run detection + self.detect_media_os() # Run detection else: self.widget("install-os-type-label").hide() self.widget("install-os-version-label").hide() diff --git a/virtManager/createinterface.py b/virtManager/createinterface.py index 3c6e4cd4..fbe73c2c 100644 --- a/virtManager/createinterface.py +++ b/virtManager/createinterface.py @@ -58,6 +58,7 @@ IP_DHCP = 0 IP_STATIC = 1 IP_NONE = 2 + class vmmCreateInterface(vmmGObjectUI): __gsignals__ = {} diff --git a/virtManager/createpool.py b/virtManager/createpool.py index 5566d899..04c31a04 100644 --- a/virtManager/createpool.py +++ b/virtManager/createpool.py @@ -35,6 +35,7 @@ from virtinst import Storage PAGE_NAME = 0 PAGE_FORMAT = 1 + class vmmCreatePool(vmmGObjectUI): def __init__(self, conn): vmmGObjectUI.__init__(self, diff --git a/virtManager/createvol.py b/virtManager/createvol.py index d1206afe..ec1a14d8 100644 --- a/virtManager/createvol.py +++ b/virtManager/createvol.py @@ -35,6 +35,7 @@ from virtinst import Storage DEFAULT_ALLOC = 0 DEFAULT_CAP = 8192 + class vmmCreateVolume(vmmGObjectUI): __gsignals__ = { "vol-created": (GObject.SignalFlags.RUN_FIRST, None, []), diff --git a/virtManager/delete.py b/virtManager/delete.py index 23154b94..403ff7b6 100644 --- a/virtManager/delete.py +++ b/virtManager/delete.py @@ -43,6 +43,7 @@ STORAGE_ROW_ICON = 5 STORAGE_ROW_ICON_SIZE = 6 STORAGE_ROW_TOOLTIP = 7 + class vmmDeleteDialog(vmmGObjectUI): def __init__(self): vmmGObjectUI.__init__(self, "vmm-delete.ui", "vmm-delete") @@ -322,12 +323,14 @@ def prepare_storage_list(storage_list): infoCol.add_attribute(info_img, 'stock-size', STORAGE_ROW_ICON_SIZE) infoCol.set_sort_column_id(STORAGE_ROW_ICON) + def storage_item_toggled(src, index, storage_list): active = src.get_active() model = storage_list.get_model() model[index][STORAGE_ROW_CONFIRM] = not active + def can_delete(conn, vol, path): """Is the passed path even deleteable""" ret = True @@ -353,6 +356,7 @@ def can_delete(conn, vol, path): return (ret, msg) + def do_we_default(conn, vm_name, vol, path, ro, shared): """ Returns (do we delete by default?, info string if not)""" info = "" diff --git a/virtManager/details.py b/virtManager/details.py index 6038428b..56a2a589 100644 --- a/virtManager/details.py +++ b/virtManager/details.py @@ -140,6 +140,7 @@ PAGE_CONSOLE = 0 PAGE_DETAILS = 1 PAGE_DYNAMIC_OFFSET = 2 + def prettyify_disk_bus(bus): if bus in ["ide", "sata", "scsi", "usb"]: return bus.upper() @@ -155,6 +156,7 @@ def prettyify_disk_bus(bus): return bus + def prettyify_disk(devtype, bus, idx): busstr = prettyify_disk_bus(bus) or "" @@ -173,6 +175,7 @@ def prettyify_disk(devtype, bus, idx): return "%s %s" % (ret, idx) + def safeint(val, fmt="%.3d"): try: int(val) @@ -180,12 +183,14 @@ def safeint(val, fmt="%.3d"): return str(val) return fmt % int(val) + def prettyify_bytes(val): if val > (1024 * 1024 * 1024): return "%2.2f GB" % (val / (1024.0 * 1024.0 * 1024.0)) else: return "%2.2f MB" % (val / (1024.0 * 1024.0)) + def build_redir_label(redirdev): # String shown in the devices details section addrlabel = "" @@ -249,6 +254,7 @@ def build_hostdev_label(hostdev): return srclabel, hwlabel + def lookup_nodedev(vmmconn, hostdev): def intify(val, do_hex=False): try: @@ -303,6 +309,7 @@ def lookup_nodedev(vmmconn, hostdev): return found_dev + class vmmDetails(vmmGObjectUI): __gsignals__ = { "action-save-domain": (GObject.SignalFlags.RUN_FIRST, None, [str, str]), @@ -3029,7 +3036,7 @@ class vmmDetails(vmmGObjectUI): return ident = "%s:%s" % (inp.type, inp.bus) - if ident == "tablet:usb": + if ident == "tablet:usb": dev = _("EvTouch USB Graphics Tablet") elif ident == "mouse:usb": dev = _("Generic USB Mouse") diff --git a/virtManager/domain.py b/virtManager/domain.py index c0e64da9..82a7ac8b 100644 --- a/virtManager/domain.py +++ b/virtManager/domain.py @@ -34,6 +34,7 @@ import virtinst.support as support from virtManager import util from virtManager.libvirtobject import vmmLibvirtObject + def compare_device(origdev, newdev, idx): devprops = { "disk" : ["target", "bus"], @@ -74,6 +75,7 @@ def compare_device(origdev, newdev, idx): return True + def find_device(guest, origdev): devlist = guest.get_devices(origdev.virtual_device_type) for idx in range(len(devlist)): @@ -83,6 +85,7 @@ def find_device(guest, origdev): return None + def start_job_progress_thread(vm, meter, progtext): current_thread = threading.currentThread() @@ -96,7 +99,7 @@ def start_job_progress_thread(vm, meter, progtext): try: jobinfo = vm.job_info() data_total = float(jobinfo[3]) - #data_processed = float(jobinfo[4]) + # data_processed = float(jobinfo[4]) data_remaining = float(jobinfo[5]) # data_total is 0 if the job hasn't started yet @@ -122,6 +125,7 @@ def start_job_progress_thread(vm, meter, progtext): t.daemon = True t.start() + class vmmInspectionData(object): def __init__(self): self.type = None @@ -134,6 +138,7 @@ class vmmInspectionData(object): self.icon = None self.applications = None + class vmmDomain(vmmLibvirtObject): """ Class wrapping virDomain libvirt objects. Is also extended to be @@ -1298,7 +1303,7 @@ class vmmDomain(vmmLibvirtObject): self.record[1]["timestamp"])) else: ret = 0.0 - return max(ret, 0, 0) # avoid negative values at poweroff + return max(ret, 0, 0) # avoid negative values at poweroff def _set_max_rate(self, record, what): if record[what] > self.maxRecord[what]: diff --git a/virtManager/engine.py b/virtManager/engine.py index bdf98987..344e67b2 100644 --- a/virtManager/engine.py +++ b/virtManager/engine.py @@ -54,6 +54,7 @@ from virtManager.systray import vmmSystray # XXX: gtk3 has issues here debug_ref_leaks = False + def default_uri(): tryuri = None if os.path.exists("/var/lib/xend") and os.path.exists("/proc/xen"): @@ -71,6 +72,7 @@ DETAILS_PERF = 1 DETAILS_CONFIG = 2 DETAILS_CONSOLE = 3 + def _safe_getattr(obj, name): if not hasattr(obj, name): return None diff --git a/virtManager/error.py b/virtManager/error.py index ca1a9568..91716c99 100644 --- a/virtManager/error.py +++ b/virtManager/error.py @@ -26,6 +26,7 @@ import traceback from virtManager.baseclass import vmmGObject + def _launch_dialog(dialog, primary_text, secondary_text, title, sync=True): dialog.set_property("text", primary_text) diff --git a/virtManager/guidiff.py b/virtManager/guidiff.py index abe85204..6d219c2c 100644 --- a/virtManager/guidiff.py +++ b/virtManager/guidiff.py @@ -20,6 +20,7 @@ _is_gui = True + class stubclass(object): def __init__(self, *args, **kwargs): ignore = args @@ -35,12 +36,14 @@ class stubclass(object): ignore = attr ignore = val + def is_gui(isgui=None): global _is_gui if isgui is not None: _is_gui = isgui return _is_gui + def get_running_config(): if _is_gui: import virtManager.util diff --git a/virtManager/halhelper.py b/virtManager/halhelper.py index 33b186ec..432ff020 100644 --- a/virtManager/halhelper.py +++ b/virtManager/halhelper.py @@ -33,18 +33,21 @@ from virtManager.mediadev import vmmMediaDevice _hal_helper = None + def get_hal_helper(init=True): global _hal_helper if not _hal_helper and init: _hal_helper = vmmHalHelper() return _hal_helper + def cleanup(): global _hal_helper if _hal_helper: _hal_helper.cleanup() _hal_helper = None + def get_net_bridge_owner(name_ignore, sysfspath): # Now magic to determine if the device is part of a bridge brportpath = os.path.join(sysfspath, "brport") @@ -60,6 +63,7 @@ def get_net_bridge_owner(name_ignore, sysfspath): return None + def get_net_mac_address(name_ignore, sysfspath): mac = None addrpath = sysfspath + "/address" @@ -69,6 +73,7 @@ def get_net_mac_address(name_ignore, sysfspath): df.close() return mac + def get_bonding_masters(): masters = [] if os.path.exists("/sys/class/net/bonding_masters"): @@ -83,12 +88,14 @@ def get_bonding_masters(): masters = rline[:].split(' ') return masters + def is_net_bonding_slave(name_ignore, sysfspath): masterpath = sysfspath + "/master" if os.path.exists(masterpath): return True return False + class vmmHalHelper(vmmGObject): __gsignals__ = { "netdev-added": (GObject.SignalFlags.RUN_FIRST, None, [object]), diff --git a/virtManager/host.py b/virtManager/host.py index a55ed2a9..ed83807f 100644 --- a/virtManager/host.py +++ b/virtManager/host.py @@ -43,6 +43,7 @@ from virtManager.graphwidgets import Sparkline INTERFACE_PAGE_INFO = 0 INTERFACE_PAGE_ERROR = 1 + class vmmHost(vmmGObjectUI): __gsignals__ = { "action-exit-app": (GObject.SignalFlags.RUN_FIRST, None, []), @@ -1271,6 +1272,7 @@ def init_pool_list(pool_list, changed_func): pool_list.append_column(poolCol) poolListModel.set_sort_column_id(1, Gtk.SortType.ASCENDING) + def refresh_pool_in_list(pool_list, conn, uuid): for row in pool_list.get_model(): if row[0] == uuid: @@ -1279,6 +1281,7 @@ def refresh_pool_in_list(pool_list, conn, uuid): row[2] = conn.get_pool(uuid).is_active() return + def populate_storage_pools(pool_list, conn): model = pool_list.get_model() model.clear() @@ -1297,6 +1300,7 @@ def populate_storage_pools(pool_list, conn): pool_list.get_selection().select_iter(_iter) pool_list.get_selection().emit("changed") + def get_pool_size_percent(conn, uuid): pool = conn.get_pool(uuid) cap = pool.get_capacity() diff --git a/virtManager/inspection.py b/virtManager/inspection.py index 35529f7b..fa81e0ef 100644 --- a/virtManager/inspection.py +++ b/virtManager/inspection.py @@ -22,11 +22,12 @@ from threading import Thread import logging import os -from guestfs import GuestFS # pylint: disable=F0401 +from guestfs import GuestFS # pylint: disable=F0401 from virtManager.baseclass import vmmGObject from virtManager.domain import vmmInspectionData + class vmmInspection(vmmGObject): # Can't find a way to make Thread release our reference _leak_check = False @@ -36,7 +37,7 @@ class vmmInspection(vmmGObject): self._thread = Thread(name="inspection thread", target=self._run) self._thread.daemon = True - self._wait = 15 * 1000 # 15 seconds + self._wait = 15 * 1000 # 15 seconds self._q = Queue() self._conns = {} @@ -182,17 +183,17 @@ class vmmInspection(vmmGObject): root = roots[0] # Inspection results. - typ = g.inspect_get_type(root) # eg. "linux" - distro = g.inspect_get_distro(root) # eg. "fedora" - major_version = g.inspect_get_major_version(root) # eg. 14 - minor_version = g.inspect_get_minor_version(root) # eg. 0 - hostname = g.inspect_get_hostname(root) # string - product_name = g.inspect_get_product_name(root) # string + typ = g.inspect_get_type(root) # eg. "linux" + distro = g.inspect_get_distro(root) # eg. "fedora" + major_version = g.inspect_get_major_version(root) # eg. 14 + minor_version = g.inspect_get_minor_version(root) # eg. 0 + hostname = g.inspect_get_hostname(root) # string + product_name = g.inspect_get_product_name(root) # string # Added in libguestfs 1.9.13: product_variant = None if hasattr(g, "inspect_get_product_variant"): - product_variant = g.inspect_get_product_variant(root) # string + product_variant = g.inspect_get_product_variant(root) # string # For inspect_list_applications and inspect_get_icon we # require that the guest filesystems are mounted. However diff --git a/virtManager/interface.py b/virtManager/interface.py index 335e209b..933b65c6 100644 --- a/virtManager/interface.py +++ b/virtManager/interface.py @@ -23,6 +23,7 @@ from virtinst import Interface from virtManager import util from virtManager.libvirtobject import vmmLibvirtObject + class vmmInterface(vmmLibvirtObject): def __init__(self, conn, interface, name, active): vmmLibvirtObject.__init__(self, conn) diff --git a/virtManager/keyring.py b/virtManager/keyring.py index 96f26105..008aee35 100644 --- a/virtManager/keyring.py +++ b/virtManager/keyring.py @@ -21,7 +21,7 @@ import logging try: - from gi.repository import GnomeKeyring # pylint: disable=E0611 + from gi.repository import GnomeKeyring # pylint: disable=E0611 except: GnomeKeyring = None logging.debug("GnomeKeyring bindings not installed, no keyring support") diff --git a/virtManager/libvirtobject.py b/virtManager/libvirtobject.py index 03aa87bb..310f8cc5 100644 --- a/virtManager/libvirtobject.py +++ b/virtManager/libvirtobject.py @@ -29,6 +29,7 @@ import libxml2 from virtManager.baseclass import vmmGObject + def _sanitize_xml(xml): xml = libxml2.parseDoc(xml).serialize() # Strip starting line @@ -38,6 +39,7 @@ def _sanitize_xml(xml): xml += "\n" return xml + class vmmLibvirtObject(vmmGObject): __gsignals__ = { "config-changed": (GObject.SignalFlags.RUN_FIRST, None, []), diff --git a/virtManager/mediadev.py b/virtManager/mediadev.py index 7db0a465..6c5a9002 100644 --- a/virtManager/mediadev.py +++ b/virtManager/mediadev.py @@ -34,6 +34,7 @@ MEDIA_CDROM = "cdrom" MEDIA_TIMEOUT = 3 + class vmmMediaDevice(vmmGObject): __gsignals__ = { "media-added": (GObject.SignalFlags.RUN_FIRST, None, []), diff --git a/virtManager/migrate.py b/virtManager/migrate.py index 8e4b5b56..4cc2a4f0 100644 --- a/virtManager/migrate.py +++ b/virtManager/migrate.py @@ -36,6 +36,7 @@ from virtManager.baseclass import vmmGObjectUI from virtManager.asyncjob import vmmAsyncJob from virtManager.domain import vmmDomain + def uri_join(uri_tuple): scheme, user, host, path, query, fragment = uri_tuple diff --git a/virtManager/module_trace.py b/virtManager/module_trace.py index c8be8f48..5207b962 100644 --- a/virtManager/module_trace.py +++ b/virtManager/module_trace.py @@ -31,6 +31,7 @@ from types import FunctionType from types import ClassType from types import MethodType + def generate_wrapper(origfunc, name, do_tb): def newfunc(*args, **kwargs): tb = do_tb and ("\n%s" % "".join(traceback.format_stack())) or "" @@ -40,6 +41,7 @@ def generate_wrapper(origfunc, name, do_tb): return newfunc + def wrap_func(module, funcobj, tb): name = funcobj.__name__ logging.debug("wrapfunc %s %s", funcobj, name) @@ -47,6 +49,7 @@ def wrap_func(module, funcobj, tb): newfunc = generate_wrapper(funcobj, name, tb) setattr(module, name, newfunc) + def wrap_method(classobj, methodobj, tb): name = methodobj.__name__ fullname = classobj.__name__ + "." + name @@ -55,6 +58,7 @@ def wrap_method(classobj, methodobj, tb): newfunc = generate_wrapper(methodobj, fullname, tb) setattr(classobj, name, newfunc) + def wrap_class(classobj, tb): logging.debug("wrapclas %s %s", classobj, classobj.__name__) @@ -63,6 +67,7 @@ def wrap_class(classobj, tb): if type(obj) is MethodType: wrap_method(classobj, obj, tb) + def wrap_module(module, regex=None, tb=False): for name in dir(module): if regex and not re.match(regex, name): diff --git a/virtManager/netdev.py b/virtManager/netdev.py index 2d56bffb..f79a2b89 100644 --- a/virtManager/netdev.py +++ b/virtManager/netdev.py @@ -19,6 +19,7 @@ from virtManager.baseclass import vmmGObject + class vmmNetDevice(vmmGObject): def __init__(self, name, mac, is_shared, bridge=None, hal_path=None): vmmGObject.__init__(self) diff --git a/virtManager/network.py b/virtManager/network.py index ee08496d..d76e0be6 100644 --- a/virtManager/network.py +++ b/virtManager/network.py @@ -23,6 +23,7 @@ import ipaddr import libxml2 from virtManager.libvirtobject import vmmLibvirtObject + class vmmNetwork(vmmLibvirtObject): @staticmethod def pretty_desc(forward, forwardDev): @@ -125,7 +126,7 @@ class vmmNetwork(vmmLibvirtObject): routeAddr = node.xpathEval('string(./@address)') break - if goodNode == None: + if goodNode is None: for node in nodes: family = node.xpathEval('string(./@family)') if not family or family == 'ipv4': @@ -189,7 +190,7 @@ class vmmNetwork(vmmLibvirtObject): routeAddr = node.xpathEval('string(./@address)') break - if goodNode == None: + if goodNode is None: for node in nodes: family = node.xpathEval('string(./@family)') if family and family == 'ipv6': diff --git a/virtManager/nodedev.py b/virtManager/nodedev.py index 4d5eb631..3e5726d3 100644 --- a/virtManager/nodedev.py +++ b/virtManager/nodedev.py @@ -22,6 +22,7 @@ import virtinst from virtManager.libvirtobject import vmmLibvirtObject + class vmmNodeDevice(vmmLibvirtObject): def __init__(self, conn, backend, name): vmmLibvirtObject.__init__(self, conn) diff --git a/virtManager/packageutils.py b/virtManager/packageutils.py index 91045951..8509b603 100644 --- a/virtManager/packageutils.py +++ b/virtManager/packageutils.py @@ -34,6 +34,7 @@ from virtManager.asyncjob import vmmAsyncJob # PackageKit lookup helpers # ############################# + def check_packagekit(errbox, packages, ishv): """ Returns None when we determine nothing useful. @@ -109,6 +110,7 @@ def check_packagekit(errbox, packages, ishv): return do_install + def _do_async_search(asyncjob, session, pk_control, packages): found = [] try: @@ -122,6 +124,7 @@ def _do_async_search(asyncjob, session, pk_control, packages): asyncjob.set_extra_data(found) + def packagekit_install(package_list): session = dbus.SessionBus() @@ -137,6 +140,7 @@ def packagekit_install(package_list): package_list, "hide-confirm-search", timeout=timeout) + def packagekit_search(session, pk_control, package_name, packages): newstyle = False try: @@ -191,6 +195,7 @@ def packagekit_search(session, pk_control, package_name, packages): # Service helpers # ################### + def start_libvirtd(): """ Connect to systemd and start libvirtd if required diff --git a/virtManager/preferences.py b/virtManager/preferences.py index f1bb5c59..28425166 100644 --- a/virtManager/preferences.py +++ b/virtManager/preferences.py @@ -30,6 +30,7 @@ from virtManager.baseclass import vmmGObjectUI PREFS_PAGE_STATS = 0 PREFS_PAGE_VM_PREFS = 1 + class vmmPreferences(vmmGObjectUI): def __init__(self): vmmGObjectUI.__init__(self, "vmm-preferences.ui", "vmm-preferences") diff --git a/virtManager/remote.py b/virtManager/remote.py index 0e6aaa69..0c86ec79 100644 --- a/virtManager/remote.py +++ b/virtManager/remote.py @@ -20,6 +20,7 @@ import dbus.service + class vmmRemote(dbus.service.Object): def __init__(self, engine, bus_name, object_path="/com/redhat/virt/manager"): dbus.service.Object.__init__(self, bus_name, object_path) diff --git a/virtManager/storagebrowse.py b/virtManager/storagebrowse.py index 606335df..6f4d3c08 100644 --- a/virtManager/storagebrowse.py +++ b/virtManager/storagebrowse.py @@ -32,6 +32,7 @@ import virtManager.util as util from virtManager.createvol import vmmCreateVolume from virtManager.baseclass import vmmGObjectUI + class vmmStorageBrowser(vmmGObjectUI): __gsignals__ = { "storage-browse-finish": (GObject.SignalFlags.RUN_FIRST, None, [str]), diff --git a/virtManager/storagepool.py b/virtManager/storagepool.py index ced1c96d..e241368d 100644 --- a/virtManager/storagepool.py +++ b/virtManager/storagepool.py @@ -28,6 +28,7 @@ from virtManager import util from virtManager.libvirtobject import vmmLibvirtObject from virtManager.storagevol import vmmStorageVolume + class vmmStoragePool(vmmLibvirtObject): __gsignals__ = { "refreshed": (GObject.SignalFlags.RUN_FIRST, None, []) diff --git a/virtManager/storagevol.py b/virtManager/storagevol.py index 6af643c8..2a0c5789 100644 --- a/virtManager/storagevol.py +++ b/virtManager/storagevol.py @@ -21,6 +21,7 @@ from virtManager import util from virtManager.libvirtobject import vmmLibvirtObject + class vmmStorageVolume(vmmLibvirtObject): def __init__(self, conn, vol, name): vmmLibvirtObject.__init__(self, conn) diff --git a/virtManager/systray.py b/virtManager/systray.py index 1bf7557d..153614f4 100644 --- a/virtManager/systray.py +++ b/virtManager/systray.py @@ -29,10 +29,11 @@ from virtManager.baseclass import vmmGObject from virtManager.error import vmmErrorDialog try: - import appindicator # pylint: disable=F0401 + import appindicator # pylint: disable=F0401 except: appindicator = None + def build_image_menu_item(label): hasfunc = hasattr(Gtk.ImageMenuItem, "set_use_underline") if hasfunc: @@ -44,6 +45,7 @@ def build_image_menu_item(label): return menu_item + class vmmSystray(vmmGObject): __gsignals__ = { "action-toggle-manager": (GObject.SignalFlags.RUN_FIRST, None, []), diff --git a/virtManager/uihelpers.py b/virtManager/uihelpers.py index 08dc80fe..5a79959d 100644 --- a/virtManager/uihelpers.py +++ b/virtManager/uihelpers.py @@ -46,15 +46,18 @@ OPTICAL_IS_VALID = 5 err_dial = vmmErrorDialog() + def set_error_parent(parent): global err_dial err_dial.set_parent(parent) err_dial = err_dial + def cleanup(): global err_dial err_dial = None + def spin_get_helper(widget): adj = widget.get_adjustment() txt = widget.get_text() @@ -69,6 +72,7 @@ def spin_get_helper(widget): # Helpers for shared storage UI between create/addhardware # ############################################################ + def set_sparse_tooltip(widget): sparse_str = _("Fully allocating storage may take longer now, " "but the OS install phase will be quicker. \n\n" @@ -79,6 +83,7 @@ def set_sparse_tooltip(widget): "do not support full allocation.") widget.set_tooltip_text(sparse_str) + def host_disk_space(conn): pool = util.get_default_pool(conn) path = util.get_default_dir(conn) @@ -96,6 +101,7 @@ def host_disk_space(conn): return float(avail / 1024.0 / 1024.0 / 1024.0) + def host_space_tick(conn, widget): try: max_storage = host_disk_space(conn) @@ -113,6 +119,7 @@ def host_space_tick(conn, widget): return 1 + def check_default_pool_active(topwin, conn): default_pool = util.get_default_pool(conn) if default_pool and not default_pool.is_active(): @@ -136,6 +143,8 @@ def check_default_pool_active(topwin, conn): ##################################################### # Hardware model list building (for details, addhw) # ##################################################### + + def build_video_combo(vm, video_dev, no_default=None): video_dev_model = Gtk.ListStore(str, str) video_dev.set_model(video_dev_model) @@ -146,6 +155,7 @@ def build_video_combo(vm, video_dev, no_default=None): populate_video_combo(vm, video_dev, no_default) + def populate_video_combo(vm, video_dev, no_default=None): video_dev_model = video_dev.get_model() has_spice = bool([g for g in vm.get_graphics_devices() @@ -168,6 +178,7 @@ def populate_video_combo(vm, video_dev, no_default=None): if len(video_dev_model) > 0: video_dev.set_active(0) + def build_sound_combo(vm, combo, no_default=False): dev_model = Gtk.ListStore(str) combo.set_model(dev_model) @@ -190,6 +201,7 @@ def build_sound_combo(vm, combo, no_default=False): if len(dev_model) > 0: combo.set_active(0) + def build_watchdogmodel_combo(vm, combo, no_default=False): ignore = vm dev_model = Gtk.ListStore(str) @@ -206,6 +218,7 @@ def build_watchdogmodel_combo(vm, combo, no_default=False): if len(dev_model) > 0: combo.set_active(0) + def build_watchdogaction_combo(vm, combo, no_default=False): ignore = vm dev_model = Gtk.ListStore(str, str) @@ -222,6 +235,7 @@ def build_watchdogaction_combo(vm, combo, no_default=False): if len(dev_model) > 0: combo.set_active(0) + def build_source_mode_combo(vm, combo): source_mode = Gtk.ListStore(str, str) combo.set_model(source_mode) @@ -232,6 +246,7 @@ def build_source_mode_combo(vm, combo): populate_source_mode_combo(vm, combo) combo.set_active(0) + def populate_source_mode_combo(vm, combo): ignore = vm model = combo.get_model() @@ -244,6 +259,7 @@ def populate_source_mode_combo(vm, combo): model.append(["private", "Private"]) model.append(["passthrough", "Passthrough"]) + def build_smartcard_mode_combo(vm, combo): dev_model = Gtk.ListStore(str, str) combo.set_model(dev_model) @@ -263,6 +279,7 @@ def build_smartcard_mode_combo(vm, combo): break combo.set_active(idx) + def populate_smartcard_mode_combo(vm, combo): ignore = vm model = combo.get_model() @@ -274,6 +291,7 @@ def populate_smartcard_mode_combo(vm, combo): # TODO # model.append(["host-certificates", "Host Certificates"]) + def build_redir_type_combo(vm, combo): source_mode = Gtk.ListStore(str, str, bool) combo.set_model(source_mode) @@ -284,6 +302,7 @@ def build_redir_type_combo(vm, combo): populate_redir_type_combo(vm, combo) combo.set_active(0) + def populate_redir_type_combo(vm, combo): ignore = vm model = combo.get_model() @@ -293,6 +312,7 @@ def populate_redir_type_combo(vm, combo): model.append(["spicevmc", "Spice channel", False]) model.append(["tcp", "TCP", True]) + def build_netmodel_combo(vm, combo): dev_model = Gtk.ListStore(str, str) combo.set_model(dev_model) @@ -304,6 +324,7 @@ def build_netmodel_combo(vm, combo): populate_netmodel_combo(vm, combo) combo.set_active(0) + def populate_netmodel_combo(vm, combo): model = combo.get_model() model.clear() @@ -324,6 +345,7 @@ def populate_netmodel_combo(vm, combo): for m in mod_list: model.append([m, m]) + def build_cache_combo(vm, combo, no_default=False): ignore = vm dev_model = Gtk.ListStore(str, str) @@ -341,6 +363,7 @@ def build_cache_combo(vm, combo, no_default=False): dev_model.append([None, "default"]) combo.set_active(0) + def build_io_combo(vm, combo, no_default=False): ignore = vm dev_model = Gtk.ListStore(str, str) @@ -358,6 +381,7 @@ def build_io_combo(vm, combo, no_default=False): dev_model.append([None, "default"]) combo.set_active(0) + def build_disk_bus_combo(vm, combo, no_default=False): ignore = vm dev_model = Gtk.ListStore(str, str) @@ -371,6 +395,7 @@ def build_disk_bus_combo(vm, combo, no_default=False): dev_model.append([None, "default"]) combo.set_active(-1) + def build_vnc_keymap_combo(vm, combo, no_default=False): ignore = vm @@ -396,6 +421,7 @@ def build_vnc_keymap_combo(vm, combo, no_default=False): # Storage format list/combo helpers # ##################################### + def build_storage_format_combo(vm, combo): dev_model = Gtk.ListStore(str) combo.set_model(dev_model) @@ -415,6 +441,7 @@ def build_storage_format_combo(vm, combo): # Widgets for listing network device options (in create, addhardware) # ####################################################################### + def pretty_network_desc(nettype, source=None, netobj=None): if nettype == VirtualNetworkInterface.TYPE_USER: return _("Usermode networking") @@ -436,6 +463,7 @@ def pretty_network_desc(nettype, source=None, netobj=None): return ret + def init_network_list(net_list, bridge_box, source_mode_box=None, source_mode_label=None, vport_expander=None): @@ -452,6 +480,7 @@ def init_network_list(net_list, bridge_box, net_list.add_attribute(text, 'text', 2) net_list.add_attribute(text, 'sensitive', 3) + def net_list_changed(net_list, bridge_box, source_mode_box, source_mode_label, vport_expander): active = net_list.get_active() @@ -473,6 +502,7 @@ def net_list_changed(net_list, bridge_box, bridge_box.set_property("visible", show_bridge) + def get_network_selection(net_list, bridge_entry): idx = net_list.get_active() if idx == -1: @@ -489,6 +519,7 @@ def get_network_selection(net_list, bridge_entry): return net_type, net_src + def populate_network_list(net_list, conn, show_direct_interfaces=True): model = net_list.get_model() model.clear() @@ -633,6 +664,7 @@ def populate_network_list(net_list, conn, show_direct_interfaces=True): set_active(default) return return_warn + def validate_network(parent, conn, nettype, devname, macaddr, model=None): set_error_parent(parent) @@ -702,6 +734,7 @@ def validate_network(parent, conn, nettype, devname, macaddr, model=None): return net + def generate_macaddr(conn): newmac = "" try: @@ -730,6 +763,7 @@ def init_mediadev_combo(widget): widget.add_attribute(text, 'text', OPTICAL_LABEL) widget.add_attribute(text, 'sensitive', OPTICAL_IS_VALID) + def populate_mediadev_combo(conn, widget, devtype): sigs = [] @@ -745,10 +779,12 @@ def populate_mediadev_combo(conn, widget, devtype): return sigs + def set_mediadev_default(model): if len(model) == 0: model.append([None, _("No device present"), False, None, None, False]) + def set_row_from_object(row, obj): row[OPTICAL_DEV_PATH] = obj.get_path() row[OPTICAL_LABEL] = obj.pretty_label() @@ -757,6 +793,7 @@ def set_row_from_object(row, obj): row[OPTICAL_MEDIA_KEY] = obj.get_media_key() row[OPTICAL_IS_VALID] = True + def mediadev_removed(ignore_helper, key, widget): model = widget.get_model() active = widget.get_active() @@ -777,6 +814,7 @@ def mediadev_removed(ignore_helper, key, widget): set_mediadev_default(model) mediadev_set_default_selection(widget) + def mediadev_added(ignore_helper, newobj, widget, devtype): model = widget.get_model() @@ -797,6 +835,7 @@ def mediadev_added(ignore_helper, newobj, widget, devtype): mediadev_set_default_selection(widget) + def mediadev_media_changed(newobj, widget): model = widget.get_model() active = widget.get_active() @@ -819,6 +858,7 @@ def mediadev_media_changed(newobj, widget): mediadev_set_default_selection(widget) + def mediadev_set_default_selection(widget): # Set the first active cdrom device as selected, otherwise none model = widget.get_model() @@ -895,6 +935,8 @@ def build_shutdown_button_menu(widget, shutdown_cb, reboot_cb, reset_cb, ##################################### # Path permissions checker for qemu # ##################################### + + def check_path_search_for_qemu(parent, conn, path): set_error_parent(parent) @@ -950,6 +992,7 @@ def check_path_search_for_qemu(parent, conn, path): # Interface startmode widget builder # ###################################### + def build_startmode_combo(start_list): start_model = Gtk.ListStore(str) start_list.set_model(start_model) diff --git a/virtManager/util.py b/virtManager/util.py index adddf83c..219f51ec 100644 --- a/virtManager/util.py +++ b/virtManager/util.py @@ -31,15 +31,19 @@ running_config = None xml_escape = virtinst.util.xml_escape # FIXME: selinux policy also has a ~/VirtualMachines/isos dir + + def get_default_pool_path(conn): if conn.is_session_uri(): return os.path.expanduser("~/VirtualMachines") return "/var/lib/libvirt/images" + def get_default_pool_name(conn): ignore = conn return "default" + def build_default_pool(vmmconn): """ Helper to build the 'default' storage pool @@ -70,15 +74,18 @@ def build_default_pool(vmmconn): raise RuntimeError(_("Couldn't create default storage pool '%s': %s") % (path, str(e))) + def get_ideal_path_info(conn, name): path = get_default_dir(conn) suffix = ".img" return (path, name, suffix) + def get_ideal_path(conn, name): target, name, suffix = get_ideal_path_info(conn, name) return os.path.join(target, name) + suffix + def get_default_pool(conn): pool = None default_name = get_default_pool_name(conn) @@ -89,6 +96,7 @@ def get_default_pool(conn): return pool + def get_default_dir(conn): pool = get_default_pool(conn) @@ -97,6 +105,7 @@ def get_default_dir(conn): else: return running_config.get_default_image_dir(conn) + def get_default_path(conn, name, collidelist=None): collidelist = collidelist or [] pool = get_default_pool(conn) @@ -180,7 +189,7 @@ def browse_local(parent, dialog_name, conn, start_folder=None, value, and store the user chosen path. """ - from gi.repository import Gtk # pylint: disable=E0611 + from gi.repository import Gtk # pylint: disable=E0611 # Initial setup overwrite_confirm = False @@ -245,15 +254,18 @@ def browse_local(parent, dialog_name, conn, start_folder=None, browse_reason) return ret + def dup_lib_conn(libconn): conn = _dup_all_conn(None, libconn) if isinstance(conn, virtManager.connection.vmmConnection): return conn.vmm return conn + def dup_conn(conn): return _dup_all_conn(conn, None) + def _dup_all_conn(conn, libconn): is_readonly = False @@ -284,6 +296,7 @@ def _dup_all_conn(conn, libconn): return newconn + def pretty_hv(gtype, domtype): """ Convert XML and bar @@ -310,6 +323,7 @@ def pretty_hv(gtype, domtype): return label + def uuidstr(rawuuid): hx = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'] @@ -321,6 +335,7 @@ def uuidstr(rawuuid): uuid.append('-') return "".join(uuid) + def iface_in_use_by(conn, name): use_str = "" for i in conn.list_interface_names(): @@ -332,6 +347,7 @@ def iface_in_use_by(conn, name): return use_str + def pretty_mem(val): val = int(val) if val > (10 * 1024 * 1024): @@ -339,6 +355,7 @@ def pretty_mem(val): else: return "%2.0f MB" % (val / 1024.0) + def pretty_bytes(val): val = int(val) if val > (1024 * 1024 * 1024): @@ -348,6 +365,7 @@ def pretty_bytes(val): xpath = virtinst.util.get_xml_path + def chkbox_helper(src, getcb, setcb, text1, text2=None, alwaysrecord=False, default=True, @@ -359,7 +377,7 @@ def chkbox_helper(src, getcb, setcb, text1, text2=None, @alwaysrecord: Don't require user to select 'yes' to record chkbox value @default: What value to return if getcb tells us not to prompt """ - from gi.repository import Gtk # pylint: disable=E0611 + from gi.repository import Gtk # pylint: disable=E0611 do_prompt = getcb() if not do_prompt: @@ -374,6 +392,7 @@ def chkbox_helper(src, getcb, setcb, text1, text2=None, return response + def get_list_selection(widget): selection = widget.get_selection() active = selection.get_selected() @@ -383,6 +402,7 @@ def get_list_selection(widget): return treestore[treeiter] return None + def set_list_selection(widget, rownum): path = str(rownum) selection = widget.get_selection() diff --git a/virtManagerTui/adddomain.py b/virtManagerTui/adddomain.py index 5a5ec8f9..61936d70 100644 --- a/virtManagerTui/adddomain.py +++ b/virtManagerTui/adddomain.py @@ -50,6 +50,7 @@ OS_VARIANT = "os.variant" MEMORY = "memory" CPUS = "cpus" + class DomainConfigScreen(VmmTuiConfigScreen): def __init__(self): VmmTuiConfigScreen.__init__(self, "Create A New Virtual Machine") @@ -348,7 +349,7 @@ class DomainConfigScreen(VmmTuiConfigScreen): return False def page_has_next(self, page): - if page is SELECT_POOL_PAGE: + if page is SELECT_POOL_PAGE: return self.__has_pools elif page is SELECT_VOLUME_PAGE: return self.__has_volumes @@ -572,6 +573,7 @@ class DomainConfigScreen(VmmTuiConfigScreen): return [snack.Label("Ready to begin installation of %s" % self.__config.get_guest_name()), grid] + def AddDomain(): screen = DomainConfigScreen() screen.start() diff --git a/virtManagerTui/addhost.py b/virtManagerTui/addhost.py index 911f57d7..a66819cf 100644 --- a/virtManagerTui/addhost.py +++ b/virtManagerTui/addhost.py @@ -39,6 +39,7 @@ CONNECTIONS = {CONNECTION_LOCAL : "Local", CONNECTION_SSL : "Remote SSL/TLS with x509 certificate", CONNECTION_SSH : "Remote tunnel over SSH"} + class AddHostConfigScreen(VmmTuiConfigScreen): def __init__(self): VmmTuiConfigScreen.__init__(self, "Add A Remote Host") @@ -81,8 +82,8 @@ class AddHostConfigScreen(VmmTuiConfigScreen): conn = self.__connection.getSelection() hostname = self.__hostname.value() - if hv is HYPERVISOR_XEN: - if conn is CONNECTION_LOCAL: + if hv is HYPERVISOR_XEN: + if conn is CONNECTION_LOCAL: url = "xen:///" elif conn is CONNECTION_KERBEROS: url = "xen+tcp:///" + hostname + "/" @@ -91,7 +92,7 @@ class AddHostConfigScreen(VmmTuiConfigScreen): elif conn is CONNECTION_SSH: url = "xen+ssh:///" + hostname + "/" elif hv is HYPERVISOR_KVM: - if conn is CONNECTION_LOCAL: + if conn is CONNECTION_LOCAL: url = "qemu:///system" elif conn is CONNECTION_KERBEROS: url = "qemu+tcp://" + hostname + "/system" @@ -148,6 +149,7 @@ class AddHostConfigScreen(VmmTuiConfigScreen): return [snack.Label("Confirm Connection"), grid] + def AddHost(): screen = AddHostConfigScreen() screen.start() diff --git a/virtManagerTui/addnetwork.py b/virtManagerTui/addnetwork.py index 8d934841..f545103e 100644 --- a/virtManagerTui/addnetwork.py +++ b/virtManagerTui/addnetwork.py @@ -37,6 +37,7 @@ NETWORK_TYPE_PAGE = 6 SELECT_PHYSICAL_NETWORK_PAGE = 7 SUMMARY_PAGE = 8 + class AddNetworkConfigScreen(VmmTuiConfigScreen): def __init__(self): VmmTuiConfigScreen.__init__(self, "Create A Virtual Network Interface") @@ -49,7 +50,7 @@ class AddNetworkConfigScreen(VmmTuiConfigScreen): self.__ipv4_address = None def get_elements_for_page(self, screen, page): - if page is NETWORK_NAME_PAGE: + if page is NETWORK_NAME_PAGE: return self.get_network_name_page(screen) elif page is IPV4_ADDRESS_PAGE: return self.get_ipv4_address_page(screen) @@ -203,8 +204,8 @@ class AddNetworkConfigScreen(VmmTuiConfigScreen): fields = [] fields.append(("Select the DHCP range", None)) # XXX - #fields.append(("Start", self.__start_address.network)) - #fields.append(("End", self.__end_address.network)) + # fields.append(("Start", self.__start_address.network)) + # fields.append(("End", self.__end_address.network)) return [Label("Selecting The DHCP Range"), self.create_grid_from_fields(fields), Label("TIP: Unless you wish to reserve some addresses to allow static network"), @@ -255,6 +256,7 @@ class AddNetworkConfigScreen(VmmTuiConfigScreen): return [Label("Ready To Create Network"), self.create_grid_from_fields(fields)] + def AddNetwork(): screen = AddNetworkConfigScreen() screen.start() diff --git a/virtManagerTui/addpool.py b/virtManagerTui/addpool.py index c86d6cd8..f8e907ca 100644 --- a/virtManagerTui/addpool.py +++ b/virtManagerTui/addpool.py @@ -32,6 +32,7 @@ POOL_DETAILS_PAGE = 2 CONFIRM_PAGE = 3 HELPER_TEXT = "Specify a storage location to be later split in virtual machine storage" + class AddStoragePoolConfigScreen(VmmTuiConfigScreen): def __init__(self): VmmTuiConfigScreen.__init__(self, "Add A Storage Pool") @@ -45,7 +46,7 @@ class AddStoragePoolConfigScreen(VmmTuiConfigScreen): self.__source_path = None def get_elements_for_page(self, screen, page): - if page is POOL_NAME_PAGE: + if page is POOL_NAME_PAGE: return self.get_pool_name_page(screen) elif page is POOL_DETAILS_PAGE: return self.get_pool_details_page(screen) @@ -62,7 +63,7 @@ class AddStoragePoolConfigScreen(VmmTuiConfigScreen): return page is CONFIRM_PAGE def validate_input(self, page, errors): - if page is POOL_NAME_PAGE: + if page is POOL_NAME_PAGE: if utils.string_is_not_blank(self.__name.value()): if self.get_libvirt().storage_pool_exists(self.__name.value()): errors.append("Name '%s' already in use by another pool." % self.__name.value()) @@ -106,7 +107,7 @@ class AddStoragePoolConfigScreen(VmmTuiConfigScreen): if page is POOL_NAME_PAGE: self.__config.set_name(self.__name.value()) self.__config.set_type(self.__type.getSelection()) - #self._reset_flags(self.__type.current()) + # self._reset_flags(self.__type.current()) elif page is POOL_DETAILS_PAGE: if self.__config.needs_target_path(): self.__config.set_target_path(self.__target_path.value()) @@ -172,6 +173,7 @@ class AddStoragePoolConfigScreen(VmmTuiConfigScreen): Label("Confirm Pool Details"), self.create_grid_from_fields(fields)] + def AddStoragePool(): screen = AddStoragePoolConfigScreen() screen.start() diff --git a/virtManagerTui/addvolume.py b/virtManagerTui/addvolume.py index 865067f4..5893c1c7 100644 --- a/virtManagerTui/addvolume.py +++ b/virtManagerTui/addvolume.py @@ -30,6 +30,7 @@ VOLUME_FORMAT_PAGE = 3 MAX_CAPACITY_PAGE = 4 CONFIRM_PAGE = 5 + class AddVolumeConfigScreen(StorageListConfigScreen): def __init__(self): StorageListConfigScreen.__init__(self, "Add A New Storage Volume") @@ -40,7 +41,7 @@ class AddVolumeConfigScreen(StorageListConfigScreen): self.__formats = None def get_elements_for_page(self, screen, page): - if page is SELECT_POOL_PAGE: + if page is SELECT_POOL_PAGE: return self.get_storage_pool_list_page(screen) elif page is VOLUME_NAME_PAGE: return self.get_volume_name_page(screen) @@ -189,6 +190,7 @@ class AddVolumeConfigScreen(StorageListConfigScreen): return [snack.Label("Ready To Allocation New Storage Volume"), grid] + def AddStorageVolume(): screen = AddVolumeConfigScreen() screen.start() diff --git a/virtManagerTui/changehost.py b/virtManagerTui/changehost.py index d6aa9378..3cdab63d 100644 --- a/virtManagerTui/changehost.py +++ b/virtManagerTui/changehost.py @@ -24,6 +24,7 @@ from virtManagerTui.hostlistconfigscreen import HostListConfigScreen CONNECTION_LIST_PAGE = 1 CONNECTED_PAGE = 2 + class ChangeHostConfigScreen(HostListConfigScreen): def __init__(self): HostListConfigScreen.__init__(self, "") @@ -32,13 +33,13 @@ class ChangeHostConfigScreen(HostListConfigScreen): return "Currently: %s" % self.get_libvirt().get_url() def get_elements_for_page(self, screen, page): - if page is CONNECTION_LIST_PAGE: + if page is CONNECTION_LIST_PAGE: return self.get_connection_list_page(screen) elif page is CONNECTED_PAGE: return self.get_connected_page(screen) def process_input(self, page): - if page is CONNECTION_LIST_PAGE: + if page is CONNECTION_LIST_PAGE: logging.info("Changing libvirt connection to %s", self.get_selected_connection()) self.get_libvirt().open_connection(self.get_selected_connection()) @@ -60,6 +61,7 @@ class ChangeHostConfigScreen(HostListConfigScreen): ignore = screen return [snack.Label("Connected to %s" % self.get_selected_connection())] + def ChangeHost(): screen = ChangeHostConfigScreen() screen.start() diff --git a/virtManagerTui/createmeter.py b/virtManagerTui/createmeter.py index f4ba7fdc..7ffc34ab 100644 --- a/virtManagerTui/createmeter.py +++ b/virtManagerTui/createmeter.py @@ -19,6 +19,7 @@ import urlgrabber.progress as progress import logging + class CreateMeter(progress.BaseMeter): def _do_start(self, now=None): logging.info("Starting...") diff --git a/virtManagerTui/createuser.py b/virtManagerTui/createuser.py index 4dbfc109..44d04d42 100644 --- a/virtManagerTui/createuser.py +++ b/virtManagerTui/createuser.py @@ -26,6 +26,7 @@ import libuser DETAILS_PAGE = 1 CONFIRM_PAGE = 2 + class CreateUserConfigScreen(ConfigScreen): def __init__(self): ConfigScreen.__init__(self, "Create A User Account") @@ -37,7 +38,7 @@ class CreateUserConfigScreen(ConfigScreen): self.__user_worker = UserWorker() def get_elements_for_page(self, screen, page): - if page is DETAILS_PAGE: + if page is DETAILS_PAGE: return self.get_details_page(screen) elif page is CONFIRM_PAGE: return self.get_confirm_page(screen) @@ -108,6 +109,7 @@ class CreateUserConfigScreen(ConfigScreen): return [snack.Label("Create this user account?"), grid] + def CreateUser(): screen = CreateUserConfigScreen() screen.start() diff --git a/virtManagerTui/domainconfig.py b/virtManagerTui/domainconfig.py index 86c410fd..b1cc2bf5 100644 --- a/virtManagerTui/domainconfig.py +++ b/virtManagerTui/domainconfig.py @@ -18,6 +18,7 @@ from virtinst import Guest + class DomainConfig: LOCAL_INSTALL = "local" NETWORK_INSTALL = "network" diff --git a/virtManagerTui/domainlistconfigscreen.py b/virtManagerTui/domainlistconfigscreen.py index eed624b6..13b7cc93 100644 --- a/virtManagerTui/domainlistconfigscreen.py +++ b/virtManagerTui/domainlistconfigscreen.py @@ -20,6 +20,7 @@ import snack from virtManagerTui.vmmconfigscreen import VmmTuiConfigScreen + class DomainListConfigScreen(VmmTuiConfigScreen): '''Provides a base class for all config screens that require a domain list.''' @@ -29,7 +30,7 @@ class DomainListConfigScreen(VmmTuiConfigScreen): self.__domain_list = None def get_domain_list_page(self, screen, defined=True, created=True): - ignore = screen # pylint ignore since it is not used here + ignore = screen # pylint ignore since it is not used here domuuids = self.get_libvirt().list_domains(defined, created) self.__has_domains = bool(domuuids) result = None diff --git a/virtManagerTui/hostconnect.py b/virtManagerTui/hostconnect.py index 6e81b23a..4765ac94 100644 --- a/virtManagerTui/hostconnect.py +++ b/virtManagerTui/hostconnect.py @@ -18,10 +18,12 @@ from newt_syrup.configscreen import ConfigScreen + class HostConnectConfigScreen(ConfigScreen): def __init__(self): ConfigScreen.__init__(self, "Host Connect") + def HostConnect(): screen = HostConnectConfigScreen() screen.start() diff --git a/virtManagerTui/hostlistconfigscreen.py b/virtManagerTui/hostlistconfigscreen.py index 40cd6ebf..ba51466f 100644 --- a/virtManagerTui/hostlistconfigscreen.py +++ b/virtManagerTui/hostlistconfigscreen.py @@ -20,6 +20,7 @@ import snack from virtManagerTui.vmmconfigscreen import VmmTuiConfigScreen + class HostListConfigScreen(VmmTuiConfigScreen): '''Provides a base class for working with lists of libvirt hosts.''' diff --git a/virtManagerTui/hostmenu.py b/virtManagerTui/hostmenu.py index ff3072c2..4eb3b40c 100644 --- a/virtManagerTui/hostmenu.py +++ b/virtManagerTui/hostmenu.py @@ -26,6 +26,7 @@ SELECT_HOST = 1 ADD_HOST = 2 REMOVE_HOST = 3 + class HostMenuScreen(MenuScreen): def __init__(self): MenuScreen.__init__(self, "Host Menu Screen") @@ -36,13 +37,14 @@ class HostMenuScreen(MenuScreen): ("Remove A Host", REMOVE_HOST)) def handle_selection(self, item): - if item is SELECT_HOST: + if item is SELECT_HOST: ChangeHost() elif item is ADD_HOST: AddHost() elif item is REMOVE_HOST: RemoveHost() + def HostMenu(): screen = HostMenuScreen() screen.start() diff --git a/virtManagerTui/libvirtworker.py b/virtManagerTui/libvirtworker.py index 7541a1cf..8c54ba71 100644 --- a/virtManagerTui/libvirtworker.py +++ b/virtManagerTui/libvirtworker.py @@ -31,16 +31,19 @@ DEFAULT_URL = "qemu:///system" default_url = DEFAULT_URL + def set_default_url(url): logging.info("Changing DEFAULT_URL to %s", url) global default_url default_url = url + def get_default_url(): logging.info("Returning default URL of %s", default_url) return default_url + class VirtManagerConfig: def __init__(self, filename=None): if filename is None: @@ -73,6 +76,7 @@ class VirtManagerConfig: print >> output, entry output.close() + class LibvirtWorker: '''Provides utilities for interfacing with libvirt.''' def __init__(self, url=None): @@ -320,7 +324,7 @@ class LibvirtWorker: pool.conn = self.__conn pool.get_xml_config() newpool = pool.install(meter=meter, - build=True, # config.get_build_pool(), + build=True, # config.get_build_pool(), create=True) newpool.setAutostart(True) diff --git a/virtManagerTui/listdomains.py b/virtManagerTui/listdomains.py index 3d30379a..23236a84 100755 --- a/virtManagerTui/listdomains.py +++ b/virtManagerTui/listdomains.py @@ -20,6 +20,7 @@ import snack from virtManagerTui.domainlistconfigscreen import DomainListConfigScreen + class ListDomainsConfigScreen(DomainListConfigScreen): LIST_PAGE = 1 DETAIL_PAGE = 2 @@ -77,7 +78,7 @@ class ListDomainsConfigScreen(DomainListConfigScreen): semodel, setype, vmlabel = domain.get_seclabel() caps = self.get_libvirt().get_capabilities() - if caps.host.secmodel and caps.host.secmodel.model: + if caps.host.secmodel and caps.host.secmodel.model: semodel = caps.host.secmodel.model fields.append(("Model", semodel or "None")) @@ -97,6 +98,7 @@ class ListDomainsConfigScreen(DomainListConfigScreen): return [grid] + def ListDomains(): screen = ListDomainsConfigScreen() screen.start() diff --git a/virtManagerTui/listnetworks.py b/virtManagerTui/listnetworks.py index bbf20d3a..28be40d7 100644 --- a/virtManagerTui/listnetworks.py +++ b/virtManagerTui/listnetworks.py @@ -34,7 +34,7 @@ class ListNetworksConfigScreen(NetworkListConfigScreen): return (page is DETAILS_PAGE) def get_elements_for_page(self, screen, page): - if page is LIST_PAGE: + if page is LIST_PAGE: return self.get_network_list_page(screen) elif page is DETAILS_PAGE: return self.get_network_details_page(screen) @@ -73,6 +73,7 @@ class ListNetworksConfigScreen(NetworkListConfigScreen): return [Label("Network Interface Details"), self.create_grid_from_fields(fields)] + def ListNetworks(): screen = ListNetworksConfigScreen() screen.start() diff --git a/virtManagerTui/listpools.py b/virtManagerTui/listpools.py index b74aa9c5..8e717c66 100644 --- a/virtManagerTui/listpools.py +++ b/virtManagerTui/listpools.py @@ -26,12 +26,13 @@ from newt_syrup import utils LIST_PAGE = 1 DETAILS_PAGE = 2 + class ListStoragePoolsConfigScreen(StorageListConfigScreen): def __init__(self): StorageListConfigScreen.__init__(self, "List Storage Pools") def get_elements_for_page(self, screen, page): - if page is LIST_PAGE: + if page is LIST_PAGE: return self.get_storage_pool_list_page(screen) elif page is DETAILS_PAGE: return self.get_pool_details_page(screen) @@ -63,6 +64,7 @@ class ListStoragePoolsConfigScreen(StorageListConfigScreen): return [Label("Details For Storage Pool: %s" % self.get_selected_pool()), self.create_grid_from_fields(fields)] + def ListStoragePools(): screen = ListStoragePoolsConfigScreen() screen.start() diff --git a/virtManagerTui/mainmenu.py b/virtManagerTui/mainmenu.py index af295efa..95c0ed7d 100644 --- a/virtManagerTui/mainmenu.py +++ b/virtManagerTui/mainmenu.py @@ -16,12 +16,12 @@ # MA 02110-1301, USA. A copy of the GNU General Public License is # also available at http://www.gnu.org/copyleft/gpl.html. -from newt_syrup.menuscreen import MenuScreen +from newt_syrup.menuscreen import MenuScreen -from virtManagerTui.nodemenu import NodeMenu -from virtManagerTui.netmenu import NetworkMenu +from virtManagerTui.nodemenu import NodeMenu +from virtManagerTui.netmenu import NetworkMenu from virtManagerTui.storagemenu import StoragePoolMenu -from virtManagerTui.hostmenu import HostMenu +from virtManagerTui.hostmenu import HostMenu NODE_MENU = 1 NETWORK_MENU = 2 @@ -29,6 +29,7 @@ STORAGE_MENU = 3 HOST_MENU = 4 EXIT_CONSOLE = 99 + class MainMenuScreen(MenuScreen): def __init__(self): MenuScreen.__init__(self, "Main Menu") @@ -40,7 +41,7 @@ class MainMenuScreen(MenuScreen): ("Host Administration", HOST_MENU)) def handle_selection(self, page): - if page is NODE_MENU: + if page is NODE_MENU: NodeMenu() elif page is NETWORK_MENU: NetworkMenu() @@ -49,6 +50,7 @@ class MainMenuScreen(MenuScreen): elif page is HOST_MENU: HostMenu() + def MainMenu(): screen = MainMenuScreen() screen.start() diff --git a/virtManagerTui/migratedomain.py b/virtManagerTui/migratedomain.py index cf96f095..1b52db30 100644 --- a/virtManagerTui/migratedomain.py +++ b/virtManagerTui/migratedomain.py @@ -24,6 +24,7 @@ LIST_DOMAINS = 1 SELECT_TARGET = 2 CONFIRM_PAGE = 3 + class MigrateDomainConfigScreen(DomainListConfigScreen): def __init__(self): DomainListConfigScreen.__init__(self, "Migrate Virtual Machine") @@ -32,7 +33,7 @@ class MigrateDomainConfigScreen(DomainListConfigScreen): self.__targets = None def get_elements_for_page(self, screen, page): - if page is LIST_DOMAINS: + if page is LIST_DOMAINS: return self.get_domain_list_page(screen) elif page is SELECT_TARGET: return self.get_target_page(screen) @@ -40,7 +41,7 @@ class MigrateDomainConfigScreen(DomainListConfigScreen): return self.get_confirm_page(screen) def page_has_next(self, page): - if page is LIST_DOMAINS: + if page is LIST_DOMAINS: return self.has_selectable_domains() else: return page < CONFIRM_PAGE @@ -52,7 +53,7 @@ class MigrateDomainConfigScreen(DomainListConfigScreen): return page is CONFIRM_PAGE def validate_input(self, page, errors): - if page is LIST_DOMAINS: + if page is LIST_DOMAINS: return self.get_selected_domain() is not None elif page is SELECT_TARGET: if self.__targets.current() is None: @@ -84,6 +85,7 @@ class MigrateDomainConfigScreen(DomainListConfigScreen): grid.setField(self.__confirm, 0, 0) return [grid] + def MigrateDomain(): screen = MigrateDomainConfigScreen() screen.start() diff --git a/virtManagerTui/netmenu.py b/virtManagerTui/netmenu.py index 089b9dba..434d6e61 100644 --- a/virtManagerTui/netmenu.py +++ b/virtManagerTui/netmenu.py @@ -18,11 +18,11 @@ from newt_syrup.menuscreen import MenuScreen -from virtManagerTui.addnetwork import AddNetwork -from virtManagerTui.startnetwork import StartNetwork -from virtManagerTui.stopnetwork import StopNetwork -from virtManagerTui.removenetwork import RemoveNetwork -from virtManagerTui.listnetworks import ListNetworks +from virtManagerTui.addnetwork import AddNetwork +from virtManagerTui.startnetwork import StartNetwork +from virtManagerTui.stopnetwork import StopNetwork +from virtManagerTui.removenetwork import RemoveNetwork +from virtManagerTui.listnetworks import ListNetworks ADD_NETWORK = 1 START_NETWORK = 2 @@ -30,6 +30,7 @@ STOP_NETWORK = 3 REMOVE_NETWORK = 4 LIST_NETWORKS = 5 + class NetworkMenuScreen(MenuScreen): def __init__(self): MenuScreen.__init__(self, "Network Administration") @@ -42,7 +43,7 @@ class NetworkMenuScreen(MenuScreen): ("List Networks", LIST_NETWORKS)) def handle_selection(self, item): - if item is ADD_NETWORK: + if item is ADD_NETWORK: AddNetwork() elif item is START_NETWORK: StartNetwork() @@ -53,6 +54,7 @@ class NetworkMenuScreen(MenuScreen): elif item is LIST_NETWORKS: ListNetworks() + def NetworkMenu(): screen = NetworkMenuScreen() screen.start() diff --git a/virtManagerTui/networkconfig.py b/virtManagerTui/networkconfig.py index 02505cc9..3246ff7d 100644 --- a/virtManagerTui/networkconfig.py +++ b/virtManagerTui/networkconfig.py @@ -18,6 +18,7 @@ import ipaddr + class NetworkConfig: def __init__(self): self.__name = "" diff --git a/virtManagerTui/networklistconfigscreen.py b/virtManagerTui/networklistconfigscreen.py index 909b04b0..b019310d 100644 --- a/virtManagerTui/networklistconfigscreen.py +++ b/virtManagerTui/networklistconfigscreen.py @@ -20,6 +20,7 @@ import snack from virtManagerTui.vmmconfigscreen import VmmTuiConfigScreen + class NetworkListConfigScreen(VmmTuiConfigScreen): '''Provides a base class for all config screens that require a network list.''' diff --git a/virtManagerTui/nodeadmin.py b/virtManagerTui/nodeadmin.py index 5f631403..721dacff 100644 --- a/virtManagerTui/nodeadmin.py +++ b/virtManagerTui/nodeadmin.py @@ -21,6 +21,7 @@ import sys from virtManagerTui.mainmenu import MainMenu + def NodeAdmin(): MainMenu() diff --git a/virtManagerTui/nodemenu.py b/virtManagerTui/nodemenu.py index e57199f1..85d46eab 100644 --- a/virtManagerTui/nodemenu.py +++ b/virtManagerTui/nodemenu.py @@ -16,16 +16,16 @@ # MA 02110-1301, USA. A copy of the GNU General Public License is # also available at http://www.gnu.org/copyleft/gpl.html. -from newt_syrup.menuscreen import MenuScreen +from newt_syrup.menuscreen import MenuScreen -from virtManagerTui.adddomain import AddDomain -from virtManagerTui.startdomain import StartDomain -from virtManagerTui.stopdomain import StopDomain -from virtManagerTui.pausedomain import PauseDomain -from virtManagerTui.removedomain import RemoveDomain -from virtManagerTui.listdomains import ListDomains -from virtManagerTui.migratedomain import MigrateDomain -from virtManagerTui.createuser import CreateUser +from virtManagerTui.adddomain import AddDomain +from virtManagerTui.startdomain import StartDomain +from virtManagerTui.stopdomain import StopDomain +from virtManagerTui.pausedomain import PauseDomain +from virtManagerTui.removedomain import RemoveDomain +from virtManagerTui.listdomains import ListDomains +from virtManagerTui.migratedomain import MigrateDomain +from virtManagerTui.createuser import CreateUser ADD_DOMAIN = 1 START_DOMAIN = 2 @@ -36,6 +36,7 @@ LIST_DOMAINS = 6 MIGRATE_DOMAIN = 7 CREATE_USER = 8 + class NodeMenuScreen(MenuScreen): def __init__(self): MenuScreen.__init__(self, "Node Administration") @@ -68,6 +69,7 @@ class NodeMenuScreen(MenuScreen): elif item is CREATE_USER: CreateUser() + def NodeMenu(): screen = NodeMenuScreen() screen.start() diff --git a/virtManagerTui/pausedomain.py b/virtManagerTui/pausedomain.py index 16cfa60b..6b9d3780 100644 --- a/virtManagerTui/pausedomain.py +++ b/virtManagerTui/pausedomain.py @@ -20,6 +20,7 @@ import snack from virtManagerTui.domainlistconfigscreen import DomainListConfigScreen + class PauseDomainConfigScreen(DomainListConfigScreen): LIST_PAGE = 1 STOP_PAGE = 2 @@ -67,6 +68,7 @@ class PauseDomainConfigScreen(DomainListConfigScreen): grid.setField(snack.Label("%s was successfully paused." % self.get_selected_domain().get_name()), 0, 0) return [grid] + def PauseDomain(): screen = PauseDomainConfigScreen() screen.start() diff --git a/virtManagerTui/poolconfig.py b/virtManagerTui/poolconfig.py index 33c6e1fe..47ec7c6f 100644 --- a/virtManagerTui/poolconfig.py +++ b/virtManagerTui/poolconfig.py @@ -20,6 +20,7 @@ from virtinst import Storage ROOT_TARGET_PATH = "/var/lib/libvirt/images/%s" + class PoolConfig: def __init__(self, libvirt): self.__libvirt = libvirt @@ -58,7 +59,7 @@ class PoolConfig: self.__needs_source_path = False self.__needs_build_pool = False if pooltype is not None: - if pooltype is Storage.StoragePool.TYPE_DIR: + if pooltype is Storage.StoragePool.TYPE_DIR: self.__needs_target_path = True self.__target_path = ROOT_TARGET_PATH % self.__name self.__build_pool = True @@ -149,5 +150,5 @@ class PoolConfig: def set_build_pool(self, build_pool): self.__build_pool = build_pool - def get_build_pool(self): + def get_build_pool(self): return self.__build_pool diff --git a/virtManagerTui/removedomain.py b/virtManagerTui/removedomain.py index d39fd170..148ac871 100644 --- a/virtManagerTui/removedomain.py +++ b/virtManagerTui/removedomain.py @@ -20,6 +20,7 @@ import snack from virtManagerTui.domainlistconfigscreen import DomainListConfigScreen + class RemoveDomainConfigScreen(DomainListConfigScreen): LIST_PAGE = 1 CONFIRM_PAGE = 2 @@ -30,7 +31,7 @@ class RemoveDomainConfigScreen(DomainListConfigScreen): self.__confirm_remove = None def get_elements_for_page(self, screen, page): - if page is self.LIST_PAGE: + if page is self.LIST_PAGE: return self.get_domain_list_page(screen) elif page is self.CONFIRM_PAGE: return self.get_confirm_page(screen) @@ -38,21 +39,21 @@ class RemoveDomainConfigScreen(DomainListConfigScreen): return self.get_remove_page(screen) def page_has_next(self, page): - if page is self.LIST_PAGE: + if page is self.LIST_PAGE: return self.has_selectable_domains() elif page is self.CONFIRM_PAGE: return True return False def page_has_back(self, page): - if page is self.CONFIRM_PAGE: + if page is self.CONFIRM_PAGE: return True elif page is self.REMOVE_PAGE: return True return False def get_back_page(self, page): - if page is self.CONFIRM_PAGE: + if page is self.CONFIRM_PAGE: return self.LIST_PAGE elif page is self.REMOVE_PAGE: return self.LIST_PAGE @@ -89,6 +90,7 @@ class RemoveDomainConfigScreen(DomainListConfigScreen): grid.setField(snack.Label("%s has been removed." % self.get_selected_domain().get_name()), 0, 0) return [grid] + def RemoveDomain(): screen = RemoveDomainConfigScreen() screen.start() diff --git a/virtManagerTui/removehost.py b/virtManagerTui/removehost.py index bb239a9b..23017656 100644 --- a/virtManagerTui/removehost.py +++ b/virtManagerTui/removehost.py @@ -23,13 +23,14 @@ from virtManagerTui.hostlistconfigscreen import HostListConfigScreen SELECT_HOST_PAGE = 1 CONFIRM_REMOVE_PAGE = 2 + class RemoveHostConfigScreen(HostListConfigScreen): def __init__(self): HostListConfigScreen.__init__(self, "Remove Host Connection") self.__confirm = None def get_elements_for_page(self, screen, page): - if page is SELECT_HOST_PAGE: + if page is SELECT_HOST_PAGE: return self.get_connection_list_page(screen) elif page is CONFIRM_REMOVE_PAGE: return self.get_confirm_remove_page(screen) @@ -44,7 +45,7 @@ class RemoveHostConfigScreen(HostListConfigScreen): return page is CONFIRM_REMOVE_PAGE def validate_input(self, page, errors): - if page is SELECT_HOST_PAGE: + if page is SELECT_HOST_PAGE: return True elif page is CONFIRM_REMOVE_PAGE: if self.__confirm.value(): @@ -66,6 +67,7 @@ class RemoveHostConfigScreen(HostListConfigScreen): return [snack.Label("Remove Host Connection"), grid] + def RemoveHost(): screen = RemoveHostConfigScreen() screen.start() diff --git a/virtManagerTui/removenetwork.py b/virtManagerTui/removenetwork.py index 46d2a0d0..6e0f644b 100644 --- a/virtManagerTui/removenetwork.py +++ b/virtManagerTui/removenetwork.py @@ -25,6 +25,7 @@ LIST_PAGE = 1 CONFIRM_PAGE = 2 REMOVE_PAGE = 3 + class RemoveNetworkConfigScreen(NetworkListConfigScreen): def __init__(self): NetworkListConfigScreen.__init__(self, "Remove A Network") @@ -32,7 +33,7 @@ class RemoveNetworkConfigScreen(NetworkListConfigScreen): self.__confirm_remove = None def get_elements_for_page(self, screen, page): - if page is LIST_PAGE: + if page is LIST_PAGE: return self.get_network_list_page(screen, started=False) elif page is CONFIRM_PAGE: return self.get_confirm_page(screen) @@ -54,13 +55,13 @@ class RemoveNetworkConfigScreen(NetworkListConfigScreen): return False def get_back_page(self, page): - if page is CONFIRM_PAGE: + if page is CONFIRM_PAGE: return LIST_PAGE elif page is REMOVE_PAGE: return LIST_PAGE def validate_input(self, page, errors): - if page is LIST_PAGE: + if page is LIST_PAGE: return True elif page is CONFIRM_PAGE: network = self.get_selected_network() @@ -87,6 +88,7 @@ class RemoveNetworkConfigScreen(NetworkListConfigScreen): network_name = self.__deleted_network_name return [Label("Network has been removed: %s" % network_name)] + def RemoveNetwork(): screen = RemoveNetworkConfigScreen() screen.start() diff --git a/virtManagerTui/removepool.py b/virtManagerTui/removepool.py index 32b4f817..fccaa77b 100644 --- a/virtManagerTui/removepool.py +++ b/virtManagerTui/removepool.py @@ -26,13 +26,14 @@ LIST_POOLS_PAGE = 1 CONFIRM_PAGE = 2 FINISHED_REMOVING = 3 + class RemoveStoragePoolConfigScreen(StorageListConfigScreen): def __init__(self): StorageListConfigScreen.__init__(self, "Remove A Storage Pool") self.__confirm = None def get_elements_for_page(self, screen, page): - if page is LIST_POOLS_PAGE: + if page is LIST_POOLS_PAGE: return self.get_storage_pool_list_page(screen) elif page is CONFIRM_PAGE: return self.get_confirm_page(screen) @@ -91,6 +92,7 @@ class RemoveStoragePoolConfigScreen(StorageListConfigScreen): state = "was not " return [Label("Storage pool '%s' %sdeleted." % (pool, state))] + def RemoveStoragePool(): screen = RemoveStoragePoolConfigScreen() screen.start() diff --git a/virtManagerTui/removevolume.py b/virtManagerTui/removevolume.py index 4570c65b..68f96f1f 100644 --- a/virtManagerTui/removevolume.py +++ b/virtManagerTui/removevolume.py @@ -25,6 +25,7 @@ SELECT_POOL_PAGE = 1 SELECT_VOLUME_PAGE = 2 CONFIRM_PAGE = 3 + class RemoveVolumeConfigScreen(StorageListConfigScreen): def __init__(self): StorageListConfigScreen.__init__(self, "Add A New Storage Volume") @@ -32,7 +33,7 @@ class RemoveVolumeConfigScreen(StorageListConfigScreen): self.__confirm = None def get_elements_for_page(self, screen, page): - if page is SELECT_POOL_PAGE: + if page is SELECT_POOL_PAGE: return self.get_storage_pool_list_page(screen) elif page is SELECT_VOLUME_PAGE: return self.get_storage_volume_list_page(screen) @@ -40,14 +41,14 @@ class RemoveVolumeConfigScreen(StorageListConfigScreen): return self.get_confirm_page(screen) def page_has_next(self, page): - if page is SELECT_POOL_PAGE: + if page is SELECT_POOL_PAGE: return self.has_selectable_pools() elif page is SELECT_VOLUME_PAGE: return self.has_selectable_volumes() return False def validate_input(self, page, errors): - if page is SELECT_POOL_PAGE: + if page is SELECT_POOL_PAGE: return self.get_selected_pool() is not None elif page is SELECT_VOLUME_PAGE: return self.get_selected_volume() is not None @@ -77,6 +78,7 @@ class RemoveVolumeConfigScreen(StorageListConfigScreen): return [snack.Label("Remove Selected Storage Volume"), grid] + def RemoveStorageVolume(): screen = RemoveVolumeConfigScreen() screen.start() diff --git a/virtManagerTui/startdomain.py b/virtManagerTui/startdomain.py index 4723518c..fcd6f6cf 100644 --- a/virtManagerTui/startdomain.py +++ b/virtManagerTui/startdomain.py @@ -21,6 +21,7 @@ import snack from virtManagerTui.domainlistconfigscreen import DomainListConfigScreen + class StartDomainConfigScreen(DomainListConfigScreen): LIST_PAGE = 1 START_PAGE = 2 @@ -66,6 +67,7 @@ class StartDomainConfigScreen(DomainListConfigScreen): grid.setField(snack.Label("%s was successfully started." % self.get_selected_domain().get_name()), 0, 0) return [grid] + def StartDomain(): screen = StartDomainConfigScreen() screen.start() diff --git a/virtManagerTui/startnetwork.py b/virtManagerTui/startnetwork.py index 16781f78..c19ddc84 100644 --- a/virtManagerTui/startnetwork.py +++ b/virtManagerTui/startnetwork.py @@ -24,12 +24,13 @@ from virtManagerTui.networklistconfigscreen import NetworkListConfigScreen LIST_PAGE = 1 START_PAGE = 2 + class StartNetworkConfigScreen(NetworkListConfigScreen): def __init__(self): NetworkListConfigScreen.__init__(self, "Start A Network") def get_elements_for_page(self, screen, page): - if page is LIST_PAGE: + if page is LIST_PAGE: return self.get_network_list_page(screen, started=False) elif page is START_PAGE: return self.get_start_network_page(screen) @@ -55,6 +56,7 @@ class StartNetworkConfigScreen(NetworkListConfigScreen): network = self.get_selected_network() return [Label("%s was successfully started." % network.get_name())] + def StartNetwork(): screen = StartNetworkConfigScreen() screen.start() diff --git a/virtManagerTui/startpool.py b/virtManagerTui/startpool.py index 1b1c8329..4907b7c9 100644 --- a/virtManagerTui/startpool.py +++ b/virtManagerTui/startpool.py @@ -23,12 +23,13 @@ from virtManagerTui.storagelistconfigscreen import StorageListConfigScreen LIST_POOLS_PAGE = 1 FINAL_PAGE = 2 + class StartStoragePoolConfigScreen(StorageListConfigScreen): def __init__(self): StorageListConfigScreen.__init__(self, "Start A Storage Pool") def get_elements_for_page(self, screen, page): - if page is LIST_POOLS_PAGE: + if page is LIST_POOLS_PAGE: return self.get_storage_pool_list_page(screen, created=False) elif page is FINAL_PAGE: return self.get_final_page(screen) @@ -56,6 +57,7 @@ class StartStoragePoolConfigScreen(StorageListConfigScreen): self.set_finished() return [Label("Storage pool started: %s" % self.get_selected_pool())] + def StartStoragePool(): screen = StartStoragePoolConfigScreen() screen.start() diff --git a/virtManagerTui/stopdomain.py b/virtManagerTui/stopdomain.py index b7bf3bd4..c11f67eb 100644 --- a/virtManagerTui/stopdomain.py +++ b/virtManagerTui/stopdomain.py @@ -20,6 +20,7 @@ import snack from virtManagerTui.domainlistconfigscreen import DomainListConfigScreen + class StopDomainConfigScreen(DomainListConfigScreen): LIST_PAGE = 1 STOP_PAGE = 2 @@ -66,6 +67,7 @@ class StopDomainConfigScreen(DomainListConfigScreen): grid.setField(snack.Label("%s was successfully stopped." % self.get_selected_domain().get_name()), 0, 0) return [grid] + def StopDomain(): screen = StopDomainConfigScreen() screen.start() diff --git a/virtManagerTui/stopnetwork.py b/virtManagerTui/stopnetwork.py index 703deb8c..6fa9173c 100644 --- a/virtManagerTui/stopnetwork.py +++ b/virtManagerTui/stopnetwork.py @@ -24,12 +24,13 @@ import logging LIST_PAGE = 1 STOP_PAGE = 2 + class StopNetworkConfigScreen(NetworkListConfigScreen): def __init__(self): NetworkListConfigScreen.__init__(self, "Stop A Network") def get_elements_for_page(self, screen, page): - if page is LIST_PAGE: + if page is LIST_PAGE: return self.get_network_list_page(screen, defined=False) elif page is STOP_PAGE: return self.get_stop_network_page(screen) @@ -58,6 +59,7 @@ class StopNetworkConfigScreen(NetworkListConfigScreen): network = self.get_selected_network() return [Label("%s has been stopped." % network.get_name())] + def StopNetwork(): screen = StopNetworkConfigScreen() screen.start() diff --git a/virtManagerTui/stoppool.py b/virtManagerTui/stoppool.py index f09dfba0..96391ee9 100644 --- a/virtManagerTui/stoppool.py +++ b/virtManagerTui/stoppool.py @@ -23,12 +23,13 @@ from virtManagerTui.storagelistconfigscreen import StorageListConfigScreen LIST_POOLS_PAGE = 1 FINAL_PAGE = 2 + class StopStoragePoolConfigScreen(StorageListConfigScreen): def __init__(self): StorageListConfigScreen.__init__(self, "Stop A Storage Pool") def get_elements_for_page(self, screen, page): - if page is LIST_POOLS_PAGE: + if page is LIST_POOLS_PAGE: return self.get_storage_pool_list_page(screen, defined=False) elif page is FINAL_PAGE: return self.get_final_page(screen) @@ -56,6 +57,7 @@ class StopStoragePoolConfigScreen(StorageListConfigScreen): self.set_finished() return [Label("Storage pool stopped: %s" % self.get_selected_pool())] + def StopStoragePool(): screen = StopStoragePoolConfigScreen() screen.start() diff --git a/virtManagerTui/storagelistconfigscreen.py b/virtManagerTui/storagelistconfigscreen.py index 63fb4418..97005cdd 100644 --- a/virtManagerTui/storagelistconfigscreen.py +++ b/virtManagerTui/storagelistconfigscreen.py @@ -20,6 +20,7 @@ import snack from virtManagerTui.vmmconfigscreen import VmmTuiConfigScreen + class StorageListConfigScreen(VmmTuiConfigScreen): '''Provides a base class for any configuration screen that deals with storage pool lists.''' diff --git a/virtManagerTui/storagemenu.py b/virtManagerTui/storagemenu.py index aa6dc095..68dd745e 100644 --- a/virtManagerTui/storagemenu.py +++ b/virtManagerTui/storagemenu.py @@ -18,13 +18,13 @@ from newt_syrup.menuscreen import MenuScreen -from virtManagerTui.addpool import AddStoragePool -from virtManagerTui.startpool import StartStoragePool -from virtManagerTui.stoppool import StopStoragePool -from virtManagerTui.removepool import RemoveStoragePool -from virtManagerTui.addvolume import AddStorageVolume -from virtManagerTui.removevolume import RemoveStorageVolume -from virtManagerTui.listpools import ListStoragePools +from virtManagerTui.addpool import AddStoragePool +from virtManagerTui.startpool import StartStoragePool +from virtManagerTui.stoppool import StopStoragePool +from virtManagerTui.removepool import RemoveStoragePool +from virtManagerTui.addvolume import AddStorageVolume +from virtManagerTui.removevolume import RemoveStorageVolume +from virtManagerTui.listpools import ListStoragePools ADD_POOL = 1 START_POOL = 2 @@ -34,6 +34,7 @@ ADD_VOLUME = 5 REMOVE_VOLUME = 6 LIST_POOLS = 7 + class StoragePoolMenuScreen(MenuScreen): def __init__(self): MenuScreen.__init__(self, "Storage Pool Administration") @@ -48,7 +49,7 @@ class StoragePoolMenuScreen(MenuScreen): ("List Storage Pools", LIST_POOLS)) def handle_selection(self, item): - if item is ADD_POOL: + if item is ADD_POOL: AddStoragePool() elif item is START_POOL: StartStoragePool() @@ -63,6 +64,7 @@ class StoragePoolMenuScreen(MenuScreen): elif item is LIST_POOLS: ListStoragePools() + def StoragePoolMenu(): screen = StoragePoolMenuScreen() screen.start() diff --git a/virtManagerTui/userworker.py b/virtManagerTui/userworker.py index a3eeb91b..908e4b7a 100644 --- a/virtManagerTui/userworker.py +++ b/virtManagerTui/userworker.py @@ -18,6 +18,7 @@ import libuser + class UserWorker: '''Provides APIs for creating, modifying and deleting user accounts.''' def __init__(self): diff --git a/virtManagerTui/vmmconfigscreen.py b/virtManagerTui/vmmconfigscreen.py index a6effe9b..bfe19e64 100644 --- a/virtManagerTui/vmmconfigscreen.py +++ b/virtManagerTui/vmmconfigscreen.py @@ -29,6 +29,7 @@ NEXT_BUTTON = "next" CANCEL_BUTTON = "cancel" FINISH_BUTTON = "finish" + class VmmTuiConfigScreen(configscreen.ConfigScreen): '''Enables the creation of navigable, multi-paged configuration screens.''' diff --git a/virtManagerTui/volumeconfig.py b/virtManagerTui/volumeconfig.py index 847b577f..da5930e3 100644 --- a/virtManagerTui/volumeconfig.py +++ b/virtManagerTui/volumeconfig.py @@ -19,6 +19,7 @@ import virtinst from virtinst import Storage + class StorageVolumeConfig: def __init__(self): self.__pool = None diff --git a/virtcli/cliconfig.py b/virtcli/cliconfig.py index 7d7fc6e9..5cb662f2 100644 --- a/virtcli/cliconfig.py +++ b/virtcli/cliconfig.py @@ -32,9 +32,11 @@ cfgpath = os.path.join(os.path.dirname(_filepath), "cli.cfg") if os.path.exists(cfgpath): cfg.read(cfgpath) + def _split_list(commastr): return [d for d in commastr.split(",") if d] + def _get_param(name, default): if not cfg.sections(): return default diff --git a/virtcli/cliutils.py b/virtcli/cliutils.py index 4dcff205..d97ce6ad 100644 --- a/virtcli/cliutils.py +++ b/virtcli/cliutils.py @@ -88,6 +88,7 @@ def setup_logging(appname, debug_stdout): sys.__excepthook__(typ, val, tb) sys.excepthook = exception_log + def setup_i18n(): try: locale.setlocale(locale.LC_ALL, '') diff --git a/virtconv/__init__.py b/virtconv/__init__.py index 9fdf2c85..8db50d5a 100644 --- a/virtconv/__init__.py +++ b/virtconv/__init__.py @@ -25,12 +25,12 @@ import os parsers_path = [os.path.join(__path__[0], "parsers/")] # iter_modules is only in Python 2.5, sadly -parser_names = [ "vmx", "virtimage", "ovf"] +parser_names = ["vmx", "virtimage", "ovf"] if hasattr(pkgutil, "iter_modules"): parser_names = [] for ignore, name, ignore in pkgutil.iter_modules(parsers_path): - parser_names += [ name ] + parser_names += [name] for name in parser_names: filename, pathname, desc = imp.find_module(name, parsers_path) diff --git a/virtconv/diskcfg.py b/virtconv/diskcfg.py index 48557e8e..f1bc1a46 100644 --- a/virtconv/diskcfg.py +++ b/virtconv/diskcfg.py @@ -80,6 +80,7 @@ checksum_types = { CSUM_SHA256 : "sha256", } + def ensuredirs(path): """ Make sure that all the containing directories of the given file @@ -91,6 +92,7 @@ def ensuredirs(path): if e.errno != errno.EEXIST: raise + def run_cmd(cmd): """ Return the exit status and output to stdout and stderr. @@ -102,9 +104,10 @@ def run_cmd(cmd): ret = proc.wait() return ret, proc.stdout.readlines(), proc.stderr.readlines() + def run_vdiskadm(args): """Run vdiskadm, returning the output.""" - ret, stdout, stderr = run_cmd([ "/usr/sbin/vdiskadm" ] + args) + ret, stdout, stderr = run_cmd(["/usr/sbin/vdiskadm"] + args) if ret != 0: raise RuntimeError("Disk conversion failed with " @@ -114,6 +117,7 @@ def run_vdiskadm(args): return stdout + class disk(object): """Definition of an individual disk instance.""" @@ -141,7 +145,7 @@ class disk(object): def copy_file(self, infile, outfile): """Copy an individual file.""" - self.clean += [ outfile ] + self.clean += [outfile] ensuredirs(outfile) shutil.copy(infile, outfile) @@ -160,13 +164,13 @@ class disk(object): necessary. """ - stdout = run_vdiskadm([ "import", "-fnp", absin, absout ]) + stdout = run_vdiskadm(["import", "-fnp", absin, absout]) for item in stdout: ignore, path = item.strip().split(':', 1) - self.clean += [ os.path.join(absout, path) ] + self.clean += [os.path.join(absout, path)] - run_vdiskadm([ "import", "-fp", absin, absout ]) + run_vdiskadm(["import", "-fp", absin, absout]) def qemu_convert(self, absin, absout, out_format): """ @@ -177,7 +181,7 @@ class disk(object): with kvm and qemu-img with qemu. Both would work. """ - self.clean += [ absout ] + self.clean += [absout] ret, ignore, stderr = run_cmd(["qemu-img", "convert", "-O", qemu_formats[out_format], absin, absout]) @@ -226,7 +230,7 @@ class disk(object): if self.format == DISK_FORMAT_VDISK: raise RuntimeError("Disk conversion failed: " "invalid vdisk '%s'" % self.path) - self.clean += [ absout ] + self.clean += [absout] self.copy_file(absin, absout) self.path = relout return True, need_conversion @@ -236,7 +240,7 @@ class disk(object): # XXX: This can go wrong for multi-part disks! # if not need_conversion: - self.clean += [ absout ] + self.clean += [absout] self.copy_file(absin, absout) self.path = relout return True, False @@ -304,6 +308,7 @@ class disk(object): self.format = out_format self.path = relout + def disk_formats(): """ Return a list of supported disk formats. diff --git a/virtconv/formats.py b/virtconv/formats.py index 2199b9ce..61eac126 100644 --- a/virtconv/formats.py +++ b/virtconv/formats.py @@ -20,7 +20,7 @@ import os -_parsers = [ ] +_parsers = [] class parser(object): @@ -57,6 +57,7 @@ class parser(object): """ raise NotImplementedError + def register_parser(new_parser): """ Register a particular config format parser. This should be called by each @@ -64,7 +65,8 @@ def register_parser(new_parser): """ global _parsers - _parsers += [ new_parser ] + _parsers += [new_parser] + def parser_by_name(name): """ @@ -74,6 +76,7 @@ def parser_by_name(name): if len(parsers): return parsers[0] + def find_parser_by_file(input_file): """ Return the parser that is capable of comprehending the given file. @@ -83,24 +86,28 @@ def find_parser_by_file(input_file): return p return None + def formats(): """ Return a list of supported formats. """ return [p.name for p in _parsers] + def input_formats(): """ Return a list of supported input formats. """ return [p.name for p in _parsers if p.can_import] + def output_formats(): """ Return a list of supported output formats. """ return [p.name for p in _parsers if p.can_export] + def find_input(path, fmt=None): """ Search for a configuration file automatically. If @format is given, @@ -120,7 +127,7 @@ def find_input(path, fmt=None): if p.identify_file(path): return (path, p.name) elif os.path.isdir(path): - for cfgfile in [ x for x in files if x.endswith(p.suffix) ]: + for cfgfile in [x for x in files if x.endswith(p.suffix)]: if p.identify_file(os.path.join(path, cfgfile)): return (os.path.join(path, cfgfile), p.name) diff --git a/virtconv/netdevcfg.py b/virtconv/netdevcfg.py index a19415c0..2c674e1d 100644 --- a/virtconv/netdevcfg.py +++ b/virtconv/netdevcfg.py @@ -23,6 +23,7 @@ NETDEV_TYPE_BRIDGE = 1 NETDEV_TYPE_DEV = 2 NETDEV_TYPE_NETWORK = 3 + class netdev(object): """Definition of an individual network device.""" diff --git a/virtconv/parsers/ovf.py b/virtconv/parsers/ovf.py index d00ba45d..3c537645 100644 --- a/virtconv/parsers/ovf.py +++ b/virtconv/parsers/ovf.py @@ -71,7 +71,7 @@ DEVICE_DISK = "17" DEVICE_GRAPHICS = "24" # AllocationUnits mapping can be found in Appendix C here: -#http://www.dmtf.org/standards/documents/CIM/DSP0004.pdf +# http://www.dmtf.org/standards/documents/CIM/DSP0004.pdf @@ -82,6 +82,7 @@ def register_namespace(ctx): ctx.xpathRegisterNs("vssd", "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData") ctx.xpathRegisterNs("vmw", "http://www.vmware.com/schema/ovf") + def node_list(node): child_list = [] child = node.children @@ -90,6 +91,7 @@ def node_list(node): child = child.next return child_list + def get_child_content(parent_node, child_name): for node in node_list(parent_node): @@ -98,6 +100,7 @@ def get_child_content(parent_node, child_name): return None + def convert_alloc_val(ignore, val): # XXX: This is a hack, but should we really have to decode # allocation units = "bytes * 2^20"? @@ -117,6 +120,7 @@ def convert_alloc_val(ignore, val): return int(val) + def _xml_wrapper(xml, func): doc = None ctx = None @@ -135,6 +139,7 @@ def _xml_wrapper(xml, func): ctx.xpathFreeContext() return result + def get_xml_path(xml, path=None, func=None): """ Return the content from the passed xml xpath, or return the result @@ -145,10 +150,10 @@ def get_xml_path(xml, path=None, func=None): if path: ret = ctx.xpathEval(path) - if ret != None: + if ret is not None: if type(ret) == list: if len(ret) >= 1: - #result = ret[0].content + # result = ret[0].content result = ret else: result = ret @@ -162,6 +167,7 @@ def get_xml_path(xml, path=None, func=None): return _xml_wrapper(xml, _get_xml_path) + def _parse_hw_section(vm, nodes, file_refs, disk_section): vm.nr_vcpus = 0 disk_buses = {} @@ -201,7 +207,7 @@ def _parse_hw_section(vm, nodes, file_refs, disk_section): instance_id = get_child_content(device_node, "InstanceID") disk_buses[instance_id] = "scsi" - elif devtype in [ DEVICE_DISK ]: + elif devtype in [DEVICE_DISK]: bus_id = get_child_content(device_node, "Parent") path = get_child_content(device_node, "HostResource") @@ -252,6 +258,7 @@ def _parse_hw_section(vm, nodes, file_refs, disk_section): desc = get_child_content(device_node, "Description") logging.debug("Unhandled device type=%s desc=%s", devtype, desc) + class ovf_parser(formats.parser): """ Support for OVF appliance configurations. @@ -303,7 +310,7 @@ class ovf_parser(formats.parser): def xpath_str(path): ret = ctx.xpathEval(path) result = None - if ret != None: + if ret is not None: if type(ret) == list: if len(ret) >= 1: result = ret[0].content diff --git a/virtconv/parsers/virtimage.py b/virtconv/parsers/virtimage.py index 4ef84c10..c796e7b4 100644 --- a/virtconv/parsers/virtimage.py +++ b/virtconv/parsers/virtimage.py @@ -77,6 +77,7 @@ image_template = \ """ + def export_os_params(vm): """ Export OS-specific parameters. @@ -86,7 +87,7 @@ def export_os_params(vm): # TODO: Shouldn't be directly using _OS_TYPES here. virt-image libs ( # ImageParser?) should handle this info - ostype = Guest._OS_TYPES.get(vm.os_type) # pylint: disable=W0212 + ostype = Guest._OS_TYPES.get(vm.os_type) # pylint: disable=W0212 if ostype: osvariant = ostype.get('variants').get(vm.os_variant) @@ -110,6 +111,7 @@ def export_os_params(vm): return acpi, apic + def export_disks(vm): """ Export code for the disks. Slightly tricky for two reasons. @@ -143,7 +145,7 @@ def export_disks(vm): disks[("ide", instance)] = disk if disk.path: - paths += [ disk.path ] + paths += [disk.path] diskout = [] storage = [] @@ -181,6 +183,7 @@ def export_disks(vm): return storage, diskout + class virtimage_parser(formats.parser): """ Support for virt-install's image format (see virt-image man page). @@ -247,7 +250,7 @@ class virtimage_parser(formats.parser): ImageParser.Disk.FORMAT_QCOW: diskcfg.DISK_FORMAT_QCOW, ImageParser.Disk.FORMAT_QCOW2: diskcfg.DISK_FORMAT_QCOW2, ImageParser.Disk.FORMAT_VDI: diskcfg.DISK_FORMAT_VDI, - } + } fmt = None if disk.format in format_mappings: @@ -307,7 +310,7 @@ class virtimage_parser(formats.parser): "arch" : vm.arch, "acpi" : acpi, "apic" : apic, - } + } out = image_template % { "boot_template": boot_xml, @@ -318,7 +321,7 @@ class virtimage_parser(formats.parser): "memory" : int(vm.memory) * 1024, "interface" : interface, "storage" : "".join(storage).strip("\n"), - } + } return out diff --git a/virtconv/parsers/vmx.py b/virtconv/parsers/vmx.py index 5f6c9373..50242e47 100644 --- a/virtconv/parsers/vmx.py +++ b/virtconv/parsers/vmx.py @@ -81,6 +81,7 @@ ide%(dev)s.startConnected = "TRUE" ide%(dev)s.writeThrough = "TRUE" """ + class _VMXLine(object): """ Class tracking an individual line in a VMX/VMDK file @@ -118,6 +119,7 @@ class _VMXLine(object): raise ValueError("Path was not fourth entry in VMDK storage line") return shlex.split(content, " ", 1)[0] + class _VMXFile(object): """ Class tracking a parsed VMX/VMDK format file @@ -144,6 +146,7 @@ class _VMXFile(object): ret[line.pair[0]] = line.pair[1] return ret + def parse_vmdk(disk, filename): """ Parse a VMDK descriptor file @@ -182,6 +185,7 @@ def parse_vmdk(disk, filename): logging.debug("VMDK file parsed path %s->%s", disk.path, newpath) disk.path = newpath + def parse_netdev_entry(vm, fullkey, value): """ Parse a particular key/value for a network. Throws ValueError. @@ -206,6 +210,7 @@ def parse_netdev_entry(vm, fullkey, value): if key == "address": vm.netdevs[inst].mac = lvalue + def parse_disk_entry(vm, fullkey, value): """ Parse a particular key/value for a disk. FIXME: this should be a @@ -347,7 +352,7 @@ class vmx_parser(formats.parser): "vm_description": vm.description or "None", "vm_nr_vcpus" : vm.nr_vcpus, "vm_memory": long(vm.memory) - } + } vmx_out = _VMX_MAIN_TEMPLATE % vmx_dict vmx_out_template.append(vmx_out) @@ -363,7 +368,7 @@ class vmx_parser(formats.parser): disk_dict = { "dev": dev, "disk_filename" : disk.path - } + } disk_out = _VMX_IDE_TEMPLATE % disk_dict disk_out_template.append(disk_out) @@ -372,7 +377,7 @@ class vmx_parser(formats.parser): for devnum in vm.netdevs: eth_dict = { "dev" : devnum - } + } eth_out = _VMX_ETHERNET_TEMPLATE % eth_dict eth_out_template.append(eth_out) diff --git a/virtconv/vmcfg.py b/virtconv/vmcfg.py index db58d3ac..91aa93fe 100644 --- a/virtconv/vmcfg.py +++ b/virtconv/vmcfg.py @@ -26,6 +26,7 @@ VM_TYPE_UNKNOWN = 0 VM_TYPE_PV = 1 VM_TYPE_HVM = 2 + class vm(object): """ Generic configuration for a particular VM instance. @@ -82,6 +83,7 @@ class vm(object): raise ValueError(_("Disk %s:%s storage does not exist") % (bus, inst)) + def host(conn=None): """ Return the host, as seen in platform.system(), but possibly from a diff --git a/virtinst/Boot.py b/virtinst/Boot.py index d7631e58..b42fee72 100644 --- a/virtinst/Boot.py +++ b/virtinst/Boot.py @@ -21,6 +21,7 @@ from virtinst import util from virtinst import XMLBuilderDomain from virtinst.XMLBuilderDomain import _xml_property + class Boot(XMLBuilderDomain.XMLBuilderDomain): """ Class for generating boot device related XML @@ -50,7 +51,7 @@ class Boot(XMLBuilderDomain.XMLBuilderDomain): self._enable_bootmenu = val def _get_menu_converter(self, val): ignore = self - if val == None: + if val is None: return None return bool(val == "yes") enable_bootmenu = _xml_property(_get_enable_bootmenu, _set_enable_bootmenu, diff --git a/virtinst/CPU.py b/virtinst/CPU.py index 32af6a7e..ca13054c 100644 --- a/virtinst/CPU.py +++ b/virtinst/CPU.py @@ -22,9 +22,11 @@ from virtinst.XMLBuilderDomain import _xml_property import libxml2 + def _int_or_none(val): return val and int(val) or val + class CPUFeature(XMLBuilderDomain.XMLBuilderDomain): """ Class for generating child XML diff --git a/virtinst/CapabilitiesParser.py b/virtinst/CapabilitiesParser.py index 264db44c..708dcc4c 100644 --- a/virtinst/CapabilitiesParser.py +++ b/virtinst/CapabilitiesParser.py @@ -23,6 +23,7 @@ import re from virtinst import util + class CapabilitiesParserException(Exception): def __init__(self, msg): Exception.__init__(self, msg) @@ -31,6 +32,7 @@ class CapabilitiesParserException(Exception): FEATURE_ON = 0x01 FEATURE_OFF = 0x02 + class CPUValuesModel(object): """ Single definition from cpu_map @@ -102,6 +104,7 @@ class CPUValuesArch(object): return c raise ValueError(_("Unknown CPU model '%s'") % model) + class CPUValues(object): """ Lists valid values for domain parameters, parsed from libvirt's @@ -139,6 +142,7 @@ class CPUValues(object): return cpumap + class Features(object): """Represent a set of features. For each feature, store a bit mask of FEATURE_ON and FEATURE_OFF to indicate whether the feature can @@ -183,6 +187,7 @@ class Features(object): its value. Abstract method, must be overridden""" raise NotImplementedError("Abstract base class") + class CapabilityFeatures(Features): def __init__(self, node=None): Features.__init__(self, node) @@ -209,6 +214,7 @@ class CapabilityFeatures(Features): else: d[feature] |= FEATURE_ON + class CPU(object): def __init__(self, node=None): # e.g. "i686" or "x86_64" @@ -255,6 +261,7 @@ class CPU(object): child = child.next + class Host(object): def __init__(self, node=None): self.cpu = CPU() @@ -427,6 +434,7 @@ class Domain(object): def is_accelerated(self): return self.hypervisor_type in ["kvm", "kqemu"] + class Topology(object): def __init__(self, node=None): self.cells = [] @@ -441,6 +449,7 @@ class Topology(object): if cell.name == "cell": self.cells.append(TopologyCell(cell)) + class TopologyCell(object): def __init__(self, node=None): self.id = None @@ -457,6 +466,7 @@ class TopologyCell(object): if cpu.name == "cpu": self.cpus.append(TopologyCPU(cpu)) + class TopologyCPU(object): def __init__(self, node=None): self.id = None @@ -483,6 +493,7 @@ class SecurityModel(object): elif child.name == "doi": self.doi = child.content + class Capabilities(object): def __init__(self, node=None): self.host = None @@ -676,11 +687,13 @@ class Capabilities(object): return self._cpu_values.get_arch(arch) + def parse(xml): return util.parse_node_helper(xml, "capabilities", Capabilities, CapabilitiesParserException) + def guest_lookup(conn, caps=None, os_type=None, arch=None, typ=None, accelerated=False, machine=None): """ @@ -738,7 +751,7 @@ def guest_lookup(conn, caps=None, os_type=None, arch=None, typ=None, dtype=typ, machine=machine) - if domain == None: + if domain is None: machinestr = "with machine '%s'" % machine if not machine: machinestr = "" diff --git a/virtinst/Clock.py b/virtinst/Clock.py index 5a8d780c..e9e8acf2 100644 --- a/virtinst/Clock.py +++ b/virtinst/Clock.py @@ -20,6 +20,7 @@ from virtinst import XMLBuilderDomain from virtinst.XMLBuilderDomain import _xml_property + class Clock(XMLBuilderDomain.XMLBuilderDomain): """ Class for generating XML diff --git a/virtinst/CloneManager.py b/virtinst/CloneManager.py index 87f3f6e1..07e6c14f 100644 --- a/virtinst/CloneManager.py +++ b/virtinst/CloneManager.py @@ -46,6 +46,7 @@ from virtinst.VirtualDisk import VirtualDisk from virtinst import Storage from virtinst import util + def _listify(val): """ Return (was_val_a_list, listified_val) @@ -55,6 +56,7 @@ def _listify(val): else: return False, [val] + def generate_clone_disk_path(origpath, design, newname=None): origname = design.original_guest newname = newname or design.clone_name @@ -85,6 +87,7 @@ def generate_clone_disk_path(origpath, design, newname=None): suffix, lib_collision=False) + def generate_clone_name(design): # If the orig name is "foo-clone", we don't want the clone to be # "foo-clone-clone", we want "foo-clone1" @@ -393,10 +396,10 @@ class CloneDesign(object): """ logging.debug("Validating original guest parameters") - if self.original_guest == None and self.original_xml == None: + if self.original_guest is None and self.original_xml is None: raise RuntimeError(_("Original guest name or xml is required.")) - if self.original_guest != None and not self.original_xml: + if self.original_guest is not None and not self.original_xml: self._original_dom = self._lookup_vm(self.original_guest) self.original_xml = self._original_dom.XMLDesc(0) @@ -435,7 +438,7 @@ class CloneDesign(object): raise ValueError(_("More disks to clone than new paths specified. " "(%(passed)d specified, %(need)d needed") % {"passed" : len(self.clone_virtual_disks), - "need" : len(self.original_virtual_disks) }) + "need" : len(self.original_virtual_disks)}) logging.debug("Clone paths: %s", self._clone_devices) @@ -637,7 +640,7 @@ def start_duplicate(design, meter=None): # Define domain early to catch any xml errors before duping storage dom = design.original_conn.defineXML(design.clone_xml) - if design.preserve == True: + if design.preserve: _do_duplicate(design, meter) except Exception, e: @@ -650,6 +653,8 @@ def start_duplicate(design, meter=None): # Iterate over the list of disks, and clone them using the appropriate # clone method + + def _do_duplicate(design, meter): # Now actually do the cloning diff --git a/virtinst/DistroInstaller.py b/virtinst/DistroInstaller.py index 93a3528d..0ea6cb77 100644 --- a/virtinst/DistroInstaller.py +++ b/virtinst/DistroInstaller.py @@ -47,6 +47,7 @@ def _is_url(url, is_local): return (url.startswith("http://") or url.startswith("ftp://") or url.startswith("nfs:")) + def _sanitize_url(url): """ Do nothing for http or ftp, but make sure nfs is in the expected format @@ -66,6 +67,7 @@ def _sanitize_url(url): return url + def _build_pool(conn, meter, path): pool = util.lookup_pool_by_path(conn, path) if pool: @@ -132,7 +134,7 @@ def _upload_file(conn, meter, destpool, src): meter.start(size=size, text=_("Transferring %s") % os.path.basename(src)) while True: - #blocksize = (1024 ** 2) + # blocksize = (1024 ** 2) blocksize = 1024 data = fileobj.read(blocksize) if not data: @@ -222,7 +224,7 @@ class DistroInstaller(Installer.Installer): # Didn't determine anything about the location validated = False - if self._location_is_path or (validated == False and self.conn and + if self._location_is_path or (not validated and self.conn and util.is_storage_capable(self.conn)): # If user passed a storage tuple, OR # We couldn't determine the location type and a storage capable diff --git a/virtinst/DomainFeatures.py b/virtinst/DomainFeatures.py index 10911269..b1dbc10d 100644 --- a/virtinst/DomainFeatures.py +++ b/virtinst/DomainFeatures.py @@ -20,11 +20,13 @@ from virtinst import XMLBuilderDomain from virtinst.XMLBuilderDomain import _xml_property + def _none_or_bool(val): if val is None: return val return bool(val) + class DomainFeatures(XMLBuilderDomain.XMLBuilderDomain): """ Class for generating XML diff --git a/virtinst/DomainNumatune.py b/virtinst/DomainNumatune.py index 06da59b7..15cd7aa3 100644 --- a/virtinst/DomainNumatune.py +++ b/virtinst/DomainNumatune.py @@ -42,7 +42,7 @@ class DomainNumatune(XMLBuilderDomain.XMLBuilderDomain): if val is None or val == "": return - if type(val) is not type("string") or len(val) == 0: + if not isinstance(val, str) or len(val) == 0: raise ValueError(_("cpuset must be string")) if re.match("^[0-9,-^]*$", val) is None: raise ValueError(_("cpuset can only contain numeric, ',', '^', or " diff --git a/virtinst/Guest.py b/virtinst/Guest.py index fa7d1792..96c1866f 100644 --- a/virtinst/Guest.py +++ b/virtinst/Guest.py @@ -177,12 +177,12 @@ class Guest(XMLBuilderDomain.XMLBuilderDomain): # Set up the connection, since it is fundamental for other init conn = conn or connection - if conn == None: + if conn is None: logging.debug("No conn passed to Guest, opening URI '%s'", hypervisorURI) conn = self._open_uri(hypervisorURI) - if conn == None: + if conn is None: raise RuntimeError(_("Unable to connect to hypervisor, aborting " "installation!")) @@ -295,7 +295,7 @@ class Guest(XMLBuilderDomain.XMLBuilderDomain): util.validate_name(_("Guest"), val, lencheck=True) do_fail = False - if self.replace != True: + if self.replace is not True: try: self.conn.lookupByName(val) do_fail = True @@ -314,7 +314,7 @@ class Guest(XMLBuilderDomain.XMLBuilderDomain): def get_memory(self): return self._memory def set_memory(self, val): - if (type(val) is not type(1) or val <= 0): + if not isinstance(val, int) or val <= 0: raise ValueError(_("Memory value must be an integer greater " "than 0")) self._memory = val @@ -332,7 +332,7 @@ class Guest(XMLBuilderDomain.XMLBuilderDomain): def get_maxmemory(self): return self._maxmemory def set_maxmemory(self, val): - if (type(val) is not type(1) or val <= 0): + if not isinstance(val, int) or val <= 0: raise ValueError(_("Max Memory value must be an integer greater " "than 0")) self._maxmemory = val @@ -675,7 +675,7 @@ class Guest(XMLBuilderDomain.XMLBuilderDomain): "smartcard" : virtinst.VirtualSmartCardDevice, "redirdev" : virtinst.VirtualRedirDevice, "memballoon": virtinst.VirtualMemballoon, - } + } # Hand off all child element parsing to relevant classes caps = self._get_caps() @@ -1081,7 +1081,7 @@ class Guest(XMLBuilderDomain.XMLBuilderDomain): Remove the existing VM with the same name if requested, or error if there is a collision. """ - if force == None: + if force is None: force = self.replace vm = None @@ -1169,7 +1169,7 @@ class Guest(XMLBuilderDomain.XMLBuilderDomain): else: meter_label = _("Starting domain...") - if meter == None: + if meter is None: meter = progress.BaseMeter() meter.start(size=None, text=meter_label) @@ -1316,7 +1316,7 @@ class Guest(XMLBuilderDomain.XMLBuilderDomain): disk.device == VirtualDisk.DEVICE_DISK): disk.bus = disk_bus - if self.clock.offset == None: + if self.clock.offset is None: self.clock.offset = self._lookup_osdict_key("clock") if features["acpi"] is None: @@ -1326,7 +1326,7 @@ class Guest(XMLBuilderDomain.XMLBuilderDomain): if features["pae"] is None and self._get_caps(): features["pae"] = self._get_caps().support_pae() - if (self.installer.machine == None and + if (self.installer.machine is None and self._get_caps().host.arch == "ppc64"): self.installer.machine = "pseries" @@ -1335,7 +1335,7 @@ class Guest(XMLBuilderDomain.XMLBuilderDomain): for d in devlist_func(VirtualDevice.VIRTUAL_DEV_DISK): if (d.type == VirtualDisk.TYPE_FILE and util.is_blktap_capable() - and d.driver_name == None): + and d.driver_name is None): d.driver_name = VirtualDisk.DRIVER_TAP for d in devlist_func(VirtualDevice.VIRTUAL_DEV_INPUT): @@ -1488,7 +1488,7 @@ def _wait_for_domain(conn, name): # domain ID or b) it's been 5 seconds. this is so that # we can try to gracefully handle domain restarting failures dom = None - for ignore in range(1, int(5 / .25)): # 5 seconds, .25 second sleeps + for ignore in range(1, int(5 / .25)): # 5 seconds, .25 second sleeps try: dom = conn.lookupByName(name) if dom and dom.ID() != -1: diff --git a/virtinst/ImageFetcher.py b/virtinst/ImageFetcher.py index d4756f57..26cce8ae 100644 --- a/virtinst/ImageFetcher.py +++ b/virtinst/ImageFetcher.py @@ -102,6 +102,8 @@ class ImageFetcher: raise NotImplementedError("Must be implemented in subclass") # Base class for downloading from FTP / HTTP + + class URIImageFetcher(ImageFetcher): def hasFile(self, filename): @@ -112,6 +114,7 @@ class URIImageFetcher(ImageFetcher): raise ValueError(_("Opening URL %s failed.") % (self.location)) + class HTTPImageFetcher(URIImageFetcher): def hasFile(self, filename): @@ -125,6 +128,7 @@ class HTTPImageFetcher(URIImageFetcher): return False return True + class FTPImageFetcher(URIImageFetcher): def __init__(self, location, scratchdir): @@ -155,6 +159,7 @@ class FTPImageFetcher(URIImageFetcher): return True + class LocalImageFetcher(ImageFetcher): def __init__(self, location, scratchdir, srcdir=None): @@ -171,6 +176,8 @@ class LocalImageFetcher(ImageFetcher): # This is a fetcher capable of extracting files from a NFS server # or loopback mounted file, or local CDROM device + + class MountedImageFetcher(LocalImageFetcher): def prepareLocation(self): @@ -213,6 +220,7 @@ class MountedImageFetcher(LocalImageFetcher): except: pass + class DirectImageFetcher(LocalImageFetcher): def prepareLocation(self): diff --git a/virtinst/ImageInstaller.py b/virtinst/ImageInstaller.py index 0608e778..c6cb74fe 100644 --- a/virtinst/ImageInstaller.py +++ b/virtinst/ImageInstaller.py @@ -30,6 +30,7 @@ class ImageInstallerException(Exception): def __init__(self, msg): Exception.__init__(self, msg) + class ImageInstaller(Installer.Installer): """Installer for image-based guests""" def __init__(self, image, capabilities=None, boot_index=None, conn=None): @@ -144,10 +145,12 @@ class ImageInstaller(Installer.Installer): def _abspath(self, p): return self.image.abspath(p) + class PlatformMatchException(Exception): def __init__(self, msg): Exception.__init__(self, msg) + def match_boots(capabilities, boots): for b in boots: for g in capabilities.guests: diff --git a/virtinst/ImageParser.py b/virtinst/ImageParser.py index 7d5dac9a..5998ece0 100644 --- a/virtinst/ImageParser.py +++ b/virtinst/ImageParser.py @@ -33,12 +33,13 @@ class ParserException(Exception): def __init__(self, msg): Exception.__init__(self, msg) + class Image: """The toplevel object representing a VM image""" def __init__(self, node=None, base=None, filename=None): self.storage = {} self.domain = None - if filename == None: + if filename is None: self.filename = None else: self.filename = os.path.abspath(filename) @@ -92,6 +93,7 @@ class Image: % d.disk_id) d.disk = self.storage[d.disk_id] + class Domain: """The description of a virtual domain as part of an image""" def __init__(self, node=None): @@ -104,7 +106,7 @@ class Domain: self.parseXML(node) def parseXML(self, node): - self.boots = [ Boot(b) for b in node.xpathEval("boot") ] + self.boots = [Boot(b) for b in node.xpathEval("boot")] self.vcpu = xpathString(node, "devices/vcpu", 1) tmpmem = xpathString(node, "devices/memory") self.interface = int(node.xpathEval("count(devices/interface)")) @@ -120,6 +122,7 @@ class Domain: else: tmpmem = 0 + class ImageFeatures(CapabilitiesParser.Features): def __init__(self, node=None): CapabilitiesParser.Features.__init__(self, node) @@ -134,6 +137,7 @@ class ImageFeatures(CapabilitiesParser.Features): else: raise ParserException("The state for feature %s must be either 'on' or 'off', but is '%s'" % (feature, state)) + class Boot: """The overall description of how the image can be booted, including required capabilities of the host and mapping of disks into the VM""" @@ -184,6 +188,7 @@ class Boot: # We should make sure that kernel/initrd/cmdline are only used for pv # and without a loader + class Drive: """The mapping of a disk from the storage section to a virtual drive in a guest""" @@ -198,6 +203,7 @@ class Drive: self.disk_id = xpathString(node, "@disk") self.target = xpathString(node, "@target") + class Disk: FORMAT_RAW = "raw" FORMAT_ISO = "iso" @@ -290,16 +296,19 @@ class Disk: raise ValueError(_("Disk signature for %s does not " "match" % self.file)) + def validate(cond, msg): if not cond: raise ParserException(msg) + def xpathString(node, path, default=None): result = node.xpathEval("string(%s)" % path) if len(result) == 0: result = default return result + def parse(xml, filename): """Parse the XML description of a VM image into a data structure. Returns an object of class Image. BASE should be the directory where the disk @@ -334,6 +343,7 @@ def parse(xml, filename): return image + def parse_file(filename): f = open(filename, "r") xml = f.read() diff --git a/virtinst/ImportInstaller.py b/virtinst/ImportInstaller.py index ff35b50e..4073fafd 100644 --- a/virtinst/ImportInstaller.py +++ b/virtinst/ImportInstaller.py @@ -20,6 +20,7 @@ from virtinst import Installer from virtinst.VirtualDisk import VirtualDisk + class ImportInstaller(Installer.Installer): """ Create a Guest around an existing disk device, and perform no 'install' diff --git a/virtinst/Installer.py b/virtinst/Installer.py index 1ccec1c9..417392b9 100644 --- a/virtinst/Installer.py +++ b/virtinst/Installer.py @@ -444,7 +444,7 @@ class Installer(XMLBuilderDomain.XMLBuilderDomain): except OSError, (err, msg): logging.debug("Failed to open guest disk: %s", msg) if err == errno.EACCES and os.geteuid() != 0: - return True # non root might not have access to block devices + return True # non root might not have access to block devices else: raise diff --git a/virtinst/Interface.py b/virtinst/Interface.py index dbd4b113..400bedbc 100644 --- a/virtinst/Interface.py +++ b/virtinst/Interface.py @@ -186,7 +186,7 @@ class Interface(object): """ Returns IP protocol XML """ - if self.protocol_xml != None: + if self.protocol_xml is not None: return self.protocol_xml xml = "" for p in self.protocols: @@ -353,24 +353,25 @@ class InterfaceBridge(_InterfaceCompound): xml += " \n" return xml + class InterfaceBond(_InterfaceCompound): """ Class for building and installing libvirt interface bond xml """ - INTERFACE_BOND_MODES = [ "active-backup", "balance-alb", "balance-rr", + INTERFACE_BOND_MODES = ["active-backup", "balance-alb", "balance-rr", "balance-tlb", "balance-xor", "broadcast", - "802.3ad" ] + "802.3ad"] INTERFACE_BOND_MONITOR_MODE_ARP = "arpmon" INTERFACE_BOND_MONITOR_MODE_MII = "miimon" - INTERFACE_BOND_MONITOR_MODES = [ INTERFACE_BOND_MONITOR_MODE_ARP, - INTERFACE_BOND_MONITOR_MODE_MII ] + INTERFACE_BOND_MONITOR_MODES = [INTERFACE_BOND_MONITOR_MODE_ARP, + INTERFACE_BOND_MONITOR_MODE_MII] - INTERFACE_BOND_MONITOR_MODE_ARP_VALIDATE_MODES = [ "active", "backup", - "all" ] + INTERFACE_BOND_MONITOR_MODE_ARP_VALIDATE_MODES = ["active", "backup", + "all"] - INTERFACE_BOND_MONITOR_MODE_MII_CARRIER_TYPES = [ "netif", "ioctl" ] + INTERFACE_BOND_MONITOR_MODE_MII_CARRIER_TYPES = ["netif", "ioctl"] def __init__(self, name, conn=None): _InterfaceCompound.__init__(self, Interface.INTERFACE_TYPE_BOND, @@ -514,6 +515,7 @@ class InterfaceBond(_InterfaceCompound): xml += " \n" return xml + class InterfaceEthernet(Interface): """ Class for building and installing libvirt interface ethernet xml @@ -527,6 +529,7 @@ class InterfaceEthernet(Interface): # No ethernet specific XML return "" + class InterfaceVLAN(Interface): """ Class for building and installing libvirt interface vlan xml @@ -578,8 +581,8 @@ class InterfaceProtocol(object): INTERFACE_PROTOCOL_FAMILY_IPV4 = "ipv4" INTERFACE_PROTOCOL_FAMILY_IPV6 = "ipv6" - INTERFACE_PROTOCOL_FAMILIES = [ INTERFACE_PROTOCOL_FAMILY_IPV4, - INTERFACE_PROTOCOL_FAMILY_IPV6 ] + INTERFACE_PROTOCOL_FAMILIES = [INTERFACE_PROTOCOL_FAMILY_IPV4, + INTERFACE_PROTOCOL_FAMILY_IPV6] @staticmethod def protocol_class_for_family(family): @@ -614,6 +617,7 @@ class InterfaceProtocol(object): return xml + class InterfaceProtocolIP(InterfaceProtocol): def __init__(self, family): @@ -677,6 +681,7 @@ class InterfaceProtocolIP(InterfaceProtocol): return xml + class InterfaceProtocolIPv4(InterfaceProtocolIP): def __init__(self): InterfaceProtocolIP.__init__(self, self.INTERFACE_PROTOCOL_FAMILY_IPV4) @@ -684,6 +689,7 @@ class InterfaceProtocolIPv4(InterfaceProtocolIP): def _get_protocol_xml(self): return self._get_ip_xml() + class InterfaceProtocolIPv6(InterfaceProtocolIP): def __init__(self): InterfaceProtocolIP.__init__(self, self.INTERFACE_PROTOCOL_FAMILY_IPV6) @@ -706,6 +712,7 @@ class InterfaceProtocolIPv6(InterfaceProtocolIP): xml += self._get_ip_xml() return xml + class InterfaceProtocolIPAddress(object): def __init__(self, address, prefix=None): self._address = address diff --git a/virtinst/LiveCDInstaller.py b/virtinst/LiveCDInstaller.py index 1a848d20..195e86d0 100644 --- a/virtinst/LiveCDInstaller.py +++ b/virtinst/LiveCDInstaller.py @@ -27,6 +27,7 @@ class LiveCDInstallerException(Exception): def __init__(self, msg): Exception.__init__(self, msg) + class LiveCDInstaller(Installer.Installer): # LiveCD specific methods/overwrites diff --git a/virtinst/NodeDeviceParser.py b/virtinst/NodeDeviceParser.py index b47826ee..63ef7e2f 100644 --- a/virtinst/NodeDeviceParser.py +++ b/virtinst/NodeDeviceParser.py @@ -33,6 +33,7 @@ CAPABILITY_TYPE_STORAGE = "storage" CAPABILITY_TYPE_SCSIBUS = "scsi_host" CAPABILITY_TYPE_SCSIDEV = "scsi" + class NodeDevice(object): def __init__(self, node): self.name = None @@ -84,6 +85,7 @@ class NodeDevice(object): self._parseValueHelper(node, value_map) node = node.next + class SystemDevice(NodeDevice): def __init__(self, node): NodeDevice.__init__(self, node) @@ -125,6 +127,7 @@ class SystemDevice(NodeDevice): return desc + class NetDevice(NodeDevice): def __init__(self, node): NodeDevice.__init__(self, node) @@ -136,8 +139,8 @@ class NetDevice(NodeDevice): self.parseXML(self._getCapabilityNode(node)) def parseXML(self, node): - value_map = { "interface" : "interface", - "address" : "address", } + value_map = {"interface" : "interface", + "address" : "address"} child = node.children while child: if child.name == "capability": @@ -154,6 +157,7 @@ class NetDevice(NodeDevice): return desc + class PCIDevice(NodeDevice): def __init__(self, node): NodeDevice.__init__(self, node) @@ -171,10 +175,10 @@ class PCIDevice(NodeDevice): self.parseXML(self._getCapabilityNode(node)) def parseXML(self, node): - val_map = { "domain" : "domain", + val_map = {"domain" : "domain", "bus" : "bus", "slot" : "slot", - "function" : "function" } + "function" : "function"} child = node.children while child: if child.name == "vendor": @@ -201,6 +205,7 @@ class PCIDevice(NodeDevice): desc = "%s %s" % (devstr, str(self.product_name)) return desc + class USBDevice(NodeDevice): def __init__(self, node): NodeDevice.__init__(self, node) @@ -216,7 +221,7 @@ class USBDevice(NodeDevice): self.parseXML(self._getCapabilityNode(node)) def parseXML(self, node): - val_map = { "bus": "bus", "device": "device"} + val_map = {"bus": "bus", "device": "device"} child = node.children while child: if child.name == "vendor": @@ -239,6 +244,7 @@ class USBDevice(NodeDevice): str(self.product_name)) return desc + class StorageDevice(NodeDevice): def __init__(self, node): NodeDevice.__init__(self, node) @@ -262,7 +268,7 @@ class StorageDevice(NodeDevice): self.parseXML(self._getCapabilityNode(node)) def parseXML(self, node): - val_map = { "block" : "block", + val_map = {"block" : "block", "bus" : "bus", "drive_type" : "drive_type", "model" : "model", @@ -306,6 +312,7 @@ class StorageDevice(NodeDevice): desc = ": ".join((desc, self.name)) return desc + class USBBus(NodeDevice): def __init__(self, node): NodeDevice.__init__(self, node) @@ -318,10 +325,10 @@ class USBBus(NodeDevice): self.parseXML(self._getCapabilityNode(node)) def parseXML(self, node): - val_map = { "number" : "number", + val_map = {"number" : "number", "class" : "classval", "subclass" : "subclass", - "protocol" : "protocol" } + "protocol" : "protocol"} self._parseHelper(node, val_map) @@ -338,13 +345,14 @@ class SCSIDevice(NodeDevice): self.parseXML(self._getCapabilityNode(node)) def parseXML(self, node): - val_map = { "host" : "host", + val_map = {"host" : "host", "bus" : "bus", "target": "target", "lun" : "lun", "type" : "type"} self._parseHelper(node, val_map) + class SCSIBus(NodeDevice): def __init__(self, node): NodeDevice.__init__(self, node) @@ -360,7 +368,7 @@ class SCSIBus(NodeDevice): self.parseXML(self._getCapabilityNode(node)) def parseXML(self, node): - val_map = { "host" : "host" } + val_map = {"host" : "host"} child = node.children while child: @@ -383,6 +391,7 @@ class SCSIBus(NodeDevice): child = child.next + def is_nodedev_capable(conn): """ Check if the passed libvirt connection supports host device routines @@ -394,6 +403,7 @@ def is_nodedev_capable(conn): """ return support.check_conn_support(conn, support.SUPPORT_CONN_NODEDEV) + def is_pci_detach_capable(conn): """ Check if the passed libvirt connection support pci device Detach/Reset @@ -406,11 +416,13 @@ def is_pci_detach_capable(conn): return support.check_conn_support(conn, support.SUPPORT_NODEDEV_PCI_DETACH) + def _lookupNodeName(conn, name): nodedev = conn.nodeDeviceLookupByName(name) xml = nodedev.XMLDesc(0) return parse(xml) + def lookupNodeName(conn, name): """ Convert the passed libvirt node device name to a NodeDevice @@ -437,6 +449,7 @@ def lookupNodeName(conn, name): return devAddressToNodedev(conn, name) + def _isAddressStr(addrstr): cmp_func = None @@ -491,6 +504,7 @@ def _isAddressStr(addrstr): return cmp_func, devtype + def devAddressToNodedev(conn, addrstr): """ Look up the passed host device address string as a libvirt node device, @@ -523,6 +537,7 @@ def devAddressToNodedev(conn, addrstr): raise ValueError(_("Did not find a matching node device for '%s'") % addrstr) + def parse(xml): """ Convert the passed libvirt node device xml into a NodeDevice object @@ -540,6 +555,7 @@ def parse(xml): return util.parse_node_helper(xml, "device", _parse_func) + def _findNodeType(node): child = node.children while child: @@ -548,6 +564,7 @@ def _findNodeType(node): child = child.next return None + def _typeToDeviceClass(t): if t == CAPABILITY_TYPE_SYSTEM: return SystemDevice diff --git a/virtinst/OSDistro.py b/virtinst/OSDistro.py index cb0b9a57..d5fc3f05 100644 --- a/virtinst/OSDistro.py +++ b/virtinst/OSDistro.py @@ -36,6 +36,7 @@ from virtinst.ImageFetcher import FTPImageFetcher from virtinst.ImageFetcher import HTTPImageFetcher from virtinst.ImageFetcher import DirectImageFetcher + def safeint(c): try: val = int(c) @@ -43,6 +44,7 @@ def safeint(c): val = 0 return val + def _fetcherForURI(uri, scratchdir=None): if uri.startswith("http://"): fclass = HTTPImageFetcher @@ -57,6 +59,7 @@ def _fetcherForURI(uri, scratchdir=None): fclass = MountedImageFetcher return fclass(uri, scratchdir) + def _storeForDistro(fetcher, baseuri, typ, progresscb, arch, distro=None, scratchdir=None): stores = [] @@ -112,6 +115,7 @@ def _storeForDistro(fetcher, baseuri, typ, progresscb, arch, distro=None, "The location must be the root directory of an install tree." % baseuri)) + def _locationCheckWrapper(guest, baseuri, progresscb, scratchdir, _type, arch, callback): fetcher = _fetcherForURI(baseuri, scratchdir) @@ -133,6 +137,7 @@ def _locationCheckWrapper(guest, baseuri, progresscb, finally: fetcher.cleanupLocation() + def _acquireMedia(iskernel, guest, baseuri, progresscb, scratchdir="/var/tmp", _type=None): @@ -151,25 +156,33 @@ def _acquireMedia(iskernel, guest, baseuri, progresscb, None, media_cb) # Helper method to lookup install media distro and fetch an install kernel + + def getKernel(guest, baseuri, progresscb, scratchdir, typ): iskernel = True return _acquireMedia(iskernel, guest, baseuri, progresscb, scratchdir, typ) # Helper method to lookup install media distro and fetch a boot iso + + def getBootDisk(guest, baseuri, progresscb, scratchdir): iskernel = False return _acquireMedia(iskernel, guest, baseuri, progresscb, scratchdir) + def _check_ostype_valid(os_type): return bool(os_type in osdict.sort_helper(osdict.OS_TYPES)) + def _check_osvariant_valid(os_type, os_variant): return bool(_check_ostype_valid(os_type) and os_variant in osdict.sort_helper(osdict.OS_TYPES[os_type]["variants"])) # Attempt to detect the os type + variant for the passed location + + def detectMediaDistro(location, arch): import urlgrabber progresscb = urlgrabber.progress.BaseMeter() @@ -272,8 +285,8 @@ class Distro: if not kernelpath or not initrdpath: raise RuntimeError(_("Couldn't find %(type)s kernel for " - "%(distro)s tree.") % \ - { "distro": self.name, "type" : self.type }) + "%(distro)s tree.") % + {"distro": self.name, "type" : self.type}) return self._kernelFetchHelper(fetcher, guest, progresscb, kernelpath, initrdpath) @@ -288,7 +301,7 @@ class Distro: for path in self._boot_iso_paths: if fetcher.hasFile(path): return fetcher.acquireFile(path, progresscb) - raise RuntimeError(_("Could not find boot.iso in %s tree." % \ + raise RuntimeError(_("Could not find boot.iso in %s tree." % self.name)) def get_osdict_info(self): @@ -395,17 +408,17 @@ class GenericDistro(Distro): os_type = "linux" uses_treeinfo = True - _xen_paths = [ ("images/xen/vmlinuz", + _xen_paths = [("images/xen/vmlinuz", "images/xen/initrd.img"), # Fedora - ] - _hvm_paths = [ ("images/pxeboot/vmlinuz", + ] + _hvm_paths = [("images/pxeboot/vmlinuz", "images/pxeboot/initrd.img"), # Fedora - ] - _iso_paths = [ "images/boot.iso", # RH/Fedora + ] + _iso_paths = ["images/boot.iso", # RH/Fedora "boot/boot.iso", # Suse "current/images/netboot/mini.iso", # Debian "install/images/boot.iso", # Mandriva - ] + ] # Holds values to use when actually pulling down media _valid_kernel_path = None @@ -435,12 +448,12 @@ class GenericDistro(Distro): # If validated media paths weren't found (no treeinfo), check against # list of media location paths. for kern, init in kern_list: - if self._valid_kernel_path == None \ + if self._valid_kernel_path is None \ and fetcher.hasFile(kern) and fetcher.hasFile(init): self._valid_kernel_path = (kern, init) break for iso in self._iso_paths: - if self._valid_iso_path == None \ + if self._valid_iso_path is None \ and fetcher.hasFile(iso): self._valid_iso_path = iso break @@ -450,7 +463,7 @@ class GenericDistro(Distro): return False def acquireKernel(self, guest, fetcher, progresscb): - if self._valid_kernel_path == None: + if self._valid_kernel_path is None: raise ValueError(_("Could not find a kernel path for virt type " "'%s'" % self.type)) @@ -459,7 +472,7 @@ class GenericDistro(Distro): self._valid_kernel_path[1]) def acquireBootDisk(self, guest, fetcher, progresscb): - if self._valid_iso_path == None: + if self._valid_iso_path is None: raise ValueError(_("Could not find a boot iso path for this tree.")) return fetcher.acquireFile(self._valid_iso_path, progresscb) @@ -473,11 +486,11 @@ class RedHatDistro(Distro): os_type = "linux" uses_treeinfo = True - _boot_iso_paths = [ "images/boot.iso" ] - _hvm_kernel_paths = [ ("images/pxeboot/vmlinuz", - "images/pxeboot/initrd.img") ] - _xen_kernel_paths = [ ("images/xen/vmlinuz", - "images/xen/initrd.img") ] + _boot_iso_paths = ["images/boot.iso"] + _hvm_kernel_paths = [("images/pxeboot/vmlinuz", + "images/pxeboot/initrd.img")] + _xen_kernel_paths = [("images/xen/vmlinuz", + "images/xen/initrd.img")] def isValidStore(self, fetcher, progresscb): raise NotImplementedError @@ -491,7 +504,7 @@ class FedoraDistro(RedHatDistro): def isValidStore(self, fetcher, progresscb): if self._hasTreeinfo(fetcher, progresscb): m = re.match(".*Fedora.*", self.treeinfo.get("general", "family")) - ret = (m != None) + ret = (m is not None) if ret: lateststr, latestnum = self._latestFedoraVariant() @@ -524,6 +537,8 @@ class FedoraDistro(RedHatDistro): return ret, int(ret[6:]) # Red Hat Enterprise Linux distro check + + class RHELDistro(RedHatDistro): name = "Red Hat Enterprise Linux" @@ -532,7 +547,7 @@ class RHELDistro(RedHatDistro): if self._hasTreeinfo(fetcher, progresscb): m = re.match(".*Red Hat Enterprise Linux.*", self.treeinfo.get("general", "family")) - ret = (m != None) + ret = (m is not None) if ret: self._variantFromVersion() @@ -610,7 +625,7 @@ class CentOSDistro(RHELDistro): def isValidStore(self, fetcher, progresscb): if self._hasTreeinfo(fetcher, progresscb): m = re.match(".*CentOS.*", self.treeinfo.get("general", "family")) - ret = (m != None) + ret = (m is not None) if ret: self._variantFromVersion() @@ -623,20 +638,22 @@ class CentOSDistro(RHELDistro): return False # Scientific Linux distro check + + class SLDistro(RHELDistro): name = "Scientific Linux" - _boot_iso_paths = RHELDistro._boot_iso_paths + [ "images/SL/boot.iso" ] + _boot_iso_paths = RHELDistro._boot_iso_paths + ["images/SL/boot.iso"] _hvm_kernel_paths = RHELDistro._hvm_kernel_paths + \ - [ ("images/SL/pxeboot/vmlinuz", - "images/SL/pxeboot/initrd.img") ] + [("images/SL/pxeboot/vmlinuz", + "images/SL/pxeboot/initrd.img")] def isValidStore(self, fetcher, progresscb): if self._hasTreeinfo(fetcher, progresscb): m = re.match(".*Scientific Linux.*", self.treeinfo.get("general", "family")) - ret = (m != None) + ret = (m is not None) if ret: self._variantFromVersion() @@ -666,7 +683,7 @@ class SuseDistro(Distro): name = "SUSE" os_type = "linux" method_arg = "install" - _boot_iso_paths = [ "boot/boot.iso" ] + _boot_iso_paths = ["boot/boot.iso"] def __init__(self, uri, arch, vmtype=None, scratchdir=None): Distro.__init__(self, uri, arch, vmtype, scratchdir) @@ -680,15 +697,15 @@ class SuseDistro(Distro): oldinit += "64" # Tested with Opensuse >= 10.2, 11, and sles 10 - self._hvm_kernel_paths = [ ("boot/%s/loader/linux" % self.arch, - "boot/%s/loader/initrd" % self.arch) ] + self._hvm_kernel_paths = [("boot/%s/loader/linux" % self.arch, + "boot/%s/loader/initrd" % self.arch)] # Tested with Opensuse 10.0 self._hvm_kernel_paths.append(("boot/loader/%s" % oldkern, "boot/loader/%s" % oldinit)) # Matches Opensuse > 10.2 and sles 10 - self._xen_kernel_paths = [ ("boot/%s/vmlinuz-xen" % self.arch, - "boot/%s/initrd-xen" % self.arch) ] + self._xen_kernel_paths = [("boot/%s/vmlinuz-xen" % self.arch, + "boot/%s/initrd-xen" % self.arch)] def isValidStore(self, fetcher, progresscb): # Suse distros always have a 'directory.yast' file in the top @@ -873,7 +890,7 @@ class SuseDistro(Distro): progresscb.update(9) # Add the extra modules to the basic initrd - cmd = "cd " + cpiodir + "/initrd && ( find . | cpio --quiet -o -H newc -A -F " + cpiodir + "/initrd.img)" + cmd = "cd " + cpiodir + "/initrd && (find . | cpio --quiet -o -H newc -A -F " + cpiodir + "/initrd.img)" logging.debug("Running " + cmd) os.system(cmd) progresscb.update(10) @@ -894,7 +911,7 @@ class SuseDistro(Distro): except: os.unlink(initrdname) finally: - #pass + # pass os.system("rm -rf " + cpiodir) @@ -923,14 +940,14 @@ class DebianDistro(Distro): def _set_media_paths(self): # Use self._prefix to set media paths - self._boot_iso_paths = [ "%s/netboot/mini.iso" % self._prefix ] + self._boot_iso_paths = ["%s/netboot/mini.iso" % self._prefix] hvmroot = "%s/netboot/%s/%s/" % (self._prefix, self._installer_name, self._treeArch) xenroot = "%s/netboot/xen/" % self._prefix - self._hvm_kernel_paths = [ (hvmroot + "linux", hvmroot + "initrd.gz") ] - self._xen_kernel_paths = [ (xenroot + "vmlinuz", - xenroot + "initrd.gz") ] + self._hvm_kernel_paths = [(hvmroot + "linux", hvmroot + "initrd.gz")] + self._xen_kernel_paths = [(xenroot + "vmlinuz", + xenroot + "initrd.gz")] def isValidStore(self, fetcher, progresscb): if fetcher.hasFile("%s/MANIFEST" % self._prefix): @@ -987,9 +1004,9 @@ class MandrivaDistro(Distro): name = "Mandriva" os_type = "linux" - _boot_iso_paths = [ "install/images/boot.iso" ] + _boot_iso_paths = ["install/images/boot.iso"] # Kernels for HVM: valid for releases 2007.1, 2008.*, 2009.0 - _hvm_kernel_paths = [ ("isolinux/alt0/vmlinuz", "isolinux/alt0/all.rdz")] + _hvm_kernel_paths = [("isolinux/alt0/vmlinuz", "isolinux/alt0/all.rdz")] _xen_kernel_paths = [] def isValidStore(self, fetcher, progresscb): @@ -1010,10 +1027,13 @@ class MandrivaDistro(Distro): return False + class MageiaDistro(MandrivaDistro): name = "Mageia" # Solaris and OpenSolaris distros + + class SunDistro(Distro): name = "Solaris" @@ -1069,6 +1089,7 @@ class SunDistro(Distro): return kopts, kargs, smfargs, Bargs + class SolarisDistro(SunDistro): kernelpath = 'boot/platform/i86xpv/kernel/unix' initrdpath = 'boot/x86.miniroot' @@ -1088,11 +1109,11 @@ class SolarisDistro(SunDistro): (kopts, kargs, ignore_smfargs, kbargs) = \ self.process_extra_args(guest.extraargs) - args = [ '' ] + args = [''] if kopts: - args += [ '-%s' % kopts ] + args += ['-%s' % kopts] if kbargs: - args += [ '-B', kbargs ] + args += ['-B', kbargs] netmask = '' # Yuck. Non-default netmasks require this option to be passed. @@ -1103,7 +1124,7 @@ class SolarisDistro(SunDistro): if karg.startswith('subnet-mask'): netmask = karg.split('=')[1] else: - args += [ kargs ] + args += [kargs] iargs = '' if not guest.graphics['enabled']: @@ -1136,7 +1157,7 @@ class SolarisDistro(SunDistro): else: iargs += '-B install_media=cdrom' - args += [ '-', iargs ] + args += ['-', iargs] return ' '.join(args) def acquireKernel(self, guest, fetcher, progresscb): @@ -1159,12 +1180,13 @@ class SolarisDistro(SunDistro): raise RuntimeError(_("Solaris miniroot not found at %s") % self.initrdpath) + class OpenSolarisDistro(SunDistro): os_variant = "opensolaris" kernelpath = "platform/i86xpv/kernel/unix" - initrdpaths = [ "platform/i86pc/boot_archive", "boot/x86.microroot" ] + initrdpaths = ["platform/i86pc/boot_archive", "boot/x86.microroot"] def isValidStore(self, fetcher, progresscb): if fetcher.hasFile(self.kernelpath): diff --git a/virtinst/PXEInstaller.py b/virtinst/PXEInstaller.py index fdd231d5..cef2629b 100644 --- a/virtinst/PXEInstaller.py +++ b/virtinst/PXEInstaller.py @@ -19,6 +19,7 @@ from virtinst import Installer + class PXEInstaller(Installer.Installer): # General Installer methods diff --git a/virtinst/Seclabel.py b/virtinst/Seclabel.py index f062c18d..52a1b1c5 100644 --- a/virtinst/Seclabel.py +++ b/virtinst/Seclabel.py @@ -20,6 +20,7 @@ from virtinst import XMLBuilderDomain from virtinst.XMLBuilderDomain import _xml_property + class Seclabel(XMLBuilderDomain.XMLBuilderDomain): """ Class for generating XML @@ -36,9 +37,9 @@ class Seclabel(XMLBuilderDomain.XMLBuilderDomain): SECLABEL_MODEL_SELINUX = "selinux" SECLABEL_MODEL_DAC = "dac" SECLABEL_MODEL_NONE = "none" - SECLABEL_MODELS = [ SECLABEL_MODEL_SELINUX, + SECLABEL_MODELS = [SECLABEL_MODEL_SELINUX, SECLABEL_MODEL_DAC, - SECLABEL_MODEL_NONE ] + SECLABEL_MODEL_NONE] _dumpxml_xpath = "/domain/seclabel" def __init__(self, conn, parsexml=None, parsexmlnode=None, caps=None): diff --git a/virtinst/Storage.py b/virtinst/Storage.py index 8285ede2..54ee6312 100644 --- a/virtinst/Storage.py +++ b/virtinst/Storage.py @@ -68,10 +68,12 @@ DEFAULT_MPATH_TARGET = "/dev/mapper" VIR_STORAGE_VOL_FILE = 0 VIR_STORAGE_VOL_BLOCK = 1 + def is_create_vol_from_supported(conn): return support.check_pool_support(conn, support.SUPPORT_STORAGE_CREATEVOLFROM) + def _parse_pool_source_list(source_xml): def source_parser(node): ret_list = [] @@ -108,6 +110,7 @@ def _parse_pool_source_list(source_xml): return util.parse_node_helper(source_xml, "sources", source_parser) + class StorageObject(object): """ Base class for building any libvirt storage object. @@ -179,7 +182,7 @@ class StorageObject(object): # Validation helper functions def _validate_path(self, path): - if type(path) is not type("str") or not path.startswith("/"): + if not isinstance(path, str) or not path.startswith("/"): raise ValueError(_("'%s' is not an absolute path." % path)) def _check_name_collision(self, name): @@ -224,7 +227,7 @@ class StorageObject(object): xml = "%s" % (root_xml) + \ """ %s\n""" % (self.name) + \ - """%(stor_xml)s""" % { "stor_xml" : self._get_storage_xml() } + \ + """%(stor_xml)s""" % {"stor_xml" : self._get_storage_xml()} + \ """\n""" % (self.object_type) return xml @@ -398,7 +401,7 @@ class StoragePool(StorageObject): def get_host(self): return self._host def set_host(self, val): - if type(val) is not type("str"): + if not isinstance(val, str): raise ValueError(_("Host name must be a string")) self._host = val @@ -525,6 +528,7 @@ class DirectoryPool(StoragePool): def _get_source_xml(self): return "" + class FilesystemPool(StoragePool): """ Create a formatted partition based storage pool @@ -534,8 +538,8 @@ class FilesystemPool(StoragePool): return FileVolume get_volume_class = staticmethod(get_volume_class) - formats = [ "auto", "ext2", "ext3", "ext4", "ufs", "iso9660", "udf", - "gfs", "gfs2", "vfat", "hfs+", "xfs" ] + formats = ["auto", "ext2", "ext3", "ext4", "ufs", "iso9660", "udf", + "gfs", "gfs2", "vfat", "hfs+", "xfs"] # Register applicable property methods from parent class perms = property(StorageObject.get_perms, StorageObject.set_perms) @@ -586,6 +590,7 @@ class FilesystemPool(StoragePool): " \n" % escape(self.source_path) return xml + class NetworkFilesystemPool(StoragePool): """ Create a network mounted filesystem storage pool @@ -595,7 +600,7 @@ class NetworkFilesystemPool(StoragePool): return FileVolume get_volume_class = staticmethod(get_volume_class) - formats = [ "auto", "nfs", "glusterfs"] + formats = ["auto", "nfs", "glusterfs"] # Register applicable property methods from parent class source_path = property(StoragePool.get_source_path, @@ -649,6 +654,7 @@ class NetworkFilesystemPool(StoragePool): """ \n""" % escape(self.source_path) return xml + class LogicalPool(StoragePool): """ Create a logical (lvm volume group) storage pool @@ -750,6 +756,7 @@ class LogicalPool(StoragePool): return StoragePool.install(self, meter=meter, create=create, build=build, autostart=autostart) + class DiskPool(StoragePool): """ Create a storage pool from a physical disk @@ -767,7 +774,7 @@ class DiskPool(StoragePool): doc=_("Root location for identifying new storage" " volumes.")) - formats = [ "auto", "bsd", "dos", "dvh", "gpt", "mac", "pc98", "sun" ] + formats = ["auto", "bsd", "dos", "dvh", "gpt", "mac", "pc98", "sun"] def __init__(self, conn, name, source_path=None, target_path=None, format="auto", uuid=None): @@ -815,6 +822,7 @@ class DiskPool(StoragePool): return StoragePool.install(self, meter=meter, create=create, build=build, autostart=autostart) + class iSCSIPool(StoragePool): """ Create an iSCSI based storage pool @@ -884,6 +892,7 @@ class iSCSIPool(StoragePool): return xml + class SCSIPool(StoragePool): """ Create a SCSI based storage pool @@ -928,6 +937,7 @@ class SCSIPool(StoragePool): xml = """ \n""" % escape(self.source_path) return xml + class MultipathPool(StoragePool): """ Create a Multipath based storage pool @@ -992,7 +1002,7 @@ class StorageVolume(StorageObject): conn=conn) self._pool = None self.pool = pool - poolconn = self.pool._conn # pylint: disable=W0212 + poolconn = self.pool._conn # pylint: disable=W0212 StorageObject.__init__(self, object_type=StorageObject.TYPE_VOLUME, name=name, conn=poolconn) @@ -1068,7 +1078,7 @@ class StorageVolume(StorageObject): try: pool_object = conn.storagePoolLookupByName(pool_name) except Exception, e: - raise ValueError(_("Couldn't find storage pool '%s': %s" % \ + raise ValueError(_("Couldn't find storage pool '%s': %s" % (pool_name, str(e)))) if not isinstance(pool_object, libvirt.virStoragePool): @@ -1091,7 +1101,7 @@ class StorageVolume(StorageObject): origcap = self.capacity origall = self.allocation self._capacity = newcap - if self.allocation != None and (newcap < self.allocation): + if self.allocation is not None and (newcap < self.allocation): self._allocation = newcap ret = self.is_size_conflict() @@ -1109,7 +1119,7 @@ class StorageVolume(StorageObject): if type(val) not in (int, float, long) or val < 0: raise ValueError(_("Allocation must be a non-negative number")) newall = int(val) - if self.capacity != None and newall > self.capacity: + if self.capacity is not None and newall > self.capacity: logging.debug("Capping allocation at capacity.") newall = self.capacity origall = self._allocation @@ -1143,7 +1153,7 @@ class StorageVolume(StorageObject): if not isinstance(vol, libvirt.virStorageVol): raise ValueError(_("input_vol must be a virStorageVol")) - poolconn = self.pool._conn # pylint: disable=W0212 + poolconn = self.pool._conn # pylint: disable=W0212 if not is_create_vol_from_supported(poolconn): raise ValueError(_("Creating storage from an existing volume is" " not supported by this libvirt version.")) @@ -1196,10 +1206,10 @@ class StorageVolume(StorageObject): tar_xml = " \n" + \ "%s" % (self._get_target_xml()) + \ " \n" - return " %d\n" % self.capacity + \ - " %d\n" % self.allocation + \ - "%s" % src_xml + \ - "%s" % tar_xml + return " %d\n" % self.capacity + \ + " %d\n" % self.allocation + \ + "%s" % src_xml + \ + "%s" % tar_xml def install(self, meter=None): """ @@ -1264,7 +1274,7 @@ class StorageVolume(StorageObject): continue break - if vol == None: + if vol is None: logging.debug("Couldn't lookup storage volume in prog thread.") return @@ -1283,23 +1293,24 @@ class StorageVolume(StorageObject): 2. String message if some collision was encountered. @rtype: 2 element C{tuple}: (C{bool}, C{str}) """ - # pool info is [ pool state, capacity, allocation, available ] + # pool info is [pool state, capacity, allocation, available] avail = self.pool.info()[3] if self.allocation > avail: return (True, _("There is not enough free space on the storage " "pool to create the volume. " - "(%d M requested allocation > %d M available)" % \ + "(%d M requested allocation > %d M available)" % ((self.allocation / (1024 * 1024)), (avail / (1024 * 1024))))) elif self.capacity > avail: return (False, _("The requested volume capacity will exceed the " "available pool space when the volume is fully " "allocated. " - "(%d M requested capacity > %d M available)" % \ + "(%d M requested capacity > %d M available)" % ((self.capacity / (1024 * 1024)), (avail / (1024 * 1024))))) return (False, "") + class FileVolume(StorageVolume): """ Build and install xml for use on pools which use file based storage @@ -1333,6 +1344,7 @@ class FileVolume(StorageVolume): def _get_source_xml(self): return "" + class DiskVolume(StorageVolume): """ Build and install xml volumes for use on physical disk pools @@ -1356,6 +1368,7 @@ class DiskVolume(StorageVolume): def _get_source_xml(self): return "" + class LogicalVolume(StorageVolume): """ Build and install logical volumes for lvm pools @@ -1395,6 +1408,7 @@ class LogicalVolume(StorageVolume): def _get_source_xml(self): return "" + class CloneVolume(StorageVolume): """ Build and install a volume that is a clone of an existing volume @@ -1433,7 +1447,7 @@ class CloneVolume(StorageVolume): newxml = util.set_xml_path(xml, "/volume/name", self.name) return newxml -#class iSCSIVolume(StorageVolume): +# class iSCSIVolume(StorageVolume): # """ # Build and install xml for use on iSCSI device pools # """ diff --git a/virtinst/User.py b/virtinst/User.py index ae5b02ed..d71c0c4e 100644 --- a/virtinst/User.py +++ b/virtinst/User.py @@ -32,8 +32,8 @@ class User(object): PRIV_CREATE_DOMAIN = 4 PRIV_CREATE_NETWORK = 5 - _privs = [ PRIV_CLONE, PRIV_NFS_MOUNT, PRIV_QEMU_SYSTEM, - PRIV_CREATE_DOMAIN, PRIV_CREATE_NETWORK ] + _privs = [PRIV_CLONE, PRIV_NFS_MOUNT, PRIV_QEMU_SYSTEM, + PRIV_CREATE_DOMAIN, PRIV_CREATE_NETWORK] def __init__(self, euid): self._euid = euid @@ -68,11 +68,11 @@ class User(object): if self._euid != User.current().euid: return self._euid == 0 - import ucred # pylint: disable=F0401 + import ucred # pylint: disable=F0401 cred = ucred.get(os.getpid()) - if priv in [ self.PRIV_CLONE, + if priv in [self.PRIV_CLONE, self.PRIV_CREATE_DOMAIN, - self.PRIV_CREATE_NETWORK ]: + self.PRIV_CREATE_NETWORK]: return cred.has_priv('Effective', 'virt_manage') if priv == self.PRIV_NFS_MOUNT: return (cred.has_priv('Effective', 'sys_mount') and diff --git a/virtinst/VirtualAudio.py b/virtinst/VirtualAudio.py index 04541865..36355e26 100644 --- a/virtinst/VirtualAudio.py +++ b/virtinst/VirtualAudio.py @@ -20,12 +20,13 @@ from virtinst.VirtualDevice import VirtualDevice from virtinst.XMLBuilderDomain import _xml_property + class VirtualAudio(VirtualDevice): _virtual_device_type = VirtualDevice.VIRTUAL_DEV_AUDIO MODEL_DEFAULT = "default" - MODELS = [ "es1370", "sb16", "pcspk", "ac97", "ich6", MODEL_DEFAULT ] + MODELS = ["es1370", "sb16", "pcspk", "ac97", "ich6", MODEL_DEFAULT] def __init__(self, model=None, conn=None, parsexml=None, parsexmlnode=None, caps=None): @@ -36,7 +37,7 @@ class VirtualAudio(VirtualDevice): if self._is_parse(): return - if model == None: + if model is None: model = self.MODEL_DEFAULT self.model = model diff --git a/virtinst/VirtualCharDevice.py b/virtinst/VirtualCharDevice.py index 98a17b53..7de6a8bb 100644 --- a/virtinst/VirtualCharDevice.py +++ b/virtinst/VirtualCharDevice.py @@ -18,10 +18,11 @@ # MA 02110-1301 USA. from virtinst.VirtualDevice import VirtualDevice -from virtinst.util import xml_escape +from virtinst.util import xml_escape from virtinst.XMLBuilderDomain import _xml_property + class VirtualCharDevice(VirtualDevice): """ Base class for all character devices. Shouldn't be instantiated @@ -32,7 +33,7 @@ class VirtualCharDevice(VirtualDevice): DEV_PARALLEL = "parallel" DEV_CONSOLE = "console" DEV_CHANNEL = "channel" - dev_types = [ DEV_SERIAL, DEV_PARALLEL, DEV_CONSOLE, DEV_CHANNEL] + dev_types = [DEV_SERIAL, DEV_PARALLEL, DEV_CONSOLE, DEV_CHANNEL] CHAR_PTY = "pty" CHAR_DEV = "dev" @@ -45,9 +46,9 @@ class VirtualCharDevice(VirtualDevice): CHAR_UDP = "udp" CHAR_UNIX = "unix" CHAR_SPICEVMC = "spicevmc" - char_types = [ CHAR_PTY, CHAR_DEV, CHAR_STDIO, CHAR_FILE, CHAR_VC, + char_types = [CHAR_PTY, CHAR_DEV, CHAR_STDIO, CHAR_FILE, CHAR_VC, CHAR_PIPE, CHAR_NULL, CHAR_TCP, CHAR_UDP, CHAR_UNIX, - CHAR_SPICEVMC ] + CHAR_SPICEVMC] _non_channel_types = char_types[:] _non_channel_types.remove(CHAR_SPICEVMC) @@ -56,24 +57,24 @@ class VirtualCharDevice(VirtualDevice): DEV_SERIAL: _non_channel_types, DEV_PARALLEL: _non_channel_types, DEV_CONSOLE: _non_channel_types, - DEV_CHANNEL: [ CHAR_SPICEVMC ], - } + DEV_CHANNEL: [CHAR_SPICEVMC], + } CHAR_MODE_CONNECT = "connect" CHAR_MODE_BIND = "bind" - char_modes = [ CHAR_MODE_CONNECT, CHAR_MODE_BIND ] + char_modes = [CHAR_MODE_CONNECT, CHAR_MODE_BIND] CHAR_PROTOCOL_RAW = "raw" CHAR_PROTOCOL_TELNET = "telnet" - char_protocols = [ CHAR_PROTOCOL_RAW, CHAR_PROTOCOL_TELNET ] + char_protocols = [CHAR_PROTOCOL_RAW, CHAR_PROTOCOL_TELNET] CHAR_CHANNEL_TARGET_GUESTFWD = "guestfwd" CHAR_CHANNEL_TARGET_VIRTIO = "virtio" - target_types = [ CHAR_CHANNEL_TARGET_GUESTFWD, - CHAR_CHANNEL_TARGET_VIRTIO ] + target_types = [CHAR_CHANNEL_TARGET_GUESTFWD, + CHAR_CHANNEL_TARGET_VIRTIO] CHAR_CHANNEL_ADDRESS_VIRTIO_SERIAL = "virtio-serial" - address_types = [ CHAR_CHANNEL_ADDRESS_VIRTIO_SERIAL ] + address_types = [CHAR_CHANNEL_ADDRESS_VIRTIO_SERIAL] CHAR_CONSOLE_TARGET_SERIAL = "serial" CHAR_CONSOLE_TARGET_UML = "uml" @@ -222,14 +223,14 @@ class VirtualCharDevice(VirtualDevice): "protocol" : [self.CHAR_TCP], "bind_host" : [self.CHAR_UDP], "bind_port" : [self.CHAR_UDP], - } + } if ro: users["source_path"] += [self.CHAR_PTY] channel_users = { "target_name" : [self.CHAR_CHANNEL_TARGET_VIRTIO], - } + } if users.get(propname): return self.char_type in users[propname] @@ -469,6 +470,8 @@ class VirtualCharDevice(VirtualDevice): return xml # Back compat class for building a simple PTY 'console' element + + class VirtualConsoleDevice(VirtualCharDevice): _char_xml = VirtualCharDevice._char_empty_xml _char_type = VirtualCharDevice.CHAR_PTY @@ -484,34 +487,46 @@ class VirtualConsoleDevice(VirtualCharDevice): # Classes for each device 'type' + class VirtualCharPtyDevice(VirtualCharDevice): _char_type = VirtualCharDevice.CHAR_PTY _char_xml = VirtualCharDevice._char_empty_xml source_path = property(VirtualCharDevice.get_source_path, VirtualCharDevice.set_source_path, doc=_("PTY allocated to the guest.")) + + class VirtualCharStdioDevice(VirtualCharDevice): _char_type = VirtualCharDevice.CHAR_STDIO _char_xml = VirtualCharDevice._char_empty_xml + + class VirtualCharNullDevice(VirtualCharDevice): _char_type = VirtualCharDevice.CHAR_NULL _char_xml = VirtualCharDevice._char_empty_xml + + class VirtualCharVcDevice(VirtualCharDevice): _char_type = VirtualCharDevice.CHAR_VC _char_xml = VirtualCharDevice._char_empty_xml + class VirtualCharDevDevice(VirtualCharDevice): _char_type = VirtualCharDevice.CHAR_DEV _char_xml = VirtualCharDevice._char_file_xml source_path = property(VirtualCharDevice.get_source_path, VirtualCharDevice.set_source_path, doc=_("Host character device to attach to guest.")) + + class VirtualCharPipeDevice(VirtualCharDevice): _char_type = VirtualCharDevice.CHAR_PIPE _char_xml = VirtualCharDevice._char_file_xml source_path = property(VirtualCharDevice.get_source_path, VirtualCharDevice.set_source_path, doc=_("Named pipe to use for input and output.")) + + class VirtualCharFileDevice(VirtualCharDevice): _char_type = VirtualCharDevice.CHAR_FILE _char_xml = VirtualCharDevice._char_file_xml @@ -519,6 +534,7 @@ class VirtualCharFileDevice(VirtualCharDevice): VirtualCharDevice.set_source_path, doc=_("File path to record device output.")) + class VirtualCharUnixDevice(VirtualCharDevice): _char_type = VirtualCharDevice.CHAR_UNIX _char_xml = VirtualCharDevice._char_file_xml @@ -530,6 +546,7 @@ class VirtualCharUnixDevice(VirtualCharDevice): VirtualCharDevice.set_source_path, doc=_("Unix socket path.")) + class VirtualCharTcpDevice(VirtualCharDevice): _char_type = VirtualCharDevice.CHAR_TCP @@ -555,6 +572,7 @@ class VirtualCharTcpDevice(VirtualCharDevice): xml += " \n" % self.protocol return xml + class VirtualCharUdpDevice(VirtualCharDevice): _char_type = VirtualCharDevice.CHAR_UDP @@ -600,10 +618,11 @@ class VirtualCharUdpDevice(VirtualCharDevice): (source_host_xml, self.source_port)) return xml + class VirtualCharSpicevmcDevice(VirtualCharDevice): _char_type = VirtualCharDevice.CHAR_SPICEVMC _char_xml = VirtualCharDevice._char_empty_xml - target_types = [ VirtualCharDevice.CHAR_CHANNEL_TARGET_VIRTIO ] + target_types = [VirtualCharDevice.CHAR_CHANNEL_TARGET_VIRTIO] has_target = True def __init__(self, conn, dev_type=VirtualCharDevice.DEV_CHANNEL, diff --git a/virtinst/VirtualController.py b/virtinst/VirtualController.py index b5002ea6..44a09527 100644 --- a/virtinst/VirtualController.py +++ b/virtinst/VirtualController.py @@ -21,6 +21,7 @@ from virtinst.VirtualDevice import VirtualDevice from virtinst.XMLBuilderDomain import XMLBuilderDomain, _xml_property import logging + class VirtualController(VirtualDevice): _virtual_device_type = VirtualDevice.VIRTUAL_DEV_CONTROLLER @@ -44,7 +45,7 @@ class VirtualController(VirtualDevice): VirtualController.CONTROLLER_TYPE_SATA : "SATA", VirtualController.CONTROLLER_TYPE_VIRTIOSERIAL : "Virtio Serial", VirtualController.CONTROLLER_TYPE_USB : "USB" - } + } if ctype not in pretty_mappings: return ctype @@ -150,27 +151,32 @@ class VirtualController(VirtualDevice): class VirtualControllerIDE(VirtualController): _controller_type = VirtualController.CONTROLLER_TYPE_IDE + class VirtualControllerFDC(VirtualController): _controller_type = VirtualController.CONTROLLER_TYPE_FDC + class VirtualControllerSCSI(VirtualController): _controller_type = VirtualController.CONTROLLER_TYPE_SCSI + class VirtualControllerSATA(VirtualController): _controller_type = VirtualController.CONTROLLER_TYPE_SATA + class VirtualControllerVirtioSerial(VirtualController): _controller_type = VirtualController.CONTROLLER_TYPE_VIRTIOSERIAL def _extra_config(self): xml = "" - if self.ports != None: + if self.ports is not None: xml += " ports='%s'" % self.ports - if self.vectors != None: + if self.vectors is not None: xml += " vectors='%s'" % self.vectors return xml + class VirtualControllerUSB(VirtualController): _controller_type = VirtualController.CONTROLLER_TYPE_USB diff --git a/virtinst/VirtualDevice.py b/virtinst/VirtualDevice.py index 73f4a720..2fb2b89e 100644 --- a/virtinst/VirtualDevice.py +++ b/virtinst/VirtualDevice.py @@ -22,6 +22,7 @@ from virtinst.XMLBuilderDomain import XMLBuilderDomain, _xml_property import logging + class VirtualDevice(XMLBuilderDomain): """ Base class for all domain xml device objects. @@ -138,6 +139,7 @@ class VirtualDeviceAlias(XMLBuilderDomain): def _get_xml_config(self): return "" + class VirtualDeviceAddress(XMLBuilderDomain): ADDRESS_TYPE_PCI = "pci" diff --git a/virtinst/VirtualDisk.py b/virtinst/VirtualDisk.py index 6cc8d6df..3ce8b187 100644 --- a/virtinst/VirtualDisk.py +++ b/virtinst/VirtualDisk.py @@ -38,6 +38,7 @@ from virtinst import Storage from virtinst.VirtualDevice import VirtualDevice from virtinst.XMLBuilderDomain import _xml_property + def _vdisk_create(path, size, kind, sparse=True): force_fixed = "raw" path = os.path.expanduser(path) @@ -46,28 +47,30 @@ def _vdisk_create(path, size, kind, sparse=True): else: _type = kind + ":sparse" try: - rc = subprocess.call([ '/usr/sbin/vdiskadm', 'create', '-t', _type, - '-s', str(size), path ]) + rc = subprocess.call(['/usr/sbin/vdiskadm', 'create', '-t', _type, + '-s', str(size), path]) return rc == 0 except OSError: return False + def _vdisk_clone(path, clone): logging.debug("Using vdisk clone.") path = os.path.expanduser(path) clone = os.path.expanduser(clone) try: - rc = subprocess.call([ '/usr/sbin/vdiskadm', 'clone', path, clone ]) + rc = subprocess.call(['/usr/sbin/vdiskadm', 'clone', path, clone]) return rc == 0 except OSError: return False + def _qemu_sanitize_drvtype(phystype, fmt, manual_format=False): """ Sanitize libvirt storage volume format to a valid qemu driver type """ - raw_list = [ "iso" ] + raw_list = ["iso"] if phystype == VirtualDisk.TYPE_BLOCK: if not fmt: @@ -80,6 +83,7 @@ def _qemu_sanitize_drvtype(phystype, fmt, manual_format=False): return fmt + def _name_uid(user): """ Return UID for string username @@ -87,6 +91,7 @@ def _name_uid(user): pwdinfo = pwd.getpwnam(user) return pwdinfo[2] + def _is_dir_searchable(uid, username, path): """ Check if passed directory is searchable by uid @@ -123,6 +128,7 @@ def _is_dir_searchable(uid, username, path): return bool(re.search("user:%s:..x" % username, out)) + def _check_if_pool_source(conn, path): """ If passed path is a host disk device like /dev/sda, want to let the user @@ -150,6 +156,7 @@ def _check_if_pool_source(conn, path): return p return None + def _check_if_path_managed(conn, path): """ Determine if we can use libvirt storage APIs to create or lookup @@ -218,20 +225,21 @@ def _check_if_path_managed(conn, path): # Since there is no error, no pool was ever found err = (_("Cannot use storage '%(path)s': '%(rootdir)s' is " "not managed on the remote host.") % - { 'path' : path, + {'path' : path, 'rootdir' : os.path.dirname(path)}) else: err = (_("Cannot use storage %(path)s: %(err)s") % - { 'path' : path, 'err' : verr }) + {'path' : path, 'err' : verr}) raise ValueError(err) return vol, pool, path_is_pool + def _build_vol_install(path, pool, size, sparse): # Path wasn't a volume. See if base of path is a managed # pool, and if so, setup a StorageVolume object - if size == None: + if size is None: raise ValueError(_("Size must be specified for non " "existent volume path '%s'" % path)) @@ -419,7 +427,7 @@ class VirtualDisk(VirtualDevice): """ Try to fix any permission problems found by check_path_search_for_user - @return: Return a dictionary of entries { broken path : error msg } + @return: Return a dictionary of entries {broken path : error msg} @rtype : C{dict} """ def fix_perms(dirname, useacl=True): @@ -906,11 +914,11 @@ class VirtualDisk(VirtualDevice): self.serial) serial = _xml_property(_get_serial, _set_serial, xpath="./serial") - + def _get_iotune_read_bytes_sec(self): return self._iotune_read_bytes_sec def _set_iotune_read_bytes_sec(self, val): - if (type(val) is not type(1) or val < 0): + if not isinstance(val, int) or val < 0: raise ValueError(_("IOTune read bytes per second value must be an " "integer")) self._iotune_read_bytes_sec = val @@ -919,11 +927,11 @@ class VirtualDisk(VirtualDevice): xpath="./iotune/read_bytes_sec", get_converter=lambda s, x: int(x or 0), set_converter=lambda s, x: int(x)) - + def _get_iotune_read_iops_sec(self): return self._iotune_read_iops_sec def _set_iotune_read_iops_sec(self, val): - if (type(val) is not type(1) or val < 0): + if not isinstance(val, int) or val < 0: raise ValueError(_("IOTune read iops per second value must be an " "integer")) self._iotune_read_iops_sec = val @@ -932,11 +940,11 @@ class VirtualDisk(VirtualDevice): xpath="./iotune/read_iops_sec", get_converter=lambda s, x: int(x or 0), set_converter=lambda s, x: int(x)) - + def _get_iotune_total_bytes_sec(self): return self._iotune_total_bytes_sec def _set_iotune_total_bytes_sec(self, val): - if (type(val) is not type(1) or val < 0): + if not isinstance(val, int) or val < 0: raise ValueError(_("IOTune total bytes per second value must be an " "integer")) self._iotune_total_bytes_sec = val @@ -945,11 +953,11 @@ class VirtualDisk(VirtualDevice): xpath="./iotune/total_bytes_sec", get_converter=lambda s, x: int(x or 0), set_converter=lambda s, x: int(x)) - + def _get_iotune_total_iops_sec(self): return self._iotune_total_iops_sec def _set_iotune_total_iops_sec(self, val): - if (type(val) is not type(1) or val < 0): + if not isinstance(val, int) or val < 0: raise ValueError(_("IOTune total iops per second value must be an " "integer")) self._iotune_total_iops_sec = val @@ -958,11 +966,11 @@ class VirtualDisk(VirtualDevice): xpath="./iotune/total_iops_sec", get_converter=lambda s, x: int(x or 0), set_converter=lambda s, x: int(x)) - + def _get_iotune_write_bytes_sec(self): return self._iotune_write_bytes_sec def _set_iotune_write_bytes_sec(self, val): - if (type(val) is not type(1) or val < 0): + if not isinstance(val, int) or val < 0: raise ValueError(_("IOTune write bytes per second value must be an " "integer")) self._iotune_write_bytes_sec = val @@ -971,11 +979,11 @@ class VirtualDisk(VirtualDevice): xpath="./iotune/write_bytes_sec", get_converter=lambda s, x: int(x or 0), set_converter=lambda s, x: int(x)) - + def _get_iotune_write_iops_sec(self): return self._iotune_write_iops_sec def _set_iotune_write_iops_sec(self, val): - if (type(val) is not type(1) or val < 0): + if not isinstance(val, int) or val < 0: raise ValueError(_("IOTune write iops per second value must be an " "integer")) self._iotune_write_iops_sec = val @@ -1107,7 +1115,7 @@ class VirtualDisk(VirtualDevice): dtype = None if self.vol_object: - # vol info is [ vol type (file or block), capacity, allocation ] + # vol info is [vol type (file or block), capacity, allocation] t = self.vol_object.info()[0] if t == libvirt.VIR_STORAGE_VOL_FILE: dtype = self.TYPE_FILE @@ -1194,9 +1202,9 @@ class VirtualDisk(VirtualDevice): Return bool representing if managed storage parameters have been explicitly specified or filled in """ - return bool(self.vol_object != None or - self.vol_install != None or - self._pool_object != None) + return bool(self.vol_object is not None or + self.vol_install is not None or + self._pool_object is not None) def creating_storage(self): """ @@ -1392,7 +1400,7 @@ class VirtualDisk(VirtualDevice): # if a destination file exists and sparse flg is True, # this priority takes a existing file. - if (os.path.exists(self.path) == False and self.sparse == True): + if (not os.path.exists(self.path) and self.sparse): clone_block_size = 4096 sparse = True fd = None @@ -1553,7 +1561,7 @@ class VirtualDisk(VirtualDevice): if self.serial: ret += (" %s\n" % util.xml_escape(self.serial)) - + if (self.iotune_read_bytes_sec or self.iotune_read_iops_sec or self.iotune_total_bytes_sec or self.iotune_total_iops_sec or self.iotune_write_bytes_sec or self.iotune_write_iops_sec): diff --git a/virtinst/VirtualFilesystem.py b/virtinst/VirtualFilesystem.py index fc9b9d07..d67c43e3 100644 --- a/virtinst/VirtualFilesystem.py +++ b/virtinst/VirtualFilesystem.py @@ -22,6 +22,7 @@ import os from virtinst.VirtualDevice import VirtualDevice from virtinst.XMLBuilderDomain import _xml_property + class VirtualFilesystem(VirtualDevice): _virtual_device_type = VirtualDevice.VIRTUAL_DEV_FILESYSTEM diff --git a/virtinst/VirtualGraphics.py b/virtinst/VirtualGraphics.py index 82c6be39..da71fd76 100644 --- a/virtinst/VirtualGraphics.py +++ b/virtinst/VirtualGraphics.py @@ -25,6 +25,7 @@ from virtinst.VirtualDevice import VirtualDevice from virtinst import support from virtinst.XMLBuilderDomain import _xml_property + def _get_mode_prop(channel_type): # pylint: disable=W0212 xpath = "./channel[@name='%s']/@mode" % channel_type @@ -34,6 +35,7 @@ def _get_mode_prop(channel_type): s._channels[channel_type] = val return _xml_property(get_mode, set_mode, xpath=xpath) + class VirtualGraphics(VirtualDevice): _virtual_device_type = VirtualDevice.VIRTUAL_DEV_GRAPHICS @@ -165,7 +167,7 @@ class VirtualGraphics(VirtualDevice): return self._keymap def set_keymap(self, val): # At this point, 'None' is a valid value - if val == None: + if val is None: self._keymap = None return @@ -179,7 +181,7 @@ class VirtualGraphics(VirtualDevice): val = util.default_keymap() elif len(val) > 16: raise ValueError(_("Keymap must be less than 16 characters")) - elif re.match("^[a-zA-Z0-9_-]*$", val) == None: + elif re.match("^[a-zA-Z0-9_-]*$", val) is None: raise ValueError(_("Keymap can only contain alphanumeric, " "'_', or '-' characters")) @@ -269,8 +271,8 @@ class VirtualGraphics(VirtualDevice): doautoport = (canautoport and (port in [None, -1] and tlsPort in [None, -1])) - portxml = (port != None and (" port='%d'" % port) or "") - tlsportxml = (tlsPort != None and (" tlsPort='%d'" % tlsPort) or "") + portxml = (port is not None and (" port='%d'" % port) or "") + tlsportxml = (tlsPort is not None and (" tlsPort='%d'" % tlsPort) or "") autoportxml = (doautoport and " autoport='yes'" or "") keymapxml = (keymap and (" keymap='%s'" % keymap) or "") @@ -279,7 +281,7 @@ class VirtualGraphics(VirtualDevice): passwdValidToxml = (passwdValidTo and (" passwdValidTo='%s'" % passwdValidTo) or "") - xauthxml = (xauth and (" xauth='%s'" % xauth) or "") + xauthxml = (xauth and (" xauth='%s'" % xauth) or "") displayxml = (display and (" display='%s'" % display) or "") socketxml = (socket and (" socket='%s'" % socket) or "") diff --git a/virtinst/VirtualHostDevice.py b/virtinst/VirtualHostDevice.py index 790ef2c5..f5740d07 100644 --- a/virtinst/VirtualHostDevice.py +++ b/virtinst/VirtualHostDevice.py @@ -23,6 +23,7 @@ import logging from virtinst.XMLBuilderDomain import _xml_property + class VirtualHostDevice(VirtualDevice): _virtual_device_type = VirtualDevice.VIRTUAL_DEV_HOSTDEV @@ -184,7 +185,7 @@ class VirtualHostDevice(VirtualDevice): ignore = conn def _get_xml_config(self): - xml = (" \n" % \ + xml = (" \n" % (self.mode, self.type, self.managed and "yes" or "no")) xml += " \n" xml += self._get_source_xml() diff --git a/virtinst/VirtualInputDevice.py b/virtinst/VirtualInputDevice.py index 0d6a8594..d692ac40 100644 --- a/virtinst/VirtualInputDevice.py +++ b/virtinst/VirtualInputDevice.py @@ -20,6 +20,7 @@ from virtinst.VirtualDevice import VirtualDevice from virtinst.XMLBuilderDomain import _xml_property + class VirtualInputDevice(VirtualDevice): _virtual_device_type = VirtualDevice.VIRTUAL_DEV_INPUT diff --git a/virtinst/VirtualMemballoon.py b/virtinst/VirtualMemballoon.py index f68dcba4..053d6658 100644 --- a/virtinst/VirtualMemballoon.py +++ b/virtinst/VirtualMemballoon.py @@ -20,12 +20,13 @@ from virtinst.VirtualDevice import VirtualDevice from virtinst.XMLBuilderDomain import _xml_property + class VirtualMemballoon(VirtualDevice): _virtual_device_type = VirtualDevice.VIRTUAL_DEV_MEMBALLOON MODEL_DEFAULT = "virtio" - MODELS = [ "xen", "none", MODEL_DEFAULT ] + MODELS = ["xen", "none", MODEL_DEFAULT] def __init__(self, conn=None, model=MODEL_DEFAULT, parsexml=None, parsexmlnode=None, caps=None): diff --git a/virtinst/VirtualNetworkInterface.py b/virtinst/VirtualNetworkInterface.py index 6bc338be..7a22c278 100644 --- a/virtinst/VirtualNetworkInterface.py +++ b/virtinst/VirtualNetworkInterface.py @@ -45,6 +45,7 @@ def _compareMAC(p, q): return -1 return 0 + def _countMACaddr(vms, searchmac): if not searchmac: return @@ -64,6 +65,7 @@ def _countMACaddr(vms, searchmac): count += util.get_xml_path(xml, func=count_cb) return count + class VirtualPort(XMLBuilderDomain.XMLBuilderDomain): def __init__(self, conn, parsexml=None, parsexmlnode=None, caps=None): @@ -114,6 +116,7 @@ class VirtualPort(XMLBuilderDomain.XMLBuilderDomain): # FIXME: This should be implemented, currently we can only parse return "" + class VirtualNetworkInterface(VirtualDevice): _virtual_device_type = VirtualDevice.VIRTUAL_DEV_NET @@ -225,7 +228,7 @@ class VirtualNetworkInterface(VirtualDevice): Conveninece function, try to set the relevant value per the network type """ - if self.type == self.TYPE_VIRTUAL: + if self.type == self.TYPE_VIRTUAL: self.network = newsource elif self.type == self.TYPE_BRIDGE: self.bridge = newsource @@ -272,7 +275,7 @@ class VirtualNetworkInterface(VirtualDevice): try: net = self.conn.networkLookupByName(newnet) except libvirt.libvirtError, e: - raise ValueError(_("Virtual network '%s' does not exist: %s") \ + raise ValueError(_("Virtual network '%s' does not exist: %s") % (newnet, str(e))) if not _is_net_active(net): raise ValueError(_("Virtual network '%s' has not been " diff --git a/virtinst/VirtualRedirDevice.py b/virtinst/VirtualRedirDevice.py index 3a509fe0..3d3aa92f 100644 --- a/virtinst/VirtualRedirDevice.py +++ b/virtinst/VirtualRedirDevice.py @@ -23,15 +23,16 @@ from virtinst.VirtualDevice import VirtualDevice from virtinst.XMLBuilderDomain import _xml_property + class VirtualRedirDevice(VirtualDevice): _virtual_device_type = VirtualDevice.VIRTUAL_DEV_REDIRDEV BUS_DEFAULT = "usb" - _buses = [ "usb" ] + _buses = ["usb"] TYPE_DEFAULT = "spicevmc" - _types = [ "tcp", "spicevmc", None ] + _types = ["tcp", "spicevmc", None] def __init__(self, bus=BUS_DEFAULT, stype=TYPE_DEFAULT, conn=None, parsexml=None, parsexmlnode=None, caps=None): @@ -102,13 +103,13 @@ class VirtualRedirDevice(VirtualDevice): raise ValueError(_("Could not determine or unsupported format of '%s'") % serverstr) def _get_xml_config(self): - xml = (" \n" % \ + xml += (" \n" % (self.host, self.service)) xml += " " return xml diff --git a/virtinst/VirtualSmartCardDevice.py b/virtinst/VirtualSmartCardDevice.py index d8124417..fe347955 100644 --- a/virtinst/VirtualSmartCardDevice.py +++ b/virtinst/VirtualSmartCardDevice.py @@ -22,16 +22,17 @@ from virtinst.VirtualDevice import VirtualDevice from virtinst.XMLBuilderDomain import _xml_property + class VirtualSmartCardDevice(VirtualDevice): _virtual_device_type = VirtualDevice.VIRTUAL_DEV_SMARTCARD # Default models list MODE_DEFAULT = "passthrough" - _modes = [ "passthrough", "host-certificates", "host" ] + _modes = ["passthrough", "host-certificates", "host"] TYPE_DEFAULT = "tcp" - _types = [ "tcp", "spicevmc", None ] + _types = ["tcp", "spicevmc", None] def __init__(self, conn, mode=MODE_DEFAULT, parsexml=None, parsexmlnode=None, caps=None): diff --git a/virtinst/VirtualVideoDevice.py b/virtinst/VirtualVideoDevice.py index bf959bc8..8619ebd1 100644 --- a/virtinst/VirtualVideoDevice.py +++ b/virtinst/VirtualVideoDevice.py @@ -20,13 +20,14 @@ from virtinst.VirtualDevice import VirtualDevice from virtinst.XMLBuilderDomain import _xml_property + class VirtualVideoDevice(VirtualDevice): _virtual_device_type = VirtualDevice.VIRTUAL_DEV_VIDEO # Default models list MODEL_DEFAULT = "default" - _model_types = [ "cirrus", "vga", "vmvga", "xen", "qxl", MODEL_DEFAULT] + _model_types = ["cirrus", "vga", "vmvga", "xen", "qxl", MODEL_DEFAULT] @staticmethod def pretty_model(model): diff --git a/virtinst/VirtualWatchdog.py b/virtinst/VirtualWatchdog.py index 023b8827..ecfe55f5 100644 --- a/virtinst/VirtualWatchdog.py +++ b/virtinst/VirtualWatchdog.py @@ -20,12 +20,13 @@ from virtinst.VirtualDevice import VirtualDevice from virtinst.XMLBuilderDomain import _xml_property + class VirtualWatchdog(VirtualDevice): _virtual_device_type = VirtualDevice.VIRTUAL_DEV_WATCHDOG MODEL_DEFAULT = "default" - MODELS = [ "i6300esb", "ib700", MODEL_DEFAULT ] + MODELS = ["i6300esb", "ib700", MODEL_DEFAULT] ACTION_DEFAULT = "default" ACTION_SHUTDOWN = "shutdown" diff --git a/virtinst/XMLBuilderDomain.py b/virtinst/XMLBuilderDomain.py index 17407de5..74e0eed9 100644 --- a/virtinst/XMLBuilderDomain.py +++ b/virtinst/XMLBuilderDomain.py @@ -56,6 +56,7 @@ def _unref_doc(doc): finally: _xml_refs_lock.release() + def _ref_doc(doc): if not doc: return @@ -100,12 +101,14 @@ def _sanitize_libxml_xml(xml): xml += "\n" return xml + def _get_xpath_node(ctx, xpath, is_multi=False): node = ctx.xpathEval(xpath) if not is_multi: return (node and node[0] or None) return node + def _build_xpath_node(ctx, xpath, addnode=None): """ Build all nodes required to set an xpath. If we have XML , and want @@ -208,6 +211,7 @@ def _build_xpath_node(ctx, xpath, addnode=None): return parentnode + def _remove_xpath_node(ctx, xpath, dofree=True): """ Remove an XML node tree if it has no content @@ -380,6 +384,7 @@ def _xml_property(fget=None, fset=None, fdel=None, doc=None, return property(fget=new_getter, fset=new_setter, doc=doc) + class XMLBuilderDomain(object): """ Base for all classes which build or parse domain XML diff --git a/virtinst/cli.py b/virtinst/cli.py index f2113337..e8aa6d72 100644 --- a/virtinst/cli.py +++ b/virtinst/cli.py @@ -83,6 +83,7 @@ class VirtStreamHandler(logging.StreamHandler): except: self.handleError(record) + class VirtOptionParser(optparse.OptionParser): '''Subclass to get print_help to work properly with non-ascii text''' @@ -112,6 +113,7 @@ class VirtOptionParser(optparse.OptionParser): file.write(encodedhelp) + class VirtHelpFormatter(optparse.IndentedHelpFormatter): """ Subclass the default help formatter to allow printing newline characters @@ -137,6 +139,7 @@ class VirtHelpFormatter(optparse.IndentedHelpFormatter): ret.extend(self.oldwrap(line, width)) return ret + def setupParser(usage=None): parse_class = VirtOptionParser @@ -145,9 +148,11 @@ def setupParser(usage=None): version=cliconfig.__version__) return parser + def earlyLogging(): logging.basicConfig(level=logging.DEBUG, format='%(message)s') + def setupLogging(appname, debug=False, do_quiet=False): global quiet quiet = do_quiet @@ -223,9 +228,11 @@ def setupLogging(appname, debug=False, do_quiet=False): _virtinst_uri_magic = "__virtinst_test__" + def is_virtinst_test_uri(uri): return uri and uri.startswith(_virtinst_uri_magic) + def open_test_uri(uri): """ This hack allows us to fake various drivers via passing a magic @@ -313,6 +320,7 @@ def open_test_uri(uri): return conn + def getConnection(uri): if (uri and not User.current().has_priv(User.PRIV_CREATE_DOMAIN, uri)): fail(_("Must be root to create Xen guests")) @@ -339,6 +347,7 @@ def open_connection(uri): return libvirt.openAuth(uri, [valid_auth_options, authcb, authcb_data], open_flags) + def do_creds(creds, cbdata): try: return _do_creds(creds, cbdata) @@ -346,6 +355,7 @@ def do_creds(creds, cbdata): logging.debug("Error in creds callback.", exc_info=True) raise + def _do_creds(creds, cbdata_ignore): if (len(creds) == 1 and @@ -360,10 +370,12 @@ def _do_creds(creds, cbdata_ignore): return _do_creds_authname(creds) # PolicyKit auth + + def _do_creds_polkit(action): if os.getuid() == 0: logging.debug("Skipping policykit check as root") - return 0 # Success + return 0 # Success logging.debug("Doing policykit for %s", action) import subprocess @@ -404,6 +416,8 @@ def _do_creds_polkit(action): return 0 # SASL username/pass auth + + def _do_creds_authname(creds): retindex = 4 @@ -441,24 +455,30 @@ def fail(msg, do_exit=True): if do_exit: _fail_exit() + def print_stdout(msg, do_force=False): if do_force or not quiet: print msg + def print_stderr(msg): logging.debug(msg) print >> sys.stderr, msg + def _fail_exit(): sys.exit(1) + def nice_exit(): print_stdout(_("Exiting at user request.")) sys.exit(0) + def virsh_start_cmd(guest): return ("virsh --connect %s start %s" % (guest.get_uri(), guest.name)) + def install_fail(guest): virshcmd = virsh_start_cmd(guest) @@ -469,6 +489,7 @@ def install_fail(guest): "otherwise, please restart your installation.") % virshcmd) sys.exit(1) + def build_default_pool(guest): if not virtinst.util.is_storage_capable(guest.conn): @@ -494,6 +515,7 @@ def build_default_pool(guest): raise RuntimeError(_("Couldn't create default storage pool '%s': %s") % (DEFAULT_POOL_PATH, str(e))) + def partition(string, sep): if not string: return (None, None, None) @@ -514,14 +536,17 @@ def set_force(val=True): global force force = val + def set_prompt(prompt=True): # Set whether we allow prompts, or fail if a prompt pops up global doprompt doprompt = prompt + def is_prompt(): return doprompt + def yes_or_no_convert(s): if s is None: return None @@ -533,12 +558,14 @@ def yes_or_no_convert(s): return False return None + def yes_or_no(s): ret = yes_or_no_convert(s) - if ret == None: + if ret is None: raise ValueError(_("A yes or no response is required")) return ret + def prompt_for_input(noprompt_err, prompt="", val=None, failed=False): if val is not None: return val @@ -554,6 +581,7 @@ def prompt_for_input(noprompt_err, prompt="", val=None, failed=False): sys.stdout.flush() return sys.stdin.readline().strip() + def prompt_for_yes_or_no(warning, question): """catches yes_or_no errors and ensures a valid bool return""" if force: @@ -576,6 +604,7 @@ def prompt_for_yes_or_no(warning, question): continue return res + def prompt_loop(prompt_txt, noprompt_err, passed_val, obj, param_name, err_txt="%s", func=None): """ @@ -761,6 +790,7 @@ def disk_prompt(conn, origpath, origsize, origsparse, name_missing = _("--name is required") ram_missing = _("--ram amount in MB is required") + def get_name(name, guest, image_name=None): prompt_txt = _("What is the name of your virtual machine?") err_txt = name_missing @@ -769,6 +799,7 @@ def get_name(name, guest, image_name=None): name = image_name prompt_loop(prompt_txt, err_txt, name, guest, "name") + def get_memory(memory, guest, image_memory=None): prompt_txt = _("How much RAM should be allocated (in megabytes)?") err_txt = ram_missing @@ -785,6 +816,7 @@ def get_memory(memory, guest, image_memory=None): prompt_loop(prompt_txt, err_txt, memory, guest, "memory", func=check_memory) + def get_uuid(uuid, guest): if uuid: try: @@ -792,6 +824,7 @@ def get_uuid(uuid, guest): except ValueError, e: fail(e) + def get_vcpus(guest, vcpus, check_cpu, image_vcpus=None): """ @param vcpus: value of the option '--vcpus' (str or None) @@ -821,6 +854,7 @@ def get_vcpus(guest, vcpus, check_cpu, image_vcpus=None): if not prompt_for_yes_or_no(msg, askmsg): nice_exit() + def get_cpuset(guest, cpuset, memory): conn = guest.conn if cpuset and cpuset != "auto": @@ -839,6 +873,7 @@ def get_cpuset(guest, cpuset, memory): return + def _default_network_opts(guest): opts = "" if User.current().has_priv(User.PRIV_CREATE_NETWORK, guest.get_uri()): @@ -849,6 +884,7 @@ def _default_network_opts(guest): return opts + def digest_networks(guest, options, numnics=1): macs = listify(options.mac) networks = listify(options.network) @@ -876,6 +912,7 @@ def digest_networks(guest, options, numnics=1): return networks, macs + def get_networks(guest, networks, macs): for idx in range(len(networks)): mac = macs[idx] @@ -887,6 +924,7 @@ def get_networks(guest, networks, macs): except Exception, e: fail(_("Error in network device parameters: %s") % str(e)) + def set_os_variant(guest, distro_type, distro_variant): if not distro_type and not distro_variant: # Default to distro autodetection @@ -899,6 +937,7 @@ def set_os_variant(guest, distro_type, distro_variant): if (distro_variant and str(distro_variant).lower() != "none"): guest.set_os_variant(distro_variant) + def digest_graphics(guest, options, default_override=None): vnc = options.vnc vncport = options.vncport @@ -951,6 +990,7 @@ def digest_graphics(guest, options, default_override=None): logging.debug("--graphics compat generated: %s", optstr) return [optstr] + def get_graphics(guest, graphics): for optstr in graphics: try: @@ -961,6 +1001,7 @@ def get_graphics(guest, graphics): if dev: guest.add_device(dev) + def get_video(guest, video_models=None): video_models = video_models or [] @@ -971,6 +1012,7 @@ def get_video(guest, video_models=None): for model in video_models: guest.add_device(parse_video(guest, model)) + def get_sound(old_sound_bool, sound_opts, guest): if not sound_opts: if old_sound_bool: @@ -980,6 +1022,7 @@ def get_sound(old_sound_bool, sound_opts, guest): for opts in listify(sound_opts): guest.add_device(parse_sound(guest, opts)) + def get_hostdevs(hostdevs, guest): if not hostdevs: return @@ -987,6 +1030,7 @@ def get_hostdevs(hostdevs, guest): for devname in hostdevs: guest.add_device(parse_hostdev(guest, devname)) + def get_smartcard(guest, sc_opts): for sc in listify(sc_opts): try: @@ -997,6 +1041,7 @@ def get_smartcard(guest, sc_opts): if dev: guest.add_device(dev) + def get_controller(guest, sc_opts): for sc in listify(sc_opts): try: @@ -1007,6 +1052,7 @@ def get_controller(guest, sc_opts): if dev: guest.add_device(dev) + def get_redirdev(guest, sc_opts): for sc in listify(sc_opts): try: @@ -1017,6 +1063,7 @@ def get_redirdev(guest, sc_opts): if dev: guest.add_device(dev) + def get_memballoon(guest, sc_opts): for sc in listify(sc_opts): try: @@ -1031,10 +1078,12 @@ def get_memballoon(guest, sc_opts): # Common CLI option/group # ############################# + def add_connect_option(parser): parser.add_option("", "--connect", metavar="URI", dest="connect", help=_("Connect to hypervisor with libvirt URI")) + def vcpu_cli_options(grp, backcompat=True): grp.add_option("", "--vcpus", dest="vcpus", help=_("Number of vcpus to configure for your guest. Ex:\n" @@ -1050,6 +1099,7 @@ def vcpu_cli_options(grp, backcompat=True): grp.add_option("", "--check-cpu", action="store_true", dest="check_cpu", help=optparse.SUPPRESS_HELP) + def graphics_option_group(parser): """ Register vnc + sdl options for virt-install and virt-image @@ -1071,6 +1121,7 @@ def graphics_option_group(parser): help=optparse.SUPPRESS_HELP) return vncg + def network_option_group(parser): """ Register common network options for virt-install and virt-image @@ -1087,6 +1138,7 @@ def network_option_group(parser): return netg + def add_net_option(devg): devg.add_option("-w", "--network", dest="network", action="append", help=_("Configure a guest network interface. Ex:\n" @@ -1094,6 +1146,7 @@ def add_net_option(devg): "--network network=my_libvirt_virtual_net\n" "--network network=mynet,model=virtio,mac=00:11...")) + def add_device_options(devg): devg.add_option("", "--controller", dest="controller", action="append", help=_("Configure a guest controller device. Ex:\n" @@ -1126,6 +1179,7 @@ def add_device_options(devg): help=_("Configure a guest memballoon device. Ex:\n" "--memballoon model=virtio")) + def add_gfx_option(devg): devg.add_option("", "--graphics", dest="graphics", action="append", help=_("Configure guest display settings. Ex:\n" @@ -1134,6 +1188,7 @@ def add_gfx_option(devg): "--graphics none\n" "--graphics vnc,password=foobar,port=5910,keymap=ja")) + def add_fs_option(devg): devg.add_option("", "--filesystem", dest="filesystems", action="append", help=_("Pass host directory to the guest. Ex: \n" @@ -1145,27 +1200,30 @@ def add_fs_option(devg): # (for options like --disk, --network, etc. # ############################################# + def get_opt_param(opts, dictnames, val=None): if type(dictnames) is not list: dictnames = [dictnames] for key in dictnames: if key in opts: - if val == None: + if val is None: val = opts[key] del(opts[key]) return val + def _build_set_param(inst, opts): def _set_param(paramname, keyname, val=None): val = get_opt_param(opts, keyname, val) - if val == None: + if val is None: return setattr(inst, paramname, val) return _set_param + def parse_optstr_tuples(optstr, compress_first=False): """ Parse optstr into a list of ordered tuples @@ -1195,6 +1253,7 @@ def parse_optstr_tuples(optstr, compress_first=False): return optlist + def parse_optstr(optstr, basedict=None, remove_first=None, compress_first=False): """ @@ -1222,7 +1281,7 @@ def parse_optstr(optstr, basedict=None, remove_first=None, if len(optlist) < len(paramlist): break - if optlist[idx][1] == None: + if optlist[idx][1] is None: optlist[idx] = (paramlist[idx], optlist[idx][0]) for opt, val in optlist: @@ -1264,6 +1323,7 @@ def parse_numatune(guest, optstring): # --vcpu parsing # ################## + def parse_vcpu(guest, optstring, default_vcpus=None): """ Helper to parse --vcpu string @@ -1301,6 +1361,7 @@ def parse_vcpu(guest, optstring, default_vcpus=None): # --cpu parsing # ################# + def parse_cpu(guest, optstring): default_dict = { "force": [], @@ -1308,7 +1369,7 @@ def parse_cpu(guest, optstring): "optional": [], "disable": [], "forbid": [], - } + } opts = parse_optstr(optstring, basedict=default_dict, remove_first="model") @@ -1355,6 +1416,7 @@ def parse_cpu(guest, optstring): # --boot parsing # ################## + def parse_boot(guest, optstring): """ Helper to parse --boot string @@ -1365,7 +1427,7 @@ def parse_boot(guest, optstring): def set_param(paramname, dictname, val=None): val = get_opt_param(opts, dictname, val) - if val == None: + if val is None: return if paramname == "loader": @@ -1385,7 +1447,7 @@ def parse_boot(guest, optstring): else: menu = yes_or_no_convert(menustr) - if menu == None: + if menu is None: fail(_("--boot menu must be 'on' or 'off'")) set_param("enable_bootmenu", "menu", menu) @@ -1414,6 +1476,7 @@ def parse_boot(guest, optstring): # --security parsing # ###################### + def parse_security(guest, security): seclist = listify(security) secopts = seclist and seclist[0] or None @@ -1477,6 +1540,7 @@ def parse_security(guest, security): _disk_counter = itertools.count() + def _parse_disk_source(guest, path, pool, vol, size, fmt, sparse): abspath = None volinst = None @@ -1530,6 +1594,7 @@ def _parse_disk_source(guest, path, pool, vol, size, fmt, sparse): return abspath, volinst, volobj + def parse_disk(guest, optstr, dev=None): """ helper to properly parse --disk options @@ -1640,6 +1705,7 @@ def parse_disk(guest, optstr, dev=None): # --network parsing # ##################### + def parse_network(guest, optstring, dev=None, mac=None): # Handle old format of bridge:foo instead of bridge=foo for prefix in ["network", "bridge"]: @@ -1685,6 +1751,7 @@ def parse_network(guest, optstring, dev=None, mac=None): # --graphics parsing # ###################### + def parse_graphics(guest, optstring, dev=None): if optstring is None: return None @@ -1713,7 +1780,7 @@ def parse_graphics(guest, optstring, dev=None): def set_param(paramname, dictname, val=None): val = get_opt_param(opts, dictname, val) - if val == None: + if val is None: return if paramname == "keymap": @@ -1737,6 +1804,7 @@ def parse_graphics(guest, optstring, dev=None): # --controller parsing # ####################### + def parse_controller(guest, optstring, dev=None): if optstring is None: return None @@ -1771,6 +1839,7 @@ def parse_controller(guest, optstring, dev=None): # --smartcard parsing # ####################### + def parse_smartcard(guest, optstring, dev=None): if optstring is None: return None @@ -1797,6 +1866,7 @@ def parse_smartcard(guest, optstring, dev=None): # --redirdev parsing # ###################### + def parse_redirdev(guest, optstring, dev=None): if optstring is None: return None @@ -1833,6 +1903,7 @@ def parse_redirdev(guest, optstring, dev=None): # --watchdog parsing # ###################### + def parse_watchdog(guest, optstring, dev=None): # Peel the model type off the front opts = parse_optstr(optstring, remove_first="model") @@ -1842,7 +1913,7 @@ def parse_watchdog(guest, optstring, dev=None): def set_param(paramname, dictname, val=None): val = get_opt_param(opts, dictname, val) - if val == None: + if val is None: return setattr(dev, paramname, val) @@ -1859,6 +1930,7 @@ def parse_watchdog(guest, optstring, dev=None): # --memballoon parsing # ######################## + def parse_memballoon(guest, optstring, dev=None): if optstring is None: return None @@ -1883,13 +1955,20 @@ def parse_memballoon(guest, optstring, dev=None): def parse_serial(guest, optstring, dev=None): return _parse_char(guest, optstring, "serial", dev) + + def parse_parallel(guest, optstring, dev=None): return _parse_char(guest, optstring, "parallel", dev) + + def parse_console(guest, optstring, dev=None): return _parse_char(guest, optstring, "console", dev) + + def parse_channel(guest, optstring, dev=None): return _parse_char(guest, optstring, "channel", dev) + def _parse_char(guest, optstring, dev_type, dev=None): """ Helper to parse --serial/--parallel options @@ -1904,14 +1983,14 @@ def _parse_char(guest, optstring, dev_type, dev=None): def set_param(paramname, dictname, val=None): val = get_opt_param(opts, dictname, val) - if val == None: + if val is None: return if not dev.supports_property(paramname): raise ValueError(_("%(devtype)s type '%(chartype)s' does not " "support '%(optname)s' option.") % {"devtype" : dev_type, "chartype": char_type, - "optname" : dictname} ) + "optname" : dictname}) setattr(dev, paramname, val) def parse_host(key): @@ -1959,7 +2038,7 @@ def parse_filesystem(guest, optstring, dev=None): def set_param(paramname, dictname, val=None): val = get_opt_param(opts, dictname, val) - if val == None: + if val is None: return setattr(dev, paramname, val) @@ -1978,6 +2057,7 @@ def parse_filesystem(guest, optstring, dev=None): # --video parsing # ################### + def parse_video(guest, optstr, dev=None): opts = {"model" : optstr} @@ -1996,6 +2076,7 @@ def parse_video(guest, optstr, dev=None): # --soundhw parsing # ##################### + def parse_sound(guest, optstr, dev=None): opts = {"model" : optstr} @@ -2014,6 +2095,7 @@ def parse_sound(guest, optstr, dev=None): # --hostdev parsing # ##################### + def parse_hostdev(guest, optstr, dev=None): # XXX: Need to implement this for virt-xml ignore = dev diff --git a/virtinst/osdict.py b/virtinst/osdict.py index 849c2997..3f8ae95d 100644 --- a/virtinst/osdict.py +++ b/virtinst/osdict.py @@ -36,28 +36,28 @@ VIDEO = VirtualDevice.VIRTUAL_DEV_VIDEO VIRTIO_DISK = { "bus" : [ (support.SUPPORT_CONN_HV_VIRTIO, "virtio"), - ] + ] } VIRTIO_NET = { "model" : [ (support.SUPPORT_CONN_HV_VIRTIO, "virtio"), - ] + ] } USB_TABLET = { "type" : [ (HV_ALL, "tablet"), - ], + ], "bus" : [ (HV_ALL, "usb"), - ] + ] } VGA_VIDEO = { "model_type": [ (HV_ALL, "vga"), - ] + ] } DEFAULTS = { @@ -71,45 +71,46 @@ DEFAULTS = { "supported": False, "devices" : { - # "devname" : { "attribute" : [( ["applicable", "hv-type", list"], - # "recommended value for hv-types" ),]}, + # "devname" : {"attribute" : [(["applicable", "hv-type", list"], + # "recommended value for hv-types"),]}, INPUT : { "type" : [ (HV_ALL, "mouse") - ], + ], "bus" : [ (HV_ALL, "ps2") - ], - }, + ], + }, DISK : { "bus" : [ (HV_ALL, None) - ], - }, + ], + }, NET : { "model": [ (HV_ALL, None) - ], - }, + ], + }, SOUND : { "model": [ (support.SUPPORT_CONN_HV_SOUND_ICH6, "ich6"), (support.SUPPORT_CONN_HV_SOUND_AC97, "ac97"), (HV_ALL, "es1370"), - ] - }, + ] + }, VIDEO : { "model_type": [ (HV_ALL, "cirrus"), - ] - }, - } + ] + }, + } } + def sort_helper(tosort, sortpref=None): """ Helps properly sorting os dictionary entires @@ -160,6 +161,7 @@ def sort_helper(tosort, sortpref=None): return retlist + def parse_key_entry(conn, hv_type, key_entry, defaults): ret = None found = False @@ -177,7 +179,7 @@ def parse_key_entry(conn, hv_type, key_entry, defaults): support_key, hv_type) - if support_ret != True: + if support_ret is not True: continue found = True @@ -192,6 +194,7 @@ def parse_key_entry(conn, hv_type, key_entry, defaults): return ret + def lookup_osdict_key(conn, hv_type, os_type, var, key): defaults = DEFAULTS[key] @@ -231,20 +234,20 @@ OS_TYPES = { "rhel2.1": { "label": "Red Hat Enterprise Linux 2.1", "distro": "rhel" - }, + }, "rhel3": { "label": "Red Hat Enterprise Linux 3", "distro": "rhel" - }, + }, "rhel4": { "label": "Red Hat Enterprise Linux 4", "distro": "rhel", "supported": True, - }, + }, "rhel5": { "label": "Red Hat Enterprise Linux 5", "distro": "rhel", - }, + }, "rhel5.4": { "label": "Red Hat Enterprise Linux 5.4 or later", "distro": "rhel", @@ -252,8 +255,8 @@ OS_TYPES = { "devices" : { DISK : VIRTIO_DISK, NET : VIRTIO_NET, - }, - }, + }, + }, "rhel6": { "label": "Red Hat Enterprise Linux 6", "distro": "rhel", @@ -262,8 +265,8 @@ OS_TYPES = { DISK : VIRTIO_DISK, NET : VIRTIO_NET, INPUT: USB_TABLET, - } - }, + } + }, "rhel7": { "label": "Red Hat Enterprise Linux 7", "distro": "rhel", @@ -272,29 +275,29 @@ OS_TYPES = { DISK : VIRTIO_DISK, NET : VIRTIO_NET, INPUT: USB_TABLET, - } - }, + } + }, "fedora5": { "sortby": "fedora05", "label": "Fedora Core 5", "distro": "fedora" - }, + }, "fedora6": { "sortby": "fedora06", "label": "Fedora Core 6", "distro": "fedora" - }, + }, "fedora7": { "sortby": "fedora07", "label": "Fedora 7", "distro": "fedora" - }, + }, "fedora8": { "sortby": "fedora08", "label": "Fedora 8", "distro": "fedora" - }, + }, "fedora9": { "sortby": "fedora09", "label": "Fedora 9", @@ -302,18 +305,18 @@ OS_TYPES = { "devices" : { # Apparently F9 has selinux errors when installing with virtio: # https://bugzilla.redhat.com/show_bug.cgi?id=470386 - #DISK : VIRTIO_DISK, + # DISK : VIRTIO_DISK, NET : VIRTIO_NET, - } - }, + } + }, "fedora10": { "label": "Fedora 10", "distro": "fedora", "devices" : { DISK : VIRTIO_DISK, NET : VIRTIO_NET, - } - }, + } + }, "fedora11": { "label": "Fedora 11", "distro": "fedora", @@ -321,8 +324,8 @@ OS_TYPES = { DISK : VIRTIO_DISK, NET : VIRTIO_NET, INPUT: USB_TABLET, - } - }, + } + }, "fedora12": { "label": "Fedora 12", "distro": "fedora", @@ -330,16 +333,16 @@ OS_TYPES = { DISK : VIRTIO_DISK, NET : VIRTIO_NET, INPUT: USB_TABLET, - } - }, + } + }, "fedora13": { "label": "Fedora 13", "distro": "fedora", "devices" : { DISK : VIRTIO_DISK, NET : VIRTIO_NET, INPUT: USB_TABLET, - } - }, + } + }, "fedora14": { "label": "Fedora 14", "distro": "fedora", @@ -347,8 +350,8 @@ OS_TYPES = { DISK : VIRTIO_DISK, NET : VIRTIO_NET, INPUT: USB_TABLET, - } - }, + } + }, "fedora15": { "label": "Fedora 15", "distro": "fedora", @@ -357,8 +360,8 @@ OS_TYPES = { DISK : VIRTIO_DISK, NET : VIRTIO_NET, INPUT: USB_TABLET, - } - }, + } + }, "fedora16": { "label": "Fedora 16", "distro": "fedora", @@ -367,8 +370,8 @@ OS_TYPES = { DISK : VIRTIO_DISK, NET : VIRTIO_NET, INPUT: USB_TABLET, - } - }, + } + }, "fedora17": { "label": "Fedora 17", "distro": "fedora", @@ -377,8 +380,8 @@ OS_TYPES = { DISK : VIRTIO_DISK, NET : VIRTIO_NET, INPUT: USB_TABLET, - } - }, + } + }, "fedora18": { "label": "Fedora 18", "distro": "fedora", @@ -387,8 +390,8 @@ OS_TYPES = { DISK : VIRTIO_DISK, NET : VIRTIO_NET, INPUT: USB_TABLET, - } - }, + } + }, "opensuse11": { "label": "openSuse 11", @@ -397,8 +400,8 @@ OS_TYPES = { "devices" : { DISK : VIRTIO_DISK, NET : VIRTIO_NET, - }, - }, + }, + }, "opensuse12": { "label": "openSuse 12", "distro": "suse", @@ -406,14 +409,14 @@ OS_TYPES = { "devices" : { DISK : VIRTIO_DISK, NET : VIRTIO_NET, - }, - }, + }, + }, "sles10": { "label": "Suse Linux Enterprise Server", "distro": "suse", "supported": True, - }, + }, "sles11": { "label": "Suse Linux Enterprise Server 11", "distro": "suse", @@ -421,26 +424,26 @@ OS_TYPES = { "devices" : { DISK : VIRTIO_DISK, NET : VIRTIO_NET, - }, - }, + }, + }, "mandriva2009": { "label": "Mandriva Linux 2009 and earlier", "distro": "mandriva" - }, + }, "mandriva2010": { "label": "Mandriva Linux 2010 and later", "distro": "mandriva", "devices" : { DISK : VIRTIO_DISK, NET : VIRTIO_NET, - }, - }, + }, + }, "mes5": { "label": "Mandriva Enterprise Server 5.0", "distro": "mandriva", - }, + }, "mes5.1": { "label": "Mandriva Enterprise Server 5.1 and later", "distro": "mandriva", @@ -448,8 +451,8 @@ OS_TYPES = { "devices" : { DISK : VIRTIO_DISK, NET : VIRTIO_NET, - }, - }, + }, + }, "mageia1": { "label": "Mageia 1 and later", @@ -459,15 +462,15 @@ OS_TYPES = { DISK : VIRTIO_DISK, NET : VIRTIO_NET, INPUT: USB_TABLET, - }, - }, + }, + }, "debianetch": { "label": "Debian Etch", "distro": "debian", "sortby": "debian4", - }, + }, "debianlenny": { "label": "Debian Lenny", "distro": "debian", @@ -476,8 +479,8 @@ OS_TYPES = { "devices" : { DISK : VIRTIO_DISK, NET : VIRTIO_NET, - }, - }, + }, + }, "debiansqueeze": { "label": "Debian Squeeze", "distro": "debian", @@ -487,8 +490,8 @@ OS_TYPES = { DISK : VIRTIO_DISK, NET : VIRTIO_NET, INPUT: USB_TABLET, - } - }, + } + }, "debianwheezy": { "label": "Debian Wheezy", "distro": "debian", @@ -498,8 +501,8 @@ OS_TYPES = { DISK : VIRTIO_DISK, NET : VIRTIO_NET, INPUT: USB_TABLET, - } - }, + } + }, "ubuntuhardy": { "label": "Ubuntu 8.04 LTS (Hardy Heron)", @@ -507,31 +510,31 @@ OS_TYPES = { "supported": True, "devices" : { NET : VIRTIO_NET, - }, - }, + }, + }, "ubuntuintrepid": { "label": "Ubuntu 8.10 (Intrepid Ibex)", "distro": "ubuntu", "devices" : { NET : VIRTIO_NET, - }, - }, + }, + }, "ubuntujaunty": { "label": "Ubuntu 9.04 (Jaunty Jackalope)", "distro": "ubuntu", "devices" : { DISK : VIRTIO_DISK, NET : VIRTIO_NET, - }, - }, + }, + }, "ubuntukarmic": { "label": "Ubuntu 9.10 (Karmic Koala)", "distro": "ubuntu", "devices" : { DISK : VIRTIO_DISK, NET : VIRTIO_NET, - }, - }, + }, + }, "ubuntulucid": { "label": "Ubuntu 10.04 LTS (Lucid Lynx)", "distro": "ubuntu", @@ -539,16 +542,16 @@ OS_TYPES = { "devices" : { DISK : VIRTIO_DISK, NET : VIRTIO_NET, - }, - }, + }, + }, "ubuntumaverick": { "label": "Ubuntu 10.10 (Maverick Meerkat)", "distro": "ubuntu", "devices" : { DISK : VIRTIO_DISK, NET : VIRTIO_NET, - }, - }, + }, + }, "ubuntunatty": { "label": "Ubuntu 11.04 (Natty Narwhal)", "distro": "ubuntu", @@ -556,8 +559,8 @@ OS_TYPES = { "devices" : { DISK : VIRTIO_DISK, NET : VIRTIO_NET, - }, - }, + }, + }, "ubuntuoneiric": { "label": "Ubuntu 11.10 (Oneiric Ocelot)", "distro": "ubuntu", @@ -565,8 +568,8 @@ OS_TYPES = { "devices" : { DISK : VIRTIO_DISK, NET : VIRTIO_NET, - }, - }, + }, + }, "ubuntuprecise": { "label": "Ubuntu 12.04 LTS (Precise Pangolin)", "distro": "ubuntu", @@ -574,8 +577,8 @@ OS_TYPES = { "devices" : { DISK : VIRTIO_DISK, NET : VIRTIO_NET, - }, - }, + }, + }, "ubuntuquantal": { "label": "Ubuntu 12.10 (Quantal Quetzal)", "distro": "ubuntu", @@ -583,25 +586,25 @@ OS_TYPES = { "devices" : { DISK : VIRTIO_DISK, NET : VIRTIO_NET, - }, - }, + }, + }, "generic24": { "label": "Generic 2.4.x kernel" - }, + }, "generic26": { "label": "Generic 2.6.x kernel" - }, + }, "virtio26": { "sortby": "genericvirtio26", "label": "Generic 2.6.25 or later kernel with virtio", "devices" : { DISK : VIRTIO_DISK, NET : VIRTIO_NET, - }, - }, + }, + }, - }, + }, }, "windows": { @@ -611,7 +614,7 @@ OS_TYPES = { "devices" : { INPUT : USB_TABLET, VIDEO : VGA_VIDEO, - }, + }, "variants": { @@ -622,46 +625,46 @@ OS_TYPES = { "supported": True, "acpi": [(support.SUPPORT_CONN_HV_SKIP_DEFAULT_ACPI, False)], "apic": [(support.SUPPORT_CONN_HV_SKIP_DEFAULT_ACPI, False)], - }, + }, "winxp64": { "label": "Microsoft Windows XP (x86_64)", "supported": True, "sortby": "mswin564", "distro": "win", - }, + }, "win2k": { "label": "Microsoft Windows 2000", "sortby" : "mswin4", "distro": "win", "acpi": [(support.SUPPORT_CONN_HV_SKIP_DEFAULT_ACPI, False)], "apic": [(support.SUPPORT_CONN_HV_SKIP_DEFAULT_ACPI, False)], - }, + }, "win2k3": { "label": "Microsoft Windows Server 2003", "supported": True, "sortby" : "mswinserv2003", "distro": "winserv", - }, + }, "win2k8": { "label": "Microsoft Windows Server 2008", "supported": True, "sortby": "mswinserv2008", "distro": "winserv", - }, + }, "vista": { "label": "Microsoft Windows Vista", "supported": True, "sortby": "mswin6", "distro": "win", - }, + }, "win7": { "label": "Microsoft Windows 7", "supported": True, "sortby": "mswin7", "distro": "win", - }, + }, - }, + }, }, "solaris": { @@ -672,21 +675,21 @@ OS_TYPES = { "solaris9": { "label": "Sun Solaris 9", - }, + }, "solaris10": { "label": "Sun Solaris 10", "devices" : { INPUT : USB_TABLET, - }, - }, + }, + }, "opensolaris": { "label": "Sun OpenSolaris", "devices" : { INPUT : USB_TABLET, - }, - }, + }, + }, - }, + }, }, "unix": { @@ -697,33 +700,33 @@ OS_TYPES = { "label": "FreeBSD 6.x" , # http://www.nabble.com/Re%3A-Qemu%3A-bridging-on-FreeBSD-7.0-STABLE-p15919603.html "devices" : { - NET : { "model" : [ (HV_ALL, "ne2k_pci") ] } - }, - }, + NET : {"model" : [(HV_ALL, "ne2k_pci")]} + }, + }, "freebsd7": { "label": "FreeBSD 7.x" , "devices" : { - NET : { "model" : [ (HV_ALL, "ne2k_pci") ] } - }, - }, + NET : {"model" : [(HV_ALL, "ne2k_pci")]} + }, + }, "freebsd8": { "label": "FreeBSD 8.x" , "supported": True, "devices" : { - NET : { "model" : [ (HV_ALL, "e1000") ] } - }, - }, + NET : {"model" : [(HV_ALL, "e1000")]} + }, + }, "openbsd4": { "label": "OpenBSD 4.x" , # http://calamari.reverse-dns.net:980/cgi-bin/moin.cgi/OpenbsdOnQemu # https://www.redhat.com/archives/et-mgmt-tools/2008-June/msg00018.html "devices" : { - NET : { "model" : [ (HV_ALL, "pcnet") ] } - }, - }, + NET : {"model" : [(HV_ALL, "pcnet")]} + }, + }, - }, + }, }, "other": { @@ -734,25 +737,25 @@ OS_TYPES = { "label": "MS-DOS", "acpi": False, "apic": False, - }, + }, "netware4": { "label": "Novell Netware 4", - }, + }, "netware5": { "label": "Novell Netware 5", - }, + }, "netware6": { "label": "Novell Netware 6", "pv_cdrom_install": True, - }, + }, "generic": { "supported": True, "label": "Generic" - }, + }, - }, + }, } } diff --git a/virtinst/support.py b/virtinst/support.py index dfe4bae8..b361ea2e 100644 --- a/virtinst/support.py +++ b/virtinst/support.py @@ -110,95 +110,95 @@ _support_dict = { SUPPORT_CONN_STORAGE : { "function" : "virConnect.listStoragePools", "args" : (), - }, + }, SUPPORT_CONN_NODEDEV : { "function" : "virConnect.listDevices", "args" : (None, 0), - }, + }, SUPPORT_CONN_FINDPOOLSOURCES : { "function" : "virConnect.findStoragePoolSources", - }, + }, SUPPORT_CONN_KEYMAP_AUTODETECT : { - "drv_version" : [ ("qemu", 11000) ], - }, + "drv_version" : [("qemu", 11000)], + }, SUPPORT_CONN_GETHOSTNAME : { "function" : "virConnect.getHostname()", "args" : (), - }, + }, SUPPORT_CONN_DOMAIN_VIDEO : { "version" : 6005, - }, + }, SUPPORT_CONN_NETWORK : { "function" : "virConnect.listNetworks", "args" : (), - }, + }, SUPPORT_CONN_INTERFACE : { "function" : "virConnect.listInterfaces", "args" : (), - }, + }, SUPPORT_CONN_MAXVCPUS_XML : { "version" : 8005, - }, + }, SUPPORT_CONN_STREAM : { # Earliest version with working bindings "version" : 9003, "function" : "virConnect.newStream", "args" : (0,), - }, + }, # Domain checks SUPPORT_DOMAIN_GETVCPUS : { "function" : "virDomain.vcpus", "args" : (), - }, + }, SUPPORT_DOMAIN_XML_INACTIVE : { "function" : "virDomain.XMLDesc", "args" : (), "flag" : "VIR_DOMAIN_XML_INACTIVE", - }, + }, SUPPORT_DOMAIN_XML_SECURE : { "function" : "virDomain.XMLDesc", "args" : (), "flag" : "VIR_DOMAIN_XML_SECURE", - }, + }, SUPPORT_DOMAIN_MANAGED_SAVE : { "function" : "virDomain.hasManagedSaveImage", "args" : (0,), - }, + }, SUPPORT_DOMAIN_MIGRATE_DOWNTIME : { "function" : "virDomain.migrateSetMaxDowntime", # Use a bogus flags value, so that we don't overwrite existing # downtime value "args" : (30, 12345678), - }, + }, SUPPORT_DOMAIN_JOB_INFO : { "function" : "virDomain.jobInfo", "args" : (), - }, + }, SUPPORT_DOMAIN_CONSOLE_STREAM : { "version" : 9003, - }, + }, SUPPORT_DOMAIN_SET_METADATA : { "version" : 9010, - }, + }, # Pool checks @@ -206,88 +206,94 @@ _support_dict = { SUPPORT_STORAGE_CREATEVOLFROM : { "function" : "virStoragePool.createXMLFrom", "version" : 6004, - }, + }, # Nodedev checks # This can't ever require a nodedev object for back compat reasons SUPPORT_NODEDEV_PCI_DETACH : { "function" : "virNodeDevice.dettach", "version" : 6001, - }, + }, # Interface checks SUPPORT_INTERFACE_XML_INACTIVE : { "function" : "virInterface.XMLDesc", "args" : (), "flag" : "VIR_INTERFACE_XML_INACTIVE", - }, + }, # Conn HV checks SUPPORT_CONN_HV_VIRTIO : { - "drv_version": [ ("qemu", 0) ], - "hv_version" : [ ("kvm", 0) ], - }, + "drv_version": [("qemu", 0)], + "hv_version" : [("kvm", 0)], + }, SUPPORT_CONN_HV_SKIP_DEFAULT_ACPI : { - "drv_version" : [ ("xen", -3001000)], - }, + "drv_version" : [("xen", -3001000)], + }, SUPPORT_CONN_HV_SOUND_AC97 : { "version" : 6000, "force_version" : True, - "drv_version" : [ ("qemu", 11000), ], - }, + "drv_version" : [("qemu", 11000), ], + }, SUPPORT_CONN_HV_SOUND_ICH6 : { "version" : 8008, - "drv_version" : [ ("qemu", 14000), ], - "rhel6_drv_version" : [ ("qemu", 12001) ], + "drv_version" : [("qemu", 14000), ], + "rhel6_drv_version" : [("qemu", 12001)], "rhel6_version" : 8007, - }, + }, SUPPORT_CONN_HV_GRAPHICS_SPICE : { "version" : 8006, - "drv_version" : [ ("qemu", 14000), ], - }, + "drv_version" : [("qemu", 14000), ], + }, SUPPORT_CONN_HV_CHAR_SPICEVMC : { "version" : 8008, - "drv_version" : [ ("qemu", 14000), ], - }, + "drv_version" : [("qemu", 14000), ], + }, SUPPORT_CONN_HV_DIRECT_INTERFACE : { "version" : 8007, - "drv_version" : [ ("qemu", 0), ], - }, + "drv_version" : [("qemu", 0), ], + }, SUPPORT_CONN_HV_FILESYSTEM : { - "drv_version" : [ ("qemu", 13000), + "drv_version" : [("qemu", 13000), ("lxc", 0), ("openvz", 0), ("test", 0)], - "drv_libvirt_version" : [ ("qemu", 8005), + "drv_libvirt_version" : [("qemu", 8005), ("lxc", 0), ("openvz", 0), ("test", 0)], - }, + }, SUPPORT_STREAM_UPLOAD : { # Latest I tested with, and since we will use it by default # for URL installs, want to be sure it works "version" : 9004, - }, + }, } # XXX: RHEL6 has lots of feature backports, and since libvirt doesn't # really offer any XML feature introspection, we have to use hacks to # make sure we aren't generating bogus config on non RHEL _rhel6 = False + + def set_rhel6(val): global _rhel6 _rhel6 = bool(val) + + def get_rhel6(): return _rhel6 # Pull a connection object from the passed libvirt object + + def _get_conn_from_object(obj): if not hasattr(obj, "_conn"): return obj @@ -295,6 +301,8 @@ def _get_conn_from_object(obj): # Check that command is present in the python bindings, and return the # the requested function + + def _get_command(funcname, objname=None, obj=None): if not obj: obj = libvirt @@ -310,15 +318,21 @@ def _get_command(funcname, objname=None, obj=None): return getattr(obj, funcname) # Make sure libvirt object 'objname' has function 'funcname' + + def _has_command(funcname, objname=None, obj=None): return bool(_get_command(funcname, objname, obj)) # Make sure libvirt object has flag 'flag_name' + + def _get_flag(flag_name): return _get_command(flag_name) # Try to call the passed function, and look for signs that libvirt or driver # doesn't support it + + def _try_command(func, args, check_all_error=False): try: func(*args) @@ -337,10 +351,14 @@ def _try_command(func, args, check_all_error=False): return True # Version of the local libvirt library + + def _local_lib_ver(): return libvirt.getVersion() # Version of libvirt library/daemon on the connection (could be remote) + + def _daemon_lib_ver(conn, uri, force_version, minimum_libvirt_version): # Always force the required version if it's after the version which # has getLibVersion @@ -361,6 +379,8 @@ def _daemon_lib_ver(conn, uri, force_version, minimum_libvirt_version): return conn.getLibVersion() # Return the hypervisor version + + def _hv_ver(conn, uri): drv_type = uriutil.get_uri_driver(uri) args = () @@ -385,6 +405,7 @@ def _hv_ver(conn, uri): return ret + def _split_function_name(function): if not function: return (None, None) @@ -395,6 +416,7 @@ def _split_function_name(function): else: return (output[0], output[1]) + def _check_support(conn, feature, data=None): """ Attempt to determine if a specific libvirt feature is support given @@ -554,6 +576,7 @@ def _check_support(conn, feature, data=None): # Public API below + def is_error_nosupport(err): """ Check if passed exception indicates that the called libvirt command isn't @@ -571,29 +594,39 @@ def is_error_nosupport(err): return False + def support_threading(): return bool(_local_lib_ver() >= 6000) + + def support_openauth(): return bool(_local_lib_ver() >= 4000) + def check_conn_support(conn, feature): return _check_support(conn, feature, conn) + def check_conn_hv_support(conn, feature, hv): return _check_support(conn, feature, hv) + def check_domain_support(dom, feature): return _check_support(_get_conn_from_object(dom), feature, dom) + def check_pool_support(pool, feature): return _check_support(_get_conn_from_object(pool), feature, pool) + def check_nodedev_support(nodedev, feature): return _check_support(_get_conn_from_object(nodedev), feature, nodedev) + def check_interface_support(nodedev, feature): return _check_support(_get_conn_from_object(nodedev), feature, nodedev) + def check_stream_support(conn, feature): return (check_conn_support(conn, SUPPORT_CONN_STREAM) and _check_support(conn, feature, conn)) diff --git a/virtinst/uriutil.py b/virtinst/uriutil.py index b9a0804e..653fa377 100644 --- a/virtinst/uriutil.py +++ b/virtinst/uriutil.py @@ -28,7 +28,7 @@ def uri_split(uri): fragment) """ def splitnetloc(url, start=0): - for c in '/?#': # the order is important! + for c in '/?#': # the order is important! delim = url.find(c, start) if delim >= 0: break diff --git a/virtinst/util.py b/virtinst/util.py index bc4626b6..ac254e62 100644 --- a/virtinst/util.py +++ b/virtinst/util.py @@ -37,14 +37,16 @@ import libxml2 from virtinst import uriutil + def listify(l): if l is None: return [] elif type(l) != list: - return [ l ] + return [l] else: return l + def is_vdisk(path): if not os.path.exists("/usr/sbin/vdiskadm"): return False @@ -55,6 +57,7 @@ def is_vdisk(path): return True return False + def stat_disk(path): """Returns the tuple (isreg, size).""" if not os.path.exists(path): @@ -82,6 +85,7 @@ def stat_disk(path): return True, 0 + def blkdev_size(path): """Return the size of the block device. We can't use os.stat() as that returns zero on many platforms.""" @@ -91,6 +95,7 @@ def blkdev_size(path): os.close(fd) return size + def sanitize_arch(arch): """Ensure passed architecture string is the format we expect it. Returns the sanitized result""" @@ -103,6 +108,7 @@ def sanitize_arch(arch): return "x86_64" return arch + def vm_uuid_collision(conn, uuid): """ Check if passed UUID string is in use by another guest of the connection @@ -110,6 +116,7 @@ def vm_uuid_collision(conn, uuid): """ return libvirt_collision(conn.lookupByUUIDString, uuid) + def libvirt_collision(collision_cb, val): """ Run the passed collision function with val as the only argument: @@ -125,6 +132,7 @@ def libvirt_collision(collision_cb, val): pass return check + def validate_uuid(val): if type(val) is not str: raise ValueError(_("UUID must be a string.")) @@ -144,6 +152,7 @@ def validate_uuid(val): "-" + val[16:20] + "-" + val[20:32]) return val + def validate_name(name_type, val, lencheck=False): if type(val) is not str or len(val) == 0: raise ValueError(_("%s name must be a string") % name_type) @@ -155,10 +164,11 @@ def validate_name(name_type, val, lencheck=False): if re.match("^[0-9]+$", val): raise ValueError(_("%s name can not be only numeric characters") % name_type) - if re.match("^[a-zA-Z0-9._-]+$", val) == None: + if re.match("^[a-zA-Z0-9._-]+$", val) is None: raise ValueError(_("%s name can only contain alphanumeric, '_', '.', " "or '-' characters") % name_type) + def validate_macaddr(val): if val is None: return @@ -170,6 +180,8 @@ def validate_macaddr(val): if form is None: raise ValueError(_("MAC address must be of the format " "AA:BB:CC:DD:EE:FF")) + + def xml_append(orig, new): """ Little function that helps generate consistent xml @@ -180,6 +192,7 @@ def xml_append(orig, new): orig += "\n" return orig + new + def fetch_all_guests(conn): """ Return 2 lists: ([all_running_vms], [all_nonrunning_vms]) @@ -209,6 +222,7 @@ def fetch_all_guests(conn): return (active, inactive) + def set_xml_path(xml, path, newval): """ Set the passed xml xpath to the new value @@ -222,7 +236,7 @@ def set_xml_path(xml, path, newval): ctx = doc.xpathNewContext() ret = ctx.xpathEval(path) - if ret != None: + if ret is not None: if type(ret) == list: if len(ret) == 1: ret[0].setContent(newval) @@ -306,6 +320,7 @@ def default_nic(): return dev + def default_bridge(conn=None): if platform.system() == 'SunOS': return ["bridge", default_nic()] @@ -368,6 +383,7 @@ def parse_node_helper(xml, root_name, callback, exec_class=ValueError): return ret + def find_xkblayout(path): """ Reads a keyboard layout from a file that defines an XKBLAYOUT @@ -393,6 +409,7 @@ def find_xkblayout(path): f.close() return kt + def find_keymap_from_etc_default(): """ Look under /etc/default for the host machine's keymap. @@ -403,13 +420,14 @@ def find_keymap_from_etc_default(): """ KEYBOARD_DEFAULT = "/etc/default/keyboard" - paths = [ KEYBOARD_DEFAULT, CONSOLE_SETUP_CONF ] + paths = [KEYBOARD_DEFAULT, CONSOLE_SETUP_CONF] for path in paths: kt = find_xkblayout(path) - if kt != None: + if kt is not None: break return kt + def generate_uuid(conn): for ignore in range(256): uuid = uuidToString(randomUUID(), conn=conn) @@ -426,11 +444,12 @@ KEYBOARD_DIR = "/etc/sysconfig/keyboard" XORG_CONF = "/etc/X11/xorg.conf" CONSOLE_SETUP_CONF = "/etc/default/console-setup" + def default_route(nic=None): if platform.system() == 'SunOS': - cmd = [ '/usr/bin/netstat', '-rn' ] + cmd = ['/usr/bin/netstat', '-rn'] if nic: - cmd += [ '-I', nic ] + cmd += ['-I', nic] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) for line in proc.stdout.readlines(): @@ -445,7 +464,7 @@ def default_route(nic=None): defn = 0 for line in d.xreadlines(): info = line.split() - if (len(info) != 11): # 11 = typical num of fields in the file + if (len(info) != 11): # 11 = typical num of fields in the file logging.warn(_("Invalid line length while parsing %s."), route_file) logging.warn(_("Defaulting bridge to xenbr%d"), defn) @@ -467,6 +486,7 @@ def default_network(conn): return ret + def default_connection(): if os.path.exists('/var/lib/xend'): if os.path.exists('/dev/xen/evtchn'): @@ -491,7 +511,7 @@ def is_blktap_capable(): if platform.system() == 'SunOS': return False - #return os.path.exists("/dev/xen/blktapctrl") + # return os.path.exists("/dev/xen/blktapctrl") f = open("/proc/modules") lines = f.readlines() f.close() @@ -531,7 +551,7 @@ def randomMAC(typ, conn=None): # Testing hack return "00:11:22:33:44:55" - ouis = { 'xen': [ 0x00, 0x16, 0x3E ], 'qemu': [ 0x52, 0x54, 0x00 ] } + ouis = {'xen': [0x00, 0x16, 0x3E], 'qemu': [0x52, 0x54, 0x00]} try: oui = ouis[typ] @@ -553,6 +573,7 @@ def randomUUID(): """Generate a random UUID.""" return [random.randint(0, 255) for ignore in range(0, 16)] + def uuidToString(u, conn=None): if conn and hasattr(conn, "_virtinst__fake_conn_predictable"): # Testing hack @@ -610,11 +631,13 @@ def _xorg_keymap(): f.close() return kt + def _console_setup_keymap(): """Look in /etc/default/console-setup for the host machine's keymap, and attempt to map it to a keymap supported by qemu""" return find_xkblayout(CONSOLE_SETUP_CONF) + def default_keymap(): """Look in /etc/sysconfig for the host machine's keymap, and attempt to map it to a keymap supported by qemu""" @@ -636,9 +659,9 @@ def default_keymap(): s = f.readline() if s == "": break - if re.search("KEYTABLE", s) != None or \ - (re.search("KEYBOARD", s) != None and - re.search("KEYBOARDTYPE", s) == None): + if re.search("KEYTABLE", s) is not None or \ + (re.search("KEYBOARD", s) is not None and + re.search("KEYBOARDTYPE", s) is None): if s.count('"'): delim = '"' elif s.count('='): @@ -648,7 +671,7 @@ def default_keymap(): kt = s.split(delim)[1].strip() f.close() - if kt == None: + if kt is None: logging.debug("Did not parse any usable keymapping.") return default @@ -669,6 +692,7 @@ def is_storage_capable(conn): return support.check_conn_support(conn, support.SUPPORT_CONN_STORAGE) + def get_xml_path(xml, path=None, func=None): """ Return the content from the passed xml xpath, or return the result @@ -684,7 +708,7 @@ def get_xml_path(xml, path=None, func=None): if path: ret = ctx.xpathEval(path) - if ret != None: + if ret is not None: if type(ret) == list: if len(ret) >= 1: result = ret[0].content @@ -703,6 +727,7 @@ def get_xml_path(xml, path=None, func=None): ctx.xpathFreeContext() return result + def lookup_pool_by_path(conn, path): """ Return the first pool with matching matching target path. @@ -729,6 +754,7 @@ def lookup_pool_by_path(conn, path): return p return None + def check_keytable(kt): from virtinst import keytable @@ -755,6 +781,7 @@ def check_keytable(kt): return keymap + def _test(): import doctest doctest.testmod()