feat(Anaconda): Local Repo
This commit is contained in:
1 parent
fbc5a9c872
commit
6befd049dc
203 files changed
+23997
-7
No files matched your search
@@ -0,0 +1,139 @@
|
||||
#
|
||||
# __init__.py - Basic stuff for exception handling
|
||||
#
|
||||
# Copyright (C) 2009 Red Hat, Inc.
|
||||
# All rights reserved.
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 2 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
# Author(s): Chris Lumens <clumens@redhat.com>
|
||||
#
|
||||
|
||||
from collections import namedtuple
|
||||
|
||||
# These constants represent the return values of buttons on the initial
|
||||
# exception handling dialog - the dialog that first pops up when an
|
||||
# exception is hit.
|
||||
MAIN_RESPONSE_DEBUG = 0
|
||||
MAIN_RESPONSE_SAVE = 1
|
||||
MAIN_RESPONSE_QUIT = 2
|
||||
MAIN_RESPONSE_SHELL = 3
|
||||
MAIN_RESPONSE_NONE = 4
|
||||
|
||||
class ConfigError(Exception):
|
||||
"""Exception class for the configuration related errors."""
|
||||
|
||||
pass
|
||||
|
||||
class Config(object):
|
||||
"""Hold configuration info useful throughout the exception handling
|
||||
classes. This prevents having to pass a bunch of arguments to a
|
||||
bunch of different functions. A Config instance must be created
|
||||
before creating an ExceptionHandler instance.
|
||||
"""
|
||||
def __init__(self, *args, **kwargs):
|
||||
"""Create a new Config instance. Arguments may be passed in to
|
||||
set any of the configuration values. Unknown arguments will
|
||||
be ignored. Instance attributes:
|
||||
|
||||
attrSkipList -- A list of strings. When handling a traceback,
|
||||
any attributes found with the same name as an
|
||||
element of this list will not be written to
|
||||
the dump. This is to prevent writing potentially
|
||||
sensitive information like passwords. The names
|
||||
must be given without the leading name of the
|
||||
object passed to handler.install(). For instance,
|
||||
if handler.install() gets an Anaconda instance
|
||||
with the name "anaconda" and you want to skip
|
||||
anaconda.id.rootPassword, "id.rootPassword" should
|
||||
be listed in attrSkipList.
|
||||
fileList -- A list of files to find on the system and add
|
||||
to the traceback dump.
|
||||
localSkipList -- A list of strings. When handling a traceback,
|
||||
any local variables found with their name containing
|
||||
an element of this list will not be written to
|
||||
the dump. This is subtely different from
|
||||
attrSkipList.
|
||||
callbackDict -- A dictionary having item names as keys and pairs
|
||||
(function, attchmnt_only) as values.
|
||||
@see register_callback
|
||||
programName -- The name of the erroring program.
|
||||
programVersion -- The version number of the erroring program.
|
||||
Both programName and programVersion are used
|
||||
throughout the exception handler, so must be
|
||||
set.
|
||||
programArch -- The architecture of the erroring program.
|
||||
"""
|
||||
self.attrSkipList = []
|
||||
self.fileList = []
|
||||
self.localSkipList = []
|
||||
self.callbackDict = dict()
|
||||
self.programName = None
|
||||
self.programVersion = None
|
||||
self.programArch = None
|
||||
|
||||
# Override the defaults set above with whatever's passed in as an
|
||||
# argument. Unknown arguments get thrown away.
|
||||
for (key, val) in kwargs.items():
|
||||
if key in self.__dict__:
|
||||
self.__dict__[key] = val
|
||||
|
||||
# Make sure required things are set.
|
||||
if not self.programName:
|
||||
raise ValueError("programName must be set.")
|
||||
|
||||
if not self.programVersion:
|
||||
raise ValueError("programVersion must be set.")
|
||||
|
||||
def register_callback(self, item_name, callback, attchmnt_only=False,
|
||||
override=False):
|
||||
"""
|
||||
Register new callback that will be called when data about the
|
||||
crash is collected. The returned value will be included as the
|
||||
'item_name' item.
|
||||
|
||||
:param item_name: name of the item storing the value returned by the
|
||||
'callback' function
|
||||
:type item_name: string
|
||||
:param callback: a function to be called
|
||||
:type callback: a function of type: () -> string
|
||||
:param attchmnt_only: whether the returned valued should be included only
|
||||
as an attachment or also in the main '*-tb' file
|
||||
(defaults to False)
|
||||
:type attchmnt_only: bool
|
||||
:param override: whether to override the previously registered callback
|
||||
with the same item name or not (may raise exception)
|
||||
:type override: bool
|
||||
|
||||
:raise ConfigError: if callback with the 'item_name' has already been
|
||||
registered and 'override' is not set to True
|
||||
:return: None
|
||||
|
||||
"""
|
||||
|
||||
if item_name not in self.callbackDict or override:
|
||||
self.callbackDict[item_name] = (callback, attchmnt_only)
|
||||
else:
|
||||
msg = "Callback with name '%s' already registered" % item_name
|
||||
raise ConfigError(msg)
|
||||
|
||||
# type, value and stack are items provided by Python for the exception handler
|
||||
ExceptionInfo = namedtuple("ExceptionInfo", ["type", "value", "stack"])
|
||||
|
||||
# ExceptionInfo instance plus the object that should be dumped
|
||||
DumpInfo = namedtuple("DumpInfo", ["exc_info", "object"])
|
||||
|
||||
# information about a package (as provided e.g. by rpm)
|
||||
PackageInfo = namedtuple("PackageInfo", ["name", "version", "release", "epoch",
|
||||
"arch"])
|
||||
@@ -0,0 +1,551 @@
|
||||
#
|
||||
# dump.py - general exception formatting and saving
|
||||
#
|
||||
# Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2009 Red Hat, Inc.
|
||||
# All rights reserved.
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 2 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
# Author(s): Matt Wilson <msw@redhat.com>
|
||||
# Erik Troan <ewt@redhat.com>
|
||||
# Chris Lumens <clumens@redhat.com>
|
||||
#
|
||||
# pylint: disable=bare-except,broad-except
|
||||
|
||||
import copy
|
||||
import inspect
|
||||
import os
|
||||
import traceback
|
||||
import sys
|
||||
import codecs
|
||||
import six
|
||||
from meh import PackageInfo
|
||||
from meh.safe_string import SafeStr
|
||||
|
||||
# Python 2/3 compatibilty
|
||||
try:
|
||||
longtype = long # pylint: disable=undefined-variable
|
||||
except NameError:
|
||||
longtype = int
|
||||
|
||||
try:
|
||||
unitype = unicode # pylint: disable=undefined-variable
|
||||
except NameError:
|
||||
unitype = str
|
||||
|
||||
class ExceptionDump(object):
|
||||
"""This class represents a traceback and contains several useful methods
|
||||
for manipulating a traceback. In general, clients should not have to
|
||||
use this class. It is mainly for internal use.
|
||||
"""
|
||||
def __init__(self, exc_info, config_obj):
|
||||
"""Create a new ExceptionDump instance. Instance attributes:
|
||||
|
||||
:param exc_info: info about the exception provided by Python
|
||||
:type exc_info: an instance of the meh.ExceptionInfo class
|
||||
:param config_obj: configuration for python-meh
|
||||
:type config_obj: an instance of the meh.Config class
|
||||
"""
|
||||
|
||||
if inspect.istraceback(exc_info.stack):
|
||||
self.stack = inspect.getinnerframes(exc_info.stack)
|
||||
else:
|
||||
self.stack = exc_info.stack
|
||||
|
||||
self.conf = config_obj
|
||||
self.type = exc_info.type
|
||||
self.value = exc_info.value
|
||||
|
||||
self._dumpHash = {}
|
||||
|
||||
@property
|
||||
def desc(self):
|
||||
# The description is a single line of text that should be used anywhere
|
||||
# the bug needs to quickly be summarized. The most obvious example of
|
||||
# this is when saving to bugzilla. We can populate the UI with this
|
||||
# string so the user doesn't need to come up with one.
|
||||
if self.type and self.value:
|
||||
return traceback.format_exception_only(self.type, self.value)[0].strip()
|
||||
else:
|
||||
return ""
|
||||
|
||||
def _get_environment_info(self):
|
||||
"""
|
||||
Returns dictionary containing these items for a bugreport header
|
||||
|
||||
architecture
|
||||
cmdline
|
||||
component
|
||||
executable
|
||||
kernel
|
||||
package
|
||||
release
|
||||
other involved packages
|
||||
|
||||
:rtype: dict (string -> string)
|
||||
"""
|
||||
|
||||
RELEASE_NAME_FILE = "/etc/system-release"
|
||||
|
||||
class RPMinfoError(Exception):
|
||||
"""Exception for errors in rpm queries"""
|
||||
pass
|
||||
|
||||
def get_python_opts():
|
||||
"""
|
||||
Returns python's command line options
|
||||
|
||||
:return: list of python's command line options
|
||||
:rtype: list
|
||||
|
||||
"""
|
||||
|
||||
flags_to_opts = {
|
||||
"debug": "-d",
|
||||
"py3k_warning": "-3",
|
||||
"division_new": "-Qnew",
|
||||
"division_warning": "-Q",
|
||||
"inspect": "-i",
|
||||
"interactive": "-i",
|
||||
"optimize": "-O",
|
||||
"dont_write_bytecode": "-B",
|
||||
"no_user_site": "-s",
|
||||
"no_site": "-S",
|
||||
"ignore_environment": "-E",
|
||||
"tabcheck": "-t",
|
||||
"verbose": "-v",
|
||||
"unicode": "-u",
|
||||
"bytes_warning": "-b",
|
||||
"quiet": "-q",
|
||||
}
|
||||
|
||||
ret = set()
|
||||
for flag in flags_to_opts.keys():
|
||||
if getattr(sys.flags, flag, None):
|
||||
ret.add(flags_to_opts[flag])
|
||||
ret = list(ret)
|
||||
return ret
|
||||
|
||||
def get_package_and_component(file_=sys.argv[0]):
|
||||
"""
|
||||
Returns package and component names for file (by default for script itself).
|
||||
|
||||
:param file_: filename
|
||||
:type file_: string
|
||||
:return: tuple containing package info and component name for the file
|
||||
:rtype: (PackageInfo, str)
|
||||
:raise RPMinfoError: if package and component for the file cannot be found
|
||||
|
||||
"""
|
||||
|
||||
import rpm
|
||||
ts = rpm.TransactionSet()
|
||||
mi = ts.dbMatch("basenames", file_)
|
||||
try:
|
||||
header = next(mi)
|
||||
except StopIteration:
|
||||
raise RPMinfoError("Cannot get package and component for file "+
|
||||
"{0}".format(file_))
|
||||
pkg_info = PackageInfo(header["name"].decode("utf-8"), header["version"].decode("utf-8"),
|
||||
header["release"].decode("utf-8"),
|
||||
u"%d" % header["epoch"] if header["epoch"] else u"0",
|
||||
header["arch"].decode("utf-8"))
|
||||
|
||||
# cuts the name from the NVR format: foo-blah-2.8.8-2.fc17.src.rpm
|
||||
srpm_name = header["sourcerpm"].decode("utf-8")
|
||||
name_end = len(srpm_name)
|
||||
try:
|
||||
name_end = srpm_name.rindex('-')
|
||||
name_end = srpm_name[:name_end].rindex('-')
|
||||
except ValueError:
|
||||
# expected exception
|
||||
pass
|
||||
|
||||
component = srpm_name[:name_end]
|
||||
|
||||
return (pkg_info, component)
|
||||
|
||||
def get_release_version():
|
||||
"""Returns release version (according to RELEASE_NAME_FILE)"""
|
||||
try:
|
||||
with open(RELEASE_NAME_FILE, "r") as file_:
|
||||
return file_.readline().rstrip()
|
||||
except IOError:
|
||||
return "Cannot get release name."
|
||||
|
||||
def get_other_packages(self):
|
||||
"""
|
||||
Returns a set of additional packages whose files appear in
|
||||
traceback.
|
||||
|
||||
:rtype: set
|
||||
|
||||
"""
|
||||
packages = set()
|
||||
if not self.stack:
|
||||
return packages
|
||||
|
||||
for (_frame, fn, _lineno, _func, _ctx, _idx) in self.stack:
|
||||
try:
|
||||
pkg_info = get_package_and_component(fn)[0]
|
||||
package = "{0.name}-{0.version}-{0.release}.{0.arch}".format(
|
||||
pkg_info)
|
||||
packages.add(package)
|
||||
except RPMinfoError:
|
||||
continue
|
||||
|
||||
try:
|
||||
pkg_info = get_package_and_component()[0]
|
||||
package = "{0.name}-{0.version}-{0.release}.{0.arch}".format(
|
||||
pkg_info)
|
||||
packages.discard(package)
|
||||
except RPMinfoError:
|
||||
pass
|
||||
return packages
|
||||
|
||||
def get_environment_variables():
|
||||
"""
|
||||
Returns a list of strings containing defined environment
|
||||
variables and their values in the following format:
|
||||
|
||||
VARIABLE=VALUE
|
||||
|
||||
:rtype: list
|
||||
|
||||
"""
|
||||
|
||||
ret = list()
|
||||
for (key, value) in os.environ.items():
|
||||
ret.append("{0}={1}".format(key, value))
|
||||
|
||||
return ret
|
||||
|
||||
|
||||
#--begining of the method _get_environment_info--
|
||||
try:
|
||||
pkg_info, component = get_package_and_component()
|
||||
except RPMinfoError:
|
||||
pkg_info = None
|
||||
component = None
|
||||
|
||||
other_packages = ", ".join(get_other_packages(self))
|
||||
|
||||
ret = dict()
|
||||
ret["architecture"] = os.uname()[4]
|
||||
ret["cmdline"] = "{0} {1} {2}".format(sys.executable,
|
||||
" ".join(get_python_opts()),
|
||||
" ".join(sys.argv))
|
||||
if component:
|
||||
ret["component"] = component
|
||||
ret["executable"] = sys.argv[0]
|
||||
ret["kernel"] = os.uname()[2]
|
||||
if pkg_info:
|
||||
ret["pkg_info"] = pkg_info
|
||||
ret["release"] = get_release_version()
|
||||
if other_packages:
|
||||
ret["other involved packages"] = other_packages
|
||||
ret["environ"] = "\n".join(get_environment_variables())
|
||||
|
||||
return ret
|
||||
|
||||
@property
|
||||
def environment_info(self):
|
||||
return self._get_environment_info()
|
||||
|
||||
def __str__(self):
|
||||
lst = self._format_stack()
|
||||
|
||||
lst.insert(0, "%s %s exception report\n" % (self.conf.programName, self.conf.programVersion))
|
||||
lst.insert(1, "Traceback (most recent call last):\n")
|
||||
|
||||
if self.type is not None and self.value is not None:
|
||||
lst.extend(traceback.format_exception_only(self.type, self.value))
|
||||
|
||||
return "".join(lst)
|
||||
|
||||
def _format_stack(self):
|
||||
if not self.stack:
|
||||
return []
|
||||
|
||||
frames = []
|
||||
for (_frame, fn, lineno, func, ctx, _idx) in self.stack:
|
||||
if isinstance(ctx, list):
|
||||
code = "".join(ctx)
|
||||
else:
|
||||
code = ctx
|
||||
|
||||
frames.append((fn, lineno, func, code))
|
||||
|
||||
return traceback.format_list(frames)
|
||||
|
||||
# Create a string representation of a class. This method will recursively
|
||||
# handle all attributes of the base given class.
|
||||
def _dumpClass(self, instance, level=0, parentkey="", skipList=None):
|
||||
# This is horribly cheesy, and bound to require maintainence in the
|
||||
# future. The problem is that anything subclassed from object fails
|
||||
# the types.InstanceType test we used to have which means those
|
||||
# objects never get dumped. However, most everything basic in
|
||||
# python is derived from object so we can't just check for the super
|
||||
# class. Any instances of the following types will just be printed
|
||||
# out, and everything else will be assumed to be something that
|
||||
# needs to be recursed on.
|
||||
def __isSimpleType(instance):
|
||||
return isinstance(instance, bool) or \
|
||||
isinstance(instance, complex) or \
|
||||
isinstance(instance, float) or \
|
||||
isinstance(instance, int) or \
|
||||
isinstance(instance, longtype) or \
|
||||
isinstance(instance, type(None)) or \
|
||||
isinstance(instance, bytes) or \
|
||||
isinstance(instance, str) or \
|
||||
isinstance(instance, unitype) or \
|
||||
not hasattr(instance, "__class__") or \
|
||||
not hasattr(instance, "__dict__")
|
||||
|
||||
ret = SafeStr()
|
||||
|
||||
if not skipList:
|
||||
skipList = []
|
||||
|
||||
# protect from loops
|
||||
try:
|
||||
# Store the id(), not the instance name to protect against
|
||||
# instances that cannot be hashed.
|
||||
if not id(instance) in self._dumpHash:
|
||||
self._dumpHash[id(instance)] = None
|
||||
else:
|
||||
ret += "Already dumped (%s instance)\n" % instance.__class__.__name__
|
||||
return ret
|
||||
except TypeError:
|
||||
ret += "Cannot dump object\n"
|
||||
return ret
|
||||
|
||||
if ("__str__" in instance.__class__.__dict__ or
|
||||
"__repr__" in instance.__class__.__dict__):
|
||||
try:
|
||||
ret += "%s\n" % (instance,)
|
||||
except:
|
||||
ret += "\n"
|
||||
|
||||
return ret
|
||||
|
||||
ret += "%s instance, containing members:\n" %\
|
||||
(instance.__class__.__name__)
|
||||
pad = ' ' * ((level) * 2)
|
||||
|
||||
for key, value in instance.__dict__.items():
|
||||
if key.startswith("_%s__" % instance.__class__.__name__):
|
||||
continue
|
||||
|
||||
if parentkey != "":
|
||||
curkey = parentkey + "." + key
|
||||
else:
|
||||
curkey = key
|
||||
|
||||
# Don't dump objects that are in our skip list, though ones that are
|
||||
# None are probably okay.
|
||||
if eval("instance.%s is not None" % key) and \
|
||||
eval("id(instance.%s)" % key) in skipList:
|
||||
ret += "%s%s: Skipped\n" % (pad, curkey)
|
||||
continue
|
||||
|
||||
if isinstance(value, list):
|
||||
ret += "%s%s: [" % (pad, curkey)
|
||||
first = 1
|
||||
for item in value:
|
||||
if not first:
|
||||
ret += ", "
|
||||
else:
|
||||
first = 0
|
||||
|
||||
if __isSimpleType(item):
|
||||
ret += "%s" % (item,)
|
||||
else:
|
||||
ret += self._dumpClass(item, level + 1, skipList=skipList)
|
||||
ret += "]\n"
|
||||
elif isinstance(value, dict):
|
||||
# append things one after another so that e.g. binary data is
|
||||
# replaced by hexa values separately
|
||||
ret += pad
|
||||
ret += curkey
|
||||
ret += ": {"
|
||||
first = 1
|
||||
for k, v in value.items():
|
||||
if not first:
|
||||
ret += ", "
|
||||
else:
|
||||
first = 0
|
||||
if isinstance(k, str) or isinstance(k, unitype):
|
||||
ret += "'"
|
||||
ret += k
|
||||
ret += "': "
|
||||
else:
|
||||
ret += "%s: " % (k,)
|
||||
|
||||
if __isSimpleType(v):
|
||||
ret += "%s" % (v,)
|
||||
else:
|
||||
ret += self._dumpClass(v, level + 1, parentkey = curkey, skipList=skipList)
|
||||
ret += "}\n"
|
||||
elif __isSimpleType(value):
|
||||
ret += "%s%s: " % (pad, curkey)
|
||||
ret += value
|
||||
ret += "\n"
|
||||
else:
|
||||
ret += "%s%s: " % (pad, curkey)
|
||||
ret += self._dumpClass(value, level + 1, parentkey=curkey, skipList=skipList)
|
||||
|
||||
return ret
|
||||
|
||||
def dump(self, obj):
|
||||
"""Dump the local variables and all attributes of a given object.
|
||||
The lists of files and attrs to ignore are all taken from a
|
||||
Config object instance provided when the ExceptionDump class was
|
||||
created.
|
||||
|
||||
obj -- Any Python object. This object will have all its attributes
|
||||
written out, except for those mentioned in the attrSkipList.
|
||||
"""
|
||||
idSkipList = []
|
||||
ret = SafeStr()
|
||||
|
||||
# We need to augment the environment eval() will run in with the
|
||||
# bindings that were local when the traceback happened so that the
|
||||
# idSkipList can be populated. However since we're not allowed to
|
||||
# modify the results of locals(), we'll have to make a copy first.
|
||||
localVars = copy.copy(locals())
|
||||
if self.stack:
|
||||
localVars.update(self.stack[-1][0].f_locals)
|
||||
|
||||
# Catch attributes that do not exist at the time we do the exception dump
|
||||
# and ignore them.
|
||||
for k in self.conf.attrSkipList:
|
||||
try:
|
||||
eval("idSkipList.append(id(obj.%s))" % k, None, localVars)
|
||||
except:
|
||||
pass
|
||||
|
||||
# Write local variables to the given file descriptor, ignoring any of
|
||||
# the local skips.
|
||||
if self.stack:
|
||||
frame = self.stack[-1][0]
|
||||
ret += "\nLocal variables in innermost frame:\n"
|
||||
try:
|
||||
for (key, value) in frame.f_locals.items():
|
||||
lowered_key = key.lower()
|
||||
if any(item.lower() in lowered_key
|
||||
for item in self.conf.localSkipList):
|
||||
continue
|
||||
|
||||
ret += "%s: %s\n" % (key, value)
|
||||
except:
|
||||
pass
|
||||
|
||||
# And now dump the object's attributes.
|
||||
try:
|
||||
ret += "\n\n"
|
||||
ret += self._dumpClass(obj, skipList=idSkipList)
|
||||
except:
|
||||
ret += "\nException occurred during state dump:\n"
|
||||
ret += traceback.format_exc(None)
|
||||
|
||||
# Filter out item names and callbacks that should appear
|
||||
# only as attachments
|
||||
items_callbacks = ((name, cb) for (name, (cb, attchmnt_only))
|
||||
in self.conf.callbackDict.items()
|
||||
if not attchmnt_only)
|
||||
|
||||
# And now add data returned by the registered callbacks
|
||||
ret += "\nRegistered callbacks:\n"
|
||||
for (item_name, callback) in items_callbacks:
|
||||
try:
|
||||
callback_ret = callback()
|
||||
if callback_ret:
|
||||
ret += "%s:\n%s\n" % (item_name, callback_ret)
|
||||
except Exception as exc:
|
||||
ret += "%s: Caused error: %s\n" % (item_name, exc)
|
||||
|
||||
# And finally, write a bunch of files into the dump too.
|
||||
for fname in self.conf.fileList:
|
||||
try:
|
||||
if six.PY2:
|
||||
with codecs.open(fname, "r", "utf-8", "ignore") as fobj:
|
||||
ret += "\n\n%s:\n" % (fname,)
|
||||
for line in fobj:
|
||||
ret += line.encode("utf-8")
|
||||
else:
|
||||
with open(fname, "rt", encoding="utf-8") as fobj:
|
||||
ret += "\n\n%s:\n" % (fname,)
|
||||
for line in fobj:
|
||||
ret += line
|
||||
except IOError:
|
||||
pass
|
||||
except:
|
||||
ret += "\nException occurred during %s file copy:\n" % (fname,)
|
||||
ret += traceback.format_exc(None)
|
||||
|
||||
return ret
|
||||
|
||||
@property
|
||||
def hash(self):
|
||||
"""Create a hash for this traceback object. This is most suitable for
|
||||
searching bug filing systems for duplicates. The hash is composed
|
||||
of the basename of each file in the stack, the method names, and
|
||||
the bit of code. Line numbers and the actual exception message
|
||||
itself are left out.
|
||||
"""
|
||||
import hashlib
|
||||
s = ""
|
||||
|
||||
if self.stack:
|
||||
for (file, _lineno, func, text) in [f[1:5] for f in self.stack]:
|
||||
if isinstance(text, list):
|
||||
text = "".join(text)
|
||||
s += "%s %s %s\n" % (os.path.basename(file), func, text)
|
||||
else:
|
||||
s = "%s %s" % (self.type, self.value)
|
||||
|
||||
return hashlib.sha256(s.encode("utf-8")).hexdigest()
|
||||
|
||||
def traceback_and_object_dump(self, obj):
|
||||
"""
|
||||
Return the traceback and a text representation of an object.
|
||||
|
||||
:param obj: Any Python object. This object will have all its attributes
|
||||
written out, except for those mentioned in the attrSkipList.
|
||||
|
||||
"""
|
||||
|
||||
ret = SafeStr(str(self))
|
||||
ret += self.dump(obj)
|
||||
|
||||
return ret
|
||||
|
||||
class ReverseExceptionDump(ExceptionDump):
|
||||
"""This class provides an alternate representation of an exception. In
|
||||
this representation, the traceback is printed with the most recent call
|
||||
at the top of the stack, and the most generic call at the bottom. Note
|
||||
that this order does not affect the hash at all.
|
||||
"""
|
||||
def __str__(self):
|
||||
lst = self._format_stack()
|
||||
lst.reverse()
|
||||
|
||||
lst.insert(0, "%s %s exception report\n" % (self.conf.programName, self.conf.programVersion))
|
||||
lst.insert(1, "Traceback (most recent call first):\n")
|
||||
|
||||
if self.type is not None and self.value is not None:
|
||||
lst.extend(traceback.format_exception_only(self.type, self.value))
|
||||
|
||||
return "".join(lst)
|
||||
@@ -0,0 +1,299 @@
|
||||
# Copyright (C) 2009 Red Hat, Inc.
|
||||
# All rights reserved.
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 2 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
# Author(s): Chris Lumens <clumens@redhat.com>
|
||||
#
|
||||
from meh import MAIN_RESPONSE_DEBUG, MAIN_RESPONSE_SAVE, MAIN_RESPONSE_SHELL, MAIN_RESPONSE_QUIT, DumpInfo, ExceptionInfo
|
||||
import bdb
|
||||
import os
|
||||
import sys
|
||||
import report
|
||||
import traceback
|
||||
import subprocess
|
||||
|
||||
import gettext
|
||||
_ = lambda x: gettext.ldgettext("python-meh", x)
|
||||
|
||||
class NoNetwork(Exception):
|
||||
def __init__(self, msg=""):
|
||||
Exception.__init__(self)
|
||||
self.msg = msg
|
||||
|
||||
def __str__(self):
|
||||
return "No network is available"
|
||||
|
||||
class ExceptionHandler(object):
|
||||
def __init__(self, confObj, intfClass, exnClass):
|
||||
"""Create a new ExceptionHandler instance. Subclasses of this one may
|
||||
be created, provided they are careful to provide all the methods
|
||||
this one does. Instance attributes:
|
||||
|
||||
conf -- A filled in Config instance. At least the programName
|
||||
and programVersion are required.
|
||||
exnClass -- An instance of ExceptionDump or a subclass of it. This
|
||||
is required to know how to represent the Python
|
||||
exception internally.
|
||||
intfClass-- An instance of AbstractIntf. This is required to know
|
||||
what UI classes to use.
|
||||
"""
|
||||
self.conf = confObj
|
||||
self.exnClass = exnClass
|
||||
self.intf = intfClass
|
||||
|
||||
self._exitcode = 10
|
||||
self._exn = None
|
||||
self.exnFile = None
|
||||
self.exnText = ""
|
||||
|
||||
def _setExitCode(self, code):
|
||||
self._exitcode = code
|
||||
|
||||
exitcode = property(lambda s: s._exitcode,
|
||||
lambda s, v: s._setExitCode(v))
|
||||
|
||||
def _setExn(self, e):
|
||||
self._exn = e
|
||||
|
||||
exn = property(lambda s: s._exn,
|
||||
lambda s, v: s._setExn(v))
|
||||
|
||||
def handleException(self, dump_info):
|
||||
"""This is the main exception handling entry point. When Python
|
||||
gets an exception it doesn't know how to handle, this method will
|
||||
be called. It then saves the traceback and displays the main
|
||||
dialog asking the user what to do next. Once this method is
|
||||
called, there's no good way to go back to what you were doing
|
||||
before.
|
||||
|
||||
All arguments are passed in from the handler created by calling
|
||||
self.install(). This method should not usually be overridden by
|
||||
a subclass.
|
||||
|
||||
:type dump_info: an instance of the meh.DumpInfo class
|
||||
|
||||
"""
|
||||
|
||||
responseHash = { MAIN_RESPONSE_QUIT: self.runQuit,
|
||||
MAIN_RESPONSE_DEBUG: self.runDebug,
|
||||
MAIN_RESPONSE_SAVE: self.runSave,
|
||||
MAIN_RESPONSE_SHELL: self.runShell,
|
||||
}
|
||||
|
||||
# Quit if we got an exception when running pdb.
|
||||
if isinstance(dump_info.exc_info.value, bdb.BdbQuit):
|
||||
sys.exit(self.exitcode)
|
||||
|
||||
# Restore original exception handler.
|
||||
sys.excepthook = sys.__excepthook__
|
||||
|
||||
self.preWriteHook(dump_info)
|
||||
|
||||
# Save the exception to the filesystem first.
|
||||
self.exn = self.exnClass(dump_info.exc_info, self.conf)
|
||||
(fobj, self.exnFile) = self.openFile()
|
||||
self.exnText = self.exn.traceback_and_object_dump(dump_info.object)
|
||||
fobj.write(self.exnText)
|
||||
fobj.close()
|
||||
|
||||
self.postWriteHook(dump_info)
|
||||
|
||||
# Run initial UI screen, asking whether to save/debug/quit.
|
||||
while True:
|
||||
win = self.intf.mainExceptionWindow(str(self.exn), self.exnText)
|
||||
if not win:
|
||||
self.runQuit(dump_info.exc_info)
|
||||
|
||||
rc = win.run()
|
||||
win.destroy()
|
||||
|
||||
try:
|
||||
responseHash[rc](dump_info.exc_info)
|
||||
except KeyError:
|
||||
# This happens if (for example) the user hits Escape instead
|
||||
# of pressing a button.
|
||||
continue
|
||||
|
||||
win.destroy()
|
||||
|
||||
def preWriteHook(self, dump_info):
|
||||
"""Subclasses may supply a function with this name that will be
|
||||
called immediately before the traceback is written to disk in
|
||||
order to have any sort of special pre-write processing that needs
|
||||
to be done.
|
||||
|
||||
:type dump_info: an instance of the meh.DumpInfo class
|
||||
"""
|
||||
pass
|
||||
|
||||
def postWriteHook(self, dump_info):
|
||||
"""Subclasses may supply a function with this name that will be
|
||||
called immediately after the traceback is written to disk, but
|
||||
immediately before the UI is run. This is to provide a place for
|
||||
any special handling to happen once there is a file on disk.
|
||||
|
||||
:type dump_info: an instance of the meh.DumpInfo class
|
||||
"""
|
||||
pass
|
||||
|
||||
def install(self, obj):
|
||||
"""Install ourselves as the top level exception handler with Python.
|
||||
If this method is not called after an ExceptionHandler instance is
|
||||
created, none of the rest of this code will ever be called.
|
||||
|
||||
obj -- A Python object that may be dumped to a file when the
|
||||
exception is saved. This should be something like the top
|
||||
level object in a program.
|
||||
"""
|
||||
sys.excepthook = lambda ty, value, tb: \
|
||||
self.handleException(DumpInfo(ExceptionInfo(ty, value, tb), obj))
|
||||
|
||||
def openFile(self):
|
||||
"""Create a randomly named output file to write the exception dump to.
|
||||
This requires a programName be set in the Config instance. The
|
||||
return value is a (file descriptor, path) pair. The file must be
|
||||
closed by the caller when writing is done. Subclasses should not
|
||||
override this method unless they know what they're doing.
|
||||
"""
|
||||
import tempfile
|
||||
(fd, path) = tempfile.mkstemp("", "%s-tb-" % self.conf.programName, "/tmp")
|
||||
fo = os.fdopen(fd, "w")
|
||||
return (fo, path)
|
||||
|
||||
### Methods called by the primary exception handling dialog.
|
||||
|
||||
def runQuit(self, exc_info):
|
||||
"""This method is called when the "Exit" button is clicked. It may
|
||||
be overridden by a subclass, but the basic behavior of eventually
|
||||
quitting should be preserved.
|
||||
|
||||
:type exc_info: an instance of the meh.ExceptionInfo class
|
||||
"""
|
||||
sys.exit(self.exitcode)
|
||||
|
||||
def runDebug(self, exc_info):
|
||||
"""This method is called when the "Debug" button is clicked. It may
|
||||
be overridden by a subclass if specialized behavior is required to
|
||||
enter debug mode.
|
||||
|
||||
:type exc_info: an instance of the meh.ExceptionInfo class
|
||||
"""
|
||||
|
||||
print("")
|
||||
print(_("Use 'continue' command to quit the debugger and get back to "
|
||||
"the main menu"))
|
||||
import pdb
|
||||
pdb.post_mortem(exc_info.stack)
|
||||
#no need to quit here, let's just get back to the main dialog
|
||||
|
||||
def runShell(self, exc_info):
|
||||
"""This method is called when user requests to run a shell. It may
|
||||
be overridden by a subclass if specialized behavior is required to
|
||||
run shell (e.g. TTY switching).
|
||||
|
||||
:type exc_info: an instance of the meh.ExceptionInfo class
|
||||
|
||||
"""
|
||||
|
||||
print("")
|
||||
print(_("Exit the shell to get back to the main menu"))
|
||||
proc = subprocess.Popen(["bash", "--login"], shell=True, cwd="/")
|
||||
proc.wait()
|
||||
|
||||
def runSave(self, exc_info):
|
||||
"""This method is called when the "Save" button is clicked. It may
|
||||
be overridden by a subclass, but that's going to be a lot of work.
|
||||
|
||||
:type exc_info: an instance of the meh.ExceptionInfo class
|
||||
"""
|
||||
|
||||
params = dict()
|
||||
params.update(self.exn.environment_info)
|
||||
pkg_info = params.pop("pkg_info", None)
|
||||
|
||||
#if rpmdb queries fail (anaconda), use self.conf.* values
|
||||
if "component" not in params:
|
||||
params["component"] = self.conf.programName
|
||||
|
||||
if pkg_info:
|
||||
params["pkg_name"] = pkg_info.name
|
||||
params["pkg_version"] = pkg_info.version
|
||||
params["pkg_release"] = pkg_info.release
|
||||
params["pkg_epoch"] = pkg_info.epoch
|
||||
params["pkg_arch"] = pkg_info.arch
|
||||
params["package"] = "%s-%s-%s.%s" % (pkg_info.name, pkg_info.version,
|
||||
pkg_info.release, pkg_info.arch)
|
||||
else:
|
||||
params["pkg_name"] = self.conf.programName
|
||||
parts = self.conf.programVersion.rsplit("-", 1)
|
||||
if len(parts) == 2:
|
||||
version, release = parts
|
||||
else:
|
||||
version = parts[0]
|
||||
# not given, make something up
|
||||
release = "1"
|
||||
params["pkg_version"] = version
|
||||
params["pkg_release"] = release
|
||||
# we don't support specifying epoch in the config object and only
|
||||
# the anaconda which is not using epochs doesn't have the RPMdb to
|
||||
# query
|
||||
params["pkg_epoch"] = "0"
|
||||
params["pkg_arch"] = self.conf.programArch
|
||||
params["package"] = "{0.programName}-{0.programVersion}".format(
|
||||
self.conf)
|
||||
|
||||
params["hashmarkername"] = self.conf.programName
|
||||
params["duphash"] = self.exn.hash
|
||||
params["reason"] = self.exn.desc
|
||||
params["description"] = "The following was filed automatically by %s:\n%s" \
|
||||
% (self.conf.programName, str(self.exn))
|
||||
|
||||
tb_item_name = "%s-tb" % self.conf.programName
|
||||
params[tb_item_name] = self.exnText
|
||||
|
||||
# save data generated by callbacks
|
||||
for (item_name, (callback, _anc)) in self.conf.callbackDict.items():
|
||||
try:
|
||||
ret = callback()
|
||||
if ret:
|
||||
params[item_name] = ret
|
||||
except Exception as exc: # pylint: disable=broad-except
|
||||
params[item_name] = "Caused error: %s" % exc
|
||||
|
||||
for fpath in self.conf.fileList:
|
||||
try:
|
||||
with open(fpath, "r") as fobj:
|
||||
# would be better to use the full path here, but libreport
|
||||
# doesn't allow '/' characters in the item name
|
||||
filename = os.path.basename(fpath)
|
||||
if filename not in params:
|
||||
params[filename] = fobj.read()
|
||||
else:
|
||||
params[filename+"_file"] = fobj.read()
|
||||
except: # pylint: disable=bare-except
|
||||
#skip files we cannot read
|
||||
continue
|
||||
|
||||
# tell ABRT some more things it requires
|
||||
params["analyzer"] = "Python"
|
||||
params["backtrace"] = "".join(traceback.format_exception(exc_info.type,
|
||||
exc_info.value,
|
||||
exc_info.stack))
|
||||
|
||||
signature = report.createPythonUnhandledExceptionSignature(**params)
|
||||
|
||||
# We don't want to automatically quit here since the user may wish to
|
||||
# save somewhere else, debug, etc.
|
||||
self.intf.saveExceptionWindow(signature)
|
||||
@@ -0,0 +1,45 @@
|
||||
#
|
||||
# network.py - network configuration install data
|
||||
#
|
||||
# Copyright (C) 2008, 2009 Red Hat, Inc.
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 2 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
# Author(s): David Cantrell <dcantrell@redhat.com>
|
||||
#
|
||||
import dbus
|
||||
|
||||
# This code was taken from anaconda, and slightly adapted to not rely
|
||||
# on isys.
|
||||
NM_SERVICE = "org.freedesktop.NetworkManager"
|
||||
NM_MANAGER_PATH = "/org/freedesktop/NetworkManager"
|
||||
|
||||
NM_STATE_CONNECTED = 3
|
||||
|
||||
DBUS_PROPS_IFACE = "org.freedesktop.DBus.Properties"
|
||||
|
||||
def hasActiveNetDev():
|
||||
"""Does the system have an enabled network interface?"""
|
||||
try:
|
||||
bus = dbus.SystemBus()
|
||||
nm = bus.get_object(NM_SERVICE, NM_MANAGER_PATH)
|
||||
props = dbus.Interface(nm, DBUS_PROPS_IFACE)
|
||||
state = props.Get(NM_SERVICE, "State")
|
||||
|
||||
if int(state) == NM_STATE_CONNECTED:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
except dbus.DBusException:
|
||||
return False
|
||||
@@ -0,0 +1,71 @@
|
||||
#
|
||||
# Copyright (C) 2013 Red Hat, Inc.
|
||||
# All rights reserved.
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 2 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
# Author: Vratislav Podzimek <vpodzime@redhat.com>
|
||||
#
|
||||
#
|
||||
|
||||
import sys
|
||||
PY = int(sys.version.split('.')[0])
|
||||
|
||||
"""
|
||||
This module provides a SafeStr class.
|
||||
|
||||
@see: SafeStr
|
||||
|
||||
"""
|
||||
|
||||
class SafeStr(str):
|
||||
"""
|
||||
String class that has a modified __add__ method so that ascii strings,
|
||||
binary data represented as a byte string and unicode objects can be
|
||||
safely appended to it (not causing traceback). BINARY DATA IS OMITTED.
|
||||
|
||||
"""
|
||||
|
||||
def __add__(self, other):
|
||||
|
||||
if PY > 2:
|
||||
return SafeStr(str.__add__(self, str(other)))
|
||||
|
||||
if not (isinstance(other, str) or isinstance(other, unicode)): # pylint: disable=undefined-variable
|
||||
if hasattr(other, "__str__"):
|
||||
other = other.__str__()
|
||||
else:
|
||||
other = "OMITTED OBJECT WITHOUT __str__ METHOD"
|
||||
|
||||
if isinstance(other, unicode): # pylint: disable=undefined-variable
|
||||
ret = SafeStr(str.__add__(self, other.encode("utf-8")))
|
||||
else:
|
||||
try:
|
||||
# try to decode which doesn't cause traceback for utf-8 encoded
|
||||
# non-ascii string and ascii string
|
||||
other.decode("utf-8")
|
||||
ret = SafeStr(str.__add__(self, other))
|
||||
except UnicodeDecodeError:
|
||||
# binary data, get the representation used by Python for
|
||||
# non-ascii bytes
|
||||
|
||||
# hex(255) returns "0xff", we want "\xff"
|
||||
other_hexa = (hex(ord(char)) for char in other)
|
||||
other_backslashed = (hex_num.replace("0x", "\\x")
|
||||
for hex_num in other_hexa)
|
||||
other_repr = "".join(other_backslashed)
|
||||
|
||||
ret = SafeStr(str.__add__(self, other_repr))
|
||||
|
||||
return ret
|
||||
@@ -0,0 +1,181 @@
|
||||
# Copyright (C) 2009 Red Hat, Inc.
|
||||
# All rights reserved.
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 2 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
# Author(s): Chris Lumens <clumens@redhat.com>
|
||||
#
|
||||
|
||||
class AbstractIntf(object):
|
||||
"""The base class for Interfaces. This is an abstract class. It
|
||||
provides methods that create and run various kinds of windows.
|
||||
We provide a basic level of graphical and text oriented interfaces
|
||||
here, but it should be possible for things like anaconda to supply
|
||||
their own much more complicated ones with little effort.
|
||||
"""
|
||||
def __init__(self, *args, **kwargs):
|
||||
"""Create a new AbstractInterface instance. This method need not
|
||||
be overridden by subclasses.
|
||||
"""
|
||||
pass
|
||||
|
||||
def enableNetwork(self, *args, **kwargs):
|
||||
"""Display and run a dialog that brings up the network, if it is
|
||||
currently disabled. This method must be provided by all subclasses,
|
||||
and should return False if unsuccessful.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def exitWindow(self, title, message, *args, **kwargs):
|
||||
"""Display and run a dialog that displays a message with the proper
|
||||
buttons and images for quitting afterwards. This method must be
|
||||
provided by all subclasses.
|
||||
|
||||
title -- The window's title.
|
||||
message -- The window's text.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def mainExceptionWindow(self, text, exnFile, *args, **kwargs):
|
||||
"""Create and return an instance of the initial execption handling
|
||||
dialog. This method must be provided by all subclasses.
|
||||
|
||||
text -- The short traceback (usually, just the stack trace).
|
||||
exnFile -- A file containing the output of ExceptionDump.write().
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def messageWindow(self, title, message, *args, **kwargs):
|
||||
"""Display a generic informational message. This can be an error,
|
||||
status update, and so forth. It must be provided by all subclasses.
|
||||
|
||||
title -- The window's title.
|
||||
message -- The window's text.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def saveExceptionWindow(self, exnFile, *args, **kwargs):
|
||||
"""Create and return an instance of the exception saving dialog. This
|
||||
method must be provided by all subclasses.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
class AbstractMainExceptionWindow(object):
|
||||
"""This abstract class describes the basic level of support required of
|
||||
any interface that supplies a main exception window. The main exception
|
||||
window is the initial dialog displayed by the exception handler that
|
||||
provides the debug/save/quit options.
|
||||
"""
|
||||
def __init__(self, shortTraceback=None, longTraceback=None, *args, **kwargs):
|
||||
"""Create a new MainExceptionWindow instance. This must handle
|
||||
creating the dialog and populating it with widgets, but must not
|
||||
run the dialog. A self.dialog attribute should be created that
|
||||
refers to the dialog itself.
|
||||
|
||||
shortTraceback -- The short traceback (usually, just the stack
|
||||
trace).
|
||||
longTraceback -- The long traceback (full traceback and the main
|
||||
object dump).
|
||||
"""
|
||||
pass
|
||||
|
||||
def destroy(self, *args, **kwargs):
|
||||
"""Destroy the current dialog. This method must be provided by all
|
||||
subclasses.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def run(self, *args, **kwargs):
|
||||
"""Run the window and set a return value. This method does everything
|
||||
after the interface has been set up, but does not destroy it. This
|
||||
method must be provided by all subclasses.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
class AbstractExitWindow(object):
|
||||
"""This abstract class describes the basic level of support required of
|
||||
a basic message dialog that should be displayed before the program
|
||||
exits. All interfaces must provide this class.
|
||||
"""
|
||||
def __init__(self, title, text, *args, **kwargs):
|
||||
"""Create a new ExitWindow instance. This must handle creating the
|
||||
dialog and putting the text into it, but must not run the dialog.
|
||||
This method must be provided by all subclasses.
|
||||
|
||||
title -- The window's title.
|
||||
text -- The window's text.
|
||||
"""
|
||||
pass
|
||||
|
||||
def destroy(self, *args, **kwargs):
|
||||
"""Destroy the current dialog. This method must be provided by all
|
||||
subclasses.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def run(self, *args, **kwargs):
|
||||
"""Run the window and set a return value. This method does everything
|
||||
after the interface has been set up but does not destroy it. This
|
||||
method must be provided by all subclasses.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
class AbstractMessageWindow(object):
|
||||
"""This abstract class describes the basic level of support required of
|
||||
a basic message dialog. All interfaces must provide this class.
|
||||
"""
|
||||
def __init__(self, title, text, *args, **kwargs):
|
||||
"""Create a new MessageWindow instance. This must handle creating the
|
||||
dialog and putting the text into it, but must not run the dialog.
|
||||
This method must be provided by all subclasses.
|
||||
|
||||
title -- The window's title.
|
||||
text -- The window's text.
|
||||
"""
|
||||
pass
|
||||
|
||||
def destroy(self, *args, **kwargs):
|
||||
"""Destroy the current dialog. This method must be provided by all
|
||||
subclasses.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def run(self, *args, **kwargs):
|
||||
"""Run the window and set a return value. This method does everything
|
||||
after the interface has been set up but does not destroy it. This
|
||||
method must be provided by all subclasses.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
class AbstractSaveExceptionWindow(object):
|
||||
"""This abstract class describes the basic level of support required of
|
||||
any interface that supplies an exception saving window. The exception
|
||||
saving window is the dialog displayed if the user clicks "save" on the
|
||||
initial dialog, and presents multiple options for how the traceback
|
||||
should be saved.
|
||||
"""
|
||||
def __init__(self, *args, **kwargs):
|
||||
"""Create a new SaveExceptionWindow instance. This must handle
|
||||
creating the dialog and populating it with widgets, but must not
|
||||
run the dialog. A self.dialog attribute should be created that
|
||||
refers to the dialog itself.
|
||||
"""
|
||||
pass
|
||||
|
||||
def run(self, *args, **kwargs):
|
||||
"""Run the window and set a return value. This method does everything
|
||||
after the interface has been set up but does not destroy it. This
|
||||
method must be provided by all subclasses.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
@@ -0,0 +1,177 @@
|
||||
# Copyright (C) 2009 Red Hat, Inc.
|
||||
# All rights reserved.
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 2 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
# Author(s): Chris Lumens <clumens@redhat.com>
|
||||
#
|
||||
from meh import MAIN_RESPONSE_DEBUG, MAIN_RESPONSE_NONE, MAIN_RESPONSE_QUIT, MAIN_RESPONSE_SAVE
|
||||
from meh.ui import AbstractIntf, AbstractSaveExceptionWindow, AbstractMainExceptionWindow, AbstractMessageWindow
|
||||
import os
|
||||
import sys
|
||||
import report
|
||||
|
||||
import gi
|
||||
gi.require_version("Gtk", "3.0")
|
||||
|
||||
from gi.repository import Gtk
|
||||
|
||||
import gettext
|
||||
_ = lambda x: gettext.ldgettext("python-meh", x)
|
||||
|
||||
def find_glade_file(file):
|
||||
path = os.environ.get("GLADEPATH", "./:ui/:/tmp/updates/:/tmp/updates/ui/:/usr/share/python-meh/")
|
||||
for d in path.split(":"):
|
||||
fn = d + file
|
||||
if os.access(fn, os.R_OK):
|
||||
return fn
|
||||
raise RuntimeError("Unable to find glade file %s" % file)
|
||||
|
||||
class GraphicalIntf(AbstractIntf):
|
||||
def __init__(self, *args, **kwargs):
|
||||
AbstractIntf.__init__(self, *args, **kwargs)
|
||||
|
||||
def enableNetwork(self, *args, **kwargs):
|
||||
"""Should be provided by the inheriting class."""
|
||||
|
||||
return False
|
||||
|
||||
def exitWindow(self, title, message, *args, **kwargs):
|
||||
win = ExitWindow(title, message, *args, **kwargs)
|
||||
win.run()
|
||||
win.destroy()
|
||||
|
||||
def mainExceptionWindow(self, text, exnFile, *args, **kwargs):
|
||||
win = MainExceptionWindow(text, exnFile, *args, **kwargs)
|
||||
return win
|
||||
|
||||
def messageWindow(self, title, message, *args, **kwargs):
|
||||
win = MessageWindow(title, message, *args, **kwargs)
|
||||
win.run()
|
||||
win.destroy()
|
||||
|
||||
def saveExceptionWindow(self, signature, *args, **kwargs):
|
||||
win = SaveExceptionWindow(signature)
|
||||
win.run()
|
||||
|
||||
class SaveExceptionWindow(AbstractSaveExceptionWindow):
|
||||
def __init__(self, signature, *args, **kwargs):
|
||||
AbstractSaveExceptionWindow.__init__(self, signature, *args, **kwargs)
|
||||
self.signature = signature
|
||||
|
||||
def run(self, *args, **kwargs):
|
||||
# Don't need to check the return value of report since it will
|
||||
# handle all the UI reporting for us.
|
||||
report.report_problem_in_memory(self.signature, report.LIBREPORT_WAIT)
|
||||
|
||||
class MainExceptionWindow(AbstractMainExceptionWindow):
|
||||
def __init__(self, shortTraceback=None, longTraceback=None, *args, **kwargs):
|
||||
AbstractMainExceptionWindow.__init__(self, shortTraceback, longTraceback,
|
||||
*args, **kwargs)
|
||||
|
||||
builder = Gtk.Builder()
|
||||
builder.set_translation_domain("python-meh")
|
||||
glade_file = find_glade_file("exception-dialog.glade")
|
||||
builder.add_from_file(glade_file)
|
||||
builder.connect_signals(self)
|
||||
|
||||
self._main_window = builder.get_object("exceptionWindow")
|
||||
|
||||
# this makes sure the Meh window remains active
|
||||
# even if the exception has been triggered in a dialog
|
||||
window_group = Gtk.WindowGroup()
|
||||
window_group.add_window(self._main_window)
|
||||
|
||||
self._traceback_buffer = builder.get_object("tracebackBuffer")
|
||||
|
||||
self._traceback_buffer.set_text(longTraceback)
|
||||
self._response = MAIN_RESPONSE_QUIT
|
||||
|
||||
self._debug_button = builder.get_object("debugButton")
|
||||
|
||||
allowDebug = kwargs.get("allowDebug", sys.stdout.isatty)
|
||||
|
||||
if allowDebug and not allowDebug():
|
||||
self._debug_button.set_sensitive(False)
|
||||
|
||||
@property
|
||||
def main_window(self):
|
||||
return self._main_window
|
||||
|
||||
def destroy(self, *args, **kwargs):
|
||||
self._main_window.destroy()
|
||||
|
||||
def run(self, *args, **kwargs):
|
||||
self._main_window.show_all()
|
||||
# keep our window above dialogs
|
||||
self._main_window.set_modal(True)
|
||||
self._main_window.set_keep_above(True)
|
||||
Gtk.main()
|
||||
self.destroy()
|
||||
return self._response
|
||||
|
||||
def on_report_clicked(self, button):
|
||||
# hide our window to not interfere with libreport window
|
||||
self._main_window.hide()
|
||||
self._response = MAIN_RESPONSE_SAVE
|
||||
Gtk.main_quit()
|
||||
|
||||
def on_quit_clicked(self, button):
|
||||
self._response = MAIN_RESPONSE_QUIT
|
||||
Gtk.main_quit()
|
||||
|
||||
def on_debug_clicked(self, button):
|
||||
self._response = MAIN_RESPONSE_DEBUG
|
||||
Gtk.main_quit()
|
||||
|
||||
def on_expander_activated(self, expander, *args):
|
||||
if not expander.get_expanded():
|
||||
self._main_window.resize(600, 400)
|
||||
else:
|
||||
#resize the window back to the default size when expander is
|
||||
#minimized
|
||||
self._main_window.resize(600, 1)
|
||||
|
||||
def on_main_window_deleted(self, *args):
|
||||
self._response = MAIN_RESPONSE_NONE
|
||||
self.destroy()
|
||||
Gtk.main_quit()
|
||||
|
||||
class MessageWindow(AbstractMessageWindow):
|
||||
def __init__(self, title, text, *args, **kwargs):
|
||||
AbstractMessageWindow.__init__(self, title, text, *args, **kwargs)
|
||||
self.rc = 0
|
||||
|
||||
self.dialog = Gtk.MessageDialog(buttons=Gtk.ButtonsType.OK,
|
||||
type=Gtk.MessageType.INFO,
|
||||
message_format=text)
|
||||
self.dialog.set_title(title)
|
||||
self.dialog.set_position(Gtk.WindowPosition.CENTER)
|
||||
|
||||
def destroy(self, *args, **kwargs):
|
||||
self.dialog.destroy()
|
||||
|
||||
def run(self, *args, **kwargs):
|
||||
self.dialog.show_all()
|
||||
self.rc = self.dialog.run()
|
||||
self.dialog.destroy()
|
||||
|
||||
class ExitWindow(MessageWindow):
|
||||
def __init__(self, title, text, *args, **kwargs): # pylint: disable=super-init-not-called
|
||||
self.dialog = Gtk.MessageDialog(buttons=Gtk.ButtonsType.NONE,
|
||||
type=Gtk.MessageType.INFO,
|
||||
message_format=text)
|
||||
self.dialog.set_title(title)
|
||||
self.dialog.add_button(_("_Exit"), 0)
|
||||
self.dialog.set_position(Gtk.WindowPosition.CENTER)
|
||||
@@ -0,0 +1,225 @@
|
||||
# Copyright (C) 2009, 2013 Red Hat, Inc.
|
||||
# All rights reserved.
|
||||
#
|
||||
# This program is free software; you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 2 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
# Author(s): Chris Lumens <clumens@redhat.com>
|
||||
# Vratislav Podzimek <vpodzime@redhat.com>
|
||||
#
|
||||
from __future__ import print_function
|
||||
|
||||
from meh import MAIN_RESPONSE_DEBUG, MAIN_RESPONSE_SAVE, MAIN_RESPONSE_SHELL, MAIN_RESPONSE_QUIT
|
||||
from meh.ui import AbstractIntf, AbstractSaveExceptionWindow, AbstractMainExceptionWindow, AbstractMessageWindow
|
||||
import report
|
||||
import report.io.TextIO
|
||||
from report import LIBREPORT_WAIT, LIBREPORT_RUN_CLI
|
||||
|
||||
import os
|
||||
import sys
|
||||
if sys.version_info.major == 3:
|
||||
raw_input_fn = input
|
||||
else:
|
||||
raw_input_fn = raw_input # pylint: disable=undefined-variable
|
||||
|
||||
import gettext
|
||||
_ = lambda x: gettext.ldgettext("python-meh", x)
|
||||
|
||||
|
||||
class IOHandler(object):
|
||||
"""
|
||||
Class that provides methods for input and output. Its instance is expected
|
||||
to be passed to objects performing some I/O operations.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self, in_func=raw_input_fn, out_func=print): # pylint: disable=used-before-assignment
|
||||
"""
|
||||
Constructor for the IOhandler class. Arguments can be used to override
|
||||
default I/O functions with the custom ones.
|
||||
|
||||
:param in_func: input function similar to standard raw_input
|
||||
:type in_func: str -> str
|
||||
:param out_func: output function similar to standard print
|
||||
:type out_func: str -> None
|
||||
|
||||
"""
|
||||
|
||||
self.in_func = in_func
|
||||
self.out_func = out_func
|
||||
|
||||
def print(self, msg=""):
|
||||
self.out_func(msg)
|
||||
|
||||
def raw_input(self, prompt):
|
||||
return self.in_func(prompt)
|
||||
|
||||
class TextWindow(object):
|
||||
"""Helper class providing some common methods needed by all text windows."""
|
||||
|
||||
def __init__(self, title, *args, **kwargs):
|
||||
self._io = kwargs.get("io_handler", IOHandler())
|
||||
self._title = title
|
||||
|
||||
# short (one-char) answer meaning "yes"
|
||||
self._yes_answer = _("y")
|
||||
|
||||
# short (one-char) answer meaning "no"
|
||||
self._no_answer = _("n")
|
||||
|
||||
@property
|
||||
def _usable_width(self):
|
||||
return os.environ.get("COLUMNS", 80) - 1
|
||||
|
||||
def _print_rule(self):
|
||||
rule = self._usable_width * "="
|
||||
self._io.print(rule)
|
||||
|
||||
def print_header(self):
|
||||
self._io.print()
|
||||
self._print_rule()
|
||||
self._io.print(self._title)
|
||||
self._print_rule()
|
||||
|
||||
def destroy(self):
|
||||
self._print_rule()
|
||||
self._print_rule()
|
||||
|
||||
class TextIntf(AbstractIntf):
|
||||
def __init__(self, *args, **kwargs):
|
||||
AbstractIntf.__init__(self, *args, **kwargs)
|
||||
self.screen = kwargs.get("screen", None)
|
||||
self._io = kwargs.get("io_handler", IOHandler())
|
||||
|
||||
def set_io_handler(self, handler):
|
||||
"""
|
||||
Set different IO handler.
|
||||
|
||||
:type handler: an instance of the IOHandler class
|
||||
|
||||
"""
|
||||
self._io = handler
|
||||
|
||||
def enableNetwork(self, *args, **kwargs):
|
||||
"""Should be provided by the inheriting class."""
|
||||
|
||||
return False
|
||||
|
||||
def exitWindow(self, title, message, *args, **kwargs):
|
||||
kwargs["io_handler"] = self._io
|
||||
win = ExitWindow(title, message, *args, **kwargs)
|
||||
win.run()
|
||||
win.destroy()
|
||||
|
||||
def mainExceptionWindow(self, text, exnFile, *args, **kwargs):
|
||||
kwargs["io_handler"] = self._io
|
||||
win = MainExceptionWindow(text, exnFile, *args, **kwargs)
|
||||
return win
|
||||
|
||||
def messageWindow(self, title, message, *args, **kwargs):
|
||||
kwargs["io_handler"] = self._io
|
||||
win = MessageWindow(title, message, *args, **kwargs)
|
||||
win.run()
|
||||
win.destroy()
|
||||
|
||||
def saveExceptionWindow(self, signature, *args, **kwargs):
|
||||
kwargs["io_handler"] = self._io
|
||||
win = SaveExceptionWindow(signature, *args, **kwargs)
|
||||
win.run()
|
||||
win.destroy()
|
||||
|
||||
class SaveExceptionWindow(TextWindow, AbstractSaveExceptionWindow):
|
||||
def __init__(self, signature, *args, **kwargs):
|
||||
AbstractSaveExceptionWindow.__init__(self, signature,
|
||||
*args, **kwargs)
|
||||
TextWindow.__init__(self, _("Save exception"), *args, **kwargs)
|
||||
self.signature = signature
|
||||
|
||||
def run(self, *args, **kwargs):
|
||||
# Don't need to check the return value of report since it will
|
||||
# handle all the UI reporting for us.
|
||||
report.report_problem_in_memory(self.signature,
|
||||
LIBREPORT_WAIT|LIBREPORT_RUN_CLI)
|
||||
|
||||
class MainExceptionWindow(TextWindow, AbstractMainExceptionWindow):
|
||||
def __init__(self, shortTraceback=None, longTraceback=None, *args, **kwargs):
|
||||
AbstractMainExceptionWindow.__init__(self, shortTraceback, longTraceback,
|
||||
*args, **kwargs)
|
||||
TextWindow.__init__(self, _("An unknown error has occurred"),
|
||||
*args, **kwargs)
|
||||
self._short_traceback = shortTraceback
|
||||
self._menu_items = [(_("Report Bug"), MAIN_RESPONSE_SAVE),
|
||||
(_("Run shell"), MAIN_RESPONSE_SHELL),
|
||||
(_("Quit"), MAIN_RESPONSE_QUIT)]
|
||||
|
||||
allowDebug = kwargs.get("allowDebug", sys.stdout.isatty)
|
||||
|
||||
if allowDebug and allowDebug():
|
||||
self._menu_items.insert(1, (_("Debug"), MAIN_RESPONSE_DEBUG))
|
||||
|
||||
def run(self, *args, **kwargs):
|
||||
self.print_header()
|
||||
self._io.print(self._short_traceback)
|
||||
self._io.print(_("What do you want to do now?"))
|
||||
for (idx, item) in enumerate(self._menu_items):
|
||||
self._io.print("%d) %s" % (idx + 1, item[0]))
|
||||
|
||||
ret = -1
|
||||
num_menu_items = len(self._menu_items)
|
||||
self._io.print()
|
||||
while not (0 < ret <= num_menu_items):
|
||||
ret = self._io.raw_input(_("Please make your choice from above: "))
|
||||
try:
|
||||
ret = int(ret)
|
||||
except ValueError:
|
||||
ret = -1
|
||||
|
||||
return self._menu_items[ret - 1][1]
|
||||
|
||||
class MessageWindow(TextWindow, AbstractMessageWindow):
|
||||
def __init__(self, title, text, *args, **kwargs):
|
||||
AbstractMessageWindow.__init__(self, title, text, *args, **kwargs)
|
||||
TextWindow.__init__(self, title, *args, **kwargs)
|
||||
self._text = text
|
||||
|
||||
def run(self, *args, **kwargs):
|
||||
self.print_header()
|
||||
self._io.print(self._text)
|
||||
self._io.print()
|
||||
self._io.raw_input(_("Hit ENTER to continue"))
|
||||
|
||||
class ExitWindow(MessageWindow):
|
||||
def __init__(self, title, text, *args, **kwargs):
|
||||
MessageWindow.__init__(self, title, text, *args, **kwargs)
|
||||
|
||||
def run(self, *args, **kwargs):
|
||||
self.print_header()
|
||||
self._io.print(self._text)
|
||||
self._io.print()
|
||||
|
||||
# self._no_answer may be non-ascii string (simple .upper() doesn't work)
|
||||
no_answer_upper = self._no_answer.decode("utf-8").upper().encode("utf-8")
|
||||
answer = self._io.raw_input(_(
|
||||
"Are you sure you want to exit? [%(yes)s/%(no)s]") %
|
||||
{ "yes": self._yes_answer,
|
||||
"no": no_answer_upper })
|
||||
|
||||
# no answer means accepting the default (self._no_answer) and the answer
|
||||
# is case insensitive (and may be non-ascii)
|
||||
lower_answer = answer.decode("utf-8").lower().encode("utf-8")
|
||||
answer = lower_answer or self._no_answer
|
||||
|
||||
if answer in (self._yes_answer, self._no_answer):
|
||||
return answer == self._yes_answer
|
||||
else:
|
||||
self.run(*args, **kwargs)
|
||||
Reference in new issue
Block a user