Switch to more traditional logging structure

Init a shared log instance in virtinst/logger.py, and use that
throughout the code base, so we aren't calling directly into
'logging'. This helps protect our logging output from being
cluttered with other library output, as happens with some
'requests' usage
This commit is contained in:
Cole Robinson 2019-06-16 21:12:39 -04:00
parent 2c03ea5c92
commit f107e39989
85 changed files with 771 additions and 739 deletions

View File

@ -5,7 +5,6 @@
import atexit import atexit
import imp import imp
import logging
import os import os
# Need to do this before any tests or virtinst import # Need to do this before any tests or virtinst import
@ -15,6 +14,7 @@ os.environ.pop("_ARC_DEBUG", None)
# pylint: disable=wrong-import-position # pylint: disable=wrong-import-position
from virtinst import buildconfig from virtinst import buildconfig
from virtinst import log
# This sets all the cli bits back to their defaults # This sets all the cli bits back to their defaults
imp.reload(buildconfig) imp.reload(buildconfig)
@ -27,6 +27,7 @@ virtxml = None
def setup_logging(): def setup_logging():
import logging
rootLogger = logging.getLogger() rootLogger = logging.getLogger()
for handler in rootLogger.handlers: for handler in rootLogger.handlers:
rootLogger.removeHandler(handler) rootLogger.removeHandler(handler)

View File

@ -1,11 +1,11 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
import traceback import traceback
import unittest import unittest
import virtinst import virtinst
from virtinst import log
_do_skip = None _do_skip = None
@ -28,7 +28,7 @@ class CheckPropsTest(unittest.TestCase):
_do_skip = bool( _do_skip = bool(
result.errors or result.failures or result.skipped) result.errors or result.failures or result.skipped)
except Exception: except Exception:
logging.debug("unittest skip hack failed", exc_info=True) log.debug("unittest skip hack failed", exc_info=True)
if _do_skip: if _do_skip:
self.skipTest("skipping as other tests failed/skipped") self.skipTest("skipping as other tests failed/skipped")

View File

@ -5,7 +5,6 @@
import atexit import atexit
import io import io
import logging
import os import os
import shlex import shlex
import shutil import shutil
@ -18,6 +17,7 @@ try:
except ImportError: except ImportError:
argcomplete = None argcomplete = None
from virtinst import log
from virtinst import unattended from virtinst import unattended
from tests import virtinstall, virtclone, virtconvert, virtxml from tests import virtinstall, virtclone, virtconvert, virtxml
@ -185,7 +185,7 @@ class Command(object):
def _launch_command(self, conn): def _launch_command(self, conn):
logging.debug(self.cmdstr) log.debug(self.cmdstr)
app = self.argv[0] app = self.argv[0]
@ -253,7 +253,7 @@ class Command(object):
code, output = self._launch_command(conn) code, output = self._launch_command(conn)
logging.debug("%s\n", output) log.debug("%s\n", output)
return code, output return code, output
except Exception as e: except Exception as e:
return (-1, "".join(traceback.format_exc()) + str(e)) return (-1, "".join(traceback.format_exc()) + str(e))

View File

@ -5,11 +5,11 @@
import unittest import unittest
import os import os
import logging
from tests import utils from tests import utils
from virtinst import Cloner from virtinst import Cloner
from virtinst import log
ORIG_NAME = "clone-orig" ORIG_NAME = "clone-orig"
CLONE_NAME = "clone-new" CLONE_NAME = "clone-new"
@ -140,7 +140,7 @@ class TestClone(unittest.TestCase):
"when it shouldn't.") "when it shouldn't.")
except (ValueError, RuntimeError) as e: except (ValueError, RuntimeError) as e:
# Exception expected # Exception expected
logging.debug("Received expected exception: %s", str(e)) log.debug("Received expected exception: %s", str(e))
def testCloneStorageManaged(self): def testCloneStorageManaged(self):
disks = ["%s/new1.img" % POOL1, "%s/new2.img" % DISKPOOL] disks = ["%s/new1.img" % POOL1, "%s/new2.img" % DISKPOOL]

View File

@ -3,11 +3,11 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
import os import os
import unittest import unittest
from virtinst import StoragePool, StorageVolume from virtinst import StoragePool, StorageVolume
from virtinst import log
from tests import utils from tests import utils
@ -67,7 +67,7 @@ def createVol(conn, poolobj, volname=None, input_vol=None, clone_vol=None):
# Format here depends on libvirt-1.2.0 and later # Format here depends on libvirt-1.2.0 and later
if clone_vol and conn.local_libvirt_version() < 1002000: if clone_vol and conn.local_libvirt_version() < 1002000:
logging.debug("skip clone compare") log.debug("skip clone compare")
return return
alloc = 5 * 1024 * 1024 * 1024 alloc = 5 * 1024 * 1024 * 1024

View File

@ -3,7 +3,6 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
import os import os
import re import re
import sys import sys
@ -15,6 +14,7 @@ from tests import utils
import virtinst.progress import virtinst.progress
from virtinst import Installer from virtinst import Installer
from virtinst import Guest from virtinst import Guest
from virtinst import log
# These are all functional tests # These are all functional tests
os.environ.pop("VIRTINST_TEST_SUITE", None) os.environ.pop("VIRTINST_TEST_SUITE", None)
@ -153,7 +153,7 @@ def _testGuest(testdata, guest):
treemedia = installer._treemedia # pylint: disable=protected-access treemedia = installer._treemedia # pylint: disable=protected-access
fetcher = treemedia._cached_fetcher # pylint: disable=protected-access fetcher = treemedia._cached_fetcher # pylint: disable=protected-access
def fakeAcquireFile(filename): def fakeAcquireFile(filename):
logging.debug("Fake acquiring %s", filename) log.debug("Fake acquiring %s", filename)
return filename return filename
fetcher.acquireFile = fakeAcquireFile fetcher.acquireFile = fakeAcquireFile

View File

@ -1,11 +1,12 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
import os import os
import libvirt import libvirt
from virtinst import log
from tests.uitests import utils as uiutils from tests.uitests import utils as uiutils
@ -231,4 +232,4 @@ class Console(uiutils.UITestCase):
pool.destroy() pool.destroy()
pool.undefine() pool.undefine()
except Exception: except Exception:
logging.debug("Error cleaning up pool", exc_info=True) log.debug("Error cleaning up pool", exc_info=True)

View File

@ -1,7 +1,6 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
import os import os
import re import re
import time import time
@ -15,6 +14,8 @@ from gi.repository import Gdk
import pyatspi import pyatspi
import dogtail.utils import dogtail.utils
from virtinst import log
import tests import tests
if not dogtail.utils.isA11yEnabled(): if not dogtail.utils.isA11yEnabled():
@ -223,7 +224,7 @@ class _FuzzyPredicate(dogtail.predicate.Predicate):
return return
return True return True
except Exception as e: except Exception as e:
logging.debug( log.debug(
"got predicate exception name=%s role=%s labeller=%s: %s", "got predicate exception name=%s role=%s labeller=%s: %s",
self._name, self._roleName, self._labeller_text, e) self._name, self._roleName, self._labeller_text, e)
@ -495,7 +496,7 @@ class VMMDogtailApp(object):
try: try:
self._proc.send_signal(signal.SIGINT) self._proc.send_signal(signal.SIGINT)
except Exception: except Exception:
logging.debug("Error terminating process", exc_info=True) log.debug("Error terminating process", exc_info=True)
self._proc = None self._proc = None
return return
@ -506,7 +507,7 @@ class VMMDogtailApp(object):
self._proc = None self._proc = None
return return
logging.warning("App didn't exit gracefully from SIGINT. Killing...") log.warning("App didn't exit gracefully from SIGINT. Killing...")
try: try:
self._proc.kill() self._proc.kill()
finally: finally:

View File

@ -5,13 +5,12 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import argparse import argparse
import logging
import sys import sys
from virtinst import cli from virtinst import cli
from virtinst import Cloner from virtinst import Cloner
from virtinst import log
from virtinst.cli import fail, print_stdout, print_stderr from virtinst.cli import fail, print_stdout, print_stderr
@ -20,7 +19,7 @@ def get_clone_name(new_name, auto_clone, design):
if not new_name and auto_clone: if not new_name and auto_clone:
# Generate a name to use # Generate a name to use
new_name = design.generate_clone_name() new_name = design.generate_clone_name()
logging.debug("Auto-generated clone name '%s'", new_name) log.debug("Auto-generated clone name '%s'", new_name)
if not new_name: if not new_name:
fail(_("A name is required for the new virtual machine," fail(_("A name is required for the new virtual machine,"
@ -204,7 +203,7 @@ def main(conn=None):
print_stdout("") print_stdout("")
print_stdout(_("Clone '%s' created successfully.") % design.clone_name) print_stdout(_("Clone '%s' created successfully.") % design.clone_name)
logging.debug("end clone") log.debug("end clone")
return 0 return 0
if __name__ == "__main__": # pragma: no cover if __name__ == "__main__": # pragma: no cover

View File

@ -7,7 +7,6 @@
import argparse import argparse
import atexit import atexit
import logging
import sys import sys
import time import time
@ -15,6 +14,7 @@ import libvirt
import virtinst import virtinst
from virtinst import cli from virtinst import cli
from virtinst import log
from virtinst.cli import fail, print_stdout, print_stderr from virtinst.cli import fail, print_stdout, print_stderr
@ -40,7 +40,7 @@ def supports_pxe(guest):
xmlobj = virtinst.Network(nic.conn, parsexml=netobj.XMLDesc(0)) xmlobj = virtinst.Network(nic.conn, parsexml=netobj.XMLDesc(0))
return xmlobj.can_pxe() return xmlobj.can_pxe()
except Exception: # pragma: no cover except Exception: # pragma: no cover
logging.debug("Error checking if PXE supported", exc_info=True) log.debug("Error checking if PXE supported", exc_info=True)
return True return True
return False return False
@ -81,7 +81,7 @@ def convert_old_init(options):
if not options.boot: if not options.boot:
options.boot = [""] options.boot = [""]
options.boot[-1] += ",init=%s" % options.init options.boot[-1] += ",init=%s" % options.init
logging.debug("Converted old --init to --boot %s", options.boot[-1]) log.debug("Converted old --init to --boot %s", options.boot[-1])
def _do_convert_old_disks(options): def _do_convert_old_disks(options):
@ -109,7 +109,7 @@ def _do_convert_old_disks(options):
if optstr: if optstr:
optstr += "," optstr += ","
optstr += "sparse=no" optstr += "sparse=no"
logging.debug("Converted to new style: --disk %s", optstr) log.debug("Converted to new style: --disk %s", optstr)
opts.append(optstr) opts.append(optstr)
options.disk = opts options.disk = opts
@ -136,7 +136,7 @@ def convert_old_disks(options):
del(options.disksize) del(options.disksize)
del(options.sparse) del(options.sparse)
del(options.nodisks) del(options.nodisks)
logging.debug("Distilled --disk options: %s", options.disk) log.debug("Distilled --disk options: %s", options.disk)
def convert_old_os_options(options): def convert_old_os_options(options):
@ -160,7 +160,7 @@ def convert_old_cpuset(options):
newvcpus = options.vcpus or [] newvcpus = options.vcpus or []
newvcpus.append(",cpuset=%s" % options.cpuset) newvcpus.append(",cpuset=%s" % options.cpuset)
options.vcpus = newvcpus options.vcpus = newvcpus
logging.debug("Generated compat cpuset: --vcpus %s", options.vcpus[-1]) log.debug("Generated compat cpuset: --vcpus %s", options.vcpus[-1])
def convert_old_networks(options): def convert_old_networks(options):
@ -204,7 +204,7 @@ def convert_old_networks(options):
del(options.nonetworks) del(options.nonetworks)
options.network = networks options.network = networks
logging.debug("Distilled --network options: %s", options.network) log.debug("Distilled --network options: %s", options.network)
def convert_old_graphics(options): def convert_old_graphics(options):
@ -241,7 +241,7 @@ def convert_old_graphics(options):
if keymap: if keymap:
optstr += ",keymap=%s" % keymap optstr += ",keymap=%s" % keymap
logging.debug("--graphics compat generated: %s", optstr) log.debug("--graphics compat generated: %s", optstr)
options.graphics = [optstr] options.graphics = [optstr]
@ -321,7 +321,7 @@ def _show_nographics_warnings(options, guest, installer):
return return
if installer.cdrom: if installer.cdrom:
logging.warning(_("CDROM media does not print to the text console " log.warning(_("CDROM media does not print to the text console "
"by default, so you likely will not see text install output. " "by default, so you likely will not see text install output. "
"You might want to use --location.") + " " + "You might want to use --location.") + " " +
_cdrom_location_man_page) _cdrom_location_man_page)
@ -334,7 +334,7 @@ def _show_nographics_warnings(options, guest, installer):
# they likely won't see any output. # they likely won't see any output.
if not guest.devices.console: if not guest.devices.console:
logging.warning(_("No --console device added, you likely will not " log.warning(_("No --console device added, you likely will not "
"see text install output from the guest.")) "see text install output from the guest."))
return return
@ -348,17 +348,17 @@ def _show_memory_warnings(guest):
minram = (res.get_minimum_ram(guest.os.arch) or 0) minram = (res.get_minimum_ram(guest.os.arch) or 0)
if minram: if minram:
if (minram // 1024) > guest.currentMemory: if (minram // 1024) > guest.currentMemory:
logging.warning(_("Requested memory %s MiB is less than the " log.warning(_("Requested memory %s MiB is less than the "
"recommended %s MiB for OS %s"), rammb, "recommended %s MiB for OS %s"), rammb,
minram // (1024 * 1024), guest.osinfo.name) minram // (1024 * 1024), guest.osinfo.name)
elif rammb < 17: elif rammb < 17:
logging.warning(_("Requested memory %s MiB is abnormally low. " log.warning(_("Requested memory %s MiB is abnormally low. "
"Were you trying to specify GiB?"), rammb) "Were you trying to specify GiB?"), rammb)
def show_warnings(options, guest, installer, osdata): def show_warnings(options, guest, installer, osdata):
if options.pxe and not supports_pxe(guest): if options.pxe and not supports_pxe(guest):
logging.warning(_("The guest's network configuration does not support " log.warning(_("The guest's network configuration does not support "
"PXE")) "PXE"))
# Limit it to hvm x86 guests which presently our defaults # Limit it to hvm x86 guests which presently our defaults
@ -367,7 +367,7 @@ def show_warnings(options, guest, installer, osdata):
not osdata.is_none and not osdata.is_none and
not osdata.name == "generic" and not osdata.name == "generic" and
guest.os.is_x86() and guest.os.is_hvm()): guest.os.is_x86() and guest.os.is_hvm()):
logging.warning(_("No operating system detected, VM performance may " log.warning(_("No operating system detected, VM performance may "
"suffer. Specify an OS with --os-variant for optimal results.")) "suffer. Specify an OS with --os-variant for optimal results."))
_show_memory_warnings(guest) _show_memory_warnings(guest)
@ -630,13 +630,13 @@ def start_install(guest, installer, options):
if not conscb and options.wait is None: if not conscb and options.wait is None:
# If there isn't any console to actually connect up, # If there isn't any console to actually connect up,
# default to --wait -1 to get similarish behavior # default to --wait -1 to get similarish behavior
logging.warning(_("No console to launch for the guest, " log.warning(_("No console to launch for the guest, "
"defaulting to --wait -1")) "defaulting to --wait -1"))
options.wait = -1 options.wait = -1
waithandler = WaitHandler(options.wait) waithandler = WaitHandler(options.wait)
meter = cli.get_meter() meter = cli.get_meter()
logging.debug("Guest.has_install_phase: %s", log.debug("Guest.has_install_phase: %s",
installer.has_install_phase()) installer.has_install_phase())
# we've got everything -- try to start the install # we've got everything -- try to start the install
@ -671,7 +671,7 @@ def start_install(guest, installer, options):
options.destroy_on_exit) options.destroy_on_exit)
except KeyboardInterrupt: # pragma: no cover except KeyboardInterrupt: # pragma: no cover
logging.debug("", exc_info=True) log.debug("", exc_info=True)
print_stderr(_("Domain install interrupted.")) print_stderr(_("Domain install interrupted."))
raise raise
except Exception as e: except Exception as e:
@ -694,7 +694,7 @@ def check_domain(installer, domain, conscb, transient, waithandler):
try: try:
dominfo = domain.info() dominfo = domain.info()
state = dominfo[0] state = dominfo[0]
logging.debug("Domain state after install: %s", state) log.debug("Domain state after install: %s", state)
if state == libvirt.VIR_DOMAIN_CRASHED: if state == libvirt.VIR_DOMAIN_CRASHED:
fail(_("Domain has crashed.")) # pragma: no cover fail(_("Domain has crashed.")) # pragma: no cover
@ -702,7 +702,7 @@ def check_domain(installer, domain, conscb, transient, waithandler):
return not domain.isActive() return not domain.isActive()
except libvirt.libvirtError as e: except libvirt.libvirtError as e:
if transient and e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN: if transient and e.get_error_code() == libvirt.VIR_ERR_NO_DOMAIN:
logging.debug("transient VM shutdown and disappeared.") log.debug("transient VM shutdown and disappeared.")
return True return True
raise # pragma: no cover raise # pragma: no cover
@ -923,7 +923,7 @@ def _destroy_on_exit(domain):
domain.destroy() # pragma: no cover domain.destroy() # pragma: no cover
except libvirt.libvirtError as e: # pragma: no cover except libvirt.libvirtError as e: # pragma: no cover
if e.get_error_code() != libvirt.VIR_ERR_NO_DOMAIN: if e.get_error_code() != libvirt.VIR_ERR_NO_DOMAIN:
logging.debug("Error invoking atexit destroy_on_exit", log.debug("Error invoking atexit destroy_on_exit",
exc_info=True) exc_info=True)
@ -998,7 +998,7 @@ if __name__ == "__main__": # pragma: no cover
except SystemExit as sys_e: except SystemExit as sys_e:
sys.exit(sys_e.code) sys.exit(sys_e.code)
except KeyboardInterrupt: except KeyboardInterrupt:
logging.debug("", exc_info=True) log.debug("", exc_info=True)
print_stderr(_("Installation aborted at user request")) print_stderr(_("Installation aborted at user request"))
except Exception as main_e: except Exception as main_e:
fail(main_e) fail(main_e)

View File

@ -7,7 +7,6 @@
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import argparse import argparse
import logging
import os import os
import signal import signal
import sys import sys
@ -20,6 +19,7 @@ from gi.repository import LibvirtGLib
from virtinst import BuildConfig from virtinst import BuildConfig
from virtinst import VirtinstConnection from virtinst import VirtinstConnection
from virtinst import cli from virtinst import cli
from virtinst import log
# This is massively heavy handed, but I can't figure out any way to shut # This is massively heavy handed, but I can't figure out any way to shut
# up the slew of gtk deprecation warnings that clog up our very useful # up the slew of gtk deprecation warnings that clog up our very useful
@ -36,7 +36,7 @@ except (ValueError, AttributeError):
def _show_startup_error(msg, details): def _show_startup_error(msg, details):
logging.debug("Error starting virt-manager: %s\n%s", msg, details, log.debug("Error starting virt-manager: %s\n%s", msg, details,
exc_info=True) exc_info=True)
from virtManager.error import vmmErrorDialog from virtManager.error import vmmErrorDialog
err = vmmErrorDialog.get_instance() err = vmmErrorDialog.get_instance()
@ -81,7 +81,7 @@ def _import_gtk(leftovers):
msg = str(e) msg = str(e)
if display: if display:
msg += ": Could not open display: %s" % display msg += ": Could not open display: %s" % display
logging.debug("".join(traceback.format_exc())) log.debug("".join(traceback.format_exc()))
print(msg) print(msg)
sys.exit(1) sys.exit(1)
finally: finally:
@ -220,14 +220,14 @@ def main():
cli.setupLogging("virt-manager", options.debug, False, False) cli.setupLogging("virt-manager", options.debug, False, False)
import virtManager import virtManager
logging.debug("virt-manager version: %s", BuildConfig.version) log.debug("virt-manager version: %s", BuildConfig.version)
logging.debug("virtManager import: %s", str(virtManager)) log.debug("virtManager import: %s", str(virtManager))
if BuildConfig.running_from_srcdir: if BuildConfig.running_from_srcdir:
_setup_gsettings_path(BuildConfig.gsettings_dir) _setup_gsettings_path(BuildConfig.gsettings_dir)
if options.trace_libvirt: if options.trace_libvirt:
logging.debug("Libvirt tracing requested") log.debug("Libvirt tracing requested")
import virtManager.module_trace import virtManager.module_trace
import libvirt import libvirt
virtManager.module_trace.wrap_module(libvirt, virtManager.module_trace.wrap_module(libvirt,
@ -268,11 +268,11 @@ def main():
if leftovers: if leftovers:
raise RuntimeError("Unhandled command line options '%s'" % leftovers) raise RuntimeError("Unhandled command line options '%s'" % leftovers)
logging.debug("PyGObject version: %d.%d.%d", log.debug("PyGObject version: %d.%d.%d",
gi.version_info[0], gi.version_info[0],
gi.version_info[1], gi.version_info[1],
gi.version_info[2]) gi.version_info[2])
logging.debug("GTK version: %d.%d.%d", log.debug("GTK version: %d.%d.%d",
Gtk.get_major_version(), Gtk.get_major_version(),
Gtk.get_minor_version(), Gtk.get_minor_version(),
Gtk.get_micro_version()) Gtk.get_micro_version())
@ -333,7 +333,7 @@ def main():
from gi.repository import GLib from gi.repository import GLib
def _sigint_handler(user_data): def _sigint_handler(user_data):
ignore = user_data ignore = user_data
logging.debug("Received KeyboardInterrupt. Exiting application.") log.debug("Received KeyboardInterrupt. Exiting application.")
engine.exit_app() engine.exit_app()
GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT, GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT,
_sigint_handler, None) _sigint_handler, None)
@ -345,7 +345,7 @@ if __name__ == "__main__":
try: try:
main() main()
except KeyboardInterrupt: except KeyboardInterrupt:
logging.debug("Received KeyboardInterrupt. Exiting application.") log.debug("Received KeyboardInterrupt. Exiting application.")
except Exception as run_e: except Exception as run_e:
if "Gtk" not in globals(): if "Gtk" not in globals():
raise raise

View File

@ -6,7 +6,6 @@
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import difflib import difflib
import logging
import re import re
import sys import sys
@ -14,6 +13,7 @@ import libvirt
import virtinst import virtinst
from virtinst import cli from virtinst import cli
from virtinst import log
from virtinst import xmlutil from virtinst import xmlutil
from virtinst.cli import fail, print_stdout, print_stderr from virtinst.cli import fail, print_stdout, print_stderr
@ -44,9 +44,9 @@ def get_diff(origxml, newxml):
tofile="Altered XML")) tofile="Altered XML"))
if ret: if ret:
logging.debug("XML diff:\n%s", ret) log.debug("XML diff:\n%s", ret)
else: else:
logging.debug("No XML diff, didn't generate any change.") log.debug("No XML diff, didn't generate any change.")
return ret return ret
@ -82,7 +82,7 @@ def get_domain_and_guest(conn, domstr):
domain = conn.lookupByName(domstr) domain = conn.lookupByName(domstr)
except Exception: except Exception:
# In case the VM has a UUID or ID for a name # In case the VM has a UUID or ID for a name
logging.debug("Error looking up domain by name", exc_info=True) log.debug("Error looking up domain by name", exc_info=True)
if isint: if isint:
domain = conn.lookupByID(int(domstr)) domain = conn.lookupByID(int(domstr))
elif isuuid: elif isuuid:
@ -254,7 +254,7 @@ def setup_device(dev):
if getattr(dev, "DEVICE_TYPE", None) != "disk": if getattr(dev, "DEVICE_TYPE", None) != "disk":
return return
logging.debug("Doing setup for disk=%s", dev) log.debug("Doing setup for disk=%s", dev)
dev.build_storage(cli.get_meter()) dev.build_storage(cli.get_meter())
@ -347,7 +347,7 @@ def prepare_changes(xmlobj, options, parserclass):
diff = get_diff(origxml, newxml) diff = get_diff(origxml, newxml)
if not diff: if not diff:
logging.warning(_("No XML diff was generated. The requested " log.warning(_("No XML diff was generated. The requested "
"changes will have no effect.")) "changes will have no effect."))
if options.print_diff: if options.print_diff:
@ -521,7 +521,7 @@ def main(conn=None):
update_changes(domain, devs, action, options.confirm) update_changes(domain, devs, action, options.confirm)
performed_update = True performed_update = True
else: else:
logging.warning( log.warning(
_("The VM is not running, --update is inapplicable.")) _("The VM is not running, --update is inapplicable."))
if not options.define: if not options.define:
# --update and --no-define passed, so we are done # --update and --no-define passed, so we are done
@ -555,7 +555,7 @@ def main(conn=None):
print_stdout( print_stdout(
_("Changes will take effect after the domain is fully powered off.")) _("Changes will take effect after the domain is fully powered off."))
elif defined_xml_is_unchanged(conn, domain, original_xml): elif defined_xml_is_unchanged(conn, domain, original_xml):
logging.warning(_("XML did not change after domain define. You may " log.warning(_("XML did not change after domain define. You may "
"have changed a value that libvirt is setting by default.")) "have changed a value that libvirt is setting by default."))
return 0 return 0
@ -567,7 +567,7 @@ if __name__ == "__main__": # pragma: no cover
except SystemExit as sys_e: except SystemExit as sys_e:
sys.exit(sys_e.code) sys.exit(sys_e.code)
except KeyboardInterrupt: except KeyboardInterrupt:
logging.debug("", exc_info=True) log.debug("", exc_info=True)
print_stderr(_("Aborted at user request")) print_stderr(_("Aborted at user request"))
except Exception as main_e: except Exception as main_e:
fail(main_e) fail(main_e)

View File

@ -4,7 +4,7 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging from virtinst import log
from .baseclass import vmmGObjectUI from .baseclass import vmmGObjectUI
@ -30,13 +30,13 @@ class vmmAbout(vmmGObjectUI):
}) })
def show(self, parent): def show(self, parent):
logging.debug("Showing about") log.debug("Showing about")
self.topwin.set_version(self.config.get_appversion()) self.topwin.set_version(self.config.get_appversion())
self.topwin.set_transient_for(parent) self.topwin.set_transient_for(parent)
self.topwin.present() self.topwin.present()
def close(self, ignore1=None, ignore2=None): def close(self, ignore1=None, ignore2=None):
logging.debug("Closing about") log.debug("Closing about")
self.topwin.hide() self.topwin.hide()
return 1 return 1

View File

@ -4,7 +4,6 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
import traceback import traceback
from gi.repository import Gtk from gi.repository import Gtk
@ -15,6 +14,7 @@ from virtinst import (DeviceChannel, DeviceConsole,
DeviceInput, DeviceInterface, DevicePanic, DeviceParallel, DeviceInput, DeviceInterface, DevicePanic, DeviceParallel,
DeviceRedirdev, DeviceRng, DeviceSerial, DeviceSmartcard, DeviceRedirdev, DeviceRng, DeviceSerial, DeviceSmartcard,
DeviceSound, DeviceTpm, DeviceVideo, DeviceVsock, DeviceWatchdog) DeviceSound, DeviceTpm, DeviceVideo, DeviceVsock, DeviceWatchdog)
from virtinst import log
from . import uiutil from . import uiutil
from .fsdetails import vmmFSDetails from .fsdetails import vmmFSDetails
@ -127,7 +127,7 @@ class vmmAddHardware(vmmGObjectUI):
self._set_initial_state() self._set_initial_state()
def show(self, parent): def show(self, parent):
logging.debug("Showing addhw") log.debug("Showing addhw")
self._reset_state() self._reset_state()
self.topwin.set_transient_for(parent) self.topwin.set_transient_for(parent)
self.topwin.present() self.topwin.present()
@ -137,7 +137,7 @@ class vmmAddHardware(vmmGObjectUI):
def close(self, ignore1=None, ignore2=None): def close(self, ignore1=None, ignore2=None):
if self.is_visible(): if self.is_visible():
logging.debug("Closing addhw") log.debug("Closing addhw")
self.topwin.hide() self.topwin.hide()
if self._storagebrowser: if self._storagebrowser:
self._storagebrowser.close() self._storagebrowser.close()
@ -385,7 +385,7 @@ class vmmAddHardware(vmmGObjectUI):
vm.hotplug(**hotplug_args) vm.hotplug(**hotplug_args)
except Exception as e: except Exception as e:
did_hotplug = True did_hotplug = True
logging.debug("Hotplug failed: %s", str(e)) log.debug("Hotplug failed: %s", str(e))
hotplug_err = ((str(e), "".join(traceback.format_exc()))) hotplug_err = ((str(e), "".join(traceback.format_exc())))
if did_hotplug and not hotplug_err: if did_hotplug and not hotplug_err:
@ -1285,22 +1285,22 @@ class vmmAddHardware(vmmGObjectUI):
dev.get_parent_pool()): dev.get_parent_pool()):
poolname = dev.get_parent_pool().name() poolname = dev.get_parent_pool().name()
logging.debug("Running build_storage() for device=%s", dev) log.debug("Running build_storage() for device=%s", dev)
dev.build_storage(meter=asyncjob.get_meter()) dev.build_storage(meter=asyncjob.get_meter())
logging.debug("build_storage() complete") log.debug("build_storage() complete")
if poolname: if poolname:
try: try:
pool = self.conn.get_pool(poolname) pool = self.conn.get_pool(poolname)
self.idle_add(pool.refresh) self.idle_add(pool.refresh)
except Exception: except Exception:
logging.debug("Error looking up pool=%s for refresh after " log.debug("Error looking up pool=%s for refresh after "
"storage creation.", poolname, exc_info=True) "storage creation.", poolname, exc_info=True)
def _add_device(self, dev): def _add_device(self, dev):
xml = dev.get_xml() xml = dev.get_xml()
logging.debug("Adding device:\n%s", xml) log.debug("Adding device:\n%s", xml)
if self._remove_usb_controller: if self._remove_usb_controller:
kwargs = {} kwargs = {}
@ -1317,7 +1317,7 @@ class vmmAddHardware(vmmGObjectUI):
controller = getattr(dev, "vmm_controller", None) controller = getattr(dev, "vmm_controller", None)
if controller is not None: if controller is not None:
logging.debug("Adding controller:\n%s", log.debug("Adding controller:\n%s",
controller.get_xml()) controller.get_xml())
# Hotplug device # Hotplug device
attach_err = False attach_err = False
@ -1326,7 +1326,7 @@ class vmmAddHardware(vmmGObjectUI):
self.vm.attach_device(controller) self.vm.attach_device(controller)
self.vm.attach_device(dev) self.vm.attach_device(dev)
except Exception as e: except Exception as e:
logging.debug("Device could not be hotplugged: %s", str(e)) log.debug("Device could not be hotplugged: %s", str(e))
attach_err = (str(e), "".join(traceback.format_exc())) attach_err = (str(e), "".join(traceback.format_exc()))
if attach_err: if attach_err:
@ -1433,7 +1433,7 @@ class vmmAddHardware(vmmGObjectUI):
def _build_xmleditor_device(self, srcdev): def _build_xmleditor_device(self, srcdev):
xml = self._xmleditor.get_xml() xml = self._xmleditor.get_xml()
logging.debug("Using XML from xmleditor:\n%s", xml) log.debug("Using XML from xmleditor:\n%s", xml)
devclass = srcdev.__class__ devclass = srcdev.__class__
dev = devclass(srcdev.conn, parsexml=xml) dev = devclass(srcdev.conn, parsexml=xml)

View File

@ -3,12 +3,13 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
import os import os
from gi.repository import Gtk from gi.repository import Gtk
import virtinst import virtinst
from virtinst import log
from . import uiutil from . import uiutil
from .baseclass import vmmGObjectUI from .baseclass import vmmGObjectUI
@ -49,7 +50,7 @@ class vmmAddStorage(vmmGObjectUI):
avail = int(pool.get_available()) avail = int(pool.get_available())
return float(avail / 1024.0 / 1024.0 / 1024.0) return float(avail / 1024.0 / 1024.0 / 1024.0)
except Exception: except Exception:
logging.exception("Error determining host disk space") log.exception("Error determining host disk space")
return -1 return -1
def _update_host_space(self): def _update_host_space(self):
@ -85,7 +86,7 @@ class vmmAddStorage(vmmGObjectUI):
if not broken_paths: if not broken_paths:
return return
logging.debug("No search access for dirs: %s", broken_paths) log.debug("No search access for dirs: %s", broken_paths)
resp, chkres = src.err.warn_chkbox( resp, chkres = src.err.warn_chkbox(
_("The emulator may not have search permissions " _("The emulator may not have search permissions "
"for the path '%s'.") % path, "for the path '%s'.") % path,
@ -98,7 +99,7 @@ class vmmAddStorage(vmmGObjectUI):
if not resp: if not resp:
return return
logging.debug("Attempting to correct permission issues.") log.debug("Attempting to correct permission issues.")
errors = virtinst.DeviceDisk.fix_path_search( errors = virtinst.DeviceDisk.fix_path_search(
conn.get_backend(), searchdata) conn.get_backend(), searchdata)
if not errors: if not errors:
@ -113,7 +114,7 @@ class vmmAddStorage(vmmGObjectUI):
details += "%s : %s\n" % (p, error) details += "%s : %s\n" % (p, error)
details += "\nIt is very likely the VM will fail to start up." details += "\nIt is very likely the VM will fail to start up."
logging.debug("Permission errors:\n%s", details) log.debug("Permission errors:\n%s", details)
ignore, chkres = src.err.err_chkbox(errmsg, details, ignore, chkres = src.err.err_chkbox(errmsg, details,
_("Don't ask about these directories again.")) _("Don't ask about these directories again."))
@ -184,11 +185,11 @@ class vmmAddStorage(vmmGObjectUI):
fmt = self.conn.get_default_storage_format() fmt = self.conn.get_default_storage_format()
if disk.get_vol_install().supports_property("format"): if disk.get_vol_install().supports_property("format"):
logging.debug("Using default prefs format=%s for path=%s", log.debug("Using default prefs format=%s for path=%s",
fmt, disk.path) fmt, disk.path)
disk.get_vol_install().format = fmt disk.get_vol_install().format = fmt
else: else:
logging.debug("path=%s can not use default prefs format=%s, " log.debug("path=%s can not use default prefs format=%s, "
"not setting it", disk.path, fmt) "not setting it", disk.path, fmt)
return disk return disk

View File

@ -4,7 +4,6 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
import os import os
import sys import sys
import threading import threading
@ -16,6 +15,8 @@ from gi.repository import GLib
from gi.repository import GObject from gi.repository import GObject
from gi.repository import Gtk from gi.repository import Gtk
from virtinst import log
from . import config from . import config
@ -93,7 +94,7 @@ class vmmGObject(GObject.GObject):
for h in self._gobject_timeouts[:]: for h in self._gobject_timeouts[:]:
self.remove_gobject_timeout(h) self.remove_gobject_timeout(h)
except Exception: except Exception:
logging.exception("Error cleaning up %s", self) log.exception("Error cleaning up %s", self)
self.__cleaned_up = True self.__cleaned_up = True
@ -110,7 +111,7 @@ class vmmGObject(GObject.GObject):
if config.vmmConfig.is_initialized() and self._leak_check: if config.vmmConfig.is_initialized() and self._leak_check:
self.config.remove_object(self.object_key) self.config.remove_object(self.object_key)
except Exception: except Exception:
logging.exception("Error removing %s", self.object_key) log.exception("Error removing %s", self.object_key)
@property @property
def config(self): def config(self):
@ -190,7 +191,7 @@ class vmmGObject(GObject.GObject):
def _logtrace(self, msg=""): def _logtrace(self, msg=""):
if msg: if msg:
msg += " " msg += " "
logging.debug("%s(%s %s)\n:%s", log.debug("%s(%s %s)\n:%s",
msg, self.object_key, self._refcount(), msg, self.object_key, self._refcount(),
"".join(traceback.format_stack())) "".join(traceback.format_stack()))
@ -304,7 +305,7 @@ class vmmGObjectUI(vmmGObject):
self.topwin = None self.topwin = None
self._err = None self._err = None
except Exception: except Exception:
logging.exception("Error cleaning up %s", self) log.exception("Error cleaning up %s", self)
self.__cleaned_up = True self.__cleaned_up = True
@ -335,7 +336,7 @@ class vmmGObjectUI(vmmGObject):
except Exception: except Exception:
# If a cursor icon theme isn't installed this can cause errors # If a cursor icon theme isn't installed this can cause errors
# https://bugzilla.redhat.com/show_bug.cgi?id=1516588 # https://bugzilla.redhat.com/show_bug.cgi?id=1516588
logging.debug("Error setting cursor_type=%s", log.debug("Error setting cursor_type=%s",
cursor_type, exc_info=True) cursor_type, exc_info=True)
def set_finish_cursor(self): def set_finish_cursor(self):

View File

@ -4,7 +4,6 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
import os import os
from gi.repository import Gtk from gi.repository import Gtk
@ -13,6 +12,7 @@ from gi.repository import Gdk
import virtinst import virtinst
from virtinst import Cloner from virtinst import Cloner
from virtinst import DeviceInterface from virtinst import DeviceInterface
from virtinst import log
from . import uiutil from . import uiutil
from .baseclass import vmmGObjectUI from .baseclass import vmmGObjectUI
@ -174,7 +174,7 @@ class vmmCloneVM(vmmGObjectUI):
return None return None
def show(self, parent, vm): def show(self, parent, vm):
logging.debug("Showing clone wizard") log.debug("Showing clone wizard")
self._set_vm(vm) self._set_vm(vm)
self.reset_state() self.reset_state()
self.topwin.set_transient_for(parent) self.topwin.set_transient_for(parent)
@ -182,7 +182,7 @@ class vmmCloneVM(vmmGObjectUI):
self.topwin.present() self.topwin.present()
def close(self, ignore1=None, ignore2=None): def close(self, ignore1=None, ignore2=None):
logging.debug("Closing clone wizard") log.debug("Closing clone wizard")
self.change_mac_close() self.change_mac_close()
self.change_storage_close() self.change_storage_close()
self.topwin.hide() self.topwin.hide()
@ -415,7 +415,7 @@ class vmmCloneVM(vmmGObjectUI):
cd.skip_target = skip_targets cd.skip_target = skip_targets
cd.setup_original() cd.setup_original()
except Exception as e: except Exception as e:
logging.exception("Disk target '%s' caused clone error", log.exception("Disk target '%s' caused clone error",
force_target) force_target)
storage_add(str(e)) storage_add(str(e))
continue continue
@ -436,13 +436,13 @@ class vmmCloneVM(vmmGObjectUI):
# Generate disk path, make sure that works # Generate disk path, make sure that works
clone_path = self.generate_clone_path_name(path) clone_path = self.generate_clone_path_name(path)
logging.debug("Original path: %s\nGenerated clone path: %s", log.debug("Original path: %s\nGenerated clone path: %s",
path, clone_path) path, clone_path)
cd.clone_paths = clone_path cd.clone_paths = clone_path
size = cd.original_disks[0].get_size() size = cd.original_disks[0].get_size()
except Exception as e: except Exception as e:
logging.exception("Error setting generated path '%s'", log.exception("Error setting generated path '%s'",
clone_path) clone_path)
storage_add(str(e)) storage_add(str(e))
@ -479,7 +479,7 @@ class vmmCloneVM(vmmGObjectUI):
newpath = self.generate_clone_path_name(origpath, newname) newpath = self.generate_clone_path_name(origpath, newname)
row[STORAGE_INFO_NEW_PATH] = newpath row[STORAGE_INFO_NEW_PATH] = newpath
except Exception as e: except Exception as e:
logging.debug("Generating new path from clone name failed: %s", log.debug("Generating new path from clone name failed: %s",
str(e)) str(e))
def build_storage_entry(self, disk, storage_box): def build_storage_entry(self, disk, storage_box):
@ -603,7 +603,7 @@ class vmmCloneVM(vmmGObjectUI):
self.clone_design.clone_paths = new_disks self.clone_design.clone_paths = new_disks
except Exception as e: except Exception as e:
# Just log the error and go on. The UI will fail later if needed # Just log the error and go on. The UI will fail later if needed
logging.debug("Error setting clone_paths: %s", str(e)) log.debug("Error setting clone_paths: %s", str(e))
# If any storage cannot be cloned or shared, don't allow cloning # If any storage cannot be cloned or shared, don't allow cloning
clone = True clone = True
@ -860,7 +860,7 @@ class vmmCloneVM(vmmGObjectUI):
pool = self.conn.get_pool(poolname) pool = self.conn.get_pool(poolname)
self.idle_add(pool.refresh) self.idle_add(pool.refresh)
except Exception: except Exception:
logging.debug("Error looking up pool=%s for refresh after " log.debug("Error looking up pool=%s for refresh after "
"VM clone.", poolname, exc_info=True) "VM clone.", poolname, exc_info=True)
def change_storage_browse(self, ignore): def change_storage_browse(self, ignore):

View File

@ -5,13 +5,13 @@
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import os import os
import logging
from gi.repository import Gio from gi.repository import Gio
from gi.repository import GLib from gi.repository import GLib
from gi.repository import Gtk from gi.repository import Gtk
from virtinst import DomainCpu from virtinst import DomainCpu
from virtinst import log
from .inspection import vmmInspection from .inspection import vmmInspection
from .keyring import vmmKeyring, vmmSecret from .keyring import vmmKeyring, vmmSecret
@ -642,7 +642,7 @@ class vmmConfig(object):
_type == self.CONFIG_DIR_FLOPPY_MEDIA): _type == self.CONFIG_DIR_FLOPPY_MEDIA):
path = os.getcwd() path = os.getcwd()
logging.debug("directory for type=%s returning=%s", _type, path) log.debug("directory for type=%s returning=%s", _type, path)
return path return path
def set_default_directory(self, folder, _type): def set_default_directory(self, folder, _type):
@ -650,7 +650,7 @@ class vmmConfig(object):
if not key: if not key:
return return
logging.debug("saving directory for type=%s to %s", key, folder) log.debug("saving directory for type=%s to %s", key, folder)
self.conf.set("/paths/%s-default" % key, folder) self.conf.set("/paths/%s-default" % key, folder)
# Keyring / VNC password dealings # Keyring / VNC password dealings

View File

@ -6,11 +6,12 @@
import glob import glob
import os import os
import logging
import urllib.parse import urllib.parse
from gi.repository import Gtk from gi.repository import Gtk
from virtinst import log
from . import uiutil from . import uiutil
from .baseclass import vmmGObjectUI from .baseclass import vmmGObjectUI
from .connmanager import vmmConnectionManager from .connmanager import vmmConnectionManager
@ -77,17 +78,17 @@ class vmmConnect(vmmGObjectUI):
return None return None
def cancel(self, ignore1=None, ignore2=None): def cancel(self, ignore1=None, ignore2=None):
logging.debug("Cancelling open connection") log.debug("Cancelling open connection")
self.close() self.close()
return 1 return 1
def close(self, ignore1=None, ignore2=None): def close(self, ignore1=None, ignore2=None):
logging.debug("Closing open connection") log.debug("Closing open connection")
self.topwin.hide() self.topwin.hide()
def show(self, parent): def show(self, parent):
logging.debug("Showing open connection") log.debug("Showing open connection")
if self.is_visible(): if self.is_visible():
self.topwin.present() self.topwin.present()
return return
@ -273,7 +274,7 @@ class vmmConnect(vmmGObjectUI):
else: else:
uri = self.widget("uri-entry").get_text() uri = self.widget("uri-entry").get_text()
logging.debug("Generate URI=%s, auto=%s", uri, auto) log.debug("Generate URI=%s, auto=%s", uri, auto)
conn = vmmConnectionManager.get_instance().add_conn(uri) conn = vmmConnectionManager.get_instance().add_conn(uri)
conn.set_autoconnect(auto) conn.set_autoconnect(auto)

View File

@ -5,7 +5,6 @@
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import collections import collections
import logging
import os import os
import re import re
import time import time
@ -16,6 +15,8 @@ from gi.repository import Gtk
import libvirt import libvirt
from virtinst import log
from .baseclass import vmmGObjectUI from .baseclass import vmmGObjectUI
from . import uiutil from . import uiutil
@ -25,7 +26,7 @@ def do_we_have_session():
try: try:
bus = Gio.bus_get_sync(Gio.BusType.SYSTEM, None) bus = Gio.bus_get_sync(Gio.BusType.SYSTEM, None)
except Exception: except Exception:
logging.exception("Error getting system bus handle") log.exception("Error getting system bus handle")
return return
# Check systemd # Check systemd
@ -36,10 +37,10 @@ def do_we_have_session():
"org.freedesktop.login1.Manager", None) "org.freedesktop.login1.Manager", None)
ret = manager.GetSessionByPID("(u)", pid) ret = manager.GetSessionByPID("(u)", pid)
logging.debug("Found login1 session=%s", ret) log.debug("Found login1 session=%s", ret)
return True return True
except Exception: except Exception:
logging.exception("Couldn't connect to logind") log.exception("Couldn't connect to logind")
return False return False
@ -126,7 +127,7 @@ def creds_dialog(creds, cbdata):
dialogobj = _vmmConnectAuth(creds) dialogobj = _vmmConnectAuth(creds)
ret = dialogobj.run() ret = dialogobj.run()
except Exception: except Exception:
logging.exception("Error from creds dialog") log.exception("Error from creds dialog")
ret = -1 ret = -1
retipc.append(ret) retipc.append(ret)
@ -148,7 +149,7 @@ def connect_error(conn, errmsg, tb, warnconsole):
show_errmsg = True show_errmsg = True
if conn.is_remote(): if conn.is_remote():
logging.debug("connect_error: conn transport=%s", log.debug("connect_error: conn transport=%s",
conn.get_uri_transport()) conn.get_uri_transport())
if re.search(r"nc: .* -- 'U'", tb): if re.search(r"nc: .* -- 'U'", tb):
hint += _("The remote host requires a version of netcat/nc " hint += _("The remote host requires a version of netcat/nc "

View File

@ -4,7 +4,6 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
import os import os
import threading import threading
import time import time
@ -13,6 +12,7 @@ import traceback
import libvirt import libvirt
import virtinst import virtinst
from virtinst import log
from virtinst import pollhelpers from virtinst import pollhelpers
from . import connectauth from . import connectauth
@ -285,7 +285,7 @@ class vmmConnection(vmmGObject):
try: try:
ret.append(vol.get_xmlobj(refresh_if_nec=False)) ret.append(vol.get_xmlobj(refresh_if_nec=False))
except Exception as e: except Exception as e:
logging.debug("Fetching volume XML failed: %s", e) log.debug("Fetching volume XML failed: %s", e)
return ret return ret
self._backend.cb_fetch_all_vols = fetch_all_vols self._backend.cb_fetch_all_vols = fetch_all_vols
@ -433,7 +433,7 @@ class vmmConnection(vmmGObject):
if self._storage_capable is None: if self._storage_capable is None:
self._storage_capable = self.support.conn_storage() self._storage_capable = self.support.conn_storage()
if self._storage_capable is False: if self._storage_capable is False:
logging.debug("Connection doesn't seem to support storage " log.debug("Connection doesn't seem to support storage "
"APIs. Skipping all storage polling.") "APIs. Skipping all storage polling.")
return self._storage_capable return self._storage_capable
@ -442,7 +442,7 @@ class vmmConnection(vmmGObject):
if self._network_capable is None: if self._network_capable is None:
self._network_capable = self.support.conn_network() self._network_capable = self.support.conn_network()
if self._network_capable is False: if self._network_capable is False:
logging.debug("Connection doesn't seem to support network " log.debug("Connection doesn't seem to support network "
"APIs. Skipping all network polling.") "APIs. Skipping all network polling.")
return self._network_capable return self._network_capable
@ -451,7 +451,7 @@ class vmmConnection(vmmGObject):
if self._interface_capable is None: if self._interface_capable is None:
self._interface_capable = self.support.conn_interface() self._interface_capable = self.support.conn_interface()
if self._interface_capable is False: if self._interface_capable is False:
logging.debug("Connection doesn't seem to support interface " log.debug("Connection doesn't seem to support interface "
"APIs. Skipping all interface polling.") "APIs. Skipping all interface polling.")
return self._interface_capable return self._interface_capable
@ -489,13 +489,13 @@ class vmmConnection(vmmGObject):
if self.support.domain_xml_inactive(vm): if self.support.domain_xml_inactive(vm):
inact = libvirt.VIR_DOMAIN_XML_INACTIVE inact = libvirt.VIR_DOMAIN_XML_INACTIVE
else: else:
logging.debug("Domain XML inactive flag not supported.") log.debug("Domain XML inactive flag not supported.")
if self.support.domain_xml_secure(vm): if self.support.domain_xml_secure(vm):
inact |= libvirt.VIR_DOMAIN_XML_SECURE inact |= libvirt.VIR_DOMAIN_XML_SECURE
act = libvirt.VIR_DOMAIN_XML_SECURE act = libvirt.VIR_DOMAIN_XML_SECURE
else: else:
logging.debug("Domain XML secure flag not supported.") log.debug("Domain XML secure flag not supported.")
return inact, act return inact, act
@ -518,7 +518,7 @@ class vmmConnection(vmmGObject):
return vol return vol
except Exception as e: except Exception as e:
# Errors can happen if the volume disappeared, bug 1092739 # Errors can happen if the volume disappeared, bug 1092739
logging.debug("Error looking up volume from path=%s: %s", log.debug("Error looking up volume from path=%s: %s",
path, e) path, e)
return None return None
@ -530,7 +530,7 @@ class vmmConnection(vmmGObject):
def _change_state(self, newstate): def _change_state(self, newstate):
if self._state != newstate: if self._state != newstate:
self._state = newstate self._state = newstate
logging.debug("conn=%s changed to state=%s", log.debug("conn=%s changed to state=%s",
self.get_uri(), self.get_state_text()) self.get_uri(), self.get_state_text())
self.emit("state-changed") self.emit("state-changed")
@ -595,7 +595,7 @@ class vmmConnection(vmmGObject):
# Libvirt nodedev XML fetching can be busted # Libvirt nodedev XML fetching can be busted
# https://bugzilla.redhat.com/show_bug.cgi?id=1225771 # https://bugzilla.redhat.com/show_bug.cgi?id=1225771
if e.get_error_code() != libvirt.VIR_ERR_NO_NODE_DEVICE: if e.get_error_code() != libvirt.VIR_ERR_NO_NODE_DEVICE:
logging.debug("Error fetching nodedev XML", exc_info=True) log.debug("Error fetching nodedev XML", exc_info=True)
continue continue
if devtype and xmlobj.device_type != devtype: if devtype and xmlobj.device_type != devtype:
@ -636,11 +636,11 @@ class vmmConnection(vmmGObject):
newobj = define_cb(newxml) newobj = define_cb(newxml)
except Exception as renameerr: except Exception as renameerr:
try: try:
logging.debug("Error defining new name %s XML", log.debug("Error defining new name %s XML",
obj.class_name(), exc_info=True) obj.class_name(), exc_info=True)
newobj = define_cb(origxml) newobj = define_cb(origxml)
except Exception as fixerr: except Exception as fixerr:
logging.debug("Failed to redefine original %s!", log.debug("Failed to redefine original %s!",
obj.class_name(), exc_info=True) obj.class_name(), exc_info=True)
raise RuntimeError( raise RuntimeError(
_("%s rename failed. Attempting to recover also " _("%s rename failed. Attempting to recover also "
@ -674,7 +674,7 @@ class vmmConnection(vmmGObject):
eventstr = args.pop(-1) eventstr = args.pop(-1)
name = domain.name() name = domain.name()
logging.debug("domain xmlmisc event: domain=%s event=%s args=%s", log.debug("domain xmlmisc event: domain=%s event=%s args=%s",
name, eventstr, args) name, eventstr, args)
obj = self.get_vm(name) obj = self.get_vm(name)
if not obj: if not obj:
@ -687,7 +687,7 @@ class vmmConnection(vmmGObject):
ignore = userdata ignore = userdata
name = domain.name() name = domain.name()
logging.debug("domain lifecycle event: domain=%s %s", name, log.debug("domain lifecycle event: domain=%s %s", name,
LibvirtEnumMap.domain_lifecycle_str(state, reason)) LibvirtEnumMap.domain_lifecycle_str(state, reason))
obj = self.get_vm(name) obj = self.get_vm(name)
@ -702,7 +702,7 @@ class vmmConnection(vmmGObject):
ignore = userdata ignore = userdata
name = domain.name() name = domain.name()
logging.debug("domain agent lifecycle event: domain=%s %s", name, log.debug("domain agent lifecycle event: domain=%s %s", name,
LibvirtEnumMap.domain_agent_lifecycle_str(state, reason)) LibvirtEnumMap.domain_agent_lifecycle_str(state, reason))
obj = self.get_vm(name) obj = self.get_vm(name)
@ -717,7 +717,7 @@ class vmmConnection(vmmGObject):
ignore = userdata ignore = userdata
name = network.name() name = network.name()
logging.debug("network lifecycle event: network=%s %s", log.debug("network lifecycle event: network=%s %s",
name, LibvirtEnumMap.network_lifecycle_str(state, reason)) name, LibvirtEnumMap.network_lifecycle_str(state, reason))
obj = self.get_net(name) obj = self.get_net(name)
@ -732,7 +732,7 @@ class vmmConnection(vmmGObject):
ignore = userdata ignore = userdata
name = pool.name() name = pool.name()
logging.debug("storage pool lifecycle event: pool=%s %s", log.debug("storage pool lifecycle event: pool=%s %s",
name, LibvirtEnumMap.storage_lifecycle_str(state, reason)) name, LibvirtEnumMap.storage_lifecycle_str(state, reason))
obj = self.get_pool(name) obj = self.get_pool(name)
@ -747,7 +747,7 @@ class vmmConnection(vmmGObject):
ignore = userdata ignore = userdata
name = pool.name() name = pool.name()
logging.debug("storage pool refresh event: pool=%s", name) log.debug("storage pool refresh event: pool=%s", name)
obj = self.get_pool(name) obj = self.get_pool(name)
@ -762,7 +762,7 @@ class vmmConnection(vmmGObject):
ignore = userdata ignore = userdata
name = dev.name() name = dev.name()
logging.debug("node device lifecycle event: nodedev=%s %s", log.debug("node device lifecycle event: nodedev=%s %s",
name, LibvirtEnumMap.nodedev_lifecycle_str(state, reason)) name, LibvirtEnumMap.nodedev_lifecycle_str(state, reason))
self.schedule_priority_tick(pollnodedev=True, force=True) self.schedule_priority_tick(pollnodedev=True, force=True)
@ -772,7 +772,7 @@ class vmmConnection(vmmGObject):
ignore = userdata ignore = userdata
name = dev.name() name = dev.name()
logging.debug("node device update event: nodedev=%s", name) log.debug("node device update event: nodedev=%s", name)
obj = self.get_nodedev(name) obj = self.get_nodedev(name)
@ -795,10 +795,10 @@ class vmmConnection(vmmGObject):
None, libvirt.VIR_DOMAIN_EVENT_ID_LIFECYCLE, None, libvirt.VIR_DOMAIN_EVENT_ID_LIFECYCLE,
self._domain_lifecycle_event, None)) self._domain_lifecycle_event, None))
self.using_domain_events = True self.using_domain_events = True
logging.debug("Using domain events") log.debug("Using domain events")
except Exception as e: except Exception as e:
self.using_domain_events = False self.using_domain_events = False
logging.debug("Error registering domain events: %s", e) log.debug("Error registering domain events: %s", e)
def _add_domain_xml_event(eventname, eventval, cb=None): def _add_domain_xml_event(eventname, eventval, cb=None):
if not self.using_domain_events: if not self.using_domain_events:
@ -811,7 +811,7 @@ class vmmConnection(vmmGObject):
self.get_backend().domainEventRegisterAny( self.get_backend().domainEventRegisterAny(
None, eventid, cb, eventname)) None, eventid, cb, eventname))
except Exception as e: except Exception as e:
logging.debug("Error registering %s event: %s", log.debug("Error registering %s event: %s",
eventname, e) eventname, e)
_add_domain_xml_event("VIR_DOMAIN_EVENT_ID_BALLOON_CHANGE", 13) _add_domain_xml_event("VIR_DOMAIN_EVENT_ID_BALLOON_CHANGE", 13)
@ -829,10 +829,10 @@ class vmmConnection(vmmGObject):
self.get_backend().networkEventRegisterAny( self.get_backend().networkEventRegisterAny(
None, eventid, self._network_lifecycle_event, None)) None, eventid, self._network_lifecycle_event, None))
self.using_network_events = True self.using_network_events = True
logging.debug("Using network events") log.debug("Using network events")
except Exception as e: except Exception as e:
self.using_network_events = False self.using_network_events = False
logging.debug("Error registering network events: %s", e) log.debug("Error registering network events: %s", e)
try: try:
_check_events_disabled() _check_events_disabled()
@ -848,10 +848,10 @@ class vmmConnection(vmmGObject):
self.get_backend().storagePoolEventRegisterAny( self.get_backend().storagePoolEventRegisterAny(
None, refreshid, self._storage_pool_refresh_event, None)) None, refreshid, self._storage_pool_refresh_event, None))
self.using_storage_pool_events = True self.using_storage_pool_events = True
logging.debug("Using storage pool events") log.debug("Using storage pool events")
except Exception as e: except Exception as e:
self.using_storage_pool_events = False self.using_storage_pool_events = False
logging.debug("Error registering storage pool events: %s", e) log.debug("Error registering storage pool events: %s", e)
try: try:
_check_events_disabled() _check_events_disabled()
@ -866,10 +866,10 @@ class vmmConnection(vmmGObject):
None, updateid, self._node_device_update_event, None)) None, updateid, self._node_device_update_event, None))
self.using_node_device_events = True self.using_node_device_events = True
logging.debug("Using node device events") log.debug("Using node device events")
except Exception as e: except Exception as e:
self.using_network_events = False self.using_network_events = False
logging.debug("Error registering node device events: %s", e) log.debug("Error registering node device events: %s", e)
###################################### ######################################
@ -882,7 +882,7 @@ class vmmConnection(vmmGObject):
def close(self): def close(self):
if not self.is_disconnected(): if not self.is_disconnected():
logging.debug("conn.close() uri=%s", self.get_uri()) log.debug("conn.close() uri=%s", self.get_uri())
self._closing = True self._closing = True
try: try:
@ -896,7 +896,7 @@ class vmmConnection(vmmGObject):
for eid in self._node_device_cb_ids: for eid in self._node_device_cb_ids:
self._backend.nodeDeviceEventDeregisterAny(eid) self._backend.nodeDeviceEventDeregisterAny(eid)
except Exception: except Exception:
logging.debug("Failed to deregister events in conn cleanup", log.debug("Failed to deregister events in conn cleanup",
exc_info=True) exc_info=True)
finally: finally:
self._domain_cb_ids = [] self._domain_cb_ids = []
@ -915,13 +915,13 @@ class vmmConnection(vmmGObject):
self._remove_object_signal(obj) self._remove_object_signal(obj)
obj.cleanup() obj.cleanup()
except Exception as e: except Exception as e:
logging.debug("Failed to cleanup %s: %s", obj, e) log.debug("Failed to cleanup %s: %s", obj, e)
self._objects.cleanup() self._objects.cleanup()
self._objects = _ObjectList() self._objects = _ObjectList()
closeret = self._backend.close() closeret = self._backend.close()
if closeret == 1 and self.config.CLITestOptions.leak_debug: if closeret == 1 and self.config.CLITestOptions.leak_debug:
logging.debug("LEAK: conn close() returned 1, " log.debug("LEAK: conn close() returned 1, "
"meaning refs may have leaked.") "meaning refs may have leaked.")
self._change_state(self._STATE_DISCONNECTED) self._change_state(self._STATE_DISCONNECTED)
@ -943,7 +943,7 @@ class vmmConnection(vmmGObject):
self._change_state(self._STATE_CONNECTING) self._change_state(self._STATE_CONNECTING)
logging.debug("Scheduling background open thread for %s", log.debug("Scheduling background open thread for %s",
self.get_uri()) self.get_uri())
self._start_thread(self._open_thread, "Connect %s" % self.get_uri()) self._start_thread(self._open_thread, "Connect %s" % self.get_uri())
@ -966,12 +966,12 @@ class vmmConnection(vmmGObject):
if (libvirt_error_code == if (libvirt_error_code ==
getattr(libvirt, "VIR_ERR_AUTH_CANCELLED", None)): getattr(libvirt, "VIR_ERR_AUTH_CANCELLED", None)):
logging.debug("User cancelled auth, not raising any error.") log.debug("User cancelled auth, not raising any error.")
return False, None return False, None
if (libvirt_error_code == libvirt.VIR_ERR_AUTH_FAILED and if (libvirt_error_code == libvirt.VIR_ERR_AUTH_FAILED and
"not authorized" in libvirt_error_message.lower()): "not authorized" in libvirt_error_message.lower()):
logging.debug("Looks like we might have failed policykit " log.debug("Looks like we might have failed policykit "
"auth. Checking to see if we have a valid " "auth. Checking to see if we have a valid "
"console session") "console session")
if (not self.is_remote() and if (not self.is_remote() and
@ -983,12 +983,12 @@ class vmmConnection(vmmGObject):
return False, ConnectError return False, ConnectError
def _populate_initial_state(self): def _populate_initial_state(self):
logging.debug("libvirt version=%s", log.debug("libvirt version=%s",
self._backend.local_libvirt_version()) self._backend.local_libvirt_version())
logging.debug("daemon version=%s", log.debug("daemon version=%s",
self._backend.daemon_version()) self._backend.daemon_version())
logging.debug("conn version=%s", self._backend.conn_version()) log.debug("conn version=%s", self._backend.conn_version())
logging.debug("%s capabilities:\n%s", log.debug("%s capabilities:\n%s",
self.get_uri(), self.caps.get_xml()) self.get_uri(), self.caps.get_xml())
# Try to create the default storage pool # Try to create the default storage pool
@ -996,7 +996,7 @@ class vmmConnection(vmmGObject):
try: try:
virtinst.StoragePool.build_default_pool(self.get_backend()) virtinst.StoragePool.build_default_pool(self.get_backend())
except Exception as e: except Exception as e:
logging.debug("Building default pool failed: %s", str(e)) log.debug("Building default pool failed: %s", str(e))
self._add_conn_events() self._add_conn_events()
@ -1006,7 +1006,7 @@ class vmmConnection(vmmGObject):
if (not isinstance(e, AttributeError) and if (not isinstance(e, AttributeError) and
not self.support.is_error_nosupport(e)): not self.support.is_error_nosupport(e)):
raise raise
logging.debug("Connection doesn't support KeepAlive, " log.debug("Connection doesn't support KeepAlive, "
"skipping") "skipping")
# The initial tick will set up a threading event that will only # The initial tick will set up a threading event that will only
@ -1077,11 +1077,11 @@ class vmmConnection(vmmGObject):
name = str(obj) name = str(obj)
if not self._objects.remove(obj): if not self._objects.remove(obj):
logging.debug("Requested removal of %s=%s, but it's " log.debug("Requested removal of %s=%s, but it's "
"not in our object list.", class_name, name) "not in our object list.", class_name, name)
continue continue
logging.debug("%s=%s removed", class_name, name) log.debug("%s=%s removed", class_name, name)
self._remove_object_signal(obj) self._remove_object_signal(obj)
obj.cleanup() obj.cleanup()
@ -1093,24 +1093,24 @@ class vmmConnection(vmmGObject):
class_name = obj.class_name() class_name = obj.class_name()
if initialize_failed: if initialize_failed:
logging.debug("Blacklisting %s=%s", class_name, obj.get_name()) log.debug("Blacklisting %s=%s", class_name, obj.get_name())
count = self._objects.add_blacklist(obj) count = self._objects.add_blacklist(obj)
if count <= _ObjectList.BLACKLIST_COUNT: if count <= _ObjectList.BLACKLIST_COUNT:
logging.debug("Object added in blacklist, count=%d", count) log.debug("Object added in blacklist, count=%d", count)
else: else:
logging.debug("Object already blacklisted?") log.debug("Object already blacklisted?")
return return
else: else:
self._objects.remove_blacklist(obj) self._objects.remove_blacklist(obj)
if not self._objects.add(obj): if not self._objects.add(obj):
logging.debug("New %s=%s requested, but it's already tracked.", log.debug("New %s=%s requested, but it's already tracked.",
class_name, obj.get_name()) class_name, obj.get_name())
return return
if not obj.is_nodedev(): if not obj.is_nodedev():
# Skip nodedev logging since it's noisy and not interesting # Skip nodedev logging since it's noisy and not interesting
logging.debug("%s=%s status=%s added", class_name, log.debug("%s=%s status=%s added", class_name,
obj.get_name(), obj.run_status()) obj.get_name(), obj.run_status())
if obj.is_domain(): if obj.is_domain():
self.emit("vm-added", obj.get_connkey()) self.emit("vm-added", obj.get_connkey())
@ -1277,13 +1277,13 @@ class vmmConnection(vmmGObject):
obj.tick(stats_update=stats_update) obj.tick(stats_update=stats_update)
except Exception as e: except Exception as e:
logging.exception("Tick for %s failed", obj) log.exception("Tick for %s failed", obj)
if (isinstance(e, libvirt.libvirtError) and if (isinstance(e, libvirt.libvirtError) and
(getattr(e, "get_error_code")() == (getattr(e, "get_error_code")() ==
libvirt.VIR_ERR_SYSTEM_ERROR)): libvirt.VIR_ERR_SYSTEM_ERROR)):
# Try a simple getInfo call to see if conn was dropped # Try a simple getInfo call to see if conn was dropped
self._backend.getInfo() self._backend.getInfo()
logging.debug("vm tick raised system error but " log.debug("vm tick raised system error but "
"connection doesn't seem to have dropped. " "connection doesn't seem to have dropped. "
"Ignoring.") "Ignoring.")
@ -1382,13 +1382,13 @@ class vmmConnection(vmmGObject):
dom = e.get_error_domain() dom = e.get_error_domain()
code = e.get_error_code() code = e.get_error_code()
logging.debug("Error polling connection %s", log.debug("Error polling connection %s",
self.get_uri(), exc_info=True) self.get_uri(), exc_info=True)
if (dom in [from_remote, from_rpc] and if (dom in [from_remote, from_rpc] and
code in [sys_error, internal_error]): code in [sys_error, internal_error]):
e = None e = None
logging.debug("Not showing user error since libvirtd " log.debug("Not showing user error since libvirtd "
"appears to have stopped.") "appears to have stopped.")
self._schedule_close() self._schedule_close()

View File

@ -3,7 +3,7 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging from virtinst import log
from .baseclass import vmmGObject from .baseclass import vmmGObject
from .connection import vmmConnection from .connection import vmmConnection
@ -41,7 +41,7 @@ class vmmConnectionManager(vmmGObject):
self.emit("conn-removed", uri) self.emit("conn-removed", uri)
conn.cleanup() conn.cleanup()
except Exception: except Exception:
logging.exception("Error cleaning up conn=%s", uri) log.exception("Error cleaning up conn=%s", uri)
self._conns = {} self._conns = {}
@property @property

View File

@ -5,11 +5,11 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
from gi.repository import Gtk from gi.repository import Gtk
from gi.repository import Gdk from gi.repository import Gdk
from virtinst import log
from .baseclass import vmmGObject, vmmGObjectUI from .baseclass import vmmGObject, vmmGObjectUI
from .serialcon import vmmSerialConsole from .serialcon import vmmSerialConsole
from .sshtunnels import ConnectionInfo from .sshtunnels import ConnectionInfo
@ -690,17 +690,17 @@ class vmmConsolePages(vmmGObjectUI):
except Exception as e: except Exception as e:
# We can fail here if VM is destroyed: xen is a bit racy # We can fail here if VM is destroyed: xen is a bit racy
# and can't handle domain lookups that soon after # and can't handle domain lookups that soon after
logging.exception("Getting graphics console failed: %s", str(e)) log.exception("Getting graphics console failed: %s", str(e))
return return
if ginfo is None: if ginfo is None:
logging.debug("No graphics configured for guest") log.debug("No graphics configured for guest")
self._activate_unavailable_page( self._activate_unavailable_page(
_("Graphical console not configured for guest")) _("Graphical console not configured for guest"))
return return
if ginfo.gtype not in self.config.embeddable_graphics(): if ginfo.gtype not in self.config.embeddable_graphics():
logging.debug("Don't know how to show graphics type '%s' " log.debug("Don't know how to show graphics type '%s' "
"disabling console page", ginfo.gtype) "disabling console page", ginfo.gtype)
msg = (_("Cannot display graphical console type '%s'") msg = (_("Cannot display graphical console type '%s'")
@ -712,7 +712,7 @@ class vmmConsolePages(vmmGObjectUI):
self._activate_unavailable_page( self._activate_unavailable_page(
_("Connecting to graphical console for guest")) _("Connecting to graphical console for guest"))
logging.debug("Starting connect process for %s", ginfo.logstring()) log.debug("Starting connect process for %s", ginfo.logstring())
try: try:
if ginfo.gtype == "vnc": if ginfo.gtype == "vnc":
viewer_class = VNCViewer viewer_class = VNCViewer
@ -731,7 +731,7 @@ class vmmConsolePages(vmmGObjectUI):
self._viewer.console_open() self._viewer.console_open()
except Exception as e: except Exception as e:
logging.exception("Error connection to graphical console") log.exception("Error connection to graphical console")
self._activate_unavailable_page( self._activate_unavailable_page(
_("Error connecting to graphical console") + ":\n%s" % e) _("Error connecting to graphical console") + ":\n%s" % e)
@ -818,7 +818,7 @@ class vmmConsolePages(vmmGObjectUI):
if errdetails: if errdetails:
msg += "\n" + errdetails msg += "\n" + errdetails
if ssherr: if ssherr:
logging.debug("SSH tunnel error output: %s", ssherr) log.debug("SSH tunnel error output: %s", ssherr)
msg += "\n\n" msg += "\n\n"
msg += _("SSH tunnel error output: %s") % ssherr msg += _("SSH tunnel error output: %s") % ssherr
@ -826,7 +826,7 @@ class vmmConsolePages(vmmGObjectUI):
def _viewer_disconnected(self, ignore, errdetails, ssherr): def _viewer_disconnected(self, ignore, errdetails, ssherr):
self._activate_unavailable_page(_("Viewer disconnected.")) self._activate_unavailable_page(_("Viewer disconnected."))
logging.debug("Viewer disconnected") log.debug("Viewer disconnected")
# Make sure modifiers are set correctly # Make sure modifiers are set correctly
self._viewer_focus_changed() self._viewer_focus_changed()
@ -835,7 +835,7 @@ class vmmConsolePages(vmmGObjectUI):
self._refresh_resizeguest_from_settings() self._refresh_resizeguest_from_settings()
def _viewer_connected(self, ignore): def _viewer_connected(self, ignore):
logging.debug("Viewer connected") log.debug("Viewer connected")
self._activate_viewer_page() self._activate_viewer_page()
# Make sure modifiers are set correctly # Make sure modifiers are set correctly

View File

@ -5,7 +5,6 @@
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import io import io
import logging
import pkgutil import pkgutil
import os import os
import threading import threading
@ -17,6 +16,7 @@ from gi.repository import Pango
import virtinst import virtinst
import virtinst.generatename import virtinst.generatename
from virtinst import log
from . import uiutil from . import uiutil
from .addstorage import vmmAddStorage from .addstorage import vmmAddStorage
@ -194,7 +194,7 @@ class vmmCreate(vmmGObjectUI):
########################### ###########################
def show(self, parent, uri): def show(self, parent, uri):
logging.debug("Showing new vm wizard") log.debug("Showing new vm wizard")
if not self.is_visible(): if not self.is_visible():
self._reset_state(uri) self._reset_state(uri)
@ -205,7 +205,7 @@ class vmmCreate(vmmGObjectUI):
def _close(self, ignore1=None, ignore2=None): def _close(self, ignore1=None, ignore2=None):
if self.is_visible(): if self.is_visible():
logging.debug("Closing new vm wizard") log.debug("Closing new vm wizard")
vmmEngine.get_instance().decrement_window_counter() vmmEngine.get_instance().decrement_window_counter()
self.topwin.hide() self.topwin.hide()
@ -430,10 +430,10 @@ class vmmCreate(vmmGObjectUI):
try: try:
guest.set_uefi_path(guest.get_uefi_path()) guest.set_uefi_path(guest.get_uefi_path())
installable_arch = True installable_arch = True
logging.debug("UEFI found, setting it as default.") log.debug("UEFI found, setting it as default.")
except Exception as e: except Exception as e:
installable_arch = False installable_arch = False
logging.debug("Error checking for UEFI default", exc_info=True) log.debug("Error checking for UEFI default", exc_info=True)
msg = _("Failed to setup UEFI: %s\n" msg = _("Failed to setup UEFI: %s\n"
"Install options are limited.") % e "Install options are limited.") % e
self._show_arch_warning(msg) self._show_arch_warning(msg)
@ -659,7 +659,7 @@ class vmmCreate(vmmGObjectUI):
try: try:
self._populate_conn_state() self._populate_conn_state()
except Exception as e: except Exception as e:
logging.exception("Error setting create wizard conn state.") log.exception("Error setting create wizard conn state.")
return self._show_startup_error(str(e)) return self._show_startup_error(str(e))
@ -686,7 +686,7 @@ class vmmCreate(vmmGObjectUI):
return return
self._capsinfo = capsinfo self._capsinfo = capsinfo
logging.debug("Guest type set to os_type=%s, arch=%s, dom_type=%s", log.debug("Guest type set to os_type=%s, arch=%s, dom_type=%s",
self._capsinfo.os_type, self._capsinfo.os_type,
self._capsinfo.arch, self._capsinfo.arch,
self._capsinfo.hypervisor_type) self._capsinfo.hypervisor_type)
@ -1080,7 +1080,7 @@ class vmmCreate(vmmGObjectUI):
def _cleanup_disks_finished(error, details): def _cleanup_disks_finished(error, details):
if error: if error:
logging.debug("Error cleaning up disk images:" log.debug("Error cleaning up disk images:"
"\nerror=%s\ndetails=%s", error, details) "\nerror=%s\ndetails=%s", error, details)
self.idle_add(self._close) self.idle_add(self._close)
@ -1221,7 +1221,7 @@ class vmmCreate(vmmGObjectUI):
path, ignore = self._get_storage_path(newname, do_log=False) path, ignore = self._get_storage_path(newname, do_log=False)
self._populate_summary_storage(path=path) self._populate_summary_storage(path=path)
except Exception: except Exception:
logging.debug("Error generating storage path on name change " log.debug("Error generating storage path on name change "
"for name=%s", newname, exc_info=True) "for name=%s", newname, exc_info=True)
@ -1657,7 +1657,7 @@ class vmmCreate(vmmGObjectUI):
ram = res.get_recommended_ram(self._guest.os.arch) ram = res.get_recommended_ram(self._guest.os.arch)
n_cpus = res.get_recommended_ncpus(self._guest.os.arch) n_cpus = res.get_recommended_ncpus(self._guest.os.arch)
storage = res.get_recommended_storage(self._guest.os.arch) storage = res.get_recommended_storage(self._guest.os.arch)
logging.debug("Recommended resources for os=%s: " log.debug("Recommended resources for os=%s: "
"ram=%s ncpus=%s storage=%s", "ram=%s ncpus=%s storage=%s",
self._guest.osinfo.name, ram, n_cpus, storage) self._guest.osinfo.name, ram, n_cpus, storage)
@ -1720,12 +1720,12 @@ class vmmCreate(vmmGObjectUI):
path = failed_disk.path path = failed_disk.path
path_already_created = failed_disk.storage_was_created path_already_created = failed_disk.storage_was_created
if do_log: if do_log:
logging.debug("Reusing failed disk path=%s " log.debug("Reusing failed disk path=%s "
"already_created=%s", path, path_already_created) "already_created=%s", path, path_already_created)
else: else:
path = self._addstorage.get_default_path(vmname) path = self._addstorage.get_default_path(vmname)
if do_log: if do_log:
logging.debug("Default storage path is: %s", path) log.debug("Default storage path is: %s", path)
return path, path_already_created return path, path_already_created
@ -1771,7 +1771,7 @@ class vmmCreate(vmmGObjectUI):
except Exception as e: except Exception as e:
return self.err.val_err(_("Invalid guest name"), str(e)) return self.err.val_err(_("Invalid guest name"), str(e))
if self._is_default_storage(): if self._is_default_storage():
logging.debug("User changed VM name and using default " log.debug("User changed VM name and using default "
"storage, re-validating with new default storage path.") "storage, re-validating with new default storage path.")
# User changed the name and we are using default storage # User changed the name and we are using default storage
# which depends on the VM name. Revalidate things # which depends on the VM name. Revalidate things
@ -1840,7 +1840,7 @@ class vmmCreate(vmmGObjectUI):
def _do_start_detect_os(self, cdrom, location, forward_after_finish): def _do_start_detect_os(self, cdrom, location, forward_after_finish):
self._detect_os_in_progress = False self._detect_os_in_progress = False
logging.debug("Starting OS detection thread for cdrom=%s location=%s", log.debug("Starting OS detection thread for cdrom=%s location=%s",
cdrom, location) cdrom, location)
self.widget("create-forward").set_sensitive(False) self.widget("create-forward").set_sensitive(False)
@ -1891,7 +1891,7 @@ class vmmCreate(vmmGObjectUI):
distro = installer.detect_distro(self._guest) distro = installer.detect_distro(self._guest)
thread_results.set_distro(distro) thread_results.set_distro(distro)
except Exception: except Exception:
logging.exception("Error detecting distro.") log.exception("Error detecting distro.")
thread_results.set_failed() thread_results.set_failed()
def _report_detect_os_progress(self, idx, thread_results, def _report_detect_os_progress(self, idx, thread_results,
@ -1916,11 +1916,11 @@ class vmmCreate(vmmGObjectUI):
distro = thread_results.get_distro() distro = thread_results.get_distro()
except Exception: except Exception:
distro = None distro = None
logging.exception("Error in distro detect timeout") log.exception("Error in distro detect timeout")
spin = self.widget("install-detect-os-spinner") spin = self.widget("install-detect-os-spinner")
spin.stop() spin.stop()
logging.debug("Finished UI OS detection.") log.debug("Finished UI OS detection.")
self.widget("create-forward").set_sensitive(True) self.widget("create-forward").set_sensitive(True)
self._os_already_detected_for_media = True self._os_already_detected_for_media = True
@ -1951,7 +1951,7 @@ class vmmCreate(vmmGObjectUI):
if self._validate(page) is not True: if self._validate(page) is not True:
return False return False
logging.debug("Starting create finish() sequence") log.debug("Starting create finish() sequence")
self._failed_guest = None self._failed_guest = None
guest = self._guest guest = self._guest
@ -1967,7 +1967,7 @@ class vmmCreate(vmmGObjectUI):
self._start_install(guest) self._start_install(guest)
return return
logging.debug("User requested 'customize', launching dialog") log.debug("User requested 'customize', launching dialog")
self._show_customize_dialog(self._guest) self._show_customize_dialog(self._guest)
except Exception as e: except Exception as e:
self.reset_finish_cursor() self.reset_finish_cursor()
@ -1989,12 +1989,12 @@ class vmmCreate(vmmGObjectUI):
def customize_finished_cb(src, vdomain): def customize_finished_cb(src, vdomain):
if not self.is_visible(): if not self.is_visible():
return return
logging.debug("User finished customize dialog, starting install") log.debug("User finished customize dialog, starting install")
self._failed_guest = None self._failed_guest = None
self._start_install(vdomain.get_backend()) self._start_install(vdomain.get_backend())
def config_canceled_cb(src): def config_canceled_cb(src):
logging.debug("User closed customize window, closing wizard") log.debug("User closed customize window, closing wizard")
self._close_requested() self._close_requested()
# We specifically don't use vmmVMWindow.get_instance here since # We specifically don't use vmmVMWindow.get_instance here since
@ -2085,9 +2085,9 @@ class vmmCreate(vmmGObjectUI):
if poolname not in refresh_pools: if poolname not in refresh_pools:
refresh_pools.append(poolname) refresh_pools.append(poolname)
logging.debug("Starting background install process") log.debug("Starting background install process")
guest.installer_instance.start_install(guest, meter=meter) guest.installer_instance.start_install(guest, meter=meter)
logging.debug("Install completed") log.debug("Install completed")
# Wait for VM to show up # Wait for VM to show up
self.conn.schedule_priority_tick(pollvm=True) self.conn.schedule_priority_tick(pollvm=True)
@ -2127,7 +2127,7 @@ class vmmCreate(vmmGObjectUI):
pool = self.conn.get_pool(poolname) pool = self.conn.get_pool(poolname)
self.idle_add(pool.refresh) self.idle_add(pool.refresh)
except Exception: except Exception:
logging.debug("Error looking up pool=%s for refresh after " log.debug("Error looking up pool=%s for refresh after "
"VM creation.", poolname, exc_info=True) "VM creation.", poolname, exc_info=True)
@ -2137,19 +2137,19 @@ class vmmCreate(vmmGObjectUI):
to change, so we can restart it as needed to change, so we can restart it as needed
""" """
if vm.is_crashed(): if vm.is_crashed():
logging.debug("VM crashed, cancelling install plans.") log.debug("VM crashed, cancelling install plans.")
return True return True
if not vm.is_shutoff(): if not vm.is_shutoff():
return return
if vm.get_install_abort(): if vm.get_install_abort():
logging.debug("User manually shutdown VM, not restarting " log.debug("User manually shutdown VM, not restarting "
"guest after install.") "guest after install.")
return True return True
try: try:
logging.debug("Install should be completed, starting VM.") log.debug("Install should be completed, starting VM.")
vm.startup() vm.startup()
except Exception as e: except Exception as e:
self.err.show_err(_("Error continue install: %s") % str(e)) self.err.show_err(_("Error continue install: %s") % str(e))
@ -2162,6 +2162,7 @@ class vmmCreate(vmmGObjectUI):
Call bootstrap method from virtBootstrap and show logger messages Call bootstrap method from virtBootstrap and show logger messages
as state/details. as state/details.
""" """
import logging
import virtBootstrap import virtBootstrap
meter.start(text=_("Bootstraping container"), size=100) meter.start(text=_("Bootstraping container"), size=100)
@ -2199,7 +2200,7 @@ class vmmCreate(vmmGObjectUI):
kwargs['password'] = bootstrap_args['passwd'] kwargs['password'] = bootstrap_args['passwd']
if bootstrap_args['root_password']: if bootstrap_args['root_password']:
kwargs['root_password'] = bootstrap_args['root_password'] kwargs['root_password'] = bootstrap_args['root_password']
logging.debug('Start container bootstrap') log.debug('Start container bootstrap')
try: try:
virtBootstrap.bootstrap(**kwargs) virtBootstrap.bootstrap(**kwargs)
# Success - uncheck the 'install-oscontainer-bootstrap' checkbox # Success - uncheck the 'install-oscontainer-bootstrap' checkbox

View File

@ -5,7 +5,6 @@
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import ipaddress import ipaddress
import logging
from gi.repository import Gtk from gi.repository import Gtk
from gi.repository import Gdk from gi.repository import Gdk
@ -14,6 +13,7 @@ from gi.repository import Pango
import libvirt import libvirt
from virtinst import generatename from virtinst import generatename
from virtinst import log
from virtinst import Network from virtinst import Network
from . import uiutil from . import uiutil
@ -77,13 +77,13 @@ class vmmCreateNetwork(vmmGObjectUI):
#################### ####################
def show(self, parent): def show(self, parent):
logging.debug("Showing new network wizard") log.debug("Showing new network wizard")
self.reset_state() self.reset_state()
self.topwin.set_transient_for(parent) self.topwin.set_transient_for(parent)
self.topwin.present() self.topwin.present()
def close(self, ignore1=None, ignore2=None): def close(self, ignore1=None, ignore2=None):
logging.debug("Closing new network wizard") log.debug("Closing new network wizard")
self.topwin.hide() self.topwin.hide()
return 1 return 1
@ -387,7 +387,7 @@ class vmmCreateNetwork(vmmGObjectUI):
def _build_xmlobj_from_xmleditor(self): def _build_xmlobj_from_xmleditor(self):
xml = self._xmleditor.get_xml() xml = self._xmleditor.get_xml()
logging.debug("Using XML from xmleditor:\n%s", xml) log.debug("Using XML from xmleditor:\n%s", xml)
return Network(self.conn.get_backend(), parsexml=xml) return Network(self.conn.get_backend(), parsexml=xml)
def _build_xmlobj_from_ui(self): def _build_xmlobj_from_ui(self):
@ -464,7 +464,7 @@ class vmmCreateNetwork(vmmGObjectUI):
def _async_net_create(self, asyncjob, net): def _async_net_create(self, asyncjob, net):
ignore = asyncjob ignore = asyncjob
xml = net.get_xml() xml = net.get_xml()
logging.debug("Creating virtual network '%s' with xml:\n%s", log.debug("Creating virtual network '%s' with xml:\n%s",
net.name, xml) net.name, xml)
netobj = self.conn.get_backend().networkDefineXML(xml) netobj = self.conn.get_backend().networkDefineXML(xml)

View File

@ -4,12 +4,12 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
import os import os
from gi.repository import Gdk from gi.repository import Gdk
from gi.repository import Gtk from gi.repository import Gtk
from virtinst import log
from virtinst import StoragePool from virtinst import StoragePool
from . import uiutil from . import uiutil
@ -55,13 +55,13 @@ class vmmCreatePool(vmmGObjectUI):
####################### #######################
def show(self, parent): def show(self, parent):
logging.debug("Showing new pool wizard") log.debug("Showing new pool wizard")
self._reset_state() self._reset_state()
self.topwin.set_transient_for(parent) self.topwin.set_transient_for(parent)
self.topwin.present() self.topwin.present()
def close(self, ignore1=None, ignore2=None): def close(self, ignore1=None, ignore2=None):
logging.debug("Closing new pool wizard") log.debug("Closing new pool wizard")
self.topwin.hide() self.topwin.hide()
return 1 return 1
@ -195,7 +195,7 @@ class vmmCreatePool(vmmGObjectUI):
pool_type, pool_type,
host=host) host=host)
except Exception: except Exception:
logging.exception("Pool enumeration failed") log.exception("Pool enumeration failed")
return plist return plist
@ -343,7 +343,7 @@ class vmmCreatePool(vmmGObjectUI):
def _build_xmlobj_from_xmleditor(self): def _build_xmlobj_from_xmleditor(self):
xml = self._xmleditor.get_xml() xml = self._xmleditor.get_xml()
logging.debug("Using XML from xmleditor:\n%s", xml) log.debug("Using XML from xmleditor:\n%s", xml)
return StoragePool(self.conn.get_backend(), parsexml=xml) return StoragePool(self.conn.get_backend(), parsexml=xml)
def _make_stub_pool(self): def _make_stub_pool(self):
@ -425,10 +425,10 @@ class vmmCreatePool(vmmGObjectUI):
def _async_pool_create(self, asyncjob, pool, build): def _async_pool_create(self, asyncjob, pool, build):
meter = asyncjob.get_meter() meter = asyncjob.get_meter()
logging.debug("Starting background pool creation.") log.debug("Starting background pool creation.")
poolobj = pool.install(create=True, meter=meter, build=build) poolobj = pool.install(create=True, meter=meter, build=build)
poolobj.setAutostart(True) poolobj.setAutostart(True)
logging.debug("Pool creation succeeded") log.debug("Pool creation succeeded")
def _finish(self): def _finish(self):
pool = self._build_xmlobj(check_xmleditor=True) pool = self._build_xmlobj(check_xmleditor=True)

View File

@ -4,11 +4,10 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
from gi.repository import Gtk from gi.repository import Gtk
from gi.repository import Gdk from gi.repository import Gdk
from virtinst import log
from virtinst import StorageVolume from virtinst import StorageVolume
from . import uiutil from . import uiutil
@ -61,17 +60,17 @@ class vmmCreateVolume(vmmGObjectUI):
try: try:
parent_xml = self._parent_pool.xmlobj.get_xml() parent_xml = self._parent_pool.xmlobj.get_xml()
except Exception: except Exception:
logging.debug("Error getting parent_pool xml", exc_info=True) log.debug("Error getting parent_pool xml", exc_info=True)
parent_xml = None parent_xml = None
logging.debug("Showing new volume wizard for parent_pool=\n%s", log.debug("Showing new volume wizard for parent_pool=\n%s",
parent_xml) parent_xml)
self._reset_state() self._reset_state()
self.topwin.set_transient_for(parent) self.topwin.set_transient_for(parent)
self.topwin.present() self.topwin.present()
def close(self, ignore1=None, ignore2=None): def close(self, ignore1=None, ignore2=None):
logging.debug("Closing new volume wizard") log.debug("Closing new volume wizard")
self.topwin.hide() self.topwin.hide()
if self._storage_browser: if self._storage_browser:
self._storage_browser.close() self._storage_browser.close()
@ -177,7 +176,7 @@ class vmmCreateVolume(vmmGObjectUI):
if ret and suffix: if ret and suffix:
ret = ret.rsplit(".", 1)[0] ret = ret.rsplit(".", 1)[0]
except Exception: except Exception:
logging.exception("Error finding a default vol name") log.exception("Error finding a default vol name")
return ret return ret
@ -254,7 +253,7 @@ class vmmCreateVolume(vmmGObjectUI):
def _build_xmlobj_from_xmleditor(self): def _build_xmlobj_from_xmleditor(self):
xml = self._xmleditor.get_xml() xml = self._xmleditor.get_xml()
logging.debug("Using XML from xmleditor:\n%s", xml) log.debug("Using XML from xmleditor:\n%s", xml)
return self._make_stub_vol(xml=xml) return self._make_stub_vol(xml=xml)
def _build_xmlobj_from_ui(self): def _build_xmlobj_from_ui(self):
@ -336,9 +335,9 @@ class vmmCreateVolume(vmmGObjectUI):
vol.pool = newpool vol.pool = newpool
meter = asyncjob.get_meter() meter = asyncjob.get_meter()
logging.debug("Starting background vol creation.") log.debug("Starting background vol creation.")
vol.install(meter=meter) vol.install(meter=meter)
logging.debug("vol creation complete.") log.debug("vol creation complete.")
################ ################

View File

@ -7,13 +7,13 @@
import os import os
import stat import stat
import traceback import traceback
import logging
from gi.repository import Gtk from gi.repository import Gtk
from gi.repository import Gdk from gi.repository import Gdk
from gi.repository import Pango from gi.repository import Pango
import virtinst import virtinst
from virtinst import log
from virtinst import xmlutil from virtinst import xmlutil
from .asyncjob import vmmAsyncJob from .asyncjob import vmmAsyncJob
@ -63,14 +63,14 @@ class vmmDeleteDialog(vmmGObjectUI):
prepare_storage_list(self.widget("delete-storage-list")) prepare_storage_list(self.widget("delete-storage-list"))
def show(self, parent, vm): def show(self, parent, vm):
logging.debug("Showing delete wizard") log.debug("Showing delete wizard")
self._set_vm(vm) self._set_vm(vm)
self.reset_state() self.reset_state()
self.topwin.set_transient_for(parent) self.topwin.set_transient_for(parent)
self.topwin.present() self.topwin.present()
def close(self, ignore1=None, ignore2=None): def close(self, ignore1=None, ignore2=None):
logging.debug("Closing delete wizard") log.debug("Closing delete wizard")
self.topwin.hide() self.topwin.hide()
self._set_vm(None) self._set_vm(None)
return 1 return 1
@ -170,7 +170,7 @@ class vmmDeleteDialog(vmmGObjectUI):
try: try:
if vm.is_active(): if vm.is_active():
logging.debug("Forcing VM '%s' power off.", vm.get_name()) log.debug("Forcing VM '%s' power off.", vm.get_name())
vm.destroy() vm.destroy()
conn = vm.conn.get_backend() conn = vm.conn.get_backend()
@ -178,7 +178,7 @@ class vmmDeleteDialog(vmmGObjectUI):
for path in paths: for path in paths:
try: try:
logging.debug("Deleting path: %s", path) log.debug("Deleting path: %s", path)
meter.start(text=_("Deleting path '%s'") % path) meter.start(text=_("Deleting path '%s'") % path)
self._async_delete_path(conn, path, meter) self._async_delete_path(conn, path, meter)
except Exception as e: except Exception as e:
@ -187,7 +187,7 @@ class vmmDeleteDialog(vmmGObjectUI):
meter.end(0) meter.end(0)
if undefine: if undefine:
logging.debug("Removing VM '%s'", vm.get_name()) log.debug("Removing VM '%s'", vm.get_name())
vm.delete() vm.delete()
except Exception as e: except Exception as e:
@ -225,7 +225,7 @@ class vmmDeleteDialog(vmmGObjectUI):
try: try:
vol = conn.storageVolLookupByPath(path) vol = conn.storageVolLookupByPath(path)
except Exception: except Exception:
logging.debug("Path '%s' is not managed. Deleting locally", path) log.debug("Path '%s' is not managed. Deleting locally", path)
if vol: if vol:
vol.delete(0) vol.delete(0)
@ -398,6 +398,6 @@ def do_we_default(conn, vm_name, vol, path, ro, shared, is_media):
info = append_str(info, _("Storage is in use by the following " info = append_str(info, _("Storage is in use by the following "
"virtual machines:\n- %s " % namestr)) "virtual machines:\n- %s " % namestr))
except Exception as e: except Exception as e:
logging.exception("Failed checking disk conflict: %s", str(e)) log.exception("Failed checking disk conflict: %s", str(e))
return (not info, info) return (not info, info)

View File

@ -4,7 +4,6 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
import re import re
import traceback import traceback
@ -13,6 +12,7 @@ from gi.repository import Gtk
import libvirt import libvirt
import virtinst import virtinst
from virtinst import log
from . import uiutil from . import uiutil
from .addhardware import vmmAddHardware from .addhardware import vmmAddHardware
@ -692,7 +692,7 @@ class vmmDetails(vmmGObjectUI):
machines = capsinfo.machines[:] machines = capsinfo.machines[:]
except Exception: except Exception:
logging.exception("Error determining machine list") log.exception("Error determining machine list")
show_machine = (arch not in ["i686", "x86_64"]) show_machine = (arch not in ["i686", "x86_64"])
uiutil.set_grid_row_visible(self.widget("machine-type-title"), uiutil.set_grid_row_visible(self.widget("machine-type-title"),
@ -1923,7 +1923,7 @@ class vmmDetails(vmmGObjectUI):
# Device removal # Device removal
def remove_device(self, devobj): def remove_device(self, devobj):
logging.debug("Removing device: %s", devobj) log.debug("Removing device: %s", devobj)
if not self.err.chkbox_helper(self.config.get_confirm_removedev, if not self.err.chkbox_helper(self.config.get_confirm_removedev,
self.config.set_confirm_removedev, self.config.set_confirm_removedev,
@ -1943,7 +1943,7 @@ class vmmDetails(vmmGObjectUI):
if self.vm.is_active(): if self.vm.is_active():
self.vm.detach_device(devobj) self.vm.detach_device(devobj)
except Exception as e: except Exception as e:
logging.debug("Device could not be hotUNplugged: %s", str(e)) log.debug("Device could not be hotUNplugged: %s", str(e))
detach_err = (str(e), "".join(traceback.format_exc())) detach_err = (str(e), "".join(traceback.format_exc()))
if not detach_err: if not detach_err:

View File

@ -4,18 +4,18 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
import os import os
import time import time
import threading import threading
import libvirt import libvirt
from virtinst import DeviceController
from virtinst import DeviceDisk
from virtinst import DomainCapabilities from virtinst import DomainCapabilities
from virtinst import DomainSnapshot from virtinst import DomainSnapshot
from virtinst import Guest from virtinst import Guest
from virtinst import DeviceController from virtinst import log
from virtinst import DeviceDisk
from .libvirtobject import vmmLibvirtObject from .libvirtobject import vmmLibvirtObject
from .libvirtenummap import LibvirtEnumMap from .libvirtenummap import LibvirtEnumMap
@ -52,7 +52,7 @@ def start_job_progress_thread(vm, meter, progtext):
progress = data_total - data_remaining progress = data_total - data_remaining
meter.update(progress) meter.update(progress)
except Exception: except Exception:
logging.exception("Error calling jobinfo") log.exception("Error calling jobinfo")
return False return False
return True return True
@ -154,7 +154,7 @@ class vmmDomainSnapshot(vmmLibvirtObject):
def run_status_icon_name(self): def run_status_icon_name(self):
status = self._state_str_to_int() status = self._state_str_to_int()
if status not in LibvirtEnumMap.VM_STATUS_ICONS: if status not in LibvirtEnumMap.VM_STATUS_ICONS:
logging.debug("Unknown status %d, using NOSTATE", status) log.debug("Unknown status %d, using NOSTATE", status)
status = libvirt.VIR_DOMAIN_NOSTATE status = libvirt.VIR_DOMAIN_NOSTATE
return LibvirtEnumMap.VM_STATUS_ICONS[status] return LibvirtEnumMap.VM_STATUS_ICONS[status]
@ -338,7 +338,7 @@ class vmmDomain(vmmLibvirtObject):
# attempt may result in a lookup failure. If device is present # attempt may result in a lookup failure. If device is present
# in the active XML, assume all is good. # in the active XML, assume all is good.
if self.get_xmlobj().find_device(origdev): if self.get_xmlobj().find_device(origdev):
logging.debug("Device in active config but not inactive config.") log.debug("Device in active config but not inactive config.")
return return
raise RuntimeError(_("Could not find specified device in the " raise RuntimeError(_("Could not find specified device in the "
@ -386,7 +386,7 @@ class vmmDomain(vmmLibvirtObject):
try: try:
new_nvram.get_vol_object().delete(0) new_nvram.get_vol_object().delete(0)
except Exception as warn: except Exception as warn:
logging.debug("rename failed and new nvram was not " log.debug("rename failed and new nvram was not "
"removed: '%s'", warn) "removed: '%s'", warn)
raise error raise error
@ -394,7 +394,7 @@ class vmmDomain(vmmLibvirtObject):
try: try:
old_nvram.get_vol_object().delete(0) old_nvram.get_vol_object().delete(0)
except Exception as warn: except Exception as warn:
logging.debug("old nvram file was not removed: '%s'", warn) log.debug("old nvram file was not removed: '%s'", warn)
self.define_overview(nvram=new_nvram.path) self.define_overview(nvram=new_nvram.path)
@ -916,7 +916,7 @@ class vmmDomain(vmmLibvirtObject):
return return
devxml = devobj.get_xml() devxml = devobj.get_xml()
logging.debug("attach_device with xml=\n%s", devxml) log.debug("attach_device with xml=\n%s", devxml)
self._backend.attachDevice(devxml) self._backend.attachDevice(devxml)
def detach_device(self, devobj): def detach_device(self, devobj):
@ -927,7 +927,7 @@ class vmmDomain(vmmLibvirtObject):
return return
devxml = devobj.get_xml() devxml = devobj.get_xml()
logging.debug("detach_device with xml=\n%s", devxml) log.debug("detach_device with xml=\n%s", devxml)
self._backend.detachDevice(devxml) self._backend.detachDevice(devxml)
def _update_device(self, devobj, flags=None): def _update_device(self, devobj, flags=None):
@ -935,7 +935,7 @@ class vmmDomain(vmmLibvirtObject):
flags = getattr(libvirt, "VIR_DOMAIN_DEVICE_MODIFY_LIVE", 1) flags = getattr(libvirt, "VIR_DOMAIN_DEVICE_MODIFY_LIVE", 1)
xml = devobj.get_xml() xml = devobj.get_xml()
logging.debug("update_device with xml=\n%s", xml) log.debug("update_device with xml=\n%s", xml)
self._backend.updateDeviceFlags(xml, flags) self._backend.updateDeviceFlags(xml, flags)
def hotplug(self, vcpus=_SENTINEL, memory=_SENTINEL, maxmem=_SENTINEL, def hotplug(self, vcpus=_SENTINEL, memory=_SENTINEL, maxmem=_SENTINEL,
@ -961,7 +961,7 @@ class vmmDomain(vmmLibvirtObject):
self._backend.setVcpus(vcpus) self._backend.setVcpus(vcpus)
if memory != _SENTINEL: if memory != _SENTINEL:
logging.debug("Hotplugging curmem=%s maxmem=%s for VM '%s'", log.debug("Hotplugging curmem=%s maxmem=%s for VM '%s'",
memory, maxmem, self.get_name()) memory, maxmem, self.get_name())
actual_cur = self.get_memory() actual_cur = self.get_memory()
@ -1053,7 +1053,7 @@ class vmmDomain(vmmLibvirtObject):
if redefine: if redefine:
flags = (flags | libvirt.VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE) flags = (flags | libvirt.VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE)
else: else:
logging.debug("Creating snapshot flags=%s xml=\n%s", flags, xml) log.debug("Creating snapshot flags=%s xml=\n%s", flags, xml)
self._backend.snapshotCreateXML(xml, flags) self._backend.snapshotCreateXML(xml, flags)
def refresh_interface_addresses(self, iface): def refresh_interface_addresses(self, iface):
@ -1082,11 +1082,11 @@ class vmmDomain(vmmLibvirtObject):
self._ip_cache["arp"] = self._get_interface_addresses(arp_flag) self._ip_cache["arp"] = self._get_interface_addresses(arp_flag)
def _get_interface_addresses(self, source): def _get_interface_addresses(self, source):
logging.debug("Calling interfaceAddresses source=%s", source) log.debug("Calling interfaceAddresses source=%s", source)
try: try:
return self._backend.interfaceAddresses(source) return self._backend.interfaceAddresses(source)
except Exception as e: except Exception as e:
logging.debug("interfaceAddresses failed: %s", str(e)) log.debug("interfaceAddresses failed: %s", str(e))
return {} return {}
def get_interface_addresses(self, iface): def get_interface_addresses(self, iface):
@ -1302,7 +1302,7 @@ class vmmDomain(vmmLibvirtObject):
try: try:
self._backend.undefineFlags(flags) self._backend.undefineFlags(flags)
except libvirt.libvirtError: except libvirt.libvirtError:
logging.exception("libvirt undefineFlags failed, " log.exception("libvirt undefineFlags failed, "
"falling back to old style") "falling back to old style")
self._backend.undefine() self._backend.undefine()
@ -1359,7 +1359,7 @@ class vmmDomain(vmmLibvirtObject):
flags |= libvirt.VIR_MIGRATE_UNSAFE flags |= libvirt.VIR_MIGRATE_UNSAFE
libvirt_destconn = destconn.get_backend().get_conn_for_api_arg() libvirt_destconn = destconn.get_backend().get_conn_for_api_arg()
logging.debug("Migrating: conn=%s flags=%s uri=%s tunnel=%s " log.debug("Migrating: conn=%s flags=%s uri=%s tunnel=%s "
"unsafe=%s temporary=%s", "unsafe=%s temporary=%s",
destconn, flags, dest_uri, tunnel, unsafe, temporary) destconn, flags, dest_uri, tunnel, unsafe, temporary)
@ -1475,7 +1475,7 @@ class vmmDomain(vmmLibvirtObject):
def run_status_icon_name(self): def run_status_icon_name(self):
status = self.status() status = self.status()
if status not in LibvirtEnumMap.VM_STATUS_ICONS: if status not in LibvirtEnumMap.VM_STATUS_ICONS:
logging.debug("Unknown status %s, using NOSTATE", status) log.debug("Unknown status %s, using NOSTATE", status)
status = libvirt.VIR_DOMAIN_NOSTATE status = libvirt.VIR_DOMAIN_NOSTATE
return LibvirtEnumMap.VM_STATUS_ICONS[status] return LibvirtEnumMap.VM_STATUS_ICONS[status]
@ -1573,7 +1573,7 @@ class vmmDomainVirtinst(vmmDomain):
self._orig_backend = self._backend self._orig_backend = self._backend
self._refresh_status() self._refresh_status()
logging.debug("%s initialized with XML=\n%s", self, self._XMLDesc(0)) log.debug("%s initialized with XML=\n%s", self, self._XMLDesc(0))
def get_name(self): def get_name(self):
return self._backend.name return self._backend.name
@ -1619,13 +1619,13 @@ class vmmDomainVirtinst(vmmDomain):
return return
if origdisk.get_vol_object(): if origdisk.get_vol_object():
logging.debug( log.debug(
"Syncing vol_object=%s from origdisk=%s to newdisk=%s", "Syncing vol_object=%s from origdisk=%s to newdisk=%s",
origdisk.get_vol_object(), origdisk, newdisk) origdisk.get_vol_object(), origdisk, newdisk)
newdisk.set_vol_object(origdisk.get_vol_object(), newdisk.set_vol_object(origdisk.get_vol_object(),
origdisk.get_parent_pool()) origdisk.get_parent_pool())
elif origdisk.get_vol_install(): elif origdisk.get_vol_install():
logging.debug( log.debug(
"Syncing vol_install=%s from origdisk=%s to newdisk=%s", "Syncing vol_install=%s from origdisk=%s to newdisk=%s",
origdisk.get_vol_install(), origdisk, newdisk) origdisk.get_vol_install(), origdisk, newdisk)
newdisk.set_vol_install(origdisk.get_vol_install()) newdisk.set_vol_install(origdisk.get_vol_install())

View File

@ -4,7 +4,6 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
import os import os
import queue import queue
import threading import threading
@ -14,6 +13,8 @@ from gi.repository import Gio
from gi.repository import GLib from gi.repository import GLib
from gi.repository import Gtk from gi.repository import Gtk
from virtinst import log
from .baseclass import vmmGObject from .baseclass import vmmGObject
from .connect import vmmConnect from .connect import vmmConnect
from .connmanager import vmmConnectionManager from .connmanager import vmmConnectionManager
@ -109,9 +110,9 @@ class vmmEngine(vmmGObject):
uris = list(self._connobjs.keys()) uris = list(self._connobjs.keys())
if not uris: if not uris:
logging.debug("No stored URIs found.") log.debug("No stored URIs found.")
else: else:
logging.debug("Loading stored URIs:\n%s", log.debug("Loading stored URIs:\n%s",
" \n".join(sorted(uris))) " \n".join(sorted(uris)))
if not skip_autostart: if not skip_autostart:
@ -132,7 +133,7 @@ class vmmEngine(vmmGObject):
""" """
manager = self._get_manager() manager = self._get_manager()
logging.debug("Trying to start libvirtd through systemd") log.debug("Trying to start libvirtd through systemd")
unitname = "libvirtd.service" unitname = "libvirtd.service"
libvirtd_installed = False libvirtd_installed = False
libvirtd_active = False libvirtd_active = False
@ -146,10 +147,10 @@ class vmmEngine(vmmGObject):
"/org/freedesktop/systemd1", "/org/freedesktop/systemd1",
"org.freedesktop.systemd1.Manager", None) "org.freedesktop.systemd1.Manager", None)
units = systemd.ListUnits() units = systemd.ListUnits()
logging.debug("Successfully listed units via systemd") log.debug("Successfully listed units via systemd")
except Exception: except Exception:
units = [] units = []
logging.exception("Couldn't connect to systemd") log.exception("Couldn't connect to systemd")
libvirtd_installed = os.path.exists("/var/run/libvirt") libvirtd_installed = os.path.exists("/var/run/libvirt")
libvirtd_active = os.path.exists("/var/run/libvirt/libvirt-sock") libvirtd_active = os.path.exists("/var/run/libvirt/libvirt-sock")
@ -162,7 +163,7 @@ class vmmEngine(vmmGObject):
unitpath = unitinfo[6] unitpath = unitinfo[6]
break break
logging.debug("libvirtd_installed=%s libvirtd_active=%s unitpath=%s", log.debug("libvirtd_installed=%s libvirtd_active=%s unitpath=%s",
libvirtd_installed, libvirtd_active, unitpath) libvirtd_installed, libvirtd_active, unitpath)
# If it's not running, try to start it # If it's not running, try to start it
@ -177,14 +178,14 @@ class vmmEngine(vmmGObject):
time.sleep(2) time.sleep(2)
libvirtd_active = True libvirtd_active = True
except Exception: except Exception:
logging.exception("Error starting libvirtd") log.exception("Error starting libvirtd")
if self.config.CLITestOptions.first_run: if self.config.CLITestOptions.first_run:
logging.debug("--test-first-run, using uri=None to trigger error") log.debug("--test-first-run, using uri=None to trigger error")
tryuri = None tryuri = None
else: else:
tryuri = vmmConnect.default_uri() tryuri = vmmConnect.default_uri()
logging.debug("Probed default URI=%s", tryuri) log.debug("Probed default URI=%s", tryuri)
# Manager fail message # Manager fail message
msg = "" msg = ""
@ -249,7 +250,7 @@ class vmmEngine(vmmGObject):
# Explicitly ignore connection errors, we've done that # Explicitly ignore connection errors, we've done that
# for a while and it can be noisy # for a while and it can be noisy
if ConnectError is not None: if ConnectError is not None:
logging.debug("Autostart connection error: %s", log.debug("Autostart connection error: %s",
ConnectError.details) ConnectError.details)
add_next_to_queue() add_next_to_queue()
@ -281,7 +282,7 @@ class vmmEngine(vmmGObject):
Invoked after application.run() Invoked after application.run()
""" """
if not self._application.get_windows(): if not self._application.get_windows():
logging.debug("Initial gtkapplication activated") log.debug("Initial gtkapplication activated")
self._application.add_window(Gtk.Window()) self._application.add_window(Gtk.Window())
def _init_gtk_application(self): def _init_gtk_application(self):
@ -314,7 +315,7 @@ class vmmEngine(vmmGObject):
self._application.activate_action("cli_command", data) self._application.activate_action("cli_command", data)
if is_remote: if is_remote:
logging.debug("Connected to remote app instance.") log.debug("Connected to remote app instance.")
return return
self._application.run(None) self._application.run(None)
@ -341,7 +342,7 @@ class vmmEngine(vmmGObject):
def _add_obj_to_tick_queue(self, obj, isprio, **kwargs): def _add_obj_to_tick_queue(self, obj, isprio, **kwargs):
if self._tick_queue.full(): if self._tick_queue.full():
if not self._tick_thread_slow: if not self._tick_thread_slow:
logging.debug("Tick is slow, not running at requested rate.") log.debug("Tick is slow, not running at requested rate.")
self._tick_thread_slow = True self._tick_thread_slow = True
return return
@ -369,7 +370,7 @@ class vmmEngine(vmmGObject):
# Don't attempt to show any UI error here, since it # Don't attempt to show any UI error here, since it
# can cause dialogs to appear from nowhere if say # can cause dialogs to appear from nowhere if say
# libvirtd is shut down # libvirtd is shut down
logging.debug("Error polling connection %s", log.debug("Error polling connection %s",
conn.get_uri(), exc_info=True) conn.get_uri(), exc_info=True)
# Need to clear reference to make leak check happy # Need to clear reference to make leak check happy
@ -387,14 +388,14 @@ class vmmEngine(vmmGObject):
Public function, called by toplevel windows Public function, called by toplevel windows
""" """
self._window_count += 1 self._window_count += 1
logging.debug("window counter incremented to %s", self._window_count) log.debug("window counter incremented to %s", self._window_count)
def decrement_window_counter(self): def decrement_window_counter(self):
""" """
Public function, called by toplevel windows Public function, called by toplevel windows
""" """
self._window_count -= 1 self._window_count -= 1
logging.debug("window counter decremented to %s", self._window_count) log.debug("window counter decremented to %s", self._window_count)
self._exit_app_if_no_windows() self._exit_app_if_no_windows()
@ -414,7 +415,7 @@ class vmmEngine(vmmGObject):
if self._exiting: if self._exiting:
return return
if self._can_exit(): if self._can_exit():
logging.debug("No windows found, requesting app exit") log.debug("No windows found, requesting app exit")
self.exit_app() self.exit_app()
def exit_app(self): def exit_app(self):
@ -438,9 +439,9 @@ class vmmEngine(vmmGObject):
objs.remove(self.object_key) objs.remove(self.object_key)
for name in objs: for name in objs:
logging.debug("LEAK: %s", name) log.debug("LEAK: %s", name)
logging.debug("Exiting app normally.") log.debug("Exiting app normally.")
finally: finally:
self._application.quit() self._application.quit()
@ -499,7 +500,7 @@ class vmmEngine(vmmGObject):
@_show_startup_error @_show_startup_error
def _launch_cli_window(self, uri, show_window, clistr): def _launch_cli_window(self, uri, show_window, clistr):
logging.debug("Launching requested window '%s'", show_window) log.debug("Launching requested window '%s'", show_window)
if show_window == self.CLI_SHOW_MANAGER: if show_window == self.CLI_SHOW_MANAGER:
manager = self._get_manager() manager = self._get_manager()
manager.set_initial_selection(uri) manager.set_initial_selection(uri)
@ -532,10 +533,10 @@ class vmmEngine(vmmGObject):
show_window = variant[1] or self.CLI_SHOW_MANAGER show_window = variant[1] or self.CLI_SHOW_MANAGER
domain = variant[2] domain = variant[2]
logging.debug("processing cli command uri=%s show_window=%s domain=%s", log.debug("processing cli command uri=%s show_window=%s domain=%s",
uri, show_window, domain) uri, show_window, domain)
if not uri: if not uri:
logging.debug("No cli action requested, launching default window") log.debug("No cli action requested, launching default window")
self._get_manager().show() self._get_manager().show()
return return
@ -549,7 +550,7 @@ class vmmEngine(vmmGObject):
def _open_completed(_c, ConnectError): def _open_completed(_c, ConnectError):
if ConnectError: if ConnectError:
if conn_is_new: if conn_is_new:
logging.debug("Removing failed uri=%s", uri) log.debug("Removing failed uri=%s", uri)
vmmConnectionManager.get_instance().remove_conn(uri) vmmConnectionManager.get_instance().remove_conn(uri)
self._handle_conn_error(conn, ConnectError) self._handle_conn_error(conn, ConnectError)
else: else:

View File

@ -3,12 +3,13 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
import sys import sys
import traceback import traceback
from gi.repository import Gtk from gi.repository import Gtk
from virtinst import log
from .baseclass import vmmGObject from .baseclass import vmmGObject
@ -80,7 +81,7 @@ class vmmErrorDialog(vmmGObject):
if details.startswith(summary): if details.startswith(summary):
det = details[len(summary):].strip() det = details[len(summary):].strip()
debugmsg += "\ndetails=%s" % det debugmsg += "\ndetails=%s" % det
logging.debug(debugmsg) log.debug(debugmsg)
# Make sure we have consistent details for error dialogs # Make sure we have consistent details for error dialogs
if (dialog_type == Gtk.MessageType.ERROR and summary not in details): if (dialog_type == Gtk.MessageType.ERROR and summary not in details):
@ -124,7 +125,7 @@ class vmmErrorDialog(vmmGObject):
logtext += " %s" % text2 logtext += " %s" % text2
if isinstance(text1, Exception) or isinstance(text2, Exception): if isinstance(text1, Exception) or isinstance(text2, Exception):
logging.exception(logtext) log.exception(logtext)
else: else:
self._logtrace(logtext) self._logtrace(logtext)

View File

@ -4,7 +4,7 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging from virtinst import log
from . import uiutil from . import uiutil
from .baseclass import vmmGObjectUI from .baseclass import vmmGObjectUI
@ -84,7 +84,7 @@ class vmmHost(vmmGObjectUI):
####################### #######################
def show(self): def show(self):
logging.debug("Showing host details: %s", self.conn) log.debug("Showing host details: %s", self.conn)
vis = self.is_visible() vis = self.is_visible()
self.topwin.present() self.topwin.present()
if vis: if vis:
@ -95,7 +95,7 @@ class vmmHost(vmmGObjectUI):
def close(self, src=None, event=None): def close(self, src=None, event=None):
dummy = src dummy = src
dummy = event dummy = event
logging.debug("Closing host window for %s", self.conn) log.debug("Closing host window for %s", self.conn)
if not self.is_visible(): if not self.is_visible():
return return

View File

@ -4,11 +4,11 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
from gi.repository import Gtk from gi.repository import Gtk
from gi.repository import Pango from gi.repository import Pango
from virtinst import log
from . import uiutil from . import uiutil
from .asyncjob import vmmAsyncJob from .asyncjob import vmmAsyncJob
from .baseclass import vmmGObjectUI from .baseclass import vmmGObjectUI
@ -166,7 +166,7 @@ class vmmHostNets(vmmGObjectUI):
try: try:
self._populate_net_state(net) self._populate_net_state(net)
except Exception as e: except Exception as e:
logging.exception(e) log.exception(e)
self._set_error_page(_("Error selecting network: %s") % e) self._set_error_page(_("Error selecting network: %s") % e)
self._disable_net_apply() self._disable_net_apply()
@ -294,7 +294,7 @@ class vmmHostNets(vmmGObjectUI):
if not result: if not result:
return return
logging.debug("Deleting network '%s'", net.get_name()) log.debug("Deleting network '%s'", net.get_name())
vmmAsyncJob.simple_async_noshow(net.delete, [], self, vmmAsyncJob.simple_async_noshow(net.delete, [], self,
_("Error deleting network '%s'") % net.get_name()) _("Error deleting network '%s'") % net.get_name())
@ -303,7 +303,7 @@ class vmmHostNets(vmmGObjectUI):
if net is None: if net is None:
return return
logging.debug("Starting network '%s'", net.get_name()) log.debug("Starting network '%s'", net.get_name())
vmmAsyncJob.simple_async_noshow(net.start, [], self, vmmAsyncJob.simple_async_noshow(net.start, [], self,
_("Error starting network '%s'") % net.get_name()) _("Error starting network '%s'") % net.get_name())
@ -312,12 +312,12 @@ class vmmHostNets(vmmGObjectUI):
if net is None: if net is None:
return return
logging.debug("Stopping network '%s'", net.get_name()) log.debug("Stopping network '%s'", net.get_name())
vmmAsyncJob.simple_async_noshow(net.stop, [], self, vmmAsyncJob.simple_async_noshow(net.stop, [], self,
_("Error stopping network '%s'") % net.get_name()) _("Error stopping network '%s'") % net.get_name())
def _add_network_cb(self, src): def _add_network_cb(self, src):
logging.debug("Launching 'Add Network'") log.debug("Launching 'Add Network'")
try: try:
if self._addnet is None: if self._addnet is None:
self._addnet = vmmCreateNetwork(self.conn) self._addnet = vmmCreateNetwork(self.conn)
@ -335,7 +335,7 @@ class vmmHostNets(vmmGObjectUI):
if net is None: if net is None:
return return
logging.debug("Applying changes for network '%s'", net.get_name()) log.debug("Applying changes for network '%s'", net.get_name())
try: try:
if EDIT_NET_AUTOSTART in self._active_edits: if EDIT_NET_AUTOSTART in self._active_edits:
auto = self.widget("net-autostart").get_active() auto = self.widget("net-autostart").get_active()

View File

@ -3,10 +3,11 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
import queue import queue
import threading import threading
from virtinst import log
from .baseclass import vmmGObject from .baseclass import vmmGObject
from .connmanager import vmmConnectionManager from .connmanager import vmmConnectionManager
from .domain import vmmInspectionApplication, vmmInspectionData from .domain import vmmInspectionApplication, vmmInspectionData
@ -34,13 +35,13 @@ class vmmInspection(vmmGObject):
if cls._libguestfs_installed is None: if cls._libguestfs_installed is None:
try: try:
import guestfs as ignore # pylint: disable=import-error import guestfs as ignore # pylint: disable=import-error
logging.debug("python guestfs is installed") log.debug("python guestfs is installed")
cls._libguestfs_installed = True cls._libguestfs_installed = True
except ImportError: except ImportError:
logging.debug("python guestfs is not installed") log.debug("python guestfs is not installed")
cls._libguestfs_installed = False cls._libguestfs_installed = False
except Exception: except Exception:
logging.debug("error importing guestfs", log.debug("error importing guestfs",
exc_info=True) exc_info=True)
cls._libguestfs_installed = False cls._libguestfs_installed = False
return cls._libguestfs_installed return cls._libguestfs_installed
@ -56,7 +57,7 @@ class vmmInspection(vmmGObject):
self._cached_data = {} self._cached_data = {}
val = self.config.get_libguestfs_inspect_vms() val = self.config.get_libguestfs_inspect_vms()
logging.debug("libguestfs gsetting enabled=%s", str(val)) log.debug("libguestfs gsetting enabled=%s", str(val))
if not val: if not val:
return return
@ -85,7 +86,7 @@ class vmmInspection(vmmGObject):
# Called by the main thread whenever a VM is added to vmlist. # Called by the main thread whenever a VM is added to vmlist.
def _vm_added(self, conn, connkey): def _vm_added(self, conn, connkey):
if connkey.startswith("guestfs-"): if connkey.startswith("guestfs-"):
logging.debug("ignore libvirt/guestfs temporary VM %s", log.debug("ignore libvirt/guestfs temporary VM %s",
connkey) connkey)
return return
@ -93,7 +94,7 @@ class vmmInspection(vmmGObject):
self._q.put(obj) self._q.put(obj)
def vm_refresh(self, vm): def vm_refresh(self, vm):
logging.debug("Refresh requested for vm=%s", vm.get_name()) log.debug("Refresh requested for vm=%s", vm.get_name())
obj = ("vm_refresh", vm.conn.get_uri(), vm.get_name(), vm.get_uuid()) obj = ("vm_refresh", vm.conn.get_uri(), vm.get_name(), vm.get_uuid())
self._q.put(obj) self._q.put(obj)
@ -116,7 +117,7 @@ class vmmInspection(vmmGObject):
while True: while True:
obj = self._q.get() obj = self._q.get()
if obj is None: if obj is None:
logging.debug("libguestfs queue obj=None, exiting thread") log.debug("libguestfs queue obj=None, exiting thread")
return return
self._process_queue_item(obj) self._process_queue_item(obj)
self._q.task_done() self._q.task_done()
@ -173,7 +174,7 @@ class vmmInspection(vmmGObject):
if vmuuid in self._cached_data: if vmuuid in self._cached_data:
data = self._cached_data.get(vmuuid) data = self._cached_data.get(vmuuid)
if vm.inspection != data: if vm.inspection != data:
logging.debug("Found cached data for %s", prettyvm) log.debug("Found cached data for %s", prettyvm)
_set_vm_inspection_data(data) _set_vm_inspection_data(data)
return return
@ -181,7 +182,7 @@ class vmmInspection(vmmGObject):
data = self._inspect_vm(conn, vm) data = self._inspect_vm(conn, vm)
except Exception as e: except Exception as e:
data = _inspection_error(_("Error inspection VM: %s") % str(e)) data = _inspection_error(_("Error inspection VM: %s") % str(e))
logging.exception("%s: exception while processing", prettyvm) log.exception("%s: exception while processing", prettyvm)
_set_vm_inspection_data(data) _set_vm_inspection_data(data)
@ -203,17 +204,17 @@ class vmmInspection(vmmGObject):
g.add_libvirt_dom(vm.get_backend(), readonly=1) g.add_libvirt_dom(vm.get_backend(), readonly=1)
g.launch() g.launch()
except Exception as e: except Exception as e:
logging.debug("%s: Error launching libguestfs appliance: %s", log.debug("%s: Error launching libguestfs appliance: %s",
prettyvm, str(e)) prettyvm, str(e))
return _inspection_error( return _inspection_error(
_("Error launching libguestfs appliance: %s") % str(e)) _("Error launching libguestfs appliance: %s") % str(e))
logging.debug("%s: inspection appliance connected", prettyvm) log.debug("%s: inspection appliance connected", prettyvm)
# Inspect the operating system. # Inspect the operating system.
roots = g.inspect_os() roots = g.inspect_os()
if len(roots) == 0: if len(roots) == 0:
logging.debug("%s: no operating systems found", prettyvm) log.debug("%s: no operating systems found", prettyvm)
return _inspection_error( return _inspection_error(
_("Inspection found no operating systems.")) _("Inspection found no operating systems."))
@ -247,7 +248,7 @@ class vmmInspection(vmmGObject):
g.mount_ro(dev, mp) g.mount_ro(dev, mp)
filesystems_mounted = True filesystems_mounted = True
except Exception: except Exception:
logging.exception("%s: exception mounting %s on %s " log.exception("%s: exception mounting %s on %s "
"(ignored)", "(ignored)",
prettyvm, dev, mp) prettyvm, dev, mp)
@ -285,21 +286,21 @@ class vmmInspection(vmmGObject):
app.description = gapp["app2_description"] app.description = gapp["app2_description"]
apps.append(app) apps.append(app)
except Exception: except Exception:
logging.exception("%s: exception while listing apps (ignored)", log.exception("%s: exception while listing apps (ignored)",
prettyvm) prettyvm)
# Force the libguestfs handle to close right now. # Force the libguestfs handle to close right now.
del g del g
# Log what we found. # Log what we found.
logging.debug("%s: detected operating system: %s %s %d.%d (%s) (%s)", log.debug("%s: detected operating system: %s %s %d.%d (%s) (%s)",
prettyvm, os_type, distro, major_version, minor_version, prettyvm, os_type, distro, major_version, minor_version,
product_name, package_format) product_name, package_format)
logging.debug("hostname: %s", hostname) log.debug("hostname: %s", hostname)
if icon: if icon:
logging.debug("icon: %d bytes", len(icon)) log.debug("icon: %d bytes", len(icon))
if apps: if apps:
logging.debug("# apps: %d", len(apps)) log.debug("# apps: %d", len(apps))
data = vmmInspectionData() data = vmmInspectionData()
data.os_type = str(os_type) data.os_type = str(os_type)

View File

@ -4,11 +4,11 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
from gi.repository import Gio from gi.repository import Gio
from gi.repository import GLib from gi.repository import GLib
from virtinst import log
class vmmSecret(object): class vmmSecret(object):
def __init__(self, name, secret=None, attributes=None): def __init__(self, name, secret=None, attributes=None):
@ -42,9 +42,9 @@ class vmmKeyring(object):
"/org/freedesktop/secrets/aliases/default", "/org/freedesktop/secrets/aliases/default",
"org.freedesktop.Secret.Collection", None) "org.freedesktop.Secret.Collection", None)
logging.debug("Using keyring session %s", self._session) log.debug("Using keyring session %s", self._session)
except Exception: except Exception:
logging.exception("Error determining keyring") log.exception("Error determining keyring")
############## ##############
@ -70,7 +70,7 @@ class vmmKeyring(object):
props, params, replace)[0] props, params, replace)[0]
ret = int(_id.rsplit("/")[-1]) ret = int(_id.rsplit("/")[-1])
except Exception: except Exception:
logging.exception("Failed to add keyring secret") log.exception("Failed to add keyring secret")
return ret return ret
@ -82,7 +82,7 @@ class vmmKeyring(object):
"org.freedesktop.Secret.Item", None) "org.freedesktop.Secret.Item", None)
iface.Delete("(s)", "/") iface.Delete("(s)", "/")
except Exception: except Exception:
logging.exception("Failed to delete keyring secret") log.exception("Failed to delete keyring secret")
def get_secret(self, _id): def get_secret(self, _id):
ret = None ret = None
@ -106,6 +106,6 @@ class vmmKeyring(object):
ret = vmmSecret(label, secret, attrs) ret = vmmSecret(label, secret, attrs)
except Exception: except Exception:
logging.exception("Failed to get keyring secret id=%s", _id) log.exception("Failed to get keyring secret id=%s", _id)
return ret return ret

View File

@ -3,11 +3,13 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
import re import re
import libvirt import libvirt
from virtinst import log
if not hasattr(libvirt, "VIR_DOMAIN_PMSUSPENDED"): if not hasattr(libvirt, "VIR_DOMAIN_PMSUSPENDED"):
setattr(libvirt, "VIR_DOMAIN_PMSUSPENDED", 7) setattr(libvirt, "VIR_DOMAIN_PMSUSPENDED", 7)
@ -84,7 +86,7 @@ class _LibvirtEnumMap(object):
elif status == libvirt.VIR_DOMAIN_PMSUSPENDED: elif status == libvirt.VIR_DOMAIN_PMSUSPENDED:
return _("Suspended") return _("Suspended")
logging.debug("Unknown status %s, returning 'Unknown'", status) log.debug("Unknown status %s, returning 'Unknown'", status)
return _("Unknown") return _("Unknown")
@staticmethod @staticmethod
@ -142,11 +144,11 @@ class _LibvirtEnumMap(object):
for key in [a for a in dir(libvirt) if re.match(regex, a)]: for key in [a for a in dir(libvirt) if re.match(regex, a)]:
val = getattr(libvirt, key) val = getattr(libvirt, key)
if type(val) is not int: if type(val) is not int:
logging.debug("libvirt regex=%s key=%s val=%s " log.debug("libvirt regex=%s key=%s val=%s "
"isn't an integer", regex, key, val) "isn't an integer", regex, key, val)
continue continue
if val in ret: if val in ret:
logging.debug("libvirt regex=%s key=%s val=%s is already " log.debug("libvirt regex=%s key=%s val=%s is already "
"in dict as key=%s", regex, key, val, regex[val]) "in dict as key=%s", regex, key, val, regex[val])
continue continue
ret[val] = key ret[val] = key

View File

@ -4,7 +4,7 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging from virtinst import log
from .baseclass import vmmGObject from .baseclass import vmmGObject
@ -45,7 +45,7 @@ class vmmLibvirtObject(vmmGObject):
@staticmethod @staticmethod
def log_redefine_xml_diff(obj, origxml, newxml): def log_redefine_xml_diff(obj, origxml, newxml):
if origxml == newxml: if origxml == newxml:
logging.debug("Redefine requested for %s, but XML didn't change!", log.debug("Redefine requested for %s, but XML didn't change!",
obj) obj)
return return
@ -54,7 +54,7 @@ class vmmLibvirtObject(vmmGObject):
newxml.splitlines(1), newxml.splitlines(1),
fromfile="Original XML", fromfile="Original XML",
tofile="New XML")) tofile="New XML"))
logging.debug("Redefining %s with XML diff:\n%s", obj, diff) log.debug("Redefining %s with XML diff:\n%s", obj, diff)
@staticmethod @staticmethod
def lifecycle_action(fn): def lifecycle_action(fn):
@ -121,7 +121,7 @@ class vmmLibvirtObject(vmmGObject):
if xmlobj.name == newname: if xmlobj.name == newname:
return return
logging.debug("Changing %s name from %s to %s", log.debug("Changing %s name from %s to %s",
self, oldname, newname) self, oldname, newname)
origxml = xmlobj.get_xml() origxml = xmlobj.get_xml()
xmlobj.name = newname xmlobj.name = newname
@ -192,7 +192,7 @@ class vmmLibvirtObject(vmmGObject):
try: try:
self._init_libvirt_state() self._init_libvirt_state()
except Exception: except Exception:
logging.debug("Error initializing libvirt state for %s", self, log.debug("Error initializing libvirt state for %s", self,
exc_info=True) exc_info=True)
initialize_failed = True initialize_failed = True
@ -276,11 +276,11 @@ class vmmLibvirtObject(vmmGObject):
except Exception as e: except Exception as e:
# If we hit an exception here, it's often that the object # If we hit an exception here, it's often that the object
# disappeared, so request the poll loop to be updated # disappeared, so request the poll loop to be updated
logging.debug("Error refreshing %s from events: %s", self, e) log.debug("Error refreshing %s from events: %s", self, e)
poll_param = self._conn_tick_poll_param() poll_param = self._conn_tick_poll_param()
if poll_param: if poll_param:
kwargs = {"force": True, poll_param: True} kwargs = {"force": True, poll_param: True}
logging.debug("Scheduling priority tick with: %s", kwargs) log.debug("Scheduling priority tick with: %s", kwargs)
self.conn.schedule_priority_tick(**kwargs) self.conn.schedule_priority_tick(**kwargs)
def ensure_latest_xml(self, nosignal=False): def ensure_latest_xml(self, nosignal=False):

View File

@ -4,13 +4,12 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
from gi.repository import GObject from gi.repository import GObject
from gi.repository import Gtk from gi.repository import Gtk
from gi.repository import Gdk from gi.repository import Gdk
from gi.repository import GdkPixbuf from gi.repository import GdkPixbuf
from virtinst import log
from virtinst import xmlutil from virtinst import xmlutil
from . import vmmenu from . import vmmenu
@ -69,7 +68,7 @@ def _get_inspection_icon_pixbuf(vm, w, h):
pb.close() pb.close()
return pb.get_pixbuf() return pb.get_pixbuf()
except Exception: except Exception:
logging.exception("Error loading inspection icon data") log.exception("Error loading inspection icon data")
vm.inspection.icon = None vm.inspection.icon = None
return None return None
@ -182,7 +181,7 @@ class vmmManager(vmmGObjectUI):
if vis: if vis:
return return
logging.debug("Showing manager") log.debug("Showing manager")
if self.prev_position: if self.prev_position:
self.topwin.move(*self.prev_position) self.topwin.move(*self.prev_position)
self.prev_position = None self.prev_position = None
@ -193,7 +192,7 @@ class vmmManager(vmmGObjectUI):
if not self.is_visible(): if not self.is_visible():
return return
logging.debug("Closing manager") log.debug("Closing manager")
self.prev_position = self.topwin.get_position() self.prev_position = self.topwin.get_position()
self.topwin.hide() self.topwin.hide()
vmmEngine.get_instance().decrement_window_counter() vmmEngine.get_instance().decrement_window_counter()

View File

@ -4,13 +4,13 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
import traceback import traceback
from gi.repository import Gdk from gi.repository import Gdk
from gi.repository import Gtk from gi.repository import Gtk
from gi.repository import Pango from gi.repository import Pango
from virtinst import log
from virtinst import xmlutil from virtinst import xmlutil
from . import uiutil from . import uiutil
@ -74,14 +74,14 @@ class vmmMigrateDialog(vmmGObjectUI):
############## ##############
def show(self, parent, vm): def show(self, parent, vm):
logging.debug("Showing migrate wizard") log.debug("Showing migrate wizard")
self._set_vm(vm) self._set_vm(vm)
self._reset_state() self._reset_state()
self.topwin.set_transient_for(parent) self.topwin.set_transient_for(parent)
self.topwin.present() self.topwin.present()
def close(self, ignore1=None, ignore2=None): def close(self, ignore1=None, ignore2=None):
logging.debug("Closing migrate wizard") log.debug("Closing migrate wizard")
self.topwin.hide() self.topwin.hide()
self._set_vm(None) self._set_vm(None)
return 1 return 1
@ -409,14 +409,14 @@ class vmmMigrateDialog(vmmGObjectUI):
progWin.run() progWin.run()
def _cancel_migration(self, asyncjob, vm): def _cancel_migration(self, asyncjob, vm):
logging.debug("Cancelling migrate job") log.debug("Cancelling migrate job")
if not vm: if not vm:
return return
try: try:
vm.abort_job() vm.abort_job()
except Exception as e: except Exception as e:
logging.exception("Error cancelling migrate job") log.exception("Error cancelling migrate job")
asyncjob.show_warning(_("Error cancelling migrate job: %s") % e) asyncjob.show_warning(_("Error cancelling migrate job: %s") % e)
return return
@ -433,7 +433,7 @@ class vmmMigrateDialog(vmmGObjectUI):
vminst = srcconn.get_backend().lookupByName(origvm.get_name()) vminst = srcconn.get_backend().lookupByName(origvm.get_name())
vm = vmmDomain(srcconn, vminst, vminst.UUID()) vm = vmmDomain(srcconn, vminst, vminst.UUID())
logging.debug("Migrating vm=%s from %s to %s", vm.get_name(), log.debug("Migrating vm=%s from %s to %s", vm.get_name(),
srcconn.get_uri(), dstconn.get_uri()) srcconn.get_uri(), dstconn.get_uri())
vm.migrate(dstconn, migrate_uri, tunnel, unsafe, temporary, vm.migrate(dstconn, migrate_uri, tunnel, unsafe, temporary,

View File

@ -8,14 +8,14 @@
# python class or module. The trace output is logged using the regular # python class or module. The trace output is logged using the regular
# logging infrastructure. Invoke this with virt-manager --trace-libvirt # logging infrastructure. Invoke this with virt-manager --trace-libvirt
import logging
import re import re
import threading import threading
import time import time
import traceback import traceback
from types import FunctionType from types import FunctionType
from virtinst import log
CHECK_MAINLOOP = False CHECK_MAINLOOP = False
@ -42,7 +42,7 @@ def generate_wrapper(origfunc, name):
tb = "" tb = ""
if is_main_thread: if is_main_thread:
tb = "\n%s" % "".join(traceback.format_stack()) tb = "\n%s" % "".join(traceback.format_stack())
logging.debug("TRACE %s: thread=%s: %s %s %s%s", log.debug("TRACE %s: thread=%s: %s %s %s%s",
time.time(), threadname, name, args, kwargs, tb) time.time(), threadname, name, args, kwargs, tb)
return origfunc(*args, **kwargs) return origfunc(*args, **kwargs)
@ -51,7 +51,7 @@ def generate_wrapper(origfunc, name):
def wrap_func(module, funcobj): def wrap_func(module, funcobj):
name = funcobj.__name__ name = funcobj.__name__
logging.debug("wrapfunc %s %s", funcobj, name) log.debug("wrapfunc %s %s", funcobj, name)
newfunc = generate_wrapper(funcobj, name) newfunc = generate_wrapper(funcobj, name)
setattr(module, name, newfunc) setattr(module, name, newfunc)
@ -60,14 +60,14 @@ def wrap_func(module, funcobj):
def wrap_method(classobj, methodobj): def wrap_method(classobj, methodobj):
name = methodobj.__name__ name = methodobj.__name__
fullname = classobj.__name__ + "." + name fullname = classobj.__name__ + "." + name
logging.debug("wrapmeth %s", fullname) log.debug("wrapmeth %s", fullname)
newfunc = generate_wrapper(methodobj, fullname) newfunc = generate_wrapper(methodobj, fullname)
setattr(classobj, name, newfunc) setattr(classobj, name, newfunc)
def wrap_class(classobj): def wrap_class(classobj):
logging.debug("wrapclas %s %s", classobj, classobj.__name__) log.debug("wrapclas %s %s", classobj, classobj.__name__)
for name in dir(classobj): for name in dir(classobj):
obj = getattr(classobj, name) obj = getattr(classobj, name)

View File

@ -4,11 +4,12 @@
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import collections import collections
import logging
from gi.repository import Gtk from gi.repository import Gtk
import virtinst import virtinst
from virtinst import log
from . import uiutil from . import uiutil
from .baseclass import vmmGObjectUI from .baseclass import vmmGObjectUI
@ -307,7 +308,7 @@ class vmmNetworkList(vmmGObjectUI):
# Try to start the network # Try to start the network
try: try:
netobj.start() netobj.start()
logging.debug("Started network '%s'", devname) log.debug("Started network '%s'", devname)
except Exception as e: except Exception as e:
return self.err.show_err(_("Could not start virtual network " return self.err.show_err(_("Could not start virtual network "
"'%s': %s") % (devname, str(e))) "'%s': %s") % (devname, str(e)))

View File

@ -5,8 +5,8 @@
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import ipaddress import ipaddress
import logging
from virtinst import log
from virtinst import Network from virtinst import Network
from .libvirtobject import vmmLibvirtObject from .libvirtobject import vmmLibvirtObject
@ -98,7 +98,7 @@ class vmmNetwork(vmmLibvirtObject):
try: try:
self._leases = self._backend.DHCPLeases() self._leases = self._backend.DHCPLeases()
except Exception as e: except Exception as e:
logging.debug("Error getting %s DHCP leases: %s", self, str(e)) log.debug("Error getting %s DHCP leases: %s", self, str(e))
self._leases = [] self._leases = []
def get_dhcp_leases(self): def get_dhcp_leases(self):

View File

@ -4,12 +4,11 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
from gi.repository import Gtk from gi.repository import Gtk
from gi.repository import Gdk from gi.repository import Gdk
from virtinst import DomainCpu from virtinst import DomainCpu
from virtinst import log
from . import uiutil from . import uiutil
from .baseclass import vmmGObjectUI from .baseclass import vmmGObjectUI
@ -98,12 +97,12 @@ class vmmPreferences(vmmGObjectUI):
self.bind_escape_key_close() self.bind_escape_key_close()
def close(self, ignore1=None, ignore2=None): def close(self, ignore1=None, ignore2=None):
logging.debug("Closing preferences") log.debug("Closing preferences")
self.topwin.hide() self.topwin.hide()
return 1 return 1
def show(self, parent): def show(self, parent):
logging.debug("Showing preferences") log.debug("Showing preferences")
self.topwin.set_transient_for(parent) self.topwin.set_transient_for(parent)
self.topwin.present() self.topwin.present()

View File

@ -4,20 +4,20 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging # pylint: disable=wrong-import-order,ungrouped-imports
import gi import gi
from gi.repository import Gdk from gi.repository import Gdk
from gi.repository import Gtk from gi.repository import Gtk
from virtinst import log
# We can use either 2.91 or 2.90. This is just to silence runtime warnings # We can use either 2.91 or 2.90. This is just to silence runtime warnings
# pylint: disable=wrong-import-position
try: try:
gi.require_version("Vte", "2.91") gi.require_version("Vte", "2.91")
logging.debug("Using VTE API 2.91") log.debug("Using VTE API 2.91")
except ValueError: except ValueError:
gi.require_version("Vte", "2.90") gi.require_version("Vte", "2.90")
logging.debug("Using VTE API 2.90") log.debug("Using VTE API 2.90")
from gi.repository import Vte from gi.repository import Vte
import libvirt import libvirt
@ -49,7 +49,7 @@ class ConsoleConnection(vmmGObject):
if (events & libvirt.VIR_EVENT_HANDLE_ERROR or if (events & libvirt.VIR_EVENT_HANDLE_ERROR or
events & libvirt.VIR_EVENT_HANDLE_HANGUP): events & libvirt.VIR_EVENT_HANDLE_HANGUP):
logging.debug("Received stream ERROR/HANGUP, closing console") log.debug("Received stream ERROR/HANGUP, closing console")
self.close() self.close()
return return
@ -57,7 +57,7 @@ class ConsoleConnection(vmmGObject):
try: try:
got = self.stream.recv(1024 * 100) got = self.stream.recv(1024 * 100)
except Exception: except Exception:
logging.exception("Error receiving stream data") log.exception("Error receiving stream data")
self.close() self.close()
return return
@ -65,7 +65,7 @@ class ConsoleConnection(vmmGObject):
# This is basically EAGAIN # This is basically EAGAIN
return return
if len(got) == 0: if len(got) == 0:
logging.debug("Received EOF from stream, closing") log.debug("Received EOF from stream, closing")
self.close() self.close()
return return
@ -80,7 +80,7 @@ class ConsoleConnection(vmmGObject):
try: try:
done = self.stream.send(self.terminalToStream.encode()) done = self.stream.send(self.terminalToStream.encode())
except Exception: except Exception:
logging.exception("Error sending stream data") log.exception("Error sending stream data")
self.close() self.close()
return return
@ -104,7 +104,7 @@ class ConsoleConnection(vmmGObject):
self.close() self.close()
name = dev and dev.alias.name or None name = dev and dev.alias.name or None
logging.debug("Opening console stream for dev=%s alias=%s", log.debug("Opening console stream for dev=%s alias=%s",
dev, name) dev, name)
# libxl doesn't set aliases, their open_console just defaults to # libxl doesn't set aliases, their open_console just defaults to
# opening the first console device, so don't force prescence of # opening the first console device, so don't force prescence of
@ -125,11 +125,11 @@ class ConsoleConnection(vmmGObject):
try: try:
self.stream.eventRemoveCallback() self.stream.eventRemoveCallback()
except Exception: except Exception:
logging.exception("Error removing stream callback") log.exception("Error removing stream callback")
try: try:
self.stream.finish() self.stream.finish()
except Exception: except Exception:
logging.exception("Error finishing stream") log.exception("Error finishing stream")
self.stream = None self.stream = None
@ -284,7 +284,7 @@ class vmmSerialConsole(vmmGObject):
self.box.set_current_page(0) self.box.set_current_page(0)
return True return True
except Exception as e: except Exception as e:
logging.exception("Error opening serial console") log.exception("Error opening serial console")
self.show_error(_("Error connecting to text console: %s") % e) self.show_error(_("Error connecting to text console: %s") % e)
try: try:
self.console.close() self.console.close()
@ -307,12 +307,12 @@ class vmmSerialConsole(vmmGObject):
if port == self.target_port: if port == self.target_port:
if path != self.lastpath: if path != self.lastpath:
logging.debug("Serial console '%s' path changed to %s", log.debug("Serial console '%s' path changed to %s",
self.target_port, path) self.target_port, path)
self.lastpath = path self.lastpath = path
return dev return dev
logging.debug("No devices found for serial target port '%s'", log.debug("No devices found for serial target port '%s'",
self.target_port) self.target_port)
self.lastpath = None self.lastpath = None
return None return None

View File

@ -7,7 +7,6 @@
import datetime import datetime
import glob import glob
import io import io
import logging
import os import os
from gi.repository import Gdk from gi.repository import Gdk
@ -17,6 +16,7 @@ from gi.repository import Pango
from virtinst import DomainSnapshot from virtinst import DomainSnapshot
from virtinst import generatename from virtinst import generatename
from virtinst import log
from virtinst import xmlutil from virtinst import xmlutil
from . import uiutil from . import uiutil
@ -60,7 +60,7 @@ def _mime_to_ext(val, reverse=False):
return e return e
if val == e and reverse: if val == e and reverse:
return m return m
logging.debug("Don't know how to convert %s=%s to %s", log.debug("Don't know how to convert %s=%s to %s",
reverse and "extension" or "mime", val, reverse and "extension" or "mime", val,
reverse and "mime" or "extension") reverse and "mime" or "extension")
@ -91,13 +91,13 @@ class vmmSnapshotNew(vmmGObjectUI):
####################### #######################
def show(self, parent): def show(self, parent):
logging.debug("Showing new snapshot wizard") log.debug("Showing new snapshot wizard")
self._reset_state() self._reset_state()
self.topwin.set_transient_for(parent) self.topwin.set_transient_for(parent)
self.topwin.present() self.topwin.present()
def close(self, ignore1=None, ignore2=None): def close(self, ignore1=None, ignore2=None):
logging.debug("Closing new snapshot wizard") log.debug("Closing new snapshot wizard")
self.topwin.hide() self.topwin.hide()
return 1 return 1
@ -170,10 +170,10 @@ class vmmSnapshotNew(vmmGObjectUI):
def _get_screenshot(self): def _get_screenshot(self):
if not self.vm.is_active(): if not self.vm.is_active():
logging.debug("Skipping screenshot since VM is not active") log.debug("Skipping screenshot since VM is not active")
return return
if not self.vm.xmlobj.devices.graphics: if not self.vm.xmlobj.devices.graphics:
logging.debug("Skipping screenshot since VM has no graphics") log.debug("Skipping screenshot since VM has no graphics")
return return
try: try:
@ -184,7 +184,7 @@ class vmmSnapshotNew(vmmGObjectUI):
self._take_screenshot() self._take_screenshot()
mime, sdata = self._take_screenshot() mime, sdata = self._take_screenshot()
except Exception: except Exception:
logging.exception("Error taking screenshot") log.exception("Error taking screenshot")
return return
ext = _mime_to_ext(mime) ext = _mime_to_ext(mime)
@ -252,10 +252,10 @@ class vmmSnapshotNew(vmmGObjectUI):
return return
filename = basesn + "." + _mime_to_ext(mime) filename = basesn + "." + _mime_to_ext(mime)
logging.debug("Writing screenshot to %s", filename) log.debug("Writing screenshot to %s", filename)
open(filename, "wb").write(sndata) open(filename, "wb").write(sndata)
except Exception: except Exception:
logging.exception("Error saving screenshot") log.exception("Error saving screenshot")
def _create_new_snapshot(self): def _create_new_snapshot(self):
snap = self._validate_new_snapshot() snap = self._validate_new_snapshot()
@ -443,7 +443,7 @@ class vmmSnapshotPage(vmmGObjectUI):
try: try:
snapshots = self.vm.list_snapshots() snapshots = self.vm.list_snapshots()
except Exception as e: except Exception as e:
logging.exception(e) log.exception(e)
self._set_error_page(_("Error refreshing snapshot list: %s") % self._set_error_page(_("Error refreshing snapshot list: %s") %
str(e)) str(e))
return return
@ -656,7 +656,7 @@ class vmmSnapshotPage(vmmGObjectUI):
if not result: if not result:
return return
logging.debug("Running snapshot '%s'", snap.get_name()) log.debug("Running snapshot '%s'", snap.get_name())
vmmAsyncJob.simple_async(self.vm.revert_to_snapshot, vmmAsyncJob.simple_async(self.vm.revert_to_snapshot,
[snap], self, [snap], self,
_("Running snapshot"), _("Running snapshot"),
@ -676,7 +676,7 @@ class vmmSnapshotPage(vmmGObjectUI):
return return
for snap in snaps: for snap in snaps:
logging.debug("Deleting snapshot '%s'", snap.get_name()) log.debug("Deleting snapshot '%s'", snap.get_name())
vmmAsyncJob.simple_async(snap.delete, [], self, vmmAsyncJob.simple_async(snap.delete, [], self,
_("Deleting snapshot"), _("Deleting snapshot"),
_("Deleting snapshot '%s'") % snap.get_name(), _("Deleting snapshot '%s'") % snap.get_name(),
@ -700,5 +700,5 @@ class vmmSnapshotPage(vmmGObjectUI):
try: try:
self._set_snapshot_state(snap[0]) self._set_snapshot_state(snap[0])
except Exception as e: except Exception as e:
logging.exception(e) log.exception(e)
self._set_error_page(_("Error selecting snapshot: %s") % str(e)) self._set_error_page(_("Error selecting snapshot: %s") % str(e))

View File

@ -4,7 +4,6 @@
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import functools import functools
import logging
import os import os
import queue import queue
import socket import socket
@ -12,6 +11,8 @@ import signal
import threading import threading
import ipaddress import ipaddress
from virtinst import log
from .baseclass import vmmGObject from .baseclass import vmmGObject
@ -150,7 +151,7 @@ class _Tunnel(object):
return return
self._closed = True self._closed = True
logging.debug("Close tunnel PID=%s ERRFD=%s", log.debug("Close tunnel PID=%s ERRFD=%s",
self._pid, self._errfd and self._errfd.fileno() or None) self._pid, self._errfd and self._errfd.fileno() or None)
# Since this is a socket object, the file descriptor is closed # Since this is a socket object, the file descriptor is closed
@ -197,7 +198,7 @@ class _Tunnel(object):
self._errfd = errfds[0] self._errfd = errfds[0]
self._errfd.setblocking(0) self._errfd.setblocking(0)
logging.debug("Opened tunnel PID=%d ERRFD=%d", log.debug("Opened tunnel PID=%d ERRFD=%d",
pid, self._errfd.fileno()) pid, self._errfd.fileno())
self._pid = pid self._pid = pid
@ -249,7 +250,7 @@ def _make_ssh_command(ginfo):
argv.append("'%s'" % nc_cmd) argv.append("'%s'" % nc_cmd)
argv_str = functools.reduce(lambda x, y: x + " " + y, argv[1:]) argv_str = functools.reduce(lambda x, y: x + " " + y, argv[1:])
logging.debug("Pre-generated ssh command for ginfo: %s", argv_str) log.debug("Pre-generated ssh command for ginfo: %s", argv_str)
return argv return argv
@ -273,7 +274,7 @@ class SSHTunnels(object):
_tunnel_scheduler.schedule(self._lock, t.open, self._sshcommand, sshfd) _tunnel_scheduler.schedule(self._lock, t.open, self._sshcommand, sshfd)
retfd = os.dup(viewerfd.fileno()) retfd = os.dup(viewerfd.fileno())
logging.debug("Generated tunnel fd=%s for viewer", retfd) log.debug("Generated tunnel fd=%s for viewer", retfd)
return retfd return retfd
def close_all(self): def close_all(self):

View File

@ -3,12 +3,13 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
import re import re
import time import time
import libvirt import libvirt
from virtinst import log
from .baseclass import vmmGObject from .baseclass import vmmGObject
@ -203,17 +204,17 @@ class vmmStatsManager(vmmGObject):
return rx, tx return rx, tx
except libvirt.libvirtError as err: except libvirt.libvirtError as err:
if vm.conn.support.is_error_nosupport(err): if vm.conn.support.is_error_nosupport(err):
logging.debug("conn does not support interfaceStats") log.debug("conn does not support interfaceStats")
self._net_stats_supported = False self._net_stats_supported = False
return 0, 0 return 0, 0
logging.debug("Error in interfaceStats for '%s' dev '%s': %s", log.debug("Error in interfaceStats for '%s' dev '%s': %s",
vm.get_name(), dev, err) vm.get_name(), dev, err)
if vm.is_active(): if vm.is_active():
logging.debug("Adding %s to skip list", dev) log.debug("Adding %s to skip list", dev)
statslist.stats_net_skip.append(dev) statslist.stats_net_skip.append(dev)
else: else:
logging.debug("Aren't running, don't add to skiplist") log.debug("Aren't running, don't add to skiplist")
return 0, 0 return 0, 0
@ -263,17 +264,17 @@ class vmmStatsManager(vmmGObject):
return rd, wr return rd, wr
except libvirt.libvirtError as err: except libvirt.libvirtError as err:
if vm.conn.support.is_error_nosupport(err): if vm.conn.support.is_error_nosupport(err):
logging.debug("conn does not support blockStats") log.debug("conn does not support blockStats")
self._disk_stats_supported = False self._disk_stats_supported = False
return 0, 0 return 0, 0
logging.debug("Error in blockStats for '%s' dev '%s': %s", log.debug("Error in blockStats for '%s' dev '%s': %s",
vm.get_name(), dev, err) vm.get_name(), dev, err)
if vm.is_active(): if vm.is_active():
logging.debug("Adding %s to skip list", dev) log.debug("Adding %s to skip list", dev)
statslist.stats_disk_skip.append(dev) statslist.stats_disk_skip.append(dev)
else: else:
logging.debug("Aren't running, don't add to skiplist") log.debug("Aren't running, don't add to skiplist")
return 0, 0 return 0, 0
@ -304,7 +305,7 @@ class vmmStatsManager(vmmGObject):
wr = io[3] wr = io[3]
return rd, wr return rd, wr
except libvirt.libvirtError as e: except libvirt.libvirtError as e:
logging.debug("LXC style disk stats not supported: %s", e) log.debug("LXC style disk stats not supported: %s", e)
self._disk_stats_lxc_supported = False self._disk_stats_lxc_supported = False
for disk in vm.get_disk_devices_norefresh(): for disk in vm.get_disk_devices_norefresh():
@ -341,7 +342,7 @@ class vmmStatsManager(vmmGObject):
vm.get_backend().setMemoryStatsPeriod(secs, vm.get_backend().setMemoryStatsPeriod(secs,
libvirt.VIR_DOMAIN_AFFECT_LIVE) libvirt.VIR_DOMAIN_AFFECT_LIVE)
except Exception as e: except Exception as e:
logging.debug("Error setting memstats period: %s", e) log.debug("Error setting memstats period: %s", e)
def _old_mem_stats_helper(self, vm): def _old_mem_stats_helper(self, vm):
totalmem = 1 totalmem = 1
@ -352,10 +353,10 @@ class vmmStatsManager(vmmGObject):
curmem = max(0, totalmem - stats.get("unused", totalmem)) curmem = max(0, totalmem - stats.get("unused", totalmem))
except libvirt.libvirtError as err: except libvirt.libvirtError as err:
if vm.conn.support.is_error_nosupport(err): if vm.conn.support.is_error_nosupport(err):
logging.debug("conn does not support memoryStats") log.debug("conn does not support memoryStats")
self._mem_stats_supported = False self._mem_stats_supported = False
else: else:
logging.debug("Error reading mem stats: %s", err) log.debug("Error reading mem stats: %s", err)
return totalmem, curmem return totalmem, curmem
@ -417,10 +418,10 @@ class vmmStatsManager(vmmGObject):
ret[dom.UUIDString()] = domallstats ret[dom.UUIDString()] = domallstats
except libvirt.libvirtError as err: except libvirt.libvirtError as err:
if conn.support.is_error_nosupport(err): if conn.support.is_error_nosupport(err):
logging.debug("conn does not support getAllDomainStats()") log.debug("conn does not support getAllDomainStats()")
self._all_stats_supported = False self._all_stats_supported = False
else: else:
logging.debug("Error call getAllDomainStats(): %s", err) log.debug("Error call getAllDomainStats(): %s", err)
return ret return ret

View File

@ -4,7 +4,7 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging from virtinst import log
from . import uiutil from . import uiutil
from .baseclass import vmmGObjectUI from .baseclass import vmmGObjectUI
@ -33,7 +33,7 @@ class vmmStorageBrowser(vmmGObjectUI):
def show(self, parent): def show(self, parent):
logging.debug("Showing storage browser") log.debug("Showing storage browser")
if not self._first_run: if not self._first_run:
self._first_run = True self._first_run = True
pool = self.conn.get_default_pool() pool = self.conn.get_default_pool()
@ -46,7 +46,7 @@ class vmmStorageBrowser(vmmGObjectUI):
def close(self, ignore1=None, ignore2=None): def close(self, ignore1=None, ignore2=None):
if self.is_visible(): if self.is_visible():
logging.debug("Closing storage browser") log.debug("Closing storage browser")
self.topwin.hide() self.topwin.hide()
self.storagelist.close() self.storagelist.close()
return 1 return 1
@ -116,7 +116,7 @@ class vmmStorageBrowser(vmmGObjectUI):
def _volume_chosen(self, src, volume): def _volume_chosen(self, src, volume):
ignore = src ignore = src
logging.debug("Chosen volume XML:\n%s", volume.xmlobj.get_xml()) log.debug("Chosen volume XML:\n%s", volume.xmlobj.get_xml())
self._finish(volume.get_target_path()) self._finish(volume.get_target_path())
def _vol_sensitive_cb(self, fmt): def _vol_sensitive_cb(self, fmt):
@ -145,7 +145,7 @@ class vmmStorageBrowser(vmmGObjectUI):
dialog_type=dialog_type, browse_reason=self._browse_reason, dialog_type=dialog_type, browse_reason=self._browse_reason,
dialog_name=dialog_name, choose_button=choose_button) dialog_name=dialog_name, choose_button=choose_button)
if filename: if filename:
logging.debug("Browse local chose path=%s", filename) log.debug("Browse local chose path=%s", filename)
self._finish(filename) self._finish(filename)
def _finish(self, path): def _finish(self, path):

View File

@ -3,14 +3,13 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
from gi.repository import Gdk from gi.repository import Gdk
from gi.repository import Gtk from gi.repository import Gtk
from gi.repository import Pango from gi.repository import Pango
from virtinst import StoragePool
from virtinst import DeviceDisk from virtinst import DeviceDisk
from virtinst import log
from virtinst import StoragePool
from . import uiutil from . import uiutil
from .asyncjob import vmmAsyncJob from .asyncjob import vmmAsyncJob
@ -364,7 +363,7 @@ class vmmStorageList(vmmGObjectUI):
try: try:
self._populate_pool_state(pool) self._populate_pool_state(pool)
except Exception as e: except Exception as e:
logging.exception(e) log.exception(e)
self._set_error_page(_("Error selecting pool: %s") % e) self._set_error_page(_("Error selecting pool: %s") % e)
self._disable_pool_apply() self._disable_pool_apply()
@ -422,7 +421,7 @@ class vmmStorageList(vmmGObjectUI):
sizestr = vol.get_pretty_capacity() sizestr = vol.get_pretty_capacity()
fmt = vol.get_format() or "" fmt = vol.get_format() or ""
except Exception: except Exception:
logging.debug("Error getting volume info for '%s', " log.debug("Error getting volume info for '%s', "
"hiding it", key, exc_info=True) "hiding it", key, exc_info=True)
continue continue
@ -435,7 +434,7 @@ class vmmStorageList(vmmGObjectUI):
if not namestr: if not namestr:
namestr = None namestr = None
except Exception: except Exception:
logging.exception("Failed to determine if storage volume in " log.exception("Failed to determine if storage volume in "
"use.") "use.")
sensitive = True sensitive = True
@ -466,7 +465,7 @@ class vmmStorageList(vmmGObjectUI):
if pool is None: if pool is None:
return return
logging.debug("Stopping pool '%s'", pool.get_name()) log.debug("Stopping pool '%s'", pool.get_name())
vmmAsyncJob.simple_async_noshow(pool.stop, [], self, vmmAsyncJob.simple_async_noshow(pool.stop, [], self,
_("Error stopping pool '%s'") % pool.get_name()) _("Error stopping pool '%s'") % pool.get_name())
@ -475,12 +474,12 @@ class vmmStorageList(vmmGObjectUI):
if pool is None: if pool is None:
return return
logging.debug("Starting pool '%s'", pool.get_name()) log.debug("Starting pool '%s'", pool.get_name())
vmmAsyncJob.simple_async_noshow(pool.start, [], self, vmmAsyncJob.simple_async_noshow(pool.start, [], self,
_("Error starting pool '%s'") % pool.get_name()) _("Error starting pool '%s'") % pool.get_name())
def _pool_add_cb(self, src): def _pool_add_cb(self, src):
logging.debug("Launching 'Add Pool' wizard") log.debug("Launching 'Add Pool' wizard")
try: try:
if self._addpool is None: if self._addpool is None:
@ -500,7 +499,7 @@ class vmmStorageList(vmmGObjectUI):
if not result: if not result:
return return
logging.debug("Deleting pool '%s'", pool.get_name()) log.debug("Deleting pool '%s'", pool.get_name())
vmmAsyncJob.simple_async_noshow(pool.delete, [], self, vmmAsyncJob.simple_async_noshow(pool.delete, [], self,
_("Error deleting pool '%s'") % pool.get_name()) _("Error deleting pool '%s'") % pool.get_name())
@ -511,7 +510,7 @@ class vmmStorageList(vmmGObjectUI):
self._confirm_changes() self._confirm_changes()
logging.debug("Refresh pool '%s'", pool.get_name()) log.debug("Refresh pool '%s'", pool.get_name())
vmmAsyncJob.simple_async_noshow(pool.refresh, [], self, vmmAsyncJob.simple_async_noshow(pool.refresh, [], self,
_("Error refreshing pool '%s'") % pool.get_name()) _("Error refreshing pool '%s'") % pool.get_name())
@ -535,7 +534,7 @@ class vmmStorageList(vmmGObjectUI):
if pool is None: if pool is None:
return return
logging.debug("Launching 'Add Volume' wizard for pool '%s'", log.debug("Launching 'Add Volume' wizard for pool '%s'",
pool.get_name()) pool.get_name())
try: try:
if self._addvol is None: if self._addvol is None:
@ -566,7 +565,7 @@ class vmmStorageList(vmmGObjectUI):
pool.refresh() pool.refresh()
self.idle_add(idlecb) self.idle_add(idlecb)
logging.debug("Deleting volume '%s'", vol.get_name()) log.debug("Deleting volume '%s'", vol.get_name())
vmmAsyncJob.simple_async_noshow(cb, [], self, vmmAsyncJob.simple_async_noshow(cb, [], self,
_("Error deleting volume '%s'") % vol.get_name()) _("Error deleting volume '%s'") % vol.get_name())
@ -580,7 +579,7 @@ class vmmStorageList(vmmGObjectUI):
if pool is None: if pool is None:
return return
logging.debug("Applying changes for pool '%s'", pool.get_name()) log.debug("Applying changes for pool '%s'", pool.get_name())
try: try:
if EDIT_POOL_AUTOSTART in self._active_edits: if EDIT_POOL_AUTOSTART in self._active_edits:
auto = self.widget("pool-autostart").get_active() auto = self.widget("pool-autostart").get_active()

View File

@ -4,9 +4,9 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
import time import time
from virtinst import log
from virtinst import pollhelpers from virtinst import pollhelpers
from virtinst import StoragePool, StorageVolume from virtinst import StoragePool, StorageVolume
@ -39,7 +39,7 @@ class vmmStorageVolume(vmmLibvirtObject):
try: try:
return self._backend.XMLDesc(flags) return self._backend.XMLDesc(flags)
except Exception as e: except Exception as e:
logging.debug("XMLDesc for vol=%s failed: %s", log.debug("XMLDesc for vol=%s failed: %s",
self._backend.key(), e) self._backend.key(), e)
raise raise

View File

@ -4,12 +4,12 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
import os import os
from gi.repository import Gio from gi.repository import Gio
from gi.repository import Gtk from gi.repository import Gtk
from virtinst import log
from virtinst import xmlutil from virtinst import xmlutil
from . import vmmenu from . import vmmenu
@ -61,18 +61,18 @@ def _has_appindicator_dbus():
return True return True
return False return False
except Exception: except Exception:
logging.exception("Error checking for appindicator dbus") log.exception("Error checking for appindicator dbus")
return False return False
_USING_APPINDICATOR = False _USING_APPINDICATOR = False
if AppIndicator3: if AppIndicator3:
if not _has_appindicator_dbus(): if not _has_appindicator_dbus():
logging.debug("AppIndicator3 is available, but didn't " log.debug("AppIndicator3 is available, but didn't "
"find any dbus watcher.") "find any dbus watcher.")
else: else:
_USING_APPINDICATOR = True _USING_APPINDICATOR = True
logging.debug("Using AppIndicator3 for systray") log.debug("Using AppIndicator3 for systray")
########################### ###########################
@ -210,7 +210,7 @@ class vmmSystray(vmmGObject):
def _show_systray_changed_cb(self): def _show_systray_changed_cb(self):
do_show = self.config.get_view_system_tray() do_show = self.config.get_view_system_tray()
logging.debug("Showing systray: %s", do_show) log.debug("Showing systray: %s", do_show)
if do_show: if do_show:
self._show_systray() self._show_systray()

View File

@ -5,7 +5,6 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
import socket import socket
from gi.repository import Gdk from gi.repository import Gdk
@ -22,6 +21,8 @@ try:
except (ValueError, ImportError): except (ValueError, ImportError):
have_spice_gtk = False have_spice_gtk = False
from virtinst import log
from .baseclass import vmmGObject from .baseclass import vmmGObject
from .sshtunnels import SSHTunnels from .sshtunnels import SSHTunnels
@ -329,7 +330,7 @@ class VNCViewer(Viewer):
self.emit("size-allocate", None) self.emit("size-allocate", None)
def _auth_failure_cb(self, ignore, msg): def _auth_failure_cb(self, ignore, msg):
logging.debug("VNC auth failure. msg=%s", msg) log.debug("VNC auth failure. msg=%s", msg)
self.emit("auth-error", msg, True) self.emit("auth-error", msg, True)
def _auth_credential(self, src_ignore, credList): def _auth_credential(self, src_ignore, credList):
@ -353,7 +354,7 @@ class VNCViewer(Viewer):
withUsername = False withUsername = False
withPassword = False withPassword = False
for cred in values: for cred in values:
logging.debug("Got credential request %s", cred) log.debug("Got credential request %s", cred)
if cred == GtkVnc.DisplayCredential.PASSWORD: if cred == GtkVnc.DisplayCredential.PASSWORD:
withPassword = True withPassword = True
elif cred == GtkVnc.DisplayCredential.USERNAME: elif cred == GtkVnc.DisplayCredential.USERNAME:
@ -398,14 +399,14 @@ class VNCViewer(Viewer):
try: try:
keys = [int(k) for k in keys.split(',')] keys = [int(k) for k in keys.split(',')]
except Exception: except Exception:
logging.debug("Error in grab_keys configuration in Gsettings", log.debug("Error in grab_keys configuration in Gsettings",
exc_info=True) exc_info=True)
return return
seq = GtkVnc.GrabSequence.new(keys) seq = GtkVnc.GrabSequence.new(keys)
self._display.set_grab_keys(seq) self._display.set_grab_keys(seq)
except Exception as e: except Exception as e:
logging.debug("Error when getting the grab keys combination: %s", log.debug("Error when getting the grab keys combination: %s",
str(e)) str(e))
def _send_keys(self, keys): def _send_keys(self, keys):
@ -449,11 +450,11 @@ class VNCViewer(Viewer):
host, port, ignore = self._ginfo.get_conn_host() host, port, ignore = self._ginfo.get_conn_host()
if not self._ginfo.gsocket: if not self._ginfo.gsocket:
logging.debug("VNC connecting to host=%s port=%s", host, port) log.debug("VNC connecting to host=%s port=%s", host, port)
self._display.open_host(host, port) self._display.open_host(host, port)
return return
logging.debug("VNC connecting to socket=%s", self._ginfo.gsocket) log.debug("VNC connecting to socket=%s", self._ginfo.gsocket)
try: try:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect(self._ginfo.gsocket) sock.connect(self._ginfo.gsocket)
@ -538,7 +539,7 @@ class SpiceViewer(Viewer):
gtk_session.set_property("auto-usbredir", True) gtk_session.set_property("auto-usbredir", True)
except Exception: except Exception:
self._usbdev_manager = None self._usbdev_manager = None
logging.debug("Error initializing spice usb device manager", log.debug("Error initializing spice usb device manager",
exc_info=True) exc_info=True)
@ -553,11 +554,11 @@ class SpiceViewer(Viewer):
self._emit_disconnected() self._emit_disconnected()
elif event == SpiceClientGLib.ChannelEvent.ERROR_AUTH: elif event == SpiceClientGLib.ChannelEvent.ERROR_AUTH:
if not self._spice_session.get_property("password"): if not self._spice_session.get_property("password"):
logging.debug("Spice channel received ERROR_AUTH, but no " log.debug("Spice channel received ERROR_AUTH, but no "
"password set, assuming it wants credentials.") "password set, assuming it wants credentials.")
self.emit("need-auth", True, False) self.emit("need-auth", True, False)
else: else:
logging.debug("Spice channel received ERROR_AUTH, but a " log.debug("Spice channel received ERROR_AUTH, but a "
"password is already set. Assuming authentication failed.") "password is already set. Assuming authentication failed.")
self.emit("auth-error", channel.get_error().message, False) self.emit("auth-error", channel.get_error().message, False)
elif "ERROR" in str(event): elif "ERROR" in str(event):
@ -568,7 +569,7 @@ class SpiceViewer(Viewer):
error = None error = None
if channel.get_error(): if channel.get_error():
error = channel.get_error().message error = channel.get_error().message
logging.debug("Spice channel event=%s message=%s", event, error) log.debug("Spice channel event=%s message=%s", event, error)
msg = _("Encountered SPICE %(error-name)s") % { msg = _("Encountered SPICE %(error-name)s") % {
"error-name": event.value_nick} "error-name": event.value_nick}
@ -589,7 +590,7 @@ class SpiceViewer(Viewer):
# are still rolling in # are still rolling in
return return
logging.debug("Requesting fd for channel: %s", channel) log.debug("Requesting fd for channel: %s", channel)
channel.connect_after("channel-event", self._fd_channel_event_cb) channel.connect_after("channel-event", self._fd_channel_event_cb)
fd = self._get_fd_for_open() fd = self._get_fd_for_open()
@ -614,7 +615,7 @@ class SpiceViewer(Viewer):
channel_id = channel.get_property("channel-id") channel_id = channel.get_property("channel-id")
if channel_id != 0: if channel_id != 0:
logging.debug("Spice multi-head unsupported") log.debug("Spice multi-head unsupported")
return return
self._display_channel = channel self._display_channel = channel
@ -664,14 +665,14 @@ class SpiceViewer(Viewer):
try: try:
keys = [int(k) for k in keys.split(',')] keys = [int(k) for k in keys.split(',')]
except Exception: except Exception:
logging.debug("Error in grab_keys configuration in Gsettings", log.debug("Error in grab_keys configuration in Gsettings",
exc_info=True) exc_info=True)
return return
seq = SpiceClientGtk.GrabSequence.new(keys) seq = SpiceClientGtk.GrabSequence.new(keys)
self._display.set_grab_keys(seq) self._display.set_grab_keys(seq)
except Exception as e: except Exception as e:
logging.debug("Error when getting the grab keys combination: %s", log.debug("Error when getting the grab keys combination: %s",
str(e)) str(e))
def _send_keys(self, keys): def _send_keys(self, keys):
@ -698,7 +699,7 @@ class SpiceViewer(Viewer):
host, port, tlsport = self._ginfo.get_conn_host() host, port, tlsport = self._ginfo.get_conn_host()
self._create_spice_session() self._create_spice_session()
logging.debug("Spice connecting to host=%s port=%s tlsport=%s", log.debug("Spice connecting to host=%s port=%s tlsport=%s",
host, port, tlsport) host, port, tlsport)
self._spice_session.set_property("host", str(host)) self._spice_session.set_property("host", str(host))
if port: if port:

View File

@ -4,10 +4,10 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
from gi.repository import Gtk from gi.repository import Gtk
from virtinst import log
from .asyncjob import vmmAsyncJob from .asyncjob import vmmAsyncJob
@ -159,14 +159,14 @@ class VMActionUI(object):
@staticmethod @staticmethod
def save_cancel(asyncjob, vm): def save_cancel(asyncjob, vm):
logging.debug("Cancelling save job") log.debug("Cancelling save job")
if not vm: if not vm:
return return
try: try:
vm.abort_job() vm.abort_job()
except Exception as e: except Exception as e:
logging.exception("Error cancelling save job") log.exception("Error cancelling save job")
asyncjob.show_warning(_("Error cancelling save job: %s") % str(e)) asyncjob.show_warning(_("Error cancelling save job: %s") % str(e))
return return
@ -209,7 +209,7 @@ class VMActionUI(object):
"shutting down the OS and may cause data loss.")): "shutting down the OS and may cause data loss.")):
return return
logging.debug("Destroying vm '%s'", vm.get_name()) log.debug("Destroying vm '%s'", vm.get_name())
vmmAsyncJob.simple_async_noshow(vm.destroy, [], src, vmmAsyncJob.simple_async_noshow(vm.destroy, [], src,
_("Error shutting down domain")) _("Error shutting down domain"))
@ -221,19 +221,19 @@ class VMActionUI(object):
vm.get_name())): vm.get_name())):
return return
logging.debug("Pausing vm '%s'", vm.get_name()) log.debug("Pausing vm '%s'", vm.get_name())
vmmAsyncJob.simple_async_noshow(vm.suspend, [], src, vmmAsyncJob.simple_async_noshow(vm.suspend, [], src,
_("Error pausing domain")) _("Error pausing domain"))
@staticmethod @staticmethod
def resume(src, vm): def resume(src, vm):
logging.debug("Unpausing vm '%s'", vm.get_name()) log.debug("Unpausing vm '%s'", vm.get_name())
vmmAsyncJob.simple_async_noshow(vm.resume, [], src, vmmAsyncJob.simple_async_noshow(vm.resume, [], src,
_("Error unpausing domain")) _("Error unpausing domain"))
@staticmethod @staticmethod
def run(src, vm): def run(src, vm):
logging.debug("Starting vm '%s'", vm.get_name()) log.debug("Starting vm '%s'", vm.get_name())
if vm.has_managed_save(): if vm.has_managed_save():
def errorcb(error, details): def errorcb(error, details):
@ -278,7 +278,7 @@ class VMActionUI(object):
vm.get_name())): vm.get_name())):
return return
logging.debug("Shutting down vm '%s'", vm.get_name()) log.debug("Shutting down vm '%s'", vm.get_name())
vmmAsyncJob.simple_async_noshow(vm.shutdown, [], src, vmmAsyncJob.simple_async_noshow(vm.shutdown, [], src,
_("Error shutting down domain")) _("Error shutting down domain"))
@ -290,7 +290,7 @@ class VMActionUI(object):
vm.get_name())): vm.get_name())):
return return
logging.debug("Rebooting vm '%s'", vm.get_name()) log.debug("Rebooting vm '%s'", vm.get_name())
vmmAsyncJob.simple_async_noshow(vm.reboot, [], src, vmmAsyncJob.simple_async_noshow(vm.reboot, [], src,
_("Error rebooting domain")) _("Error rebooting domain"))
@ -305,7 +305,7 @@ class VMActionUI(object):
"shutting down the OS and may cause data loss.")): "shutting down the OS and may cause data loss.")):
return return
logging.debug("Resetting vm '%s'", vm.get_name()) log.debug("Resetting vm '%s'", vm.get_name())
vmmAsyncJob.simple_async_noshow(vm.reset, [], src, vmmAsyncJob.simple_async_noshow(vm.reset, [], src,
_("Error resetting domain")) _("Error resetting domain"))

View File

@ -4,11 +4,11 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
from gi.repository import Gdk from gi.repository import Gdk
from gi.repository import Gtk from gi.repository import Gtk
from virtinst import log
from . import vmmenu from . import vmmenu
from .baseclass import vmmGObjectUI from .baseclass import vmmGObjectUI
from .details import vmmDetails from .details import vmmDetails
@ -174,7 +174,7 @@ class vmmVMWindow(vmmGObjectUI):
self.vm = None self.vm = None
def show(self): def show(self):
logging.debug("Showing VM details: %s", self.vm) log.debug("Showing VM details: %s", self.vm)
vis = self.is_visible() vis = self.is_visible()
self.topwin.present() self.topwin.present()
if vis: if vis:
@ -194,15 +194,15 @@ class vmmVMWindow(vmmGObjectUI):
self.cleanup() self.cleanup()
def _customize_cancel(self): def _customize_cancel(self):
logging.debug("Asking to cancel customization") log.debug("Asking to cancel customization")
result = self.err.yes_no( result = self.err.yes_no(
_("This will abort the installation. Are you sure?")) _("This will abort the installation. Are you sure?"))
if not result: if not result:
logging.debug("Customize cancel aborted") log.debug("Customize cancel aborted")
return return
logging.debug("Canceling customization") log.debug("Canceling customization")
return self._close() return self._close()
def _customize_cancel_clicked(self, src): def _customize_cancel_clicked(self, src):
@ -214,7 +214,7 @@ class vmmVMWindow(vmmGObjectUI):
def close(self, ignore1=None, ignore2=None): def close(self, ignore1=None, ignore2=None):
if self.is_visible(): if self.is_visible():
logging.debug("Closing VM details: %s", self.vm) log.debug("Closing VM details: %s", self.vm)
return self._close() return self._close()
def _close(self): def _close(self):
@ -230,7 +230,7 @@ class vmmVMWindow(vmmGObjectUI):
try: try:
self.console.details_close_viewer() self.console.details_close_viewer()
except Exception: except Exception:
logging.error("Failure when disconnecting from desktop server") log.error("Failure when disconnecting from desktop server")
self.emit("closed") self.emit("closed")
vmmEngine.get_instance().decrement_window_counter() vmmEngine.get_instance().decrement_window_counter()
@ -535,7 +535,7 @@ class vmmVMWindow(vmmGObjectUI):
browse_reason=self.config.CONFIG_DIR_SCREENSHOT, browse_reason=self.config.CONFIG_DIR_SCREENSHOT,
default_name=default) default_name=default)
if not path: if not path:
logging.debug("No screenshot path given, skipping save.") log.debug("No screenshot path given, skipping save.")
return return
filename = path filename = path

View File

@ -7,13 +7,13 @@
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
# #
import logging
import os import os
import re import re
import shutil import shutil
import subprocess import subprocess
import tempfile import tempfile
from virtinst import log
from virtinst import StoragePool from virtinst import StoragePool
@ -74,15 +74,15 @@ def _run_cmd(cmd):
""" """
Return the exit status and output to stdout and stderr. Return the exit status and output to stdout and stderr.
""" """
logging.debug("Running command: %s", " ".join(cmd)) log.debug("Running command: %s", " ".join(cmd))
proc = subprocess.Popen(cmd, stderr=subprocess.PIPE, proc = subprocess.Popen(cmd, stderr=subprocess.PIPE,
stdout=subprocess.PIPE, stdout=subprocess.PIPE,
close_fds=True) close_fds=True)
stdout, stderr = proc.communicate() stdout, stderr = proc.communicate()
ret = proc.wait() ret = proc.wait()
logging.debug("stdout=%s", stdout) log.debug("stdout=%s", stdout)
logging.debug("stderr=%s", stderr) log.debug("stderr=%s", stderr)
if ret == 0: if ret == 0:
return return
@ -199,7 +199,7 @@ class VirtConverter(object):
parser = _find_parser_by_name(input_name) parser = _find_parser_by_name(input_name)
input_file = os.path.abspath(input_file) input_file = os.path.abspath(input_file)
logging.debug("converter __init__ with input=%s parser=%s", log.debug("converter __init__ with input=%s parser=%s",
input_file, parser) input_file, parser)
(self._input_file, (self._input_file,
@ -207,7 +207,7 @@ class VirtConverter(object):
self._force_clean) = _find_input(input_file, parser, self.print_cb) self._force_clean) = _find_input(input_file, parser, self.print_cb)
self._top_dir = os.path.dirname(os.path.abspath(self._input_file)) self._top_dir = os.path.dirname(os.path.abspath(self._input_file))
logging.debug("converter not input_file=%s parser=%s", log.debug("converter not input_file=%s parser=%s",
self._input_file, self.parser) self._input_file, self.parser)
self._guest = self.parser.export_libvirt(self.conn, self._guest = self.parser.export_libvirt(self.conn,
@ -296,7 +296,7 @@ class VirtConverter(object):
continue continue
if disk_format and disk.driver_type == disk_format: if disk_format and disk.driver_type == disk_format:
logging.debug("path=%s is already in requested format=%s", log.debug("path=%s is already in requested format=%s",
disk.path, disk_format) disk.path, disk_format)
disk_format = None disk_format = None

View File

@ -5,11 +5,11 @@
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
# #
import logging
import os import os
import xml.etree.ElementTree import xml.etree.ElementTree
import virtinst import virtinst
from virtinst import log
from .formats import parser_class from .formats import parser_class
@ -184,7 +184,7 @@ def _import_file(conn, input_file):
if any([p for p in parsed_sections if p in env_node.tag]): if any([p for p in parsed_sections if p in env_node.tag]):
continue continue
logging.debug("Unhandled XML section '%s'", log.debug("Unhandled XML section '%s'",
env_node.tag) env_node.tag)
if not _convert_bool_val(env_node.attrib.get("required")): if not _convert_bool_val(env_node.attrib.get("required")):
@ -274,11 +274,11 @@ class ovf_parser(parser_class):
root = xml.etree.ElementTree.parse(input_file).getroot() root = xml.etree.ElementTree.parse(input_file).getroot()
return root.tag == ("{%s}Envelope" % OVF_NAMESPACES["ovf"]) return root.tag == ("{%s}Envelope" % OVF_NAMESPACES["ovf"])
except Exception: except Exception:
logging.debug("Error parsing OVF XML", exc_info=True) log.debug("Error parsing OVF XML", exc_info=True)
return False return False
@staticmethod @staticmethod
def export_libvirt(conn, input_file): def export_libvirt(conn, input_file):
logging.debug("Importing OVF XML:\n%s", open(input_file).read()) log.debug("Importing OVF XML:\n%s", open(input_file).read())
return _import_file(conn, input_file) return _import_file(conn, input_file)

View File

@ -8,12 +8,12 @@
# #
import collections import collections
import logging
import os import os
import re import re
import shlex import shlex
import virtinst import virtinst
from virtinst import log
from virtinst import xmlutil from virtinst import xmlutil
from .formats import parser_class from .formats import parser_class
@ -92,10 +92,10 @@ def parse_vmdk(filename):
# Detect if passed file is a descriptor file # Detect if passed file is a descriptor file
# Assume descriptor isn't larger than 10K # Assume descriptor isn't larger than 10K
if not os.path.exists(filename): if not os.path.exists(filename):
logging.debug("VMDK file '%s' doesn't exist", filename) log.debug("VMDK file '%s' doesn't exist", filename)
return return
if os.path.getsize(filename) > (10 * 1024): if os.path.getsize(filename) > (10 * 1024):
logging.debug("VMDK file '%s' too big to be a descriptor", filename) log.debug("VMDK file '%s' too big to be a descriptor", filename)
return return
f = open(filename, "r") f = open(filename, "r")
@ -105,7 +105,7 @@ def parse_vmdk(filename):
try: try:
vmdkfile = _VMXFile(content) vmdkfile = _VMXFile(content)
except Exception: except Exception:
logging.exception("%s looked like a vmdk file, but parsing failed", log.exception("%s looked like a vmdk file, but parsing failed",
filename) filename)
return return
@ -202,7 +202,7 @@ def parse_disk_entry(conn, disks, fullkey, value, topdir):
# See if the filename is actually a VMDK descriptor file # See if the filename is actually a VMDK descriptor file
newpath = parse_vmdk(os.path.join(topdir, disk.path)) newpath = parse_vmdk(os.path.join(topdir, disk.path))
if newpath: if newpath:
logging.debug("VMDK file parsed path %s->%s", log.debug("VMDK file parsed path %s->%s",
disk.path, newpath) disk.path, newpath)
disk.path = newpath disk.path = newpath
@ -243,7 +243,7 @@ class vmx_parser(parser_class):
infile = open(input_file, "r") infile = open(input_file, "r")
contents = infile.readlines() contents = infile.readlines()
infile.close() infile.close()
logging.debug("Importing VMX file:\n%s", "".join(contents)) log.debug("Importing VMX file:\n%s", "".join(contents))
vmxfile = _VMXFile(contents) vmxfile = _VMXFile(contents)
config = vmxfile.pairs() config = vmxfile.pairs()

View File

@ -64,3 +64,5 @@ from virtinst.cloner import Cloner
from virtinst.snapshot import DomainSnapshot from virtinst.snapshot import DomainSnapshot
from virtinst.connection import VirtinstConnection from virtinst.connection import VirtinstConnection
from virtinst.logger import log

View File

@ -6,10 +6,10 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
import pwd import pwd
from .domain import DomainCpu from .domain import DomainCpu
from .logger import log
from .xmlbuilder import XMLBuilder, XMLChildProperty, XMLProperty from .xmlbuilder import XMLBuilder, XMLChildProperty, XMLProperty
@ -88,7 +88,7 @@ class _CapsHost(XMLBuilder):
user = pwd.getpwuid(uid)[0] user = pwd.getpwuid(uid)[0]
return user, uid return user, uid
except Exception: # pragma: no cover except Exception: # pragma: no cover
logging.debug("Exception parsing qemu dac baselabel=%s", log.debug("Exception parsing qemu dac baselabel=%s",
label, exc_info=True) label, exc_info=True)
return None, None # pragma: no cover return None, None # pragma: no cover

View File

@ -8,8 +8,6 @@
import argparse import argparse
import collections import collections
import logging
import logging.handlers
import os import os
import re import re
import shlex import shlex
@ -25,6 +23,7 @@ from .buildconfig import BuildConfig
from .connection import VirtinstConnection from .connection import VirtinstConnection
from .devices import (Device, DeviceController, DeviceDisk, DeviceGraphics, from .devices import (Device, DeviceController, DeviceDisk, DeviceGraphics,
DeviceInterface, DevicePanic) DeviceInterface, DevicePanic)
from .logger import log
from .nodedev import NodeDevice from .nodedev import NodeDevice
from .osdict import OSDB from .osdict import OSDB
from .storage import StoragePool, StorageVolume from .storage import StoragePool, StorageVolume
@ -116,6 +115,7 @@ def setupParser(usage, description, introspection_epilog=False):
def earlyLogging(): def earlyLogging():
import logging
logging.basicConfig(level=logging.DEBUG, format='%(message)s') logging.basicConfig(level=logging.DEBUG, format='%(message)s')
@ -145,7 +145,7 @@ def setupLogging(appname, debug_stdout, do_quiet, cli_app=True):
not os.access(logfile, os.W_OK)): not os.access(logfile, os.W_OK)):
raise RuntimeError("No write access to logfile %s" % logfile) raise RuntimeError("No write access to logfile %s" % logfile)
except Exception as e: # pragma: no cover except Exception as e: # pragma: no cover
logging.warning("Error setting up logfile: %s", e) log.warning("Error setting up logfile: %s", e)
logfile = None logfile = None
dateFormat = "%a, %d %b %Y %H:%M:%S" dateFormat = "%a, %d %b %Y %H:%M:%S"
@ -153,19 +153,24 @@ def setupLogging(appname, debug_stdout, do_quiet, cli_app=True):
"%(levelname)s (%(module)s:%(lineno)d) %(message)s") "%(levelname)s (%(module)s:%(lineno)d) %(message)s")
streamErrorFormat = "%(levelname)-8s %(message)s" streamErrorFormat = "%(levelname)-8s %(message)s"
import logging
import logging.handlers
rootLogger = logging.getLogger() rootLogger = logging.getLogger()
# Undo early logging # Undo early logging
for handler in rootLogger.handlers: for handler in rootLogger.handlers:
rootLogger.removeHandler(handler) rootLogger.removeHandler(handler)
# Undo any logging on our log handler. Needed for test suite
for handler in log.handlers:
log.removeHandler(handler)
rootLogger.setLevel(logging.DEBUG) log.setLevel(logging.DEBUG)
if logfile: if logfile:
fileHandler = logging.handlers.RotatingFileHandler( fileHandler = logging.handlers.RotatingFileHandler(
logfile, "ae", 1024 * 1024, 5) logfile, "ae", 1024 * 1024, 5)
fileHandler.setFormatter( fileHandler.setFormatter(
logging.Formatter(fileFormat, dateFormat)) logging.Formatter(fileFormat, dateFormat))
rootLogger.addHandler(fileHandler) log.addHandler(fileHandler)
streamHandler = logging.StreamHandler(sys.stderr) streamHandler = logging.StreamHandler(sys.stderr)
if debug_stdout: if debug_stdout:
@ -184,11 +189,11 @@ def setupLogging(appname, debug_stdout, do_quiet, cli_app=True):
streamHandler = None streamHandler = None
if streamHandler: if streamHandler:
rootLogger.addHandler(streamHandler) log.addHandler(streamHandler)
# Log uncaught exceptions # Log uncaught exceptions
def exception_log(typ, val, tb): # pragma: no cover def exception_log(typ, val, tb): # pragma: no cover
logging.debug("Uncaught exception:\n%s", log.debug("Uncaught exception:\n%s",
"".join(traceback.format_exception(typ, val, tb))) "".join(traceback.format_exception(typ, val, tb)))
if not debug_stdout: if not debug_stdout:
# If we are already logging to stdout, don't double print # If we are already logging to stdout, don't double print
@ -196,10 +201,8 @@ def setupLogging(appname, debug_stdout, do_quiet, cli_app=True):
sys.__excepthook__(typ, val, tb) sys.__excepthook__(typ, val, tb)
sys.excepthook = exception_log sys.excepthook = exception_log
logging.getLogger("requests").setLevel(logging.ERROR)
# Log the app command string # Log the app command string
logging.debug("Launched with command line: %s", " ".join(sys.argv)) log.debug("Launched with command line: %s", " ".join(sys.argv))
def in_testsuite(): def in_testsuite():
@ -215,10 +218,10 @@ def getConnection(uri, conn=None):
# preopened connection passed in via test suite # preopened connection passed in via test suite
return conn return conn
logging.debug("Requesting libvirt URI %s", (uri or "default")) log.debug("Requesting libvirt URI %s", (uri or "default"))
conn = VirtinstConnection(uri) conn = VirtinstConnection(uri)
conn.open(_openauth_cb, None) conn.open(_openauth_cb, None)
logging.debug("Received libvirt URI %s", conn.uri) log.debug("Received libvirt URI %s", conn.uri)
return conn return conn
@ -230,9 +233,9 @@ def _openauth_cb(creds, _cbdata):
noecho = credtype in [ noecho = credtype in [
libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_NOECHOPROMPT] libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_NOECHOPROMPT]
if not prompt: if not prompt:
logging.error("No prompt for auth credtype=%s", credtype) log.error("No prompt for auth credtype=%s", credtype)
return -1 return -1
logging.debug("openauth_cb prompt=%s", prompt) log.debug("openauth_cb prompt=%s", prompt)
prompt += ": " prompt += ": "
if noecho: if noecho:
@ -254,22 +257,22 @@ def fail(msg, do_exit=True):
""" """
Convenience function when failing in cli app Convenience function when failing in cli app
""" """
logging.debug("".join(traceback.format_stack())) log.debug("".join(traceback.format_stack()))
logging.error(msg) log.error(msg)
if sys.exc_info()[0] is not None: if sys.exc_info()[0] is not None:
logging.debug("", exc_info=True) log.debug("", exc_info=True)
if do_exit: if do_exit:
_fail_exit() _fail_exit()
def print_stdout(msg, do_force=False): def print_stdout(msg, do_force=False):
logging.debug(msg) log.debug(msg)
if do_force or not get_global_state().quiet: if do_force or not get_global_state().quiet:
print(msg) print(msg)
def print_stderr(msg): def print_stderr(msg):
logging.debug(msg) log.debug(msg)
print(msg, file=sys.stderr) print(msg, file=sys.stderr)
@ -295,14 +298,14 @@ def install_fail(guest):
def set_prompt(prompt): def set_prompt(prompt):
# Set whether we allow prompts, or fail if a prompt pops up # Set whether we allow prompts, or fail if a prompt pops up
if prompt: if prompt:
logging.warning("--prompt mode is no longer supported.") log.warning("--prompt mode is no longer supported.")
def check_path_search(conn, path): def check_path_search(conn, path):
searchdata = DeviceDisk.check_path_search(conn, path) searchdata = DeviceDisk.check_path_search(conn, path)
if not searchdata.fixlist: if not searchdata.fixlist:
return return
logging.warning(_("%s may not be accessible by the hypervisor. " log.warning(_("%s may not be accessible by the hypervisor. "
"You will need to grant the '%s' user search permissions for " "You will need to grant the '%s' user search permissions for "
"the following directories: %s"), "the following directories: %s"),
path, searchdata.user, searchdata.fixlist) # pragma: no cover path, searchdata.user, searchdata.fixlist) # pragma: no cover
@ -315,10 +318,10 @@ def validate_disk(dev, warn_overwrite=False):
fail(msg + (_(" (Use --check %s=off or " fail(msg + (_(" (Use --check %s=off or "
"--check all=off to override)") % checkname)) "--check all=off to override)") % checkname))
logging.debug("Skipping --check %s error condition '%s'", log.debug("Skipping --check %s error condition '%s'",
checkname, msg) checkname, msg)
if warn_on_skip: if warn_on_skip:
logging.warning(msg) log.warning(msg)
def check_path_exists(dev): def check_path_exists(dev):
""" """
@ -361,7 +364,7 @@ def validate_disk(dev, warn_overwrite=False):
def _run_console(domain, args): def _run_console(domain, args):
ignore = domain ignore = domain
logging.debug("Running: %s", " ".join(args)) log.debug("Running: %s", " ".join(args))
if in_testsuite(): if in_testsuite():
print_stdout("testsuite console command: %s" % args) print_stdout("testsuite console command: %s" % args)
args = ["/bin/true"] args = ["/bin/true"]
@ -385,7 +388,7 @@ def _gfx_console(guest, domain):
if guest.has_gl() or guest.has_listen_none(): if guest.has_gl() or guest.has_listen_none():
args.append("--attach") args.append("--attach")
logging.debug("Launching virt-viewer for graphics type '%s'", log.debug("Launching virt-viewer for graphics type '%s'",
guest.devices.graphics[0].type) guest.devices.graphics[0].type)
return _run_console(domain, args) return _run_console(domain, args)
@ -395,7 +398,7 @@ def _txt_console(guest, domain):
"--connect", guest.conn.uri, "--connect", guest.conn.uri,
"console", guest.name] "console", guest.name]
logging.debug("Connecting to text console") log.debug("Connecting to text console")
return _run_console(domain, args) return _run_console(domain, args)
@ -415,10 +418,10 @@ def connect_console(guest, domain, consolecb, wait, destroy_on_exit):
try: try:
os.waitpid(child, 0) os.waitpid(child, 0)
except OSError as e: # pragma: no cover except OSError as e: # pragma: no cover
logging.debug("waitpid error: %s", e) log.debug("waitpid error: %s", e)
if destroy_on_exit and domain.isActive(): if destroy_on_exit and domain.isActive():
logging.debug("console exited and destroy_on_exit passed, destroying") log.debug("console exited and destroy_on_exit passed, destroying")
domain.destroy() domain.destroy()
@ -431,20 +434,20 @@ def get_console_cb(guest):
if gtype not in ["default", if gtype not in ["default",
DeviceGraphics.TYPE_VNC, DeviceGraphics.TYPE_VNC,
DeviceGraphics.TYPE_SPICE]: DeviceGraphics.TYPE_SPICE]:
logging.debug("No viewer to launch for graphics type '%s'", gtype) log.debug("No viewer to launch for graphics type '%s'", gtype)
return return
if not in_testsuite(): if not in_testsuite():
try: try:
subprocess.check_output(["virt-viewer", "--version"]) subprocess.check_output(["virt-viewer", "--version"])
except OSError: except OSError:
logging.warning(_("Unable to connect to graphical console: " log.warning(_("Unable to connect to graphical console: "
"virt-viewer not installed. Please install " "virt-viewer not installed. Please install "
"the 'virt-viewer' package.")) "the 'virt-viewer' package."))
return None return None
if not os.environ.get("DISPLAY", ""): if not os.environ.get("DISPLAY", ""):
logging.warning(_("Graphics requested but DISPLAY is not set. " log.warning(_("Graphics requested but DISPLAY is not set. "
"Not running virt-viewer.")) "Not running virt-viewer."))
return None return None
@ -1451,7 +1454,7 @@ class VirtCLIParser(metaclass=_InitClass):
ret += xmlutil.listify(objs) ret += xmlutil.listify(objs)
except Exception as e: except Exception as e:
logging.debug("Exception parsing inst=%s optstr=%s", log.debug("Exception parsing inst=%s optstr=%s",
inst, self.optstr, exc_info=True) inst, self.optstr, exc_info=True)
fail(_("Error: %(cli_flag_name)s %(options)s: %(err)s") % fail(_("Error: %(cli_flag_name)s %(options)s: %(err)s") %
{"cli_flag_name": self.cli_flag_name(), {"cli_flag_name": self.cli_flag_name(),
@ -1482,7 +1485,7 @@ class VirtCLIParser(metaclass=_InitClass):
ret.append(inst) ret.append(inst)
self._check_leftover_opts(optdict) self._check_leftover_opts(optdict)
except Exception as e: except Exception as e:
logging.debug("Exception parsing inst=%s optstr=%s", log.debug("Exception parsing inst=%s optstr=%s",
inst, self.optstr, exc_info=True) inst, self.optstr, exc_info=True)
fail(_("Error: %(cli_flag_name)s %(options)s: %(err)s") % fail(_("Error: %(cli_flag_name)s %(options)s: %(err)s") %
{"cli_flag_name": self.cli_flag_name(), {"cli_flag_name": self.cli_flag_name(),
@ -2881,7 +2884,7 @@ class ParserDisk(VirtCLIParser):
raise ValueError(_("Storage volume must be specified as " raise ValueError(_("Storage volume must be specified as "
"vol=poolname/volname")) "vol=poolname/volname"))
poolname, volname = volname.split("/") poolname, volname = volname.split("/")
logging.debug("Parsed --disk volume as: pool=%s vol=%s", log.debug("Parsed --disk volume as: pool=%s vol=%s",
poolname, volname) poolname, volname)
super()._parse(inst) super()._parse(inst)
@ -3198,14 +3201,14 @@ class ParserGraphics(VirtCLIParser):
if inst.conn.is_qemu() and inst.gl: if inst.conn.is_qemu() and inst.gl:
if inst.type != "spice": if inst.type != "spice":
logging.warning("graphics type=%s does not support GL", inst.type) log.warning("graphics type=%s does not support GL", inst.type)
elif not inst.conn.support.conn_spice_gl(): elif not inst.conn.support.conn_spice_gl():
logging.warning("qemu/libvirt version may not support spice GL") log.warning("qemu/libvirt version may not support spice GL")
if inst.conn.is_qemu() and inst.rendernode: if inst.conn.is_qemu() and inst.rendernode:
if inst.type != "spice": if inst.type != "spice":
logging.warning("graphics type=%s does not support rendernode", inst.type) log.warning("graphics type=%s does not support rendernode", inst.type)
elif not inst.conn.support.conn_spice_rendernode(): elif not inst.conn.support.conn_spice_rendernode():
logging.warning("qemu/libvirt version may not support rendernode") log.warning("qemu/libvirt version may not support rendernode")
return ret return ret

View File

@ -7,7 +7,6 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
import re import re
import os import os
@ -19,6 +18,7 @@ from . import xmlutil
from .guest import Guest from .guest import Guest
from .devices import DeviceInterface from .devices import DeviceInterface
from .devices import DeviceDisk from .devices import DeviceDisk
from .logger import log
from .storage import StorageVolume from .storage import StorageVolume
from .devices import DeviceChannel from .devices import DeviceChannel
@ -132,7 +132,7 @@ class Cloner(object):
disk.validate() disk.validate()
disklist.append(disk) disklist.append(disk)
except Exception as e: except Exception as e:
logging.debug("Error setting clone path.", exc_info=True) log.debug("Error setting clone path.", exc_info=True)
raise ValueError(_("Could not use path '%s' for cloning: %s") % raise ValueError(_("Could not use path '%s' for cloning: %s") %
(path, str(e))) (path, str(e)))
@ -251,7 +251,7 @@ class Cloner(object):
""" """
Validate and setup all parameters needed for the original (cloned) VM Validate and setup all parameters needed for the original (cloned) VM
""" """
logging.debug("Validating original guest parameters") log.debug("Validating original guest parameters")
if self.original_guest is None and self.original_xml is None: if self.original_guest is None and self.original_xml is None:
raise RuntimeError(_("Original guest name or xml is required.")) raise RuntimeError(_("Original guest name or xml is required."))
@ -261,7 +261,7 @@ class Cloner(object):
flags = libvirt.VIR_DOMAIN_XML_SECURE flags = libvirt.VIR_DOMAIN_XML_SECURE
self.original_xml = self.original_dom.XMLDesc(flags) self.original_xml = self.original_dom.XMLDesc(flags)
logging.debug("Original XML:\n%s", self.original_xml) log.debug("Original XML:\n%s", self.original_xml)
self._guest = Guest(self.conn, parsexml=self.original_xml) self._guest = Guest(self.conn, parsexml=self.original_xml)
self._guest.id = None self._guest.id = None
@ -269,9 +269,9 @@ class Cloner(object):
# Pull clonable storage info from the original xml # Pull clonable storage info from the original xml
self._original_disks = self._get_original_disks_info() self._original_disks = self._get_original_disks_info()
logging.debug("Original paths: %s", log.debug("Original paths: %s",
[d.path for d in self.original_disks]) [d.path for d in self.original_disks])
logging.debug("Original sizes: %s", log.debug("Original sizes: %s",
[d.get_size() for d in self.original_disks]) [d.get_size() for d in self.original_disks])
# If domain has devices to clone, it must be 'off' or 'paused' # If domain has devices to clone, it must be 'off' or 'paused'
@ -373,7 +373,7 @@ class Cloner(object):
""" """
Validate and set up all parameters needed for the new (clone) VM Validate and set up all parameters needed for the new (clone) VM
""" """
logging.debug("Validating clone parameters.") log.debug("Validating clone parameters.")
self._clone_xml = self.original_xml self._clone_xml = self.original_xml
@ -383,14 +383,14 @@ class Cloner(object):
{"passed": len(self.clone_disks), {"passed": len(self.clone_disks),
"need": len(self.original_disks)}) "need": len(self.original_disks)})
logging.debug("Clone paths: %s", [d.path for d in self.clone_disks]) log.debug("Clone paths: %s", [d.path for d in self.clone_disks])
self._guest.name = self._clone_name self._guest.name = self._clone_name
self._guest.uuid = self._clone_uuid self._guest.uuid = self._clone_uuid
self._clone_macs.reverse() self._clone_macs.reverse()
for dev in self._guest.devices.graphics: for dev in self._guest.devices.graphics:
if dev.port and dev.port != -1: if dev.port and dev.port != -1:
logging.warning(_("Setting the graphics device port to autoport, " log.warning(_("Setting the graphics device port to autoport, "
"in order to avoid conflicting.")) "in order to avoid conflicting."))
dev.port = -1 dev.port = -1
@ -434,14 +434,14 @@ class Cloner(object):
# Save altered clone xml # Save altered clone xml
self._clone_xml = self._guest.get_xml() self._clone_xml = self._guest.get_xml()
logging.debug("Clone guest xml is\n%s", self._clone_xml) log.debug("Clone guest xml is\n%s", self._clone_xml)
def start_duplicate(self, meter=None): def start_duplicate(self, meter=None):
""" """
Actually perform the duplication: cloning disks if needed and defining Actually perform the duplication: cloning disks if needed and defining
the new clone xml. the new clone xml.
""" """
logging.debug("Starting duplicate.") log.debug("Starting duplicate.")
meter = progress.ensure_meter(meter) meter = progress.ensure_meter(meter)
dom = None dom = None
@ -459,12 +459,12 @@ class Cloner(object):
if self._nvram_disk: if self._nvram_disk:
self._nvram_disk.build_storage(meter) self._nvram_disk.build_storage(meter)
except Exception as e: except Exception as e:
logging.debug("Duplicate failed: %s", str(e)) log.debug("Duplicate failed: %s", str(e))
if dom: if dom:
dom.undefine() dom.undefine()
raise raise
logging.debug("Duplicating finished.") log.debug("Duplicating finished.")
def generate_clone_disk_path(self, origpath, newname=None): def generate_clone_disk_path(self, origpath, newname=None):
origname = self.original_guest origname = self.original_guest
@ -555,7 +555,7 @@ class Cloner(object):
raise ValueError(_("Disk path '%s' does not exist.") % raise ValueError(_("Disk path '%s' does not exist.") %
newd.path) newd.path)
except Exception as e: except Exception as e:
logging.debug("Exception creating clone disk objects", log.debug("Exception creating clone disk objects",
exc_info=True) exc_info=True)
raise ValueError(_("Could not determine original disk " raise ValueError(_("Could not determine original disk "
"information: %s" % str(e))) "information: %s" % str(e)))

View File

@ -4,7 +4,6 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
import os import os
import weakref import weakref
@ -14,6 +13,7 @@ from . import pollhelpers
from . import support from . import support
from . import Capabilities from . import Capabilities
from .guest import Guest from .guest import Guest
from .logger import log
from .nodedev import NodeDevice from .nodedev import NodeDevice
from .storage import StoragePool, StorageVolume from .storage import StoragePool, StorageVolume
from .uri import URI, MagicURI from .uri import URI, MagicURI
@ -248,7 +248,7 @@ class VirtinstConnection(object):
xml = vol.XMLDesc(0) xml = vol.XMLDesc(0)
ret.append(StorageVolume(weakref.proxy(self), parsexml=xml)) ret.append(StorageVolume(weakref.proxy(self), parsexml=xml))
except Exception as e: except Exception as e:
logging.debug("Fetching volume XML failed: %s", e) log.debug("Fetching volume XML failed: %s", e)
return ret return ret
def _fetch_all_vols_raw(self): def _fetch_all_vols_raw(self):
@ -342,7 +342,7 @@ class VirtinstConnection(object):
try: try:
self._daemon_version = self._libvirtconn.getLibVersion() self._daemon_version = self._libvirtconn.getLibVersion()
except Exception: except Exception:
logging.debug("Error calling getLibVersion", exc_info=True) log.debug("Error calling getLibVersion", exc_info=True)
return self._daemon_version return self._daemon_version
def conn_version(self): def conn_version(self):
@ -354,7 +354,7 @@ class VirtinstConnection(object):
try: try:
self._conn_version = self._libvirtconn.getVersion() self._conn_version = self._libvirtconn.getVersion()
except Exception: except Exception:
logging.debug("Error calling getVersion", exc_info=True) log.debug("Error calling getVersion", exc_info=True)
return self._conn_version return self._conn_version

View File

@ -6,7 +6,7 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging from ..logger import log
from .. import diskbackend from .. import diskbackend
from .. import progress from .. import progress
@ -221,7 +221,7 @@ class DeviceDisk(Device):
"path '%s'. Use libvirt APIs to manage the parent directory " "path '%s'. Use libvirt APIs to manage the parent directory "
"as a pool first.") % volname) "as a pool first.") % volname)
logging.debug("Creating volume '%s' on pool '%s'", log.debug("Creating volume '%s' on pool '%s'",
volname, poolobj.name()) volname, poolobj.name())
cap = (size * 1024 * 1024 * 1024) cap = (size * 1024 * 1024 * 1024)
@ -347,15 +347,15 @@ class DeviceDisk(Device):
self._set_default_storage_backend() self._set_default_storage_backend()
def set_vol_object(self, vol_object, parent_pool): def set_vol_object(self, vol_object, parent_pool):
logging.debug("disk.set_vol_object: volxml=\n%s", log.debug("disk.set_vol_object: volxml=\n%s",
vol_object.XMLDesc(0)) vol_object.XMLDesc(0))
logging.debug("disk.set_vol_object: poolxml=\n%s", log.debug("disk.set_vol_object: poolxml=\n%s",
parent_pool.XMLDesc(0)) parent_pool.XMLDesc(0))
self._change_backend(None, vol_object, parent_pool) self._change_backend(None, vol_object, parent_pool)
self._set_xmlpath(self.path) self._set_xmlpath(self.path)
def set_vol_install(self, vol_install): def set_vol_install(self, vol_install):
logging.debug("disk.set_vol_install: name=%s poolxml=\n%s", log.debug("disk.set_vol_install: name=%s poolxml=\n%s",
vol_install.name, vol_install.pool.XMLDesc(0)) vol_install.name, vol_install.pool.XMLDesc(0))
self._storage_backend = diskbackend.ManagedStorageCreator( self._storage_backend = diskbackend.ManagedStorageCreator(
self.conn, vol_install) self.conn, vol_install)
@ -678,7 +678,7 @@ class DeviceDisk(Device):
self.source_volume) self.source_volume)
except Exception as e: except Exception as e:
self._source_volume_err = str(e) self._source_volume_err = str(e)
logging.debug("Error fetching source pool=%s vol=%s", log.debug("Error fetching source pool=%s vol=%s",
self.source_pool, self.source_volume, exc_info=True) self.source_pool, self.source_volume, exc_info=True)
if vol_object is None and path is None: if vol_object is None and path is None:

View File

@ -4,10 +4,10 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
import os import os
from .device import Device from .device import Device
from ..logger import log
from ..xmlbuilder import XMLBuilder, XMLChildProperty, XMLProperty from ..xmlbuilder import XMLBuilder, XMLChildProperty, XMLProperty
@ -218,9 +218,9 @@ class DeviceGraphics(Device):
def _default_type(self, guest): def _default_type(self, guest):
gtype = guest.default_graphics_type gtype = guest.default_graphics_type
logging.debug("Using default_graphics=%s", gtype) log.debug("Using default_graphics=%s", gtype)
if gtype == "spice" and not self._spice_supported(): if gtype == "spice" and not self._spice_supported():
logging.debug("spice requested but HV doesn't support it. " log.debug("spice requested but HV doesn't support it. "
"Using vnc.") "Using vnc.")
gtype = "vnc" gtype = "vnc"
return gtype return gtype
@ -229,7 +229,7 @@ class DeviceGraphics(Device):
if self.type != "spice": if self.type != "spice":
return None return None
if not self.conn.is_remote(): if not self.conn.is_remote():
logging.debug("Local connection, disabling spice image " log.debug("Local connection, disabling spice image "
"compression.") "compression.")
return "off" return "off"
return None return None

View File

@ -4,11 +4,11 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
import os import os
import random import random
from .device import Device from .device import Device
from ..logger import log
from ..xmlbuilder import XMLBuilder, XMLChildProperty, XMLProperty from ..xmlbuilder import XMLBuilder, XMLChildProperty, XMLProperty
@ -42,13 +42,13 @@ def _random_mac(conn):
def _default_route(): def _default_route():
route_file = "/proc/net/route" route_file = "/proc/net/route"
if not os.path.exists(route_file): # pragma: no cover if not os.path.exists(route_file): # pragma: no cover
logging.debug("route_file=%s does not exist", route_file) log.debug("route_file=%s does not exist", route_file)
return None return None
for line in open(route_file): for line in open(route_file):
info = line.split() info = line.split()
if len(info) != 11: # pragma: no cover if len(info) != 11: # pragma: no cover
logging.debug("Unexpected field count=%s when parsing %s", log.debug("Unexpected field count=%s when parsing %s",
len(info), route_file) len(info), route_file)
break break
@ -135,7 +135,7 @@ class DeviceInterface(Device):
except RuntimeError: # pragma: no cover except RuntimeError: # pragma: no cover
continue continue
logging.debug( # pragma: no cover log.debug( # pragma: no cover
"Failed to generate non-conflicting MAC") "Failed to generate non-conflicting MAC")
return None # pragma: no cover return None # pragma: no cover

View File

@ -6,7 +6,6 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
import os import os
import re import re
import stat import stat
@ -14,6 +13,7 @@ import subprocess
import libvirt import libvirt
from .logger import log
from .storage import StoragePool, StorageVolume from .storage import StoragePool, StorageVolume
@ -139,7 +139,7 @@ def manage_path(conn, path):
if not poolname: if not poolname:
poolname = "dirpool" poolname = "dirpool"
poolname = StoragePool.find_free_name(conn, poolname) poolname = StoragePool.find_free_name(conn, poolname)
logging.debug("Attempting to build pool=%s target=%s", poolname, dirname) log.debug("Attempting to build pool=%s target=%s", poolname, dirname)
poolxml = StoragePool(conn) poolxml = StoragePool(conn)
poolxml.name = poolname poolxml.name = poolname
@ -252,16 +252,16 @@ def _fix_perms_acl(dirname, username):
stderr=subprocess.PIPE) stderr=subprocess.PIPE)
out, err = proc.communicate() out, err = proc.communicate()
logging.debug("Ran command '%s'", cmd) log.debug("Ran command '%s'", cmd)
if out or err: if out or err:
logging.debug("out=%s\nerr=%s", out, err) log.debug("out=%s\nerr=%s", out, err)
if proc.returncode != 0: if proc.returncode != 0:
raise ValueError(err) raise ValueError(err)
def _fix_perms_chmod(dirname): def _fix_perms_chmod(dirname):
logging.debug("Setting +x on %s", dirname) log.debug("Setting +x on %s", dirname)
mode = os.stat(dirname).st_mode mode = os.stat(dirname).st_mode
newmode = mode | stat.S_IXOTH newmode = mode | stat.S_IXOTH
os.chmod(dirname, newmode) os.chmod(dirname, newmode)
@ -281,8 +281,8 @@ def set_dirs_searchable(dirlist, username):
_fix_perms_acl(dirname, username) _fix_perms_acl(dirname, username)
continue continue
except Exception as e: except Exception as e:
logging.debug("setfacl failed: %s", e) log.debug("setfacl failed: %s", e)
logging.debug("trying chmod") log.debug("trying chmod")
useacl = False useacl = False
try: try:
@ -324,11 +324,11 @@ def _is_dir_searchable(dirname, uid, username):
stderr=subprocess.PIPE) stderr=subprocess.PIPE)
out, err = proc.communicate() out, err = proc.communicate()
except OSError: except OSError:
logging.debug("Didn't find the getfacl command.") log.debug("Didn't find the getfacl command.")
return False return False
if proc.returncode != 0: if proc.returncode != 0:
logging.debug("Cmd '%s' failed: %s", cmd, err) log.debug("Cmd '%s' failed: %s", cmd, err)
return False return False
pattern = "user:%s:..x" % username pattern = "user:%s:..x" % username
@ -475,7 +475,7 @@ class _StorageCreator(_StorageBase):
if err: if err:
raise ValueError(msg) raise ValueError(msg)
if msg: if msg:
logging.warning(msg) log.warning(msg)
def will_create_storage(self): def will_create_storage(self):
return True return True
@ -544,10 +544,10 @@ class CloneStorageCreator(_StorageCreator):
if self._input_path == "/dev/null": if self._input_path == "/dev/null":
# Not really sure why this check is here, # Not really sure why this check is here,
# but keeping for compat # but keeping for compat
logging.debug("Source dev was /dev/null. Skipping") log.debug("Source dev was /dev/null. Skipping")
return return
if self._input_path == self._output_path: if self._input_path == self._output_path:
logging.debug("Source and destination are the same. Skipping.") log.debug("Source and destination are the same. Skipping.")
return return
# If a destination file exists and sparse flag is True, # If a destination file exists and sparse flag is True,
@ -568,7 +568,7 @@ class CloneStorageCreator(_StorageCreator):
clone_block_size = 1024 * 1024 * 10 clone_block_size = 1024 * 1024 * 10
sparse = False sparse = False
logging.debug("Local Cloning %s to %s, sparse=%s, block_size=%s", log.debug("Local Cloning %s to %s, sparse=%s, block_size=%s",
self._input_path, self._output_path, self._input_path, self._output_path,
sparse, clone_block_size) sparse, clone_block_size)

View File

@ -4,7 +4,7 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging from ..logger import log
from ..xmlbuilder import XMLBuilder, XMLProperty, XMLChildProperty from ..xmlbuilder import XMLBuilder, XMLProperty, XMLChildProperty
@ -152,7 +152,7 @@ class DomainCpu(XMLBuilder):
break break
def set_model(self, guest, val): def set_model(self, guest, val):
logging.debug("setting cpu model %s", val) log.debug("setting cpu model %s", val)
if val: if val:
self.mode = "custom" self.mode = "custom"
if not self.match: if not self.match:
@ -179,7 +179,7 @@ class DomainCpu(XMLBuilder):
""" """
domcaps = guest.lookup_domcaps() domcaps = guest.lookup_domcaps()
if domcaps.supports_safe_host_model(): if domcaps.supports_safe_host_model():
logging.debug("Using domcaps for host-copy") log.debug("Using domcaps for host-copy")
cpu = domcaps.cpu.get_mode("host-model") cpu = domcaps.cpu.get_mode("host-model")
model = cpu.models[0].model model = cpu.models[0].model
fallback = cpu.models[0].fallback fallback = cpu.models[0].fallback
@ -284,7 +284,7 @@ class DomainCpu(XMLBuilder):
if cpu_model and cpu_model.usable != "no": if cpu_model and cpu_model.usable != "no":
return return
logging.debug("Host capabilities CPU '%s' is not supported " log.debug("Host capabilities CPU '%s' is not supported "
"according to domain capabilities. Unsetting CPU model", "according to domain capabilities. Unsetting CPU model",
self.model) self.model)
self.model = None self.model = None

View File

@ -6,13 +6,13 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
import re import re
import xml.etree.ElementTree as ET import xml.etree.ElementTree as ET
import libvirt import libvirt
from .domain import DomainCpu from .domain import DomainCpu
from .logger import log
from .xmlbuilder import XMLBuilder, XMLChildProperty, XMLProperty from .xmlbuilder import XMLBuilder, XMLChildProperty, XMLProperty
@ -158,7 +158,7 @@ class DomainCapabilities(XMLBuilder):
xml = conn.getDomainCapabilities(emulator, arch, xml = conn.getDomainCapabilities(emulator, arch,
machine, hvtype) machine, hvtype)
except Exception: except Exception:
logging.debug("Error fetching domcapabilities XML", log.debug("Error fetching domcapabilities XML",
exc_info=True) exc_info=True)
if not xml: if not xml:
@ -271,7 +271,7 @@ class DomainCapabilities(XMLBuilder):
def _get_expanded_cpu(self, mode): def _get_expanded_cpu(self, mode):
cpuXML = self._convert_mode_to_cpu(mode.get_xml()) cpuXML = self._convert_mode_to_cpu(mode.get_xml())
logging.debug("CPU XML for security flag baseline: %s", cpuXML) log.debug("CPU XML for security flag baseline: %s", cpuXML)
try: try:
expandedXML = self.conn.baselineHypervisorCPU( expandedXML = self.conn.baselineHypervisorCPU(
@ -281,7 +281,7 @@ class DomainCapabilities(XMLBuilder):
expandedXML = self.conn.baselineCPU([cpuXML], expandedXML = self.conn.baselineCPU([cpuXML],
libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES) libvirt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES)
logging.debug("Expanded CPU XML: %s", expandedXML) log.debug("Expanded CPU XML: %s", expandedXML)
return DomainCpu(self.conn, expandedXML) return DomainCpu(self.conn, expandedXML)
@ -307,7 +307,7 @@ class DomainCapabilities(XMLBuilder):
try: try:
cpu = self._get_expanded_cpu(m) cpu = self._get_expanded_cpu(m)
except libvirt.libvirtError as e: except libvirt.libvirtError as e:
logging.warning(_("Failed to get expanded CPU XML: %s"), e) log.warning(_("Failed to get expanded CPU XML: %s"), e)
break break
for feature in cpu.features: for feature in cpu.features:

View File

@ -6,7 +6,6 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
import random import random
import libvirt import libvirt
@ -17,6 +16,7 @@ from .buildconfig import BuildConfig
from .devices import * # pylint: disable=wildcard-import from .devices import * # pylint: disable=wildcard-import
from .domain import * # pylint: disable=wildcard-import from .domain import * # pylint: disable=wildcard-import
from .domcapabilities import DomainCapabilities from .domcapabilities import DomainCapabilities
from .logger import log
from .osdict import OSDB from .osdict import OSDB
from .xmlbuilder import XMLBuilder, XMLProperty, XMLChildProperty from .xmlbuilder import XMLBuilder, XMLProperty, XMLChildProperty
@ -91,12 +91,12 @@ class Guest(XMLBuilder):
raise RuntimeError(_("Domain named %s already exists!") % name) raise RuntimeError(_("Domain named %s already exists!") % name)
try: try:
logging.debug("Explicitly replacing guest '%s'", name) log.debug("Explicitly replacing guest '%s'", name)
if vm.ID() != -1: if vm.ID() != -1:
logging.debug("Destroying guest '%s'", name) log.debug("Destroying guest '%s'", name)
vm.destroy() vm.destroy()
logging.debug("Undefining guest '%s'", name) log.debug("Undefining guest '%s'", name)
vm.undefine() vm.undefine()
except libvirt.libvirtError as e: except libvirt.libvirtError as e:
raise RuntimeError(_("Could not remove old vm '%s': %s") % raise RuntimeError(_("Could not remove old vm '%s': %s") %
@ -135,7 +135,7 @@ class Guest(XMLBuilder):
conn.lookupByUUID, uuid): conn.lookupByUUID, uuid):
return uuid return uuid
logging.error("Failed to generate non-conflicting UUID") log.error("Failed to generate non-conflicting UUID")
@staticmethod @staticmethod
def generate_name(guest): def generate_name(guest):
@ -324,7 +324,7 @@ class Guest(XMLBuilder):
if os_id: if os_id:
self.__osinfo = OSDB.lookup_os_by_full_id(os_id) self.__osinfo = OSDB.lookup_os_by_full_id(os_id)
if not self.__osinfo: if not self.__osinfo:
logging.debug("XML had libosinfo os id=%s but we didn't " log.debug("XML had libosinfo os id=%s but we didn't "
"find any libosinfo object matching that", os_id) "find any libosinfo object matching that", os_id)
if not self.__osinfo: if not self.__osinfo:
@ -459,7 +459,7 @@ class Guest(XMLBuilder):
def set_os_name(self, name): def set_os_name(self, name):
obj = OSDB.lookup_os(name, raise_error=True) obj = OSDB.lookup_os(name, raise_error=True)
logging.debug("Setting Guest osinfo name %s", obj) log.debug("Setting Guest osinfo name %s", obj)
self._set_os_obj(obj) self._set_os_obj(obj)
def set_default_os_name(self): def set_default_os_name(self):
@ -584,7 +584,7 @@ class Guest(XMLBuilder):
self.features.smm = True self.features.smm = True
self.os.loader_secure = True self.os.loader_secure = True
if self.os.machine and "q35" not in self.os.machine: if self.os.machine and "q35" not in self.os.machine:
logging.warning("Changing machine type from '%s' to 'q35' " log.warning("Changing machine type from '%s' to 'q35' "
"which is required for UEFI secure boot.") "which is required for UEFI secure boot.")
self.os.machine = "q35" self.os.machine = "q35"
@ -696,7 +696,7 @@ class Guest(XMLBuilder):
self.conn.is_qemu() and self.conn.is_qemu() and
self.os.is_x86() and self.os.is_x86() and
self.type != "kvm"): self.type != "kvm"):
logging.warning("KVM acceleration not available, using '%s'", log.warning("KVM acceleration not available, using '%s'",
self.type) self.type)
def sync_vcpus_topology(self): def sync_vcpus_topology(self):
@ -787,10 +787,10 @@ class Guest(XMLBuilder):
except RuntimeError as e: except RuntimeError as e:
if self.uefi_requested: if self.uefi_requested:
raise raise
logging.debug("Error setting UEFI default", log.debug("Error setting UEFI default",
exc_info=True) exc_info=True)
logging.warning("Couldn't configure UEFI: %s", e) log.warning("Couldn't configure UEFI: %s", e)
logging.warning("Your VM may not boot successfully.") log.warning("Your VM may not boot successfully.")
def _usb_disabled(self): def _usb_disabled(self):
controllers = [c for c in self.devices.controller if controllers = [c for c in self.devices.controller if

View File

@ -5,10 +5,11 @@
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
# #
import logging
import os import os
import re import re
from .logger import log
_ETC_VCONSOLE = "/etc/vconsole.conf" _ETC_VCONSOLE = "/etc/vconsole.conf"
_KEYBOARD_DIR = "/etc/sysconfig/keyboard" _KEYBOARD_DIR = "/etc/sysconfig/keyboard"
@ -105,20 +106,20 @@ def _default_keymap():
kt = cb(f) kt = cb(f)
f.close() f.close()
if kt: if kt:
logging.debug("Found keymap=%s in %s", kt, path) log.debug("Found keymap=%s in %s", kt, path)
break break
logging.debug("Didn't find keymap in '%s'", path) log.debug("Didn't find keymap in '%s'", path)
except Exception as e: except Exception as e:
logging.debug("Error parsing '%s': %s", path, str(e)) log.debug("Error parsing '%s': %s", path, str(e))
if kt is None: if kt is None:
logging.debug("Did not parse any usable keymapping.") log.debug("Did not parse any usable keymapping.")
return default return default
kt = kt.lower() kt = kt.lower()
keymap = sanitize_keymap(kt) keymap = sanitize_keymap(kt)
if not keymap: if not keymap:
logging.debug("Didn't match keymap '%s' in keytable!", kt) log.debug("Didn't match keymap '%s' in keytable!", kt)
return default return default
return keymap return keymap

View File

@ -7,7 +7,7 @@
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import os import os
import logging from .logger import log
from . import progress from . import progress
from . import unattended from . import unattended
@ -210,7 +210,7 @@ class Installer(object):
ram = guest.osinfo.get_network_install_required_ram(guest) ram = guest.osinfo.get_network_install_required_ram(guest)
ram = (ram or 0) // 1024 ram = (ram or 0) // 1024
if ram > guest.currentMemory: if ram > guest.currentMemory:
logging.warning(_("Overriding memory to %s MiB needed for %s " log.warning(_("Overriding memory to %s MiB needed for %s "
"network install."), ram // 1024, guest.osinfo.name) "network install."), ram // 1024, guest.osinfo.name)
guest.currentMemory = ram guest.currentMemory = ram
@ -222,7 +222,7 @@ class Installer(object):
def _prepare_unattended_data(self, guest, script): def _prepare_unattended_data(self, guest, script):
expected_filename = script.get_expected_filename() expected_filename = script.get_expected_filename()
unattended_cmdline = script.generate_cmdline() unattended_cmdline = script.generate_cmdline()
logging.debug("Generated unattended cmdline: %s", unattended_cmdline) log.debug("Generated unattended cmdline: %s", unattended_cmdline)
scriptpath = script.write() scriptpath = script.write()
self._tmpfiles.append(scriptpath) self._tmpfiles.append(scriptpath)
@ -244,7 +244,7 @@ class Installer(object):
raise RuntimeError("Unattended method=cdrom installs are " raise RuntimeError("Unattended method=cdrom installs are "
"not yet supported for remote connections.") "not yet supported for remote connections.")
if not guest.osinfo.is_windows(): if not guest.osinfo.is_windows():
logging.warning("Attempting unattended method=cdrom injection " log.warning("Attempting unattended method=cdrom injection "
"for a non-windows OS. If this doesn't work, try " "for a non-windows OS. If this doesn't work, try "
"passing install media to --location") "passing install media to --location")
osguess = OSDB.guess_os_by_iso(self.cdrom) osguess = OSDB.guess_os_by_iso(self.cdrom)
@ -271,7 +271,7 @@ class Installer(object):
self._treemedia.cleanup(guest) self._treemedia.cleanup(guest)
for f in self._tmpfiles: for f in self._tmpfiles:
logging.debug("Removing %s", str(f)) log.debug("Removing %s", str(f))
os.unlink(f) os.unlink(f)
def _get_postinstall_bootdev(self, guest): def _get_postinstall_bootdev(self, guest):
@ -386,16 +386,16 @@ class Installer(object):
ret = self._treemedia.detect_distro(guest) ret = self._treemedia.detect_distro(guest)
elif self.cdrom: elif self.cdrom:
if guest.conn.is_remote(): if guest.conn.is_remote():
logging.debug("Can't detect distro for cdrom " log.debug("Can't detect distro for cdrom "
"remote connection.") "remote connection.")
else: else:
osguess = OSDB.guess_os_by_iso(self.cdrom) osguess = OSDB.guess_os_by_iso(self.cdrom)
if osguess: if osguess:
ret = osguess[0] ret = osguess[0]
else: else:
logging.debug("No media for distro detection.") log.debug("No media for distro detection.")
logging.debug("installer.detect_distro returned=%s", ret) log.debug("installer.detect_distro returned=%s", ret)
return ret return ret
def set_unattended_data(self, unattended_data): def set_unattended_data(self, unattended_data):
@ -438,9 +438,9 @@ class Installer(object):
install_xml = self._get_install_xml(guest, meter) install_xml = self._get_install_xml(guest, meter)
final_xml = guest.get_xml() final_xml = guest.get_xml()
logging.debug("Generated install XML: %s", log.debug("Generated install XML: %s",
(install_xml and ("\n" + install_xml) or "None required")) (install_xml and ("\n" + install_xml) or "None required"))
logging.debug("Generated boot XML: \n%s", final_xml) log.debug("Generated boot XML: \n%s", final_xml)
return install_xml, final_xml return install_xml, final_xml
@ -493,10 +493,10 @@ class Installer(object):
domain = self.conn.defineXML(final_xml) domain = self.conn.defineXML(final_xml)
try: try:
logging.debug("XML fetched from libvirt object:\n%s", log.debug("XML fetched from libvirt object:\n%s",
domain.XMLDesc(0)) domain.XMLDesc(0))
except Exception as e: # pragma: no cover except Exception as e: # pragma: no cover
logging.debug("Error fetching XML from libvirt object: %s", e) log.debug("Error fetching XML from libvirt object: %s", e)
return domain return domain
def _flag_autostart(self, domain): def _flag_autostart(self, domain):
@ -508,7 +508,7 @@ class Installer(object):
except Exception as e: # pragma: no cover except Exception as e: # pragma: no cover
if not self.conn.support.is_error_nosupport(e): if not self.conn.support.is_error_nosupport(e):
raise raise
logging.warning("Could not set autostart flag: libvirt " log.warning("Could not set autostart flag: libvirt "
"connection does not support autostart.") "connection does not support autostart.")
@ -562,7 +562,7 @@ class Installer(object):
return return
for disk in clean_disks: for disk in clean_disks:
logging.debug("Removing created disk path=%s vol_object=%s", log.debug("Removing created disk path=%s vol_object=%s",
disk.path, disk.get_vol_object()) disk.path, disk.get_vol_object())
name = os.path.basename(disk.path) name = os.path.basename(disk.path)
@ -578,6 +578,6 @@ class Installer(object):
meter.end(0) meter.end(0)
except Exception as e: # pragma: no cover except Exception as e: # pragma: no cover
logging.debug("Failed to remove disk '%s'", log.debug("Failed to remove disk '%s'",
name, exc_info=True) name, exc_info=True)
logging.error("Failed to remove disk '%s': %s", name, e) log.error("Failed to remove disk '%s': %s", name, e)

View File

@ -4,15 +4,16 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
import os import os
import shutil import shutil
import subprocess import subprocess
import tempfile import tempfile
from .logger import log
def _run_initrd_commands(initrd, tempdir): def _run_initrd_commands(initrd, tempdir):
logging.debug("Appending to the initrd.") log.debug("Appending to the initrd.")
find_proc = subprocess.Popen(['find', '.', '-print0'], find_proc = subprocess.Popen(['find', '.', '-print0'],
stdout=subprocess.PIPE, stdout=subprocess.PIPE,
@ -36,11 +37,11 @@ def _run_initrd_commands(initrd, tempdir):
cpioerr = cpio_proc.stderr.read() cpioerr = cpio_proc.stderr.read()
gziperr = gzip_proc.stderr.read() gziperr = gzip_proc.stderr.read()
if finderr: # pragma: no cover if finderr: # pragma: no cover
logging.debug("find stderr=%s", finderr) log.debug("find stderr=%s", finderr)
if cpioerr: # pragma: no cover if cpioerr: # pragma: no cover
logging.debug("cpio stderr=%s", cpioerr) log.debug("cpio stderr=%s", cpioerr)
if gziperr: # pragma: no cover if gziperr: # pragma: no cover
logging.debug("gzip stderr=%s", gziperr) log.debug("gzip stderr=%s", gziperr)
def _run_iso_commands(iso, tempdir): def _run_iso_commands(iso, tempdir):
@ -50,9 +51,9 @@ def _run_iso_commands(iso, tempdir):
"-input-charset", "utf8", "-input-charset", "utf8",
"-rational-rock", "-rational-rock",
tempdir] tempdir]
logging.debug("Running iso build command: %s", cmd) log.debug("Running iso build command: %s", cmd)
output = subprocess.check_output(cmd, stderr=subprocess.STDOUT) output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
logging.debug("cmd output: %s", output) log.debug("cmd output: %s", output)
def _perform_generic_injections(injections, scratchdir, media, cb): def _perform_generic_injections(injections, scratchdir, media, cb):
@ -69,7 +70,7 @@ def _perform_generic_injections(injections, scratchdir, media, cb):
else: else:
dst = os.path.basename(filename) dst = os.path.basename(filename)
logging.debug("Injecting src=%s dst=%s into media=%s", log.debug("Injecting src=%s dst=%s into media=%s",
filename, dst, media) filename, dst, media)
shutil.copy(filename, os.path.join(tempdir, dst)) shutil.copy(filename, os.path.join(tempdir, dst))

View File

@ -4,7 +4,6 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
import os import os
from . import progress from . import progress
@ -13,6 +12,7 @@ from . import urlfetcher
from .devices import DeviceDisk from .devices import DeviceDisk
from .installerinject import perform_initrd_injections from .installerinject import perform_initrd_injections
from .kernelupload import upload_kernel_initrd from .kernelupload import upload_kernel_initrd
from .logger import log
from .osdict import OSDB from .osdict import OSDB
@ -59,9 +59,9 @@ class InstallerTreeMedia(object):
dev.validate() dev.validate()
return dev.path return dev.path
except Exception as e: except Exception as e:
logging.debug("Error validating install location", exc_info=True) log.debug("Error validating install location", exc_info=True)
if path.startswith("nfs:"): if path.startswith("nfs:"):
logging.warning("NFS URL installs are no longer supported. " log.warning("NFS URL installs are no longer supported. "
"Access your install media over an alternate transport " "Access your install media over an alternate transport "
"like HTTP, or manually mount the NFS share and install " "like HTTP, or manually mount the NFS share and install "
"from the local directory mount point.") "from the local directory mount point.")
@ -240,7 +240,7 @@ class InstallerTreeMedia(object):
install_args = None install_args = None
if unattended_script: if unattended_script:
install_args = unattended_script.generate_cmdline() install_args = unattended_script.generate_cmdline()
logging.debug("Generated unattended cmdline: %s", install_args) log.debug("Generated unattended cmdline: %s", install_args)
elif self.is_network_url() and cache.kernel_url_arg: elif self.is_network_url() and cache.kernel_url_arg:
install_args = "%s=%s" % (cache.kernel_url_arg, self.location) install_args = "%s=%s" % (cache.kernel_url_arg, self.location)
@ -264,11 +264,11 @@ class InstallerTreeMedia(object):
def cleanup(self, guest): def cleanup(self, guest):
ignore = guest ignore = guest
for f in self._tmpfiles: for f in self._tmpfiles:
logging.debug("Removing %s", str(f)) log.debug("Removing %s", str(f))
os.unlink(f) os.unlink(f)
for vol in self._tmpvols: for vol in self._tmpvols:
logging.debug("Removing volume '%s'", vol.name()) log.debug("Removing volume '%s'", vol.name())
vol.delete(0) vol.delete(0)
self._tmpvols = [] self._tmpvols = []

View File

@ -4,10 +4,10 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
import os import os
from . import progress from . import progress
from .logger import log
from .devices import DeviceDisk from .devices import DeviceDisk
from .storage import StoragePool, StorageVolume from .storage import StoragePool, StorageVolume
@ -19,12 +19,12 @@ def _build_pool(conn, meter, path):
""" """
pool = StoragePool.lookup_pool_by_path(conn, path) pool = StoragePool.lookup_pool_by_path(conn, path)
if pool: # pragma: no cover if pool: # pragma: no cover
logging.debug("Existing pool '%s' found for %s", pool.name(), path) log.debug("Existing pool '%s' found for %s", pool.name(), path)
StoragePool.ensure_pool_is_running(pool, refresh=True) StoragePool.ensure_pool_is_running(pool, refresh=True)
return pool return pool
name = StoragePool.find_free_name(conn, "boot-scratch") name = StoragePool.find_free_name(conn, "boot-scratch")
logging.debug("Building storage pool: path=%s name=%s", path, name) log.debug("Building storage pool: path=%s name=%s", path, name)
poolbuild = StoragePool(conn) poolbuild = StoragePool(conn)
poolbuild.type = poolbuild.TYPE_DIR poolbuild.type = poolbuild.TYPE_DIR
poolbuild.name = name poolbuild.name = name
@ -77,7 +77,7 @@ def _upload_file(conn, meter, destpool, src):
size = os.path.getsize(src) size = os.path.getsize(src)
basename = os.path.basename(src) basename = os.path.basename(src)
name = StorageVolume.find_free_name(conn, destpool, basename) name = StorageVolume.find_free_name(conn, destpool, basename)
logging.debug("Generated volume name %s", name) log.debug("Generated volume name %s", name)
vol_install = DeviceDisk.build_vol_install(conn, name, destpool, vol_install = DeviceDisk.build_vol_install(conn, name, destpool,
(float(size) / 1024.0 / 1024.0 / 1024.0), True) (float(size) / 1024.0 / 1024.0 / 1024.0), True)
@ -138,17 +138,17 @@ def upload_kernel_initrd(conn, scratchdir, system_scratchdir,
if (not conn.is_remote() and if (not conn.is_remote() and
(conn.is_session_uri() or scratchdir == system_scratchdir)): (conn.is_session_uri() or scratchdir == system_scratchdir)):
# We have access to system scratchdir, don't jump through hoops # We have access to system scratchdir, don't jump through hoops
logging.debug("Have access to preferred scratchdir so" log.debug("Have access to preferred scratchdir so"
" nothing to upload") # pragma: no cover " nothing to upload") # pragma: no cover
return kernel, initrd, tmpvols # pragma: no cover return kernel, initrd, tmpvols # pragma: no cover
if not conn.support_remote_url_install(): if not conn.support_remote_url_install():
# Needed for the test_urls suite # Needed for the test_urls suite
logging.debug("Media upload not supported") # pragma: no cover log.debug("Media upload not supported") # pragma: no cover
return kernel, initrd, tmpvols # pragma: no cover return kernel, initrd, tmpvols # pragma: no cover
# Build pool # Build pool
logging.debug("Uploading kernel/initrd media") log.debug("Uploading kernel/initrd media")
pool = _build_pool(conn, meter, system_scratchdir) pool = _build_pool(conn, meter, system_scratchdir)
kvol = _upload_file(conn, meter, pool, kernel) kvol = _upload_file(conn, meter, pool, kernel)

9
virtinst/logger.py Normal file
View File

@ -0,0 +1,9 @@
# Copyright 2019 Red Hat, Inc.
#
# This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory.
import logging
# This is exported by virtinst/__init__.py
log = logging.getLogger("virtinst")

View File

@ -4,9 +4,9 @@
# This work is licensed under the GNU GPLv2 or later. # This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import logging
import os import os
from .logger import log
from .xmlbuilder import XMLBuilder, XMLProperty, XMLChildProperty from .xmlbuilder import XMLBuilder, XMLProperty, XMLChildProperty
@ -66,7 +66,7 @@ class NodeDevice(XMLBuilder):
try: try:
return _AddressStringToNodedev(conn, idstring) return _AddressStringToNodedev(conn, idstring)
except Exception: except Exception:
logging.debug("Error looking up nodedev from idstring=%s", log.debug("Error looking up nodedev from idstring=%s",
idstring, exc_info=True) idstring, exc_info=True)
raise raise
@ -206,7 +206,7 @@ def _AddressStringToHostdev(conn, addrstr):
else: else:
raise RuntimeError("Unknown address type") raise RuntimeError("Unknown address type")
except Exception: except Exception:
logging.debug("Error parsing node device string.", exc_info=True) log.debug("Error parsing node device string.", exc_info=True)
raise raise
return hostdev return hostdev

View File

@ -7,12 +7,13 @@
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import datetime import datetime
import logging
import os import os
import re import re
from gi.repository import Libosinfo from gi.repository import Libosinfo
from .logger import log
def _in_testsuite(): def _in_testsuite():
return "VIRTINST_TEST_SUITE" in os.environ return "VIRTINST_TEST_SUITE" in os.environ
@ -221,7 +222,7 @@ class _OSDB(object):
if key in self._aliases: if key in self._aliases:
alias = self._aliases[key] alias = self._aliases[key]
# Added 2018-10-02. Maybe remove aliases in a year # Added 2018-10-02. Maybe remove aliases in a year
logging.warning( log.warning(
_("OS name '%s' is deprecated, using '%s' instead. " _("OS name '%s' is deprecated, using '%s' instead. "
"This alias will be removed in the future."), key, alias) "This alias will be removed in the future."), key, alias)
key = alias key = alias
@ -236,7 +237,7 @@ class _OSDB(object):
try: try:
media = Libosinfo.Media.create_from_location(location, None) media = Libosinfo.Media.create_from_location(location, None)
except Exception as e: except Exception as e:
logging.debug("Error creating libosinfo media object: %s", str(e)) log.debug("Error creating libosinfo media object: %s", str(e))
return None return None
if not self._os_loader.get_db().identify_media(media): if not self._os_loader.get_db().identify_media(media):
@ -255,7 +256,7 @@ class _OSDB(object):
try: try:
tree = Libosinfo.Tree.create_from_location(location, None) tree = Libosinfo.Tree.create_from_location(location, None)
except Exception as e: except Exception as e:
logging.debug("Error creating libosinfo tree object for " log.debug("Error creating libosinfo tree object for "
"location=%s : %s", location, str(e)) "location=%s : %s", location, str(e))
return None return None
@ -321,7 +322,7 @@ class _OsResources:
# value as an approximation at a 'recommended' value # value as an approximation at a 'recommended' value
val = self._get_minimum_key(key, arch) val = self._get_minimum_key(key, arch)
if val: if val:
logging.debug("No recommended value found for key='%s', " log.debug("No recommended value found for key='%s', "
"using minimum=%s * 2", key, val) "using minimum=%s * 2", key, val)
return val * 2 return val * 2
return None return None

View File

@ -5,7 +5,7 @@
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
# #
import logging from .logger import log
# Debugging helper to force old style polling # Debugging helper to force old style polling
@ -24,7 +24,7 @@ def _new_poll_helper(origmap, typename, listfunc, buildfunc):
try: try:
objs = listfunc() objs = listfunc()
except Exception as e: except Exception as e:
logging.debug("Unable to list all %ss: %s", typename, e) log.debug("Unable to list all %ss: %s", typename, e)
for obj in objs: for obj in objs:
connkey = obj.name() connkey = obj.name()
@ -64,11 +64,11 @@ def _old_poll_helper(origmap, typename,
try: try:
newActiveNames = active_list() newActiveNames = active_list()
except Exception as e: except Exception as e:
logging.debug("Unable to list active %ss: %s", typename, e) log.debug("Unable to list active %ss: %s", typename, e)
try: try:
newInactiveNames = inactive_list() newInactiveNames = inactive_list()
except Exception as e: except Exception as e:
logging.debug("Unable to list inactive %ss: %s", typename, e) log.debug("Unable to list inactive %ss: %s", typename, e)
def check_obj(name): def check_obj(name):
obj = None obj = None
@ -78,7 +78,7 @@ def _old_poll_helper(origmap, typename,
try: try:
obj = lookup_func(name) obj = lookup_func(name)
except Exception as e: except Exception as e:
logging.debug("Could not fetch %s '%s': %s", log.debug("Could not fetch %s '%s': %s",
typename, connkey, e) typename, connkey, e)
return return
@ -94,7 +94,7 @@ def _old_poll_helper(origmap, typename,
try: try:
check_obj(name) check_obj(name)
except Exception: except Exception:
logging.exception("Couldn't fetch %s '%s'", typename, name) log.exception("Couldn't fetch %s '%s'", typename, name)
return (list(origmap.values()), list(new.values()), list(current.values())) return (list(origmap.values()), list(new.values()), list(current.values()))
@ -201,12 +201,12 @@ def _old_fetch_vms(backend, origmap, build_func):
try: try:
newActiveIDs = backend.listDomainsID() newActiveIDs = backend.listDomainsID()
except Exception as e: except Exception as e:
logging.debug("Unable to list active domains: %s", e) log.debug("Unable to list active domains: %s", e)
try: try:
newInactiveNames = backend.listDefinedDomains() newInactiveNames = backend.listDefinedDomains()
except Exception as e: except Exception as e:
logging.exception("Unable to list inactive domains: %s", e) log.exception("Unable to list inactive domains: %s", e)
def add_vm(vm): def add_vm(vm):
connkey = vm.get_name() connkey = vm.get_name()
@ -237,7 +237,7 @@ def _old_fetch_vms(backend, origmap, build_func):
check_new(vm, connkey) check_new(vm, connkey)
except Exception: except Exception:
logging.exception("Couldn't fetch domain id '%s'", _id) log.exception("Couldn't fetch domain id '%s'", _id)
for name in newInactiveNames: for name in newInactiveNames:
@ -253,7 +253,7 @@ def _old_fetch_vms(backend, origmap, build_func):
check_new(vm, connkey) check_new(vm, connkey)
except Exception: except Exception:
logging.exception("Couldn't fetch domain '%s'", name) log.exception("Couldn't fetch domain '%s'", name)
return (list(origmap.values()), list(new.values()), list(current.values())) return (list(origmap.values()), list(new.values()), list(current.values()))

View File

@ -5,13 +5,13 @@
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import os import os
import logging
import threading import threading
import libvirt import libvirt
from . import generatename from . import generatename
from . import progress from . import progress
from .logger import log
from .xmlbuilder import XMLBuilder, XMLChildProperty, XMLProperty from .xmlbuilder import XMLBuilder, XMLChildProperty, XMLProperty
@ -82,7 +82,7 @@ def _lookup_default_pool(conn):
poolxml = _lookup_poolxml_by_path(conn, path) poolxml = _lookup_poolxml_by_path(conn, path)
if poolxml: if poolxml:
logging.debug("Found default pool name=%s target=%s", log.debug("Found default pool name=%s target=%s",
poolxml.name, poolxml.target_path) poolxml.name, poolxml.target_path)
return poolxml return poolxml
@ -210,7 +210,7 @@ class StoragePool(_StorageObject):
try: try:
name = "default" name = "default"
path = _preferred_default_pool_path(conn) path = _preferred_default_pool_path(conn)
logging.debug("Attempting to build default pool with target '%s'", log.debug("Attempting to build default pool with target '%s'",
path) path)
defpool = StoragePool(conn) defpool = StoragePool(conn)
defpool.type = defpool.TYPE_DIR defpool.type = defpool.TYPE_DIR
@ -259,10 +259,10 @@ class StoragePool(_StorageObject):
:param refresh: If True, run refresh() as well :param refresh: If True, run refresh() as well
""" """
if pool_object.info()[0] != libvirt.VIR_STORAGE_POOL_RUNNING: if pool_object.info()[0] != libvirt.VIR_STORAGE_POOL_RUNNING:
logging.debug("starting pool=%s", pool_object.name()) log.debug("starting pool=%s", pool_object.name())
pool_object.create(0) pool_object.create(0)
if refresh: if refresh:
logging.debug("refreshing pool=%s", pool_object.name()) log.debug("refreshing pool=%s", pool_object.name())
pool_object.refresh(0) pool_object.refresh(0)
@ -476,7 +476,7 @@ class StoragePool(_StorageObject):
"formatting disk device.")) "formatting disk device."))
xml = self.get_xml() xml = self.get_xml()
logging.debug("Creating storage pool '%s' with xml:\n%s", log.debug("Creating storage pool '%s' with xml:\n%s",
self.name, xml) self.name, xml)
meter = progress.ensure_meter(meter) meter = progress.ensure_meter(meter)
@ -510,7 +510,7 @@ class StoragePool(_StorageObject):
try: try:
pool.undefine() pool.undefine()
except Exception as e: except Exception as e:
logging.debug("Error cleaning up pool after failure: %s", log.debug("Error cleaning up pool after failure: %s",
str(e)) str(e))
raise RuntimeError(errmsg) raise RuntimeError(errmsg)
@ -677,27 +677,27 @@ class StorageVolume(_StorageObject):
def _detect_backing_store_format(self): def _detect_backing_store_format(self):
logging.debug("Attempting to detect format for backing_store=%s", log.debug("Attempting to detect format for backing_store=%s",
self.backing_store) self.backing_store)
from . import diskbackend from . import diskbackend
vol, pool = diskbackend.manage_path(self.conn, self.backing_store) vol, pool = diskbackend.manage_path(self.conn, self.backing_store)
if not vol: if not vol:
logging.debug("Didn't find any volume for backing_store") log.debug("Didn't find any volume for backing_store")
return None return None
# Only set backing format for volumes that support # Only set backing format for volumes that support
# the 'format' parameter as we know it, like qcow2 etc. # the 'format' parameter as we know it, like qcow2 etc.
volxml = StorageVolume(self.conn, vol.XMLDesc(0)) volxml = StorageVolume(self.conn, vol.XMLDesc(0))
volxml.pool = pool volxml.pool = pool
logging.debug("Found backing store volume XML:\n%s", log.debug("Found backing store volume XML:\n%s",
volxml.get_xml()) volxml.get_xml())
if volxml.supports_property("format"): if volxml.supports_property("format"):
logging.debug("Returning format=%s", volxml.format) log.debug("Returning format=%s", volxml.format)
return volxml.format return volxml.format
logging.debug("backing_store volume doesn't appear to have " log.debug("backing_store volume doesn't appear to have "
"a file format we can specify, returning None") "a file format we can specify, returning None")
return None return None
@ -733,7 +733,7 @@ class StorageVolume(_StorageObject):
if self._pool_xml.type == StoragePool.TYPE_LOGICAL: if self._pool_xml.type == StoragePool.TYPE_LOGICAL:
if self.allocation != self.capacity: if self.allocation != self.capacity:
logging.warning(_("Sparse logical volumes are not supported, " log.warning(_("Sparse logical volumes are not supported, "
"setting allocation equal to capacity")) "setting allocation equal to capacity"))
self.allocation = self.capacity self.allocation = self.capacity
@ -741,7 +741,7 @@ class StorageVolume(_StorageObject):
if isfatal: if isfatal:
raise ValueError(errmsg) raise ValueError(errmsg)
if errmsg: if errmsg:
logging.warning(errmsg) log.warning(errmsg)
def install(self, meter=None): def install(self, meter=None):
""" """
@ -751,7 +751,7 @@ class StorageVolume(_StorageObject):
self.backing_format = self._detect_backing_store_format() self.backing_format = self._detect_backing_store_format()
xml = self.get_xml() xml = self.get_xml()
logging.debug("Creating storage volume '%s' with xml:\n%s", log.debug("Creating storage volume '%s' with xml:\n%s",
self.name, xml) self.name, xml)
t = threading.Thread(target=self._progress_thread, t = threading.Thread(target=self._progress_thread,
@ -786,17 +786,17 @@ class StorageVolume(_StorageObject):
if self.input_vol: if self.input_vol:
vol = self.pool.createXMLFrom(xml, self.input_vol, cloneflags) vol = self.pool.createXMLFrom(xml, self.input_vol, cloneflags)
else: else:
logging.debug("Using vol create flags=%s", createflags) log.debug("Using vol create flags=%s", createflags)
vol = self.pool.createXML(xml, createflags) vol = self.pool.createXML(xml, createflags)
self._install_finished.set() self._install_finished.set()
t.join() t.join()
meter.end(self.capacity) meter.end(self.capacity)
logging.debug("Storage volume '%s' install complete.", log.debug("Storage volume '%s' install complete.",
self.name) self.name)
return vol return vol
except Exception as e: except Exception as e:
logging.debug("Error creating storage volume", exc_info=True) log.debug("Error creating storage volume", exc_info=True)
raise RuntimeError("Couldn't create storage volume " raise RuntimeError("Couldn't create storage volume "
"'%s': '%s'" % (self.name, str(e))) "'%s': '%s'" % (self.name, str(e)))
@ -816,7 +816,7 @@ class StorageVolume(_StorageObject):
break break
if vol is None: if vol is None:
logging.debug("Couldn't lookup storage volume in prog thread.") log.debug("Couldn't lookup storage volume in prog thread.")
return return
while True: while True:

View File

@ -8,13 +8,14 @@
import getpass import getpass
import locale import locale
import logging
import os import os
import pwd import pwd
import tempfile import tempfile
from gi.repository import Libosinfo from gi.repository import Libosinfo
from .logger import log
def _make_installconfig(script, osobj, unattended_data, arch, hostname, url): def _make_installconfig(script, osobj, unattended_data, arch, hostname, url):
""" """
@ -95,20 +96,20 @@ def _make_installconfig(script, osobj, unattended_data, arch, hostname, url):
if unattended_data.product_key: if unattended_data.product_key:
config.set_reg_product_key(unattended_data.product_key) config.set_reg_product_key(unattended_data.product_key)
logging.debug("InstallScriptConfig created with the following params:") log.debug("InstallScriptConfig created with the following params:")
logging.debug("username: %s", config.get_user_login()) log.debug("username: %s", config.get_user_login())
logging.debug("realname: %s", config.get_user_realname()) log.debug("realname: %s", config.get_user_realname())
logging.debug("user password: %s", config.get_user_password()) log.debug("user password: %s", config.get_user_password())
logging.debug("admin password: %s", config.get_admin_password()) log.debug("admin password: %s", config.get_admin_password())
logging.debug("target disk: %s", config.get_target_disk()) log.debug("target disk: %s", config.get_target_disk())
logging.debug("hardware arch: %s", config.get_hardware_arch()) log.debug("hardware arch: %s", config.get_hardware_arch())
logging.debug("hostname: %s", config.get_hostname()) log.debug("hostname: %s", config.get_hostname())
logging.debug("timezone: %s", config.get_l10n_timezone()) log.debug("timezone: %s", config.get_l10n_timezone())
logging.debug("language: %s", config.get_l10n_language()) log.debug("language: %s", config.get_l10n_language())
logging.debug("keyboard: %s", config.get_l10n_keyboard()) log.debug("keyboard: %s", config.get_l10n_keyboard())
logging.debug("url: %s", log.debug("url: %s",
config.get_installation_url()) # pylint: disable=no-member config.get_installation_url()) # pylint: disable=no-member
logging.debug("product-key: %s", config.get_reg_product_key()) log.debug("product-key: %s", config.get_reg_product_key())
return config return config
@ -147,7 +148,7 @@ class OSInstallScript:
"initrd": Libosinfo.InstallScriptInjectionMethod.INITRD, "initrd": Libosinfo.InstallScriptInjectionMethod.INITRD,
} }
logging.debug("Using '%s' injection method", namestr) log.debug("Using '%s' injection method", namestr)
injection_method = names[namestr] injection_method = names[namestr]
supported_injection_methods = self._script.get_injection_methods() supported_injection_methods = self._script.get_injection_methods()
if (injection_method & supported_injection_methods == 0): if (injection_method & supported_injection_methods == 0):
@ -164,7 +165,7 @@ class OSInstallScript:
"network": Libosinfo.InstallScriptInstallationSource.NETWORK, "network": Libosinfo.InstallScriptInstallationSource.NETWORK,
} }
logging.debug("Using '%s' installation source", namestr) log.debug("Using '%s' installation source", namestr)
self._script.set_installation_source(names[namestr]) self._script.set_installation_source(names[namestr])
def _requires_param(self, config_param): def _requires_param(self, config_param):
@ -196,8 +197,8 @@ class OSInstallScript:
content = self.generate() content = self.generate()
open(scriptpath, "w").write(content) open(scriptpath, "w").write(content)
logging.debug("Generated unattended script: %s", scriptpath) log.debug("Generated unattended script: %s", scriptpath)
logging.debug("Generated script contents:\n%s", content) log.debug("Generated script contents:\n%s", content)
return scriptpath return scriptpath
@ -265,7 +266,7 @@ def _lookup_rawscript(osinfo, profile, os_media):
(osinfo.name, profile, ", ".join(profile_names))) (osinfo.name, profile, ", ".join(profile_names)))
else: else:
profile = _find_default_profile(profile_names) profile = _find_default_profile(profile_names)
logging.warning(_("Using unattended profile '%s'"), profile) log.warning(_("Using unattended profile '%s'"), profile)
rawscripts = script_map[profile] rawscripts = script_map[profile]
# Some OSes (as Windows) have more than one installer script, # Some OSes (as Windows) have more than one installer script,
@ -273,7 +274,7 @@ def _lookup_rawscript(osinfo, profile, os_media):
# perform the unattended installation. Let's just deal with # perform the unattended installation. Let's just deal with
# multiple installer scripts when its actually needed, though. # multiple installer scripts when its actually needed, though.
usescript = rawscripts[0] usescript = rawscripts[0]
logging.debug("Install script found for profile '%s': %s", log.debug("Install script found for profile '%s': %s",
profile, usescript.get_id()) profile, usescript.get_id())
return usescript return usescript

View File

@ -5,10 +5,11 @@
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
# #
import logging
import re import re
import urllib.parse import urllib.parse
from .logger import log
def sanitize_xml_for_test_define(xml): def sanitize_xml_for_test_define(xml):
import difflib import difflib
@ -23,7 +24,7 @@ def sanitize_xml_for_test_define(xml):
diff = "\n".join(difflib.unified_diff(orig.split("\n"), diff = "\n".join(difflib.unified_diff(orig.split("\n"),
xml.split("\n"))) xml.split("\n")))
if diff: if diff:
logging.debug("virtinst test sanitizing diff\n:%s", diff) log.debug("virtinst test sanitizing diff\n:%s", diff)
return xml return xml

View File

@ -5,9 +5,9 @@
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import configparser import configparser
import logging
import re import re
from .logger import log
from .osdict import OSDB from .osdict import OSDB
@ -39,7 +39,7 @@ class _DistroCache(object):
content = self._fetcher.acquireFileContent(path) content = self._fetcher.acquireFileContent(path)
except ValueError: except ValueError:
content = None content = None
logging.debug("Failed to acquire file=%s", path) log.debug("Failed to acquire file=%s", path)
self._filecache[path] = content self._filecache[path] = content
return self._filecache[path] return self._filecache[path]
@ -68,15 +68,15 @@ class _DistroCache(object):
treeinfo.read_string(treeinfostr) treeinfo.read_string(treeinfostr)
self.treeinfo_family = treeinfo.get("general", "family") self.treeinfo_family = treeinfo.get("general", "family")
self._treeinfo = treeinfo self._treeinfo = treeinfo
logging.debug("treeinfo family=%s", self.treeinfo_family) log.debug("treeinfo family=%s", self.treeinfo_family)
if self._treeinfo.has_option("general", "version"): if self._treeinfo.has_option("general", "version"):
self.treeinfo_version = self._treeinfo.get("general", "version") self.treeinfo_version = self._treeinfo.get("general", "version")
logging.debug("Found treeinfo version=%s", self.treeinfo_version) log.debug("Found treeinfo version=%s", self.treeinfo_version)
if self._treeinfo.has_option("general", "name"): if self._treeinfo.has_option("general", "name"):
self.treeinfo_name = self._treeinfo.get("general", "name") self.treeinfo_name = self._treeinfo.get("general", "name")
logging.debug("Found treeinfo name=%s", self.treeinfo_name) log.debug("Found treeinfo name=%s", self.treeinfo_name)
return self._treeinfo return self._treeinfo
@ -87,7 +87,7 @@ class _DistroCache(object):
ret = bool(re.match(famregex, self.treeinfo_family)) ret = bool(re.match(famregex, self.treeinfo_family))
self.treeinfo_matched = ret self.treeinfo_matched = ret
if not ret: if not ret:
logging.debug("Didn't match treeinfo family regex=%s", famregex) log.debug("Didn't match treeinfo family regex=%s", famregex)
return ret return ret
def content_regex(self, filename, regex): def content_regex(self, filename, regex):
@ -102,7 +102,7 @@ class _DistroCache(object):
if re.match(regex, line): if re.match(regex, line):
return True return True
logging.debug("found filename=%s but regex=%s didn't match", log.debug("found filename=%s but regex=%s didn't match",
filename, regex) filename, regex)
return False return False
@ -121,7 +121,7 @@ class _DistroCache(object):
return [(_get_treeinfo_path("kernel"), return [(_get_treeinfo_path("kernel"),
_get_treeinfo_path("initrd"))] _get_treeinfo_path("initrd"))]
except Exception: # pragma: no cover except Exception: # pragma: no cover
logging.debug("Failed to parse treeinfo kernel/initrd", log.debug("Failed to parse treeinfo kernel/initrd",
exc_info=True) exc_info=True)
return [] return []
@ -141,7 +141,7 @@ class _DistroCache(object):
version = _safeint(verstr.split(".")[0]) version = _safeint(verstr.split(".")[0])
update = _safeint(verstr.split(".")[1]) update = _safeint(verstr.split(".")[1])
logging.debug("converted verstr=%s to version=%s update=%s", log.debug("converted verstr=%s to version=%s update=%s",
verstr, version, update) verstr, version, update)
return version, update return version, update
@ -158,7 +158,7 @@ class _DistroCache(object):
not self.libosinfo_mediaobj.get_initrd_path()): not self.libosinfo_mediaobj.get_initrd_path()):
# This can happen if the media is live media, or just # This can happen if the media is live media, or just
# with incomplete libosinfo data # with incomplete libosinfo data
logging.debug("libosinfo didn't report any media kernel/initrd " log.debug("libosinfo didn't report any media kernel/initrd "
"path for detected os_variant=%s", "path for detected os_variant=%s",
self.libosinfo_mediaobj) self.libosinfo_mediaobj)
return False return False
@ -187,12 +187,12 @@ class _SUSEContent(object):
if line.startswith(prefix + " "): if line.startswith(prefix + " "):
self.content_dict[prefix] = line.split(" ", 1)[1] self.content_dict[prefix] = line.split(" ", 1)[1]
logging.debug("SUSE content dict: %s", str(self.content_dict)) log.debug("SUSE content dict: %s", str(self.content_dict))
self.tree_arch = self._get_tree_arch() self.tree_arch = self._get_tree_arch()
self.product_name = self._get_product_name() self.product_name = self._get_product_name()
self.product_version = self._get_product_version() self.product_version = self._get_product_version()
logging.debug("SUSE content product_name=%s product_version=%s " log.debug("SUSE content product_name=%s product_version=%s "
"tree_arch=%s", self.product_name, self.product_version, "tree_arch=%s", self.product_name, self.product_version,
self.tree_arch) self.tree_arch)
@ -238,7 +238,7 @@ class _SUSEContent(object):
elif "," in self.content_dict.get("DISTRO", ""): elif "," in self.content_dict.get("DISTRO", ""):
product_name = self.content_dict["DISTRO"].rsplit(",", 1)[1] product_name = self.content_dict["DISTRO"].rsplit(",", 1)[1]
logging.debug("SUSE content product_name=%s", product_name) log.debug("SUSE content product_name=%s", product_name)
return product_name return product_name
def _get_product_version(self): def _get_product_version(self):
@ -278,7 +278,7 @@ class _SUSEContent(object):
def getDistroStore(guest, fetcher, skip_error): def getDistroStore(guest, fetcher, skip_error):
logging.debug("Finding distro store for location=%s", fetcher.location) log.debug("Finding distro store for location=%s", fetcher.location)
arch = guest.os.arch arch = guest.os.arch
_type = guest.os.os_type _type = guest.os.os_type
@ -291,7 +291,7 @@ def getDistroStore(guest, fetcher, skip_error):
continue continue
store = sclass(fetcher.location, arch, _type, cache) store = sclass(fetcher.location, arch, _type, cache)
logging.debug("Detected class=%s osvariant=%s", log.debug("Detected class=%s osvariant=%s",
store.__class__.__name__, store.get_osdict_info()) store.__class__.__name__, store.get_osdict_info())
return store return store
@ -338,7 +338,7 @@ class _DistroTree(object):
self._os_variant = self._detect_version() self._os_variant = self._detect_version()
if self._os_variant and not OSDB.lookup_os(self._os_variant): if self._os_variant and not OSDB.lookup_os(self._os_variant):
logging.debug("Detected os_variant as %s, which is not " log.debug("Detected os_variant as %s, which is not "
"in osdict.", "in osdict.",
self._os_variant) self._os_variant)
self._os_variant = None self._os_variant = None
@ -361,7 +361,7 @@ class _DistroTree(object):
""" """
Hook for subclasses to detect media os variant. Hook for subclasses to detect media os variant.
""" """
logging.debug("%s does not implement any osdict detection", self) log.debug("%s does not implement any osdict detection", self)
return None return None
@ -403,13 +403,13 @@ class _FedoraDistro(_DistroTree):
verstr = self.cache.treeinfo_version verstr = self.cache.treeinfo_version
if not verstr: # pragma: no cover if not verstr: # pragma: no cover
logging.debug("No treeinfo version? Assume latest_variant=%s", log.debug("No treeinfo version? Assume latest_variant=%s",
latest_variant) latest_variant)
return latest_variant return latest_variant
# rawhide trees changed to use version=Rawhide in Apr 2016 # rawhide trees changed to use version=Rawhide in Apr 2016
if verstr in ["development", "rawhide", "Rawhide"]: if verstr in ["development", "rawhide", "Rawhide"]:
logging.debug("treeinfo version=%s, using latest_variant=%s", log.debug("treeinfo version=%s, using latest_variant=%s",
verstr, latest_variant) verstr, latest_variant)
return latest_variant return latest_variant
@ -418,7 +418,7 @@ class _FedoraDistro(_DistroTree):
if OSDB.lookup_os(variant): if OSDB.lookup_os(variant):
return variant return variant
logging.debug( # pragma: no cover log.debug( # pragma: no cover
"variant=%s from treeinfo version=%s not found, " "variant=%s from treeinfo version=%s not found, "
"using latest_variant=%s", variant, verstr, latest_variant) "using latest_variant=%s", variant, verstr, latest_variant)
return latest_variant # pragma: no cover return latest_variant # pragma: no cover
@ -439,7 +439,7 @@ class _RHELDistro(_DistroTree):
def _detect_version(self): def _detect_version(self):
if not self.cache.treeinfo_version: if not self.cache.treeinfo_version:
logging.debug("No treeinfo version? Not setting an os_variant") log.debug("No treeinfo version? Not setting an os_variant")
return return
version, update = self.cache.split_version() version, update = self.cache.split_version()
@ -488,7 +488,7 @@ class _SuseDistro(_RHELDistro):
try: try:
cache.suse_content = _SUSEContent(content_str) cache.suse_content = _SUSEContent(content_str)
except Exception as e: except Exception as e:
logging.debug("Error parsing SUSE content file: %s", str(e)) log.debug("Error parsing SUSE content file: %s", str(e))
return False return False
if not cache.suse_content: if not cache.suse_content:
@ -674,7 +674,7 @@ class _DebianDistro(_DistroTree):
arch = re.findall(pattern, self.uri) arch = re.findall(pattern, self.uri)
if not arch: if not arch:
continue continue
logging.debug("Found pattern=%s treearch=%s in uri", log.debug("Found pattern=%s treearch=%s in uri",
pattern, arch[0]) pattern, arch[0])
return arch[0] return arch[0]
@ -682,14 +682,14 @@ class _DebianDistro(_DistroTree):
# in the URI name for --location $ISO mounts # in the URI name for --location $ISO mounts
for arch in ["i386", "amd64", "x86_64", "arm64"]: for arch in ["i386", "amd64", "x86_64", "arm64"]:
if arch in self.uri: if arch in self.uri:
logging.debug("Found treearch=%s in uri", arch) log.debug("Found treearch=%s in uri", arch)
if arch == "x86_64": if arch == "x86_64":
arch = "amd64" arch = "amd64"
return arch return arch
# Otherwise default to i386 # Otherwise default to i386
arch = "i386" arch = "i386"
logging.debug("No treearch found in uri, defaulting to arch=%s", arch) log.debug("No treearch found in uri, defaulting to arch=%s", arch)
return arch return arch
def _set_url_paths(self): def _set_url_paths(self):
@ -745,7 +745,7 @@ class _DebianDistro(_DistroTree):
oses = [n for n in OSDB.list_os() if n.name.startswith(self._debname)] oses = [n for n in OSDB.list_os() if n.name.startswith(self._debname)]
if self.cache.debian_media_type == "daily": if self.cache.debian_media_type == "daily":
logging.debug("Appears to be debian 'daily' URL, using latest " log.debug("Appears to be debian 'daily' URL, using latest "
"debian OS") "debian OS")
return oses[0].name return oses[0].name
@ -760,7 +760,7 @@ class _DebianDistro(_DistroTree):
codename = osobj.label.split()[1].lower() codename = osobj.label.split()[1].lower()
if ("/%s/" % codename) in self.uri: if ("/%s/" % codename) in self.uri:
logging.debug("Found codename=%s in the URL string", codename) log.debug("Found codename=%s in the URL string", codename)
return osobj.name return osobj.name
@ -841,7 +841,7 @@ def _build_distro_list(osobj):
# If user manually specified an os_distro, bump its URL class # If user manually specified an os_distro, bump its URL class
# to the top of the list # to the top of the list
if osobj.distro: if osobj.distro:
logging.debug("variant=%s has distro=%s, looking for matching " log.debug("variant=%s has distro=%s, looking for matching "
"distro store to prioritize", "distro store to prioritize",
osobj.name, osobj.distro) osobj.name, osobj.distro)
found_store = None found_store = None
@ -850,11 +850,11 @@ def _build_distro_list(osobj):
found_store = store found_store = store
if found_store: if found_store:
logging.debug("Prioritizing distro store=%s", found_store) log.debug("Prioritizing distro store=%s", found_store)
allstores.remove(found_store) allstores.remove(found_store)
allstores.insert(0, found_store) allstores.insert(0, found_store)
else: else:
logging.debug("No matching store found, not prioritizing anything") log.debug("No matching store found, not prioritizing anything")
import os import os
force_libosinfo = os.environ.get("VIRTINST_TEST_SUITE_FORCE_LIBOSINFO") force_libosinfo = os.environ.get("VIRTINST_TEST_SUITE_FORCE_LIBOSINFO")

View File

@ -8,7 +8,6 @@
import ftplib import ftplib
import io import io
import logging
import os import os
import subprocess import subprocess
import tempfile import tempfile
@ -16,6 +15,8 @@ import urllib
import requests import requests
from .logger import log
############################## ##############################
# Mocking for the test suite # # Mocking for the test suite #
@ -43,7 +44,7 @@ def _make_mock_url(url, filesyntax):
class _MockRequestsResponse: class _MockRequestsResponse:
def __init__(self, url): def __init__(self, url):
logging.debug("mocking requests session for url=%s", url) log.debug("mocking requests session for url=%s", url)
fn = _make_mock_url(url, filesyntax=False) fn = _make_mock_url(url, filesyntax=False)
self._content = open(fn).read() self._content = open(fn).read()
self.headers = {'content-length': len(self._content)} self.headers = {'content-length': len(self._content)}
@ -100,7 +101,7 @@ class _URLFetcher(object):
self.scratchdir = scratchdir self.scratchdir = scratchdir
self.meter = meter self.meter = meter
logging.debug("Using scratchdir=%s", scratchdir) log.debug("Using scratchdir=%s", scratchdir)
self._prepare() self._prepare()
@ -135,7 +136,7 @@ class _URLFetcher(object):
raise ValueError(_("Couldn't acquire file %s: %s") % raise ValueError(_("Couldn't acquire file %s: %s") %
(url, str(e))) (url, str(e)))
logging.debug("Fetching URI: %s", url) log.debug("Fetching URI: %s", url)
self.meter.start( self.meter.start(
text=_("Retrieving file %s...") % os.path.basename(filename), text=_("Retrieving file %s...") % os.path.basename(filename),
size=size) size=size)
@ -203,7 +204,7 @@ class _URLFetcher(object):
""" """
url = self._make_full_url(filename) url = self._make_full_url(filename)
ret = self._hasFile(url) ret = self._hasFile(url)
logging.debug("hasFile(%s) returning %s", url, ret) log.debug("hasFile(%s) returning %s", url, ret)
return ret return ret
def acquireFile(self, filename, fullurl=None): def acquireFile(self, filename, fullurl=None):
@ -220,7 +221,7 @@ class _URLFetcher(object):
fn = fileobj.name fn = fileobj.name
self._grabURL(filename, fileobj, fullurl=fullurl) self._grabURL(filename, fileobj, fullurl=fullurl)
logging.debug("Saved file to %s", fn) log.debug("Saved file to %s", fn)
return fn return fn
except: # noqa except: # noqa
if fn and os.path.exists(fn): # pragma: no cover if fn and os.path.exists(fn): # pragma: no cover
@ -250,7 +251,7 @@ class _HTTPURLFetcher(_URLFetcher):
try: try:
self._session.close() self._session.close()
except Exception: # pragma: no cover except Exception: # pragma: no cover
logging.debug("Error closing requests.session", exc_info=True) log.debug("Error closing requests.session", exc_info=True)
self._session = None self._session = None
def can_access(self): def can_access(self):
@ -264,7 +265,7 @@ class _HTTPURLFetcher(_URLFetcher):
response = self._session.head(url, allow_redirects=True) response = self._session.head(url, allow_redirects=True)
response.raise_for_status() response.raise_for_status()
except Exception as e: # pragma: no cover except Exception as e: # pragma: no cover
logging.debug("HTTP hasFile request failed: %s", str(e)) log.debug("HTTP hasFile request failed: %s", str(e))
return False return False
return True return True
@ -335,7 +336,7 @@ class _FTPURLFetcher(_URLFetcher):
try: try:
self._ftp.quit() self._ftp.quit()
except Exception: # pragma: no cover except Exception: # pragma: no cover
logging.debug("Error quitting ftp connection", exc_info=True) log.debug("Error quitting ftp connection", exc_info=True)
self._ftp = None self._ftp = None
@ -350,7 +351,7 @@ class _FTPURLFetcher(_URLFetcher):
# If it's a dir # If it's a dir
self._ftp.cwd(path) self._ftp.cwd(path)
except ftplib.all_errors as e: # pragma: no cover except ftplib.all_errors as e: # pragma: no cover
logging.debug("FTP hasFile: couldn't access %s: %s", log.debug("FTP hasFile: couldn't access %s: %s",
url, str(e)) url, str(e))
return False return False
@ -383,7 +384,7 @@ class _ISOURLFetcher(_URLFetcher):
cmd = ["isoinfo", "-J", "-i", self.location, "-x", url] cmd = ["isoinfo", "-J", "-i", self.location, "-x", url]
logging.debug("Running isoinfo: %s", cmd) log.debug("Running isoinfo: %s", cmd)
output = subprocess.check_output(cmd) output = subprocess.check_output(cmd)
return io.BytesIO(output), len(output) return io.BytesIO(output), len(output)
@ -395,7 +396,7 @@ class _ISOURLFetcher(_URLFetcher):
if not self._cache_file_list: if not self._cache_file_list:
cmd = ["isoinfo", "-J", "-i", self.location, "-f"] cmd = ["isoinfo", "-J", "-i", self.location, "-f"]
logging.debug("Running isoinfo: %s", cmd) log.debug("Running isoinfo: %s", cmd)
output = subprocess.check_output(cmd, stderr=subprocess.DEVNULL) output = subprocess.check_output(cmd, stderr=subprocess.DEVNULL)
self._cache_file_list = output.splitlines(False) self._cache_file_list = output.splitlines(False)

View File

@ -7,12 +7,12 @@
# See the COPYING file in the top-level directory. # See the COPYING file in the top-level directory.
import collections import collections
import logging
import os import os
import re import re
import string import string
import textwrap import textwrap
from .logger import log
from .xmlapi import XMLAPI from .xmlapi import XMLAPI
from . import xmlutil from . import xmlutil
@ -233,7 +233,7 @@ class XMLProperty(_XMLPropertyBase):
intkwargs["base"] = 16 intkwargs["base"] = 16
ret = int(val, **intkwargs) ret = int(val, **intkwargs)
except ValueError as e: except ValueError as e:
logging.debug("Error converting XML value to int: %s", e) log.debug("Error converting XML value to int: %s", e)
ret = val ret = val
elif self._is_yesno: elif self._is_yesno:
if val == "yes": if val == "yes":
@ -392,7 +392,7 @@ class _XMLState(object):
try: try:
self.xmlapi = XMLAPI(parsexml) self.xmlapi = XMLAPI(parsexml)
except Exception: except Exception:
logging.debug("Error parsing xml=\n%s", parsexml) log.debug("Error parsing xml=\n%s", parsexml)
raise raise
if not self.is_build: if not self.is_build: