[PATCH] cleanup: Adjusting except statement syntax
by Radek Pazdera
This patch replaces the old python's except statement syntax
except Exception, exc:
with the current one
except Exception as exc:
in the whole project.
Signed-off-by: Radek Pazdera <rpazdera(a)redhat.com>
---
Common/Daemon.py | 4 ++--
Common/Logs.py | 2 +-
Common/RecipePath.py | 2 +-
Common/SshUtils.py | 10 +++++-----
Common/XmlProcessing.py | 14 +++++++-------
Common/XmlTemplates.py | 2 +-
NetTest/NetTestController.py | 4 ++--
Tests/TestTCPConnect.py | 10 +++++-----
Tests/TestTCPListen.py | 14 +++++++-------
netconfig.py | 2 +-
nettestslave.py | 2 +-
switchconfig.py | 2 +-
swswitch.py | 2 +-
13 files changed, 35 insertions(+), 35 deletions(-)
diff --git a/Common/Daemon.py b/Common/Daemon.py
index 38bacf8..cf7dd22 100644
--- a/Common/Daemon.py
+++ b/Common/Daemon.py
@@ -41,7 +41,7 @@ class Daemon:
def _del_pidfile(self):
try:
os.remove(self._pidfile)
- except OSError, e:
+ except OSError as e:
if e.errno != 2:
raise(e)
@@ -67,6 +67,6 @@ class Daemon:
pid = os.getpid()
self._write_pid(pid)
logging.info("deamonized with pid %d" % pid)
- except OSError, e:
+ except OSError as e:
logging.error("fork failed: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1)
diff --git a/Common/Logs.py b/Common/Logs.py
index 745ed5b..8dde988 100644
--- a/Common/Logs.py
+++ b/Common/Logs.py
@@ -189,7 +189,7 @@ class Logs:
def clean_root_log_folder(cls, logRootPath):
try:
shutil.rmtree(logRootPath)
- except OSError, e:
+ except OSError as e:
if e.errno != 2:
raise
os.makedirs(logRootPath)
diff --git a/Common/RecipePath.py b/Common/RecipePath.py
index 60d035d..84c6acc 100644
--- a/Common/RecipePath.py
+++ b/Common/RecipePath.py
@@ -92,7 +92,7 @@ class HttpRecipePath(RecipePathGeneric):
try:
f = urlopen(url)
self._data = f.read()
- except IOError, err:
+ except IOError as err:
msg = "Unable to resolve path: %s (%s)" % (url, str(err))
raise Exception(msg)
diff --git a/Common/SshUtils.py b/Common/SshUtils.py
index f44f603..d287970 100644
--- a/Common/SshUtils.py
+++ b/Common/SshUtils.py
@@ -154,9 +154,9 @@ def _remote_login(session, username, password, prompt, timeout=10):
elif match == 6: # prompt
logging.log(logging.INFO, "Got shell prompt -- logged in")
break
- except ShellProcess.ProcessTimeoutError, e:
+ except ShellProcess.ProcessTimeoutError as e:
raise LoginTimeoutError(e.output)
- except ShellProcess.ProcessTerminatedError, e:
+ except ShellProcess.ProcessTerminatedError as e:
raise LoginProcessTerminatedError(e.status, e.output)
@@ -225,7 +225,7 @@ def wait_for_login(host, port, username, password, prompt, linesep="\n",
return remote_login(host, port, username, password, prompt,
linesep, log_filename, internal_timeout,
command)
- except LoginError, e:
+ except LoginError as e:
logging.debug(e)
time.sleep(2)
# Timeout expired; try one more time but don't catch exceptions
@@ -302,12 +302,12 @@ def _remote_scp(session, password_list, transfer_timeout=600, login_timeout=10):
"""elif match == 3: #Exit transfer correctly.
logging.log(logging.DEBUG2, "SCP process terminated with status 0")
break"""
- except ShellProcess.ProcessTimeoutError, e:
+ except ShellProcess.ProcessTimeoutError as e:
if authentication_done:
raise SCPTransferTimeoutError(e.output)
else:
raise SCPAuthenticationTimeoutError(e.output)
- except ShellProcess.ProcessTerminatedError, e:
+ except ShellProcess.ProcessTerminatedError as e:
if e.status == 0:
logging.log(logging.DEBUG2, "SCP process terminated with status 0")
break
diff --git a/Common/XmlProcessing.py b/Common/XmlProcessing.py
index 42057dc..d313be5 100644
--- a/Common/XmlProcessing.py
+++ b/Common/XmlProcessing.py
@@ -114,7 +114,7 @@ class XmlDomTreeInit:
self._filename = os.path.basename(filename)
try:
dom = parseString(xml_text, self._sax)
- except sax.SAXParseException, err:
+ except sax.SAXParseException as err:
pos = {"file": self._filename,
"line": err.getLineNumber(),
"col": err.getColumnNumber()}
@@ -172,7 +172,7 @@ class XmlParser(object):
if conversion_cb:
try:
converted = conversion_cb(string)
- except ValueError, err:
+ except ValueError as err:
raise XmlProcessingError("Conversion error: " + str(err), node)
return converted
@@ -259,7 +259,7 @@ class RecipeParser(XmlParser):
try:
handler = self._event_handlers[event_id]
- except KeyError, err:
+ except KeyError as err:
logging.warn("No handler found for %s event, ignoring", event_id)
return
@@ -299,7 +299,7 @@ class RecipeParser(XmlParser):
try:
dom = dom_init.parse_string(xmlstr,
filename=source_rp.abs_path())
- except IOError, err:
+ except IOError as err:
msg = "Unable to resolve include: %s" % str(err)
raise XmlProcessingError(msg, node)
@@ -335,7 +335,7 @@ class RecipeParser(XmlParser):
try:
attr_val = self._template_proc.expand_string(raw_attr_val)
- except XmlTemplateError, err:
+ except XmlTemplateError as err:
raise XmlProcessingError(str(err), node)
return self._convert_string(node, attr_val, conversion_cb)
@@ -346,7 +346,7 @@ class RecipeParser(XmlParser):
try:
content = self._template_proc.expand_string(raw_content)
- except XmlTemplateError, err:
+ except XmlTemplateError as err:
raise XmlProcessingError(str(err), node)
return self._convert_string(node, content, conversion_cb)
@@ -369,5 +369,5 @@ class RecipeParser(XmlParser):
try:
self._template_proc.define_alias(name, value)
- except XmlTemplateError, err:
+ except XmlTemplateError as err:
raise XmlProcessingError(str(err), node)
diff --git a/Common/XmlTemplates.py b/Common/XmlTemplates.py
index 9a62481..8f0d6e3 100644
--- a/Common/XmlTemplates.py
+++ b/Common/XmlTemplates.py
@@ -306,7 +306,7 @@ class XmlTemplates:
try:
recipe = self._find_definition("recipe")
return recipe
- except XmlTemplateError, err:
+ except XmlTemplateError as err:
msg = "Cannot resolve %s(): " % template_name
msg += str(err)
raise XmlTemplateError(msg)
diff --git a/NetTest/NetTestController.py b/NetTest/NetTestController.py
index 3d01310..13eefb4 100644
--- a/NetTest/NetTestController.py
+++ b/NetTest/NetTestController.py
@@ -294,7 +294,7 @@ class NetTestController:
slave_root_path = os.path.join(self._log_root_path, address)
try:
os.mkdir(slave_root_path)
- except OSError, e:
+ except OSError as e:
if e.errno != 17:
raise
@@ -484,7 +484,7 @@ class NetTestController:
slave_logging_dir = os.path.join(logging_root, hostname)
try:
os.mkdir(slave_logging_dir)
- except OSError, err:
+ except OSError as err:
if err.errno != 17:
msg = "Cannot access the logging directory %s" \
% slave_logging_dir
diff --git a/Tests/TestTCPConnect.py b/Tests/TestTCPConnect.py
index f4020f0..50e9748 100644
--- a/Tests/TestTCPConnect.py
+++ b/Tests/TestTCPConnect.py
@@ -52,7 +52,7 @@ class ConnectionWorker():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- except socket.error, msg:
+ except socket.error as msg:
logging.debug(msg)
return
@@ -60,12 +60,12 @@ class ConnectionWorker():
try:
s.connect((self._host, self._port))
- except socket.timeout, msg:
+ except socket.timeout as msg:
logging.debug("Could not connect to %s port %s" %
(self._host, self._port))
s.close()
continue
- except socket.error, msg:
+ except socket.error as msg:
logging.debug(msg)
s.close()
break
@@ -91,7 +91,7 @@ class ConnectionWorker():
data = s.sendall(rnd_str)
except socket.timeout:
continue
- except socket.error, msg:
+ except socket.error as msg:
logging.debug(msg)
s.settimeout(0)
try:
@@ -196,7 +196,7 @@ class TestTCPConnect(TestGeneric):
for w in workers:
try:
w.join()
- except OSError, e:
+ except OSError as e:
continue
workers.remove(w)
diff --git a/Tests/TestTCPListen.py b/Tests/TestTCPListen.py
index 3cf0798..4de1083 100644
--- a/Tests/TestTCPListen.py
+++ b/Tests/TestTCPListen.py
@@ -67,7 +67,7 @@ class TestTCPListen(TestGeneric):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(1)
- except socket.error, msg:
+ except socket.error as msg:
logging.debug(msg)
return
@@ -75,7 +75,7 @@ class TestTCPListen(TestGeneric):
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
s.listen(1)
- except socket.error, msg:
+ except socket.error as msg:
logging.debug(msg)
s.close()
return
@@ -87,9 +87,9 @@ class TestTCPListen(TestGeneric):
while conn == None and not closecon.value:
try:
conn, addr = s.accept()
- except socket.timeout, e:
+ except socket.timeout as e:
continue
- except socket.error, e:
+ except socket.error as e:
logging.debug(e)
s.close()
return
@@ -110,9 +110,9 @@ class TestTCPListen(TestGeneric):
while not closecon.value:
try:
data = conn.recv(1024)
- except socket.timeout, e:
+ except socket.timeout as e:
continue
- except socket.error, e:
+ except socket.error as e:
logging.debug(e)
if conn:
conn.shutdown(socket.SHUT_RDWR)
@@ -129,7 +129,7 @@ class TestTCPListen(TestGeneric):
try:
conn.shutdown(socket.SHUT_RDWR)
conn.close()
- except socket.error, msg:
+ except socket.error as msg:
logging.debug(msg)
s.close()
return
diff --git a/netconfig.py b/netconfig.py
index c0baf97..6012667 100755
--- a/netconfig.py
+++ b/netconfig.py
@@ -120,7 +120,7 @@ def main():
"dhc:m:a:",
["debug", "help", "config=", "machine-config=", "action="]
)
- except getopt.GetoptError, err:
+ except getopt.GetoptError as err:
print str(err)
usage()
sys.exit()
diff --git a/nettestslave.py b/nettestslave.py
index 365ebdd..29528ff 100755
--- a/nettestslave.py
+++ b/nettestslave.py
@@ -41,7 +41,7 @@ def main():
"dhei:p:",
["debug", "help", "daemonize", "pidfile", "port"]
)[0]
- except getopt.GetoptError, err:
+ except getopt.GetoptError as err:
print str(err)
usage()
sys.exit()
diff --git a/switchconfig.py b/switchconfig.py
index ef38581..ed2b95e 100755
--- a/switchconfig.py
+++ b/switchconfig.py
@@ -38,7 +38,7 @@ def main():
"dhc:m:a:",
["debug", "help", "config=", "machine-config=", "action="]
)
- except getopt.GetoptError, err:
+ except getopt.GetoptError as err:
print str(err)
usage()
sys.exit()
diff --git a/swswitch.py b/swswitch.py
index aa8716d..42ef900 100755
--- a/swswitch.py
+++ b/swswitch.py
@@ -44,7 +44,7 @@ def main():
"dhm:p:",
["debug", "help", "machine-config=", "port="]
)
- except getopt.GetoptError, err:
+ except getopt.GetoptError as err:
print str(err)
usage()
sys.exit()
--
1.7.7.6
11 years, 6 months
User-Defined Tests + Tools Proposal
by Radek Pazdera
Hello!
This is (another) one of my endless proposal emails, sorry about that :).
We discussed a way of enabling users to define their own tests and tools
without the necessity to add modules to site-packages/ on the controller
and all the slaves by hand.
This should be done by creating a directory at the controller machine
that will contain the tests. The controller machine will send them to
the slave through a xml-rpc method and the slave will be able to use
them.
I dug into this a little more today and I had some ideas that I'd like
to present here.
There are two things we deal with nowadays. Python test modules that
represent Test* commands directly and test tools that can be in an
arbitrary format. The tools are later used by the modules, to perform
test tasks.
I personally think, that this model is great. It allows you to set up
everything you need at the controller, e.g, prepare the test tools,
write a new command, that will allow using them with LNST, write the
recipe and then one-click execute them in your lab. You don't have
to ssh to 5 (or even more) different machines to install the tools.
That's the most tedious thing about networking tests. Manually preparing
all the machines for the tests. I think the key feature of LNST
facility is making the test setup and execution as easy and as much
automated as possible.
Currently, the test modules (Test/Test*.py) are an integral part of
the LNST package. They are available to controller machines as well as
to slave machines. The inconsistency here is, that controller doesn't
need to execute them. It only wants to take them and send them over
to the slaves. I think that we could take them out from LNST core
and treat them a little differently.
There are two categories of tests:
* upstream - currently lnst/Tests/Test*.py
* user-defined - configurable; defaults to ~/.lnst/Tests
We could put all the upstream tests to /usr/share/lnst instead of
having them within the tree directly. The test execution would then
work like this:
1. Controller starts the test
2. It will contact the slave and send him hashes of all the
Test*.py commands that will be necessary to execute the recipe
3. Slave will look within his tests cache located in /var/cache/lnst
to see if it does have the tests already
4. If not, controller will transfer all the files to the slave
5. The test can begin :-)
The key feature is, that the slave would not search any directories
other than his test cache, which would after a few executed recipes
get almost 100% hit-rate. The great thing about the hashes is, that
in case the test is changed in any way at the controller, it will
be transfered again to the slave.
Consequentially to this, we could pack LNST into two (maybe three
due to some common code) different packages:
* lnst-controller
* lnst-slave
* (lnst-common)
What do you think?
-Radek
11 years, 6 months
[lnst trac] #39: Configurable 'Logs' directory name
by fedora-badges
#39: Configurable 'Logs' directory name
------------------------+-----------------------
Reporter: rpazdera | Owner: olichtne
Type: defect | Status: new
Priority: minor | Milestone:
Component: component1 | Version:
Keywords: | Blocked By:
Blocking: |
------------------------+-----------------------
There is a config option that allows setting a logging path, but in
practice another directory called "Logs" is created within the path.
This is rather unexpected, the logs should be put into the existing
configured directory directly.
--
Ticket URL: <https://fedorahosted.org/lnst/ticket/39>
lnst <http://example.org/>
My example project
11 years, 6 months
[lnst trac] #25: Logs: reverse client and server
by fedora-badges
#25: Logs: reverse client and server
-------------------------+-----------------------
Reporter: olichtne | Owner: somebody
Type: enhancement | Status: new
Priority: minor | Milestone:
Component: component1 | Version:
Keywords: | Blocked By:
Blocking: |
-------------------------+-----------------------
We want to change the direction in which logs are being transferred.
Currently slave machines are connecting to the logging server. This isn't
ideal and it would be better if the controller would collect the logging
data from slaves on its own.
--
Ticket URL: <https://fedorahosted.org/lnst/ticket/25>
lnst <http://example.org/>
My example project
11 years, 6 months
[lnst] Logs: small path change
by Jiří Pírko
commit d24659ffc2db4945e1402a442c5b4ae6c0fa6107
Author: Ondrej Lichtner <olichtne(a)redhat.com>
Date: Thu Oct 18 16:16:28 2012 +0200
Logs: small path change
The path where logs are located is now exactly the same as what you
specify in the configuration file. Previously 'Logs' was added to the
end of this path. You now need to do this manually.
This change allows for the removal of the log_root argument of the class
Logs. Instead log_folder should be used now.
The default path where you can find logs is <lnst_dir>/Logs .
Signed-off-by: Ondrej Lichtner <olichtne(a)redhat.com>
Common/Config.py | 2 +-
Common/Logs.py | 10 ++++------
NetTest/NetTestController.py | 2 +-
3 files changed, 6 insertions(+), 8 deletions(-)
---
diff --git a/Common/Config.py b/Common/Config.py
index e76fbef..297ebea 100644
--- a/Common/Config.py
+++ b/Common/Config.py
@@ -29,7 +29,7 @@ class Config():
self.options['log'] = dict()
self.options['log']['path'] = os.path.join(
- os.path.dirname(sys.argv[0]), './')
+ os.path.dirname(sys.argv[0]), './Logs')
self.options['environment'] = dict()
self.options['environment']['mac_pool_range'] = \
diff --git a/Common/Logs.py b/Common/Logs.py
index 41c1abf..745ed5b 100644
--- a/Common/Logs.py
+++ b/Common/Logs.py
@@ -150,7 +150,6 @@ class LoggingFile(object):
class Logs:
file_handlers = []
formatter = None
- log_root = None
logFolder = None
logger = None
root_path = None
@@ -159,7 +158,7 @@ class Logs:
nameExtend = None
@classmethod
def __init__(cls,debug=0, waitForNet=False, logger=logging.getLogger(),
- recipe_path=None, log_root="Logs", to_display=True, date=None,
+ recipe_path=None, to_display=True, date=None,
nameExtend=None, log_folder=None):
logging.addLevelName(5, "DEBUG2")
logging.DEBUG2 = 5
@@ -172,11 +171,10 @@ class Logs:
'%(asctime)s| %(address)17.17s%(module)15.15s'
':%(lineno)4.4d| %(levelname)s: '
'%(message)s', '%d/%m %H:%M:%S', " "*4)
- cls.log_root = log_root
if log_folder != None:
cls.logFolder = log_folder
else:
- cls.logFolder = os.path.dirname(sys.argv[0])
+ cls.logFolder = os.path.join(os.path.dirname(sys.argv[0]), './Logs')
cls.logger = logger
cls.debug = debug
if date is None:
@@ -221,8 +219,8 @@ class Logs:
recipe_path = ""
root_logger = cls.logger
recipe_name = os.path.splitext(os.path.split(recipe_path)[1])[0]
- cls.root_path = os.path.join(cls.logFolder, cls.log_root,
- cls.date+cls.nameExtend, recipe_name)
+ cls.root_path = os.path.join(cls.logFolder, cls.date+cls.nameExtend,
+ recipe_name)
if (clean):
cls.clean_root_log_folder(cls.root_path)
for fhandler in cls.file_handlers:
diff --git a/NetTest/NetTestController.py b/NetTest/NetTestController.py
index bb12db6..3d01310 100644
--- a/NetTest/NetTestController.py
+++ b/NetTest/NetTestController.py
@@ -299,7 +299,7 @@ class NetTestController:
raise
logger = logging.getLogger(address)
- Logs(Logs.debug, False, logger, log_root=slave_root_path,
+ Logs(Logs.debug, False, logger, log_folder=slave_root_path,
to_display=False, date="")
info['logger'] = logger
11 years, 6 months
[lnst] Logs: remove unused code
by Jiří Pírko
commit 68508c6c7a0fe5d6c3228808a94013ba21278302
Author: Ondrej Lichtner <olichtne(a)redhat.com>
Date: Thu Oct 18 16:16:27 2012 +0200
Logs: remove unused code
The exception class FindRootPathError is not used anywhere except in the
following function find_test_root(). This function however is not called
at all. I am removing both of these so that they don't confuse anyone.
Signed-off-by: Ondrej Lichtner <olichtne(a)redhat.com>
Common/Logs.py | 28 ----------------------------
1 files changed, 0 insertions(+), 28 deletions(-)
---
diff --git a/Common/Logs.py b/Common/Logs.py
index ae5cfa8..41c1abf 100644
--- a/Common/Logs.py
+++ b/Common/Logs.py
@@ -22,34 +22,6 @@ def log_exc_traceback():
exception = traceback.format_exception(cmd_type, value, tb)
logging.debug(''.join(exception))
-class FindRootPathError(Exception):
- def __init__(self, path, rootFolder):
- Exception.__init__(self, path, rootFolder)
- self.path = path
- self.rootFolder = rootFolder
-
- def __str__(self):
- return ("Cannot find root folder '%s' in path '%s'" %
- (self.rootFolder, self.path))
-
-
-def find_test_root(path, rootFolder):
- """
- Find test root folder in path.
-
- @param path: Path.
- @param rootFolder: Name of test root folder.
- @return: Absolute path to test root folder.
- """
- sub = None
- path = os.path.abspath(path)
- _path = path
- while sub != rootFolder and sub != '':
- _path, sub = os.path.split(_path)
- if sub != rootFolder:
- raise FindRootPathError(path, rootFolder)
- return os.path.join(_path, sub)
-
class MultilineFormater(Formatter):
"""
11 years, 6 months
[lnst] NetTestSlave: remove method set_logging
by Jiří Pírko
commit 97c30031ef403f9d4fe0e66798c21c8c698a8504
Author: Ondrej Lichtner <olichtne(a)redhat.com>
Date: Thu Oct 18 16:16:26 2012 +0200
NetTestSlave: remove method set_logging
This method is no longer used therefore I am removing it.
Signed-off-by: Ondrej Lichtner <olichtne(a)redhat.com>
NetTest/NetTestSlave.py | 11 -----------
1 files changed, 0 insertions(+), 11 deletions(-)
---
diff --git a/NetTest/NetTestSlave.py b/NetTest/NetTestSlave.py
index cca32a9..822dc37 100644
--- a/NetTest/NetTestSlave.py
+++ b/NetTest/NetTestSlave.py
@@ -45,17 +45,6 @@ class NetTestSlaveXMLRPC:
logs = buffer.flush()
return logs
- def set_logging(self, logger_address, port):
- """
- Server side setup logging to server side.
-
- @param logger_address: Address of running logger.
- """
- connectable = test_tcp_connection(logger_address, port)
-
- Logs.append_network_hadler(logger_address, port)
- return connectable
-
def get_devices_by_hwaddr(self, hwaddr):
name_scan = scan_netdevs()
netdevs = []
11 years, 6 months
[lnst] NetTestController: fix a small Logs interface error
by Jiří Pírko
commit 642fe05354da9955447dd0e29af68c81ce0540b9
Author: Ondrej Lichtner <olichtne(a)redhat.com>
Date: Thu Oct 18 16:16:25 2012 +0200
NetTestController: fix a small Logs interface error
The Logs class provides a method for retrieving the logging root path so
we should be using it.
Signed-off-by: Ondrej Lichtner <olichtne(a)redhat.com>
NetTest/NetTestController.py | 2 +-
1 files changed, 1 insertions(+), 1 deletions(-)
---
diff --git a/NetTest/NetTestController.py b/NetTest/NetTestController.py
index 5e5a134..bb12db6 100644
--- a/NetTest/NetTestController.py
+++ b/NetTest/NetTestController.py
@@ -41,7 +41,7 @@ class NetTestController:
self._res_serializer = res_serializer
self._remote_capture_files = {}
self._config = config
- self._log_root_path = Logs.root_path
+ self._log_root_path = Logs.get_logging_root_path()
self._command_context = NetTestCommandContext()
self._machine_pool = MachinePool(config.get_option('environment',
'pool_dirs'))
11 years, 6 months
[lnst] LoggingHandler: forgotten change of makePickle docstring
by Jiří Pírko
commit 3ff85ca82e420d800ecc1c8428a9494d060e1cd2
Author: Ondrej Lichtner <olichtne(a)redhat.com>
Date: Thu Oct 18 16:16:24 2012 +0200
LoggingHandler: forgotten change of makePickle docstring
This patch changes the docstring of the method makePickle.
Signed-off-by: Ondrej Lichtner <olichtne(a)redhat.com>
Common/LoggingHandler.py | 6 +-----
1 files changed, 1 insertions(+), 5 deletions(-)
---
diff --git a/Common/LoggingHandler.py b/Common/LoggingHandler.py
index 8f188f6..7b7174e 100644
--- a/Common/LoggingHandler.py
+++ b/Common/LoggingHandler.py
@@ -31,11 +31,7 @@ class LogBuffer(logging.Handler):
def makePickle(self, record):
"""
- Pickles the record in binary format with a length prefix, and
- returns it ready for transmission across the socket.
-
- Function taken from class SocketHandler from standard python
- library logging.handlers
+ Pickles the record so that it can be sent over the xmlrpc we use.
"""
d = dict(record.__dict__)
d['msg'] = record.getMessage()
11 years, 6 months
[lnst] LoggingHandler: remove ServerHandler
by Jiří Pírko
commit 8afd7a36b9edcf8cb08eec54f09be0a1fbda9f16
Author: Ondrej Lichtner <olichtne(a)redhat.com>
Date: Thu Oct 18 16:16:23 2012 +0200
LoggingHandler: remove ServerHandler
Removing the server handler because it probably won't be used again. If
we ever need it we can find it in the history of the repo.
Signed-off-by: Ondrej Lichtner <olichtne(a)redhat.com>
Common/LoggingHandler.py | 95 ----------------------------------------------
Common/Logs.py | 2 +-
2 files changed, 1 insertions(+), 96 deletions(-)
---
diff --git a/Common/LoggingHandler.py b/Common/LoggingHandler.py
index dae27bf..8f188f6 100644
--- a/Common/LoggingHandler.py
+++ b/Common/LoggingHandler.py
@@ -5,12 +5,6 @@ LogBuffer
Handler used solely for temporarily storing messages so that they can be
retrieved later.
-ServerHandler
-Server-like logging handler.
-Stores logged messages in a buffer. Every time a new message is emitted it
-checks for incoming connections. If a connection is established it flushes the
-messages stored in the buffer to the connecting client.
-
Copyright 2012 Red Hat, Inc.
Licensed under the GNU General Public License, version 2 as
published by the Free Software Foundation; see COPYING for details.
@@ -66,92 +60,3 @@ class LogBuffer(logging.Handler):
def close(self):
self.flush()
logging.Handler.close(self)
-
-class ServerHandler(logging.Handler):
- def __init__(self, port=DEFAULT_LOG_PORT):
- logging.Handler.__init__(self)
- self.port = port
-
- self.sock = None
- self.buf = []
-
- self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- self.server_socket.setblocking(0)
- self.server_socket.bind(('0.0.0.0', self.port))
- self.server_socket.listen(1)
-
- def makePickle(self, record):
- """
- Pickles the record in binary format with a length prefix, and
- returns it ready for transmission across the socket.
-
- Function taken from class SocketHandler from standard python
- library logging.handlers
- """
- d = dict(record.__dict__)
- d['msg'] = record.getMessage()
- d['args'] = None
- d['exc_info'] = None
- s = pickle.dumps(d, 1)
- slen = struct.pack(">L", len(s))
- return slen + s
-
- def emit(self, record):
- try:
- s = self.makePickle(record)
- self.buf.append(s)
- self.send_all()
- except (KeyboardInterrupt, SystemExit):
- raise
- except:
- logging.Handler.handleError(self, record)
-
- def client_connection(self):
- if self.sock == None:
- try:
- self.sock = self.server_socket.accept()[0]
- return True
- except:
- self.sock = None
- return False
- else:
- return True
-
- def send_all(self):
- if self.client_connection():
- sent = len(self.buf)
- for record in self.buf:
- if not self.send(record):
- sent = self.buf.index(record)
- break
-
- self.buf = self.buf[sent:]
-
- def send(self, record):
- try:
- if hasattr(self.sock, "sendall"):
- self.sock.sendall(record)
- else:
- sentsofar = 0
- left = len(record)
- while left > 0:
- sent = self.sock.send(record[sentsofar:])
- sentsofar = sentsofar + sent
- left = left - sent
- return True
- except socket.error:
- self.sock.close()
- self.sock = None
- return False
-
- def close(self):
- if self.sock:
- self.sock.close()
- self.sock = None
-
- self.server_socket.close()
- self.server_socket = None
-
- self.buf = []
-
- logging.Handler.close(self)
diff --git a/Common/Logs.py b/Common/Logs.py
index 0badfe5..ae5cfa8 100644
--- a/Common/Logs.py
+++ b/Common/Logs.py
@@ -13,7 +13,7 @@ import os, sys, shutil, datetime
from logging import Formatter
import logging.handlers
import traceback
-from Common.LoggingHandler import ServerHandler, LogBuffer
+from Common.LoggingHandler import LogBuffer
LOCAL_IP = "(127.0.0.1)"
11 years, 6 months