Rework UI system to make use of the logging module

Logging was flawed as the output was e.g. heavily buffered and people
complained about missing log entries. Fix this by making use of the
standard logging facilities that offlineimap offers.

This is one big ugly patch that does many things. It fixes the
Blinkenlights backend to work again with the logging facilities.

Resize windows and hotkeys are still not handled absolut correctly, this
is left for future fixing. THe rest of the backends should be working fine.

Signed-off-by: Sebastian Spaeth <Sebastian@SSpaeth.de>
This commit is contained in:
Sebastian Spaeth 2011-10-26 16:47:21 +02:00
parent d4a11c62ea
commit cbec8bb5b2
12 changed files with 829 additions and 945 deletions

View File

@ -8,15 +8,11 @@ __author_email__= "john@complete.org"
__description__ = "Disconnected Universal IMAP Mail Synchronization/Reader Support"
__license__ = "Licensed under the GNU GPL v2+ (v2 or any later version)"
__bigcopyright__ = """%(__productname__)s %(__version__)s
%(__copyright__)s.
%(__license__)s.
""" % locals()
%(__license__)s""" % locals()
__homepage__ = "http://github.com/nicolas33/offlineimap"
banner = __bigcopyright__
from offlineimap.error import OfflineImapError
# put this last, so we don't run into circular dependencies using
# e.g. offlineimap.__version__.

View File

@ -143,7 +143,7 @@ class Account(CustomConfig.ConfigHelperMixin):
for item in kaobjs:
item.startkeepalive()
refreshperiod = int(self.refreshperiod * 60)
sleepresult = self.ui.sleep(refreshperiod, self)
@ -166,7 +166,8 @@ class Account(CustomConfig.ConfigHelperMixin):
self.ui.serverdiagnostics(remote_repo, 'Remote')
self.ui.serverdiagnostics(local_repo, 'Local')
#self.ui.serverdiagnostics(statusrepos, 'Status')
class SyncableAccount(Account):
"""A syncable email account connecting 2 repositories
@ -208,7 +209,7 @@ class SyncableAccount(Account):
self.ui.registerthread(self.name)
accountmetadata = self.getaccountmeta()
if not os.path.exists(accountmetadata):
os.mkdir(accountmetadata, 0700)
os.mkdir(accountmetadata, 0700)
self.remoterepos = Repository(self, 'remote')
self.localrepos = Repository(self, 'local')
@ -223,7 +224,7 @@ class SyncableAccount(Account):
self.sync()
except (KeyboardInterrupt, SystemExit):
raise
except OfflineImapError, e:
except OfflineImapError, e:
# Stop looping and bubble up Exception if needed.
if e.severity >= OfflineImapError.ERROR.REPO:
if looping:
@ -242,7 +243,7 @@ class SyncableAccount(Account):
self.ui.acctdone(self)
self.unlock()
if looping and self.sleeper() >= 2:
looping = 0
looping = 0
def sync(self):
"""Synchronize the account once, then return
@ -408,7 +409,7 @@ def syncfolder(accountname, remoterepos, remotefolder, localrepos,
else:
ui.debug('imap', "Not syncing to read-only repository '%s'" \
% localrepos.getname())
# Synchronize local changes
if not remoterepos.getconfboolean('readonly', False):
ui.syncingmessages(localrepos, localfolder, remoterepos, remotefolder)

View File

@ -157,9 +157,10 @@ class OfflineImap:
#read in configuration file
configfilename = os.path.expanduser(options.configfile)
config = CustomConfigParser()
if not os.path.exists(configfilename):
# TODO, initialize and make use of chosen ui for logging
logging.error(" *** Config file '%s' does not exist; aborting!" %
configfilename)
sys.exit(1)
@ -168,14 +169,17 @@ class OfflineImap:
#profile mode chosen?
if options.profiledir:
if not options.singlethreading:
# TODO, make use of chosen ui for logging
logging.warn("Profile mode: Forcing to singlethreaded.")
options.singlethreading = True
if os.path.exists(options.profiledir):
logging.warn("Profile mode: Directory '%s' already exists!" %
# TODO, make use of chosen ui for logging
logging.warn("Profile mode: Directory '%s' already exists!" %
options.profiledir)
else:
os.mkdir(options.profiledir)
threadutil.ExitNotifyThread.set_profiledir(options.profiledir)
# TODO, make use of chosen ui for logging
logging.warn("Profile mode: Potentially large data will be "
"created in '%s'" % options.profiledir)
@ -197,6 +201,7 @@ class OfflineImap:
if '.' in ui_type:
#transform Curses.Blinkenlights -> Blinkenlights
ui_type = ui_type.split('.')[-1]
# TODO, make use of chosen ui for logging
logging.warning('Using old interface name, consider using one '
'of %s' % ', '.join(UI_LIST.keys()))
try:
@ -210,12 +215,13 @@ class OfflineImap:
#set up additional log files
if options.logfile:
self.ui.setlogfd(open(options.logfile, 'wt'))
self.ui.setlogfile(options.logfile)
#welcome blurb
self.ui.init_banner()
if options.debugtype:
self.ui.logger.setLevel(logging.DEBUG)
if options.debugtype.lower() == 'all':
options.debugtype = 'imap,maildir,thread'
#force single threading?
@ -293,15 +299,15 @@ class OfflineImap:
pidfd.close()
except:
pass
try:
try:
activeaccounts = self.config.get("general", "accounts")
if options.accounts:
activeaccounts = options.accounts
activeaccounts = activeaccounts.replace(" ", "")
activeaccounts = activeaccounts.split(",")
allaccounts = accounts.AccountHashGenerator(self.config)
syncaccounts = []
for account in activeaccounts:
if account not in allaccounts:
@ -323,11 +329,11 @@ class OfflineImap:
elif sig == signal.SIGUSR2:
# tell each account to stop looping
accounts.Account.set_abort_event(self.config, 2)
signal.signal(signal.SIGHUP,sig_handler)
signal.signal(signal.SIGUSR1,sig_handler)
signal.signal(signal.SIGUSR2,sig_handler)
#various initializations that need to be performed:
offlineimap.mbnames.init(self.config, syncaccounts)
@ -352,10 +358,9 @@ class OfflineImap:
name='Sync Runner',
kwargs = {'accounts': syncaccounts,
'config': self.config})
t.setDaemon(1)
t.setDaemon(True)
t.start()
threadutil.exitnotifymonitorloop(threadutil.threadexited)
self.ui.terminate()
except KeyboardInterrupt:
self.ui.terminate(1, errormsg = 'CTRL-C pressed, aborting...')
@ -363,8 +368,8 @@ class OfflineImap:
except (SystemExit):
raise
except Exception, e:
ui.error(e)
ui.terminate()
self.ui.error(e)
self.ui.terminate()
def sync_singlethreaded(self, accs):
"""Executed if we do not want a separate syncmaster thread

View File

@ -25,12 +25,11 @@ def syncaccount(threads, config, accountname):
thread = InstanceLimitedThread(instancename = 'ACCOUNTLIMIT',
target = account.syncrunner,
name = "Account sync %s" % accountname)
thread.setDaemon(1)
thread.setDaemon(True)
thread.start()
threads.add(thread)
def syncitall(accounts, config):
currentThread().setExitMessage('SYNC_WITH_TIMER_TERMINATE')
threads = threadlist()
for accountname in accounts:
syncaccount(threads, config, accountname)

View File

@ -35,7 +35,7 @@ def semaphorereset(semaphore, originalstate):
# Now release these.
for i in range(originalstate):
semaphore.release()
class threadlist:
def __init__(self):
self.lock = Lock()
@ -70,7 +70,7 @@ class threadlist:
if not thread:
return
thread.join()
######################################################################
# Exit-notify threads
@ -81,20 +81,21 @@ exitthreads = Queue(100)
def exitnotifymonitorloop(callback):
"""An infinite "monitoring" loop watching for finished ExitNotifyThread's.
:param callback: the function to call when a thread terminated. That
function is called with a single argument -- the
ExitNotifyThread that has terminated. The monitor will
This one is supposed to run in the main thread.
:param callback: the function to call when a thread terminated. That
function is called with a single argument -- the
ExitNotifyThread that has terminated. The monitor will
not continue to monitor for other threads until
'callback' returns, so if it intends to perform long
calculations, it should start a new thread itself -- but
NOT an ExitNotifyThread, or else an infinite loop
NOT an ExitNotifyThread, or else an infinite loop
may result.
Furthermore, the monitor will hold the lock all the
Furthermore, the monitor will hold the lock all the
while the other thread is waiting.
:type callback: a callable function
"""
global exitthreads
while 1:
while 1:
# Loop forever and call 'callback' for each thread that exited
try:
# we need a timeout in the get() call, so that ctrl-c can throw
@ -124,11 +125,19 @@ def threadexited(thread):
ui.threadExited(thread)
class ExitNotifyThread(Thread):
"""This class is designed to alert a "monitor" to the fact that a thread has
exited and to provide for the ability for it to find out why."""
"""This class is designed to alert a "monitor" to the fact that a
thread has exited and to provide for the ability for it to find out
why. All instances are made daemon threads (setDaemon(True), so we
bail out when the mainloop dies."""
profiledir = None
"""class variable that is set to the profile directory if required"""
def __init__(self, *args, **kwargs):
super(ExitNotifyThread, self).__init__(*args, **kwargs)
# These are all child threads that are supposed to go away when
# the main thread is killed.
self.setDaemon(True)
def run(self):
global exitthreads
self.threadid = get_ident()
@ -220,7 +229,7 @@ class InstanceLimitedThread(ExitNotifyThread):
def start(self):
instancelimitedsems[self.instancename].acquire()
ExitNotifyThread.start(self)
def run(self):
try:
ExitNotifyThread.run(self)

View File

@ -1,148 +0,0 @@
# Blinkenlights base classes
# Copyright (C) 2003 John Goerzen
# <jgoerzen@complete.org>
#
# 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, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
from threading import RLock, currentThread
from offlineimap.ui.UIBase import UIBase
from thread import get_ident # python < 2.6 support
class BlinkenBase:
"""This is a mix-in class that should be mixed in with either UIBase
or another appropriate base class. The Tk interface, for instance,
will probably mix it in with VerboseUI."""
def acct(s, accountname):
s.gettf().setcolor('purple')
s.__class__.__bases__[-1].acct(s, accountname)
def connecting(s, hostname, port):
s.gettf().setcolor('gray')
s.__class__.__bases__[-1].connecting(s, hostname, port)
def syncfolders(s, srcrepos, destrepos):
s.gettf().setcolor('blue')
s.__class__.__bases__[-1].syncfolders(s, srcrepos, destrepos)
def syncingfolder(s, srcrepos, srcfolder, destrepos, destfolder):
s.gettf().setcolor('cyan')
s.__class__.__bases__[-1].syncingfolder(s, srcrepos, srcfolder, destrepos, destfolder)
def skippingfolder(s, folder):
s.gettf().setcolor('cyan')
s.__class__.__bases__[-1].skippingfolder(s, folder)
def loadmessagelist(s, repos, folder):
s.gettf().setcolor('green')
s._msg("Scanning folder [%s/%s]" % (s.getnicename(repos),
folder.getvisiblename()))
def syncingmessages(s, sr, sf, dr, df):
s.gettf().setcolor('blue')
s.__class__.__bases__[-1].syncingmessages(s, sr, sf, dr, df)
def copyingmessage(s, uid, num, num_to_copy, src, destfolder):
s.gettf().setcolor('orange')
s.__class__.__bases__[-1].copyingmessage(s, uid, num, num_to_copy, src,
destfolder)
def deletingmessages(s, uidlist, destlist):
s.gettf().setcolor('red')
s.__class__.__bases__[-1].deletingmessages(s, uidlist, destlist)
def deletingmessage(s, uid, destlist):
s.gettf().setcolor('red')
s.__class__.__bases__[-1].deletingmessage(s, uid, destlist)
def addingflags(s, uidlist, flags, dest):
s.gettf().setcolor('yellow')
s.__class__.__bases__[-1].addingflags(s, uidlist, flags, dest)
def deletingflags(s, uidlist, flags, dest):
s.gettf().setcolor('pink')
s.__class__.__bases__[-1].deletingflags(s, uidlist, flags, dest)
def warn(s, msg, minor = 0):
if minor:
s.gettf().setcolor('pink')
else:
s.gettf().setcolor('red')
s.__class__.__bases__[-1].warn(s, msg, minor)
def init_banner(s):
s.availablethreadframes = {}
s.threadframes = {}
#tflock protects the s.threadframes manipulation to only happen from 1 thread
s.tflock = RLock()
def threadExited(s, thread):
threadid = thread.threadid
accountname = s.getthreadaccount(thread)
s.tflock.acquire()
try:
if threadid in s.threadframes[accountname]:
tf = s.threadframes[accountname][threadid]
del s.threadframes[accountname][threadid]
s.availablethreadframes[accountname].append(tf)
tf.setthread(None)
finally:
s.tflock.release()
UIBase.threadExited(s, thread)
def gettf(s):
threadid = get_ident()
accountname = s.getthreadaccount()
s.tflock.acquire()
try:
if not accountname in s.threadframes:
s.threadframes[accountname] = {}
if threadid in s.threadframes[accountname]:
return s.threadframes[accountname][threadid]
if not accountname in s.availablethreadframes:
s.availablethreadframes[accountname] = []
if len(s.availablethreadframes[accountname]):
tf = s.availablethreadframes[accountname].pop(0)
tf.setthread(currentThread())
else:
tf = s.getaccountframe().getnewthreadframe()
s.threadframes[accountname][threadid] = tf
return tf
finally:
s.tflock.release()
def callhook(s, msg):
s.gettf().setcolor('white')
s.__class__.__bases__[-1].callhook(s, msg)
def sleep(s, sleepsecs, account):
s.gettf().setcolor('red')
s.getaccountframe().startsleep(sleepsecs)
return UIBase.sleep(s, sleepsecs, account)
def sleeping(s, sleepsecs, remainingsecs):
if remainingsecs and s.gettf().getcolor() == 'black':
s.gettf().setcolor('red')
else:
s.gettf().setcolor('black')
return s.getaccountframe().sleeping(sleepsecs, remainingsecs)

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +1,4 @@
# Copyright (C) 2007 John Goerzen
# <jgoerzen@complete.org>
# Copyright (C) 2007-2011 John Goerzen & contributors
#
# 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
@ -18,48 +17,30 @@
import urllib
import sys
import time
import logging
from UIBase import UIBase
from threading import currentThread, Lock
from threading import currentThread
import offlineimap
protocol = '6.0.0'
protocol = '7.0.0'
class MachineUI(UIBase):
def __init__(s, config, verbose = 0):
UIBase.__init__(s, config, verbose)
s.safechars=" ;,./-_=+()[]"
s.iswaiting = 0
s.outputlock = Lock()
s._printData('__init__', protocol)
def __init__(self, config, loglevel = logging.INFO):
super(MachineUI, self).__init__(config, loglevel)
self._log_con_handler.createLock()
"""lock needed to block on password input"""
def isusable(s):
return True
def _printData(self, command, msg):
self.logger.info("%s:%s:%s:%s" % (
'msg', command, currentThread().getName(), msg))
def _printData(s, command, data, dolock = True):
s._printDataOut('msg', command, data, dolock)
def _printWarn(s, command, data, dolock = True):
s._printDataOut('warn', command, data, dolock)
def _printDataOut(s, datatype, command, data, dolock = True):
if dolock:
s.outputlock.acquire()
try:
print "%s:%s:%s:%s" % \
(datatype,
urllib.quote(command, s.safechars),
urllib.quote(currentThread().getName(), s.safechars),
urllib.quote(data, s.safechars))
sys.stdout.flush()
finally:
if dolock:
s.outputlock.release()
def _display(s, msg):
def _msg(s, msg):
s._printData('_display', msg)
def warn(s, msg, minor = 0):
s._printData('warn', '%s\n%d' % (msg, int(minor)))
# TODO, remove and cleanup the unused minor stuff
self.logger.warning("%s:%s:%s:%s" % (
'warn', '', currentThread().getName(), msg))
def registerthread(s, account):
UIBase.registerthread(s, account)
@ -112,13 +93,10 @@ class MachineUI(UIBase):
self._printData('copyingmessage', "%d\n%s\n%s\n%s[%s]" % \
(uid, self.getnicename(srcfolder), srcfolder.getname(),
self.getnicename(destfolder), destfolder))
def folderlist(s, list):
return ("\f".join(["%s\t%s" % (s.getnicename(x), x.getname()) for x in list]))
def deletingmessage(s, uid, destlist):
s.deletingmessages(s, [uid], destlist)
def uidlist(s, list):
return ("\f".join([str(u) for u in list]))
@ -161,19 +139,21 @@ class MachineUI(UIBase):
return 0
def getpass(s, accountname, config, errmsg = None):
s.outputlock.acquire()
def getpass(self, accountname, config, errmsg = None):
if errmsg:
self._printData('getpasserror', "%s\n%s" % (accountname, errmsg),
False)
self._log_con_handler.acquire() # lock the console output
try:
if errmsg:
s._printData('getpasserror', "%s\n%s" % (accountname, errmsg),
False)
s._printData('getpass', accountname, False)
self._printData('getpass', accountname, False)
return (sys.stdin.readline()[:-1])
finally:
s.outputlock.release()
self._log_con_handler.release()
def init_banner(s):
s._printData('initbanner', offlineimap.banner)
def init_banner(self):
self._printData('protocol', protocol)
self._printData('initbanner', offlineimap.banner)
def callhook(s, msg):
s._printData('callhook', msg)
def callhook(self, msg):
self._printData('callhook', msg)

View File

@ -1,6 +1,5 @@
# Noninteractive UI
# Copyright (C) 2002 John Goerzen
# <jgoerzen@complete.org>
# Copyright (C) 2002-2011 John Goerzen & contributors
#
# 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
@ -16,37 +15,15 @@
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
import sys
import time
import logging
from UIBase import UIBase
class Basic(UIBase):
def getpass(s, accountname, config, errmsg = None):
raise NotImplementedError, "Prompting for a password is not supported in noninteractive mode."
"""'Quiet' simply sets log level to INFO"""
def __init__(self, config, loglevel = logging.INFO):
return super(Basic, self).__init__(config, loglevel)
def _display(s, msg):
print msg
sys.stdout.flush()
def warn(s, msg, minor = 0):
warntxt = 'WARNING'
if minor:
warntxt = 'warning'
sys.stderr.write(warntxt + ": " + str(msg) + "\n")
def sleep(s, sleepsecs, siglistener):
if s.verbose >= 0:
s._msg("Sleeping for %d:%02d" % (sleepsecs / 60, sleepsecs % 60))
return UIBase.sleep(s, sleepsecs, siglistener)
def sleeping(s, sleepsecs, remainingsecs):
if sleepsecs > 0:
time.sleep(sleepsecs)
return 0
def locked(s):
s.warn("Another OfflineIMAP is running with the same metadatadir; exiting.")
class Quiet(Basic):
def __init__(s, config, verbose = -1):
Basic.__init__(s, config, verbose)
class Quiet(UIBase):
"""'Quiet' simply sets log level to WARNING"""
def __init__(self, config, loglevel = logging.WARNING):
return super(Quiet, self).__init__(config, loglevel)

View File

@ -1,6 +1,5 @@
# TTY UI
# Copyright (C) 2002 John Goerzen
# <jgoerzen@complete.org>
# Copyright (C) 2002-2011 John Goerzen & contributors
#
# 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
@ -15,53 +14,73 @@
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
from UIBase import UIBase
from getpass import getpass
import logging
import sys
from threading import Lock, currentThread
from getpass import getpass
from offlineimap import banner
from offlineimap.ui.UIBase import UIBase
class TTYFormatter(logging.Formatter):
"""Specific Formatter that adds thread information to the log output"""
def __init__(self, *args, **kwargs):
super(TTYFormatter, self).__init__(*args, **kwargs)
self._last_log_thread = None
def format(self, record):
"""Override format to add thread information"""
log_str = super(TTYFormatter, self).format(record)
# If msg comes from a different thread than our last, prepend
# thread info. Most look like 'Account sync foo' or 'Folder
# sync foo'.
t_name = record.threadName
if t_name == 'MainThread':
return log_str # main thread doesn't get things prepended
if t_name != self._last_log_thread:
self._last_log_thread = t_name
log_str = "%s:\n %s" % (t_name, log_str)
else:
log_str = " %s" % log_str
return log_str
class TTYUI(UIBase):
def __init__(s, config, verbose = 0):
UIBase.__init__(s, config, verbose)
s.iswaiting = 0
s.outputlock = Lock()
s._lastThreaddisplay = None
def setup_consolehandler(self):
"""Backend specific console handler
def isusable(s):
Sets up things and adds them to self.logger.
:returns: The logging.Handler() for console output"""
# create console handler with a higher log level
ch = logging.StreamHandler()
#ch.setLevel(logging.DEBUG)
# create formatter and add it to the handlers
self.formatter = TTYFormatter("%(message)s")
ch.setFormatter(self.formatter)
# add the handlers to the logger
self.logger.addHandler(ch)
self.logger.info(banner)
# init lock for console output
ch.createLock()
return ch
def isusable(self):
"""TTYUI is reported as usable when invoked on a terminal"""
return sys.stdout.isatty() and sys.stdin.isatty()
def _display(s, msg):
s.outputlock.acquire()
try:
#if the next output comes from a different thread than our last one
#add the info.
#Most look like 'account sync foo' or 'Folder sync foo'.
threadname = currentThread().getName()
if (threadname == s._lastThreaddisplay \
or threadname == 'MainThread'):
print " %s" % msg
else:
print "%s:\n %s" % (threadname, msg)
s._lastThreaddisplay = threadname
sys.stdout.flush()
finally:
s.outputlock.release()
def getpass(s, accountname, config, errmsg = None):
def getpass(self, accountname, config, errmsg = None):
"""TTYUI backend is capable of querying the password"""
if errmsg:
s._msg("%s: %s" % (accountname, errmsg))
s.outputlock.acquire()
self.warn("%s: %s" % (accountname, errmsg))
self._log_con_handler.acquire() # lock the console output
try:
return getpass("%s: Enter password: " % accountname)
return getpass("Enter password for account '%s': " % accountname)
finally:
s.outputlock.release()
self._log_con_handler.release()
def mainException(s):
if isinstance(sys.exc_info()[1], KeyboardInterrupt) and \
s.iswaiting:
sys.stdout.write("Timer interrupted at user request; program terminating. \n")
s.terminate()
def mainException(self):
if isinstance(sys.exc_info()[1], KeyboardInterrupt):
self.logger.warn("Timer interrupted at user request; program "
"terminating.\n")
self.terminate()
else:
UIBase.mainException(s)
UIBase.mainException(self)

View File

@ -15,12 +15,15 @@
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
import logging
import re
import time
import sys
import os
import traceback
import threading
from Queue import Queue
from collections import deque
import offlineimap
debugtypes = {'':'Other offlineimap related sync messages',
@ -38,54 +41,72 @@ def getglobalui():
global globalui
return globalui
class UIBase:
def __init__(s, config, verbose = 0):
s.verbose = verbose
s.config = config
s.debuglist = []
s.debugmessages = {}
s.debugmsglen = 50
s.threadaccounts = {}
class UIBase(object):
def __init__(self, config, loglevel = logging.INFO):
self.config = config
self.debuglist = []
"""list of debugtypes we are supposed to log"""
self.debugmessages = {}
"""debugmessages in a deque(v) per thread(k)"""
self.debugmsglen = 50
self.threadaccounts = {}
"""dict linking active threads (k) to account names (v)"""
s.acct_startimes = {}
self.acct_startimes = {}
"""linking active accounts with the time.time() when sync started"""
s.logfile = None
s.exc_queue = Queue()
self.logfile = None
self.exc_queue = Queue()
"""saves all occuring exceptions, so we can output them at the end"""
# create logger with 'OfflineImap' app
self.logger = logging.getLogger('OfflineImap')
self.logger.setLevel(loglevel)
self._log_con_handler = self.setup_consolehandler()
"""The console handler (we need access to be able to lock it)"""
################################################## UTILS
def _msg(s, msg):
"""Generic tool called when no other works."""
s._log(msg)
s._display(msg)
def setup_consolehandler(self):
"""Backend specific console handler
def _log(s, msg):
"""Log it to disk. Returns true if it wrote something; false
otherwise."""
if s.logfile:
s.logfile.write("%s: %s\n" % (threading.currentThread().getName(),
msg))
return 1
return 0
Sets up things and adds them to self.logger.
:returns: The logging.Handler() for console output"""
# create console handler with a higher log level
ch = logging.StreamHandler()
#ch.setLevel(logging.DEBUG)
# create formatter and add it to the handlers
self.formatter = logging.Formatter("%(message)s")
ch.setFormatter(self.formatter)
# add the handlers to the logger
self.logger.addHandler(ch)
self.logger.info(offlineimap.banner)
return ch
def setlogfd(s, logfd):
s.logfile = logfd
logfd.write("This is %s %s\n" % \
(offlineimap.__productname__,
offlineimap.__version__))
logfd.write("Python: %s\n" % sys.version)
logfd.write("Platform: %s\n" % sys.platform)
logfd.write("Args: %s\n" % sys.argv)
def setlogfile(self, logfile):
"""Create file handler which logs to file"""
fh = logging.FileHandler(logfile, 'wt')
#fh.setLevel(logging.DEBUG)
file_formatter = logging.Formatter("%(asctime)s %(levelname)s: "
"%(message)s", '%Y-%m-%d %H:%M:%S')
fh.setFormatter(file_formatter)
self.logger.addHandler(fh)
# write out more verbose initial info blurb on the log file
p_ver = ".".join([str(x) for x in sys.version_info[0:3]])
msg = "OfflineImap %s starting...\n Python: %s Platform: %s\n "\
"Args: %s" % (offlineimap.__version__, p_ver, sys.platform,
" ".join(sys.argv))
record = logging.LogRecord('OfflineImap', logging.INFO, __file__,
None, msg, None, None)
fh.emit(record)
def _display(s, msg):
def _msg(self, msg):
"""Display a message."""
raise NotImplementedError
# TODO: legacy function, rip out.
self.info(msg)
def warn(s, msg, minor = 0):
if minor:
s._msg("warning: " + msg)
else:
s._msg("WARNING: " + msg)
def info(self, msg):
"""Display a message."""
self.logger.info(msg)
def warn(self, msg, minor = 0):
self.logger.warning(msg)
def error(self, exc, exc_traceback=None, msg=None):
"""Log a message at severity level ERROR
@ -146,40 +167,43 @@ class UIBase:
return self.threadaccounts[thr]
return '*Control' # unregistered thread is '*Control'
def debug(s, debugtype, msg):
thisthread = threading.currentThread()
if s.debugmessages.has_key(thisthread):
s.debugmessages[thisthread].append("%s: %s" % (debugtype, msg))
else:
s.debugmessages[thisthread] = ["%s: %s" % (debugtype, msg)]
def debug(self, debugtype, msg):
cur_thread = threading.currentThread()
if not self.debugmessages.has_key(cur_thread):
# deque(..., self.debugmsglen) would be handy but was
# introduced in p2.6 only, so we'll need to work around and
# shorten our debugmsg list manually :-(
self.debugmessages[cur_thread] = deque()
self.debugmessages[cur_thread].append("%s: %s" % (debugtype, msg))
while len(s.debugmessages[thisthread]) > s.debugmsglen:
s.debugmessages[thisthread] = s.debugmessages[thisthread][1:]
# Shorten queue if needed
if len(self.debugmessages[cur_thread]) > self.debugmsglen:
self.debugmessages[cur_thread].popleft()
if debugtype in s.debuglist:
if not s._log("DEBUG[%s]: %s" % (debugtype, msg)):
s._display("DEBUG[%s]: %s" % (debugtype, msg))
if debugtype in self.debuglist: # log if we are supposed to do so
self.logger.debug("[%s]: %s" % (debugtype, msg))
def add_debug(s, debugtype):
def add_debug(self, debugtype):
global debugtypes
if debugtype in debugtypes:
if not debugtype in s.debuglist:
s.debuglist.append(debugtype)
s.debugging(debugtype)
if not debugtype in self.debuglist:
self.debuglist.append(debugtype)
self.debugging(debugtype)
else:
s.invaliddebug(debugtype)
self.invaliddebug(debugtype)
def debugging(s, debugtype):
def debugging(self, debugtype):
global debugtypes
s._msg("Now debugging for %s: %s" % (debugtype, debugtypes[debugtype]))
self.logger.debug("Now debugging for %s: %s" % (debugtype,
debugtypes[debugtype]))
def invaliddebug(s, debugtype):
s.warn("Invalid debug type: %s" % debugtype)
def invaliddebug(self, debugtype):
self.warn("Invalid debug type: %s" % debugtype)
def locked(s):
raise Exception, "Another OfflineIMAP is running with the same metadatadir; exiting."
def getnicename(s, object):
def getnicename(self, object):
"""Return the type of a repository or Folder as string
(IMAP, Gmail, Maildir, etc...)"""
@ -187,61 +211,73 @@ class UIBase:
# Strip off extra stuff.
return re.sub('(Folder|Repository)', '', prelimname)
def isusable(s):
def isusable(self):
"""Returns true if this UI object is usable in the current
environment. For instance, an X GUI would return true if it's
being run in X with a valid DISPLAY setting, and false otherwise."""
return 1
return True
################################################## INPUT
def getpass(s, accountname, config, errmsg = None):
raise NotImplementedError
def getpass(self, accountname, config, errmsg = None):
raise NotImplementedError("Prompting for a password is not supported"\
" in this UI backend.")
def folderlist(s, list):
return ', '.join(["%s[%s]" % (s.getnicename(x), x.getname()) for x in list])
def folderlist(self, list):
return ', '.join(["%s[%s]" % \
(self.getnicename(x), x.getname()) for x in list])
################################################## WARNINGS
def msgtoreadonly(s, destfolder, uid, content, flags):
if not (s.config.has_option('general', 'ignore-readonly') and s.config.getboolean("general", "ignore-readonly")):
s.warn("Attempted to synchronize message %d to folder %s[%s], but that folder is read-only. The message will not be copied to that folder." % \
(uid, s.getnicename(destfolder), destfolder.getname()))
def msgtoreadonly(self, destfolder, uid, content, flags):
if self.config.has_option('general', 'ignore-readonly') and \
self.config.getboolean('general', 'ignore-readonly'):
return
self.warn("Attempted to synchronize message %d to folder %s[%s], "
"but that folder is read-only. The message will not be "
"copied to that folder." % (
uid, self.getnicename(destfolder), destfolder))
def flagstoreadonly(s, destfolder, uidlist, flags):
if not (s.config.has_option('general', 'ignore-readonly') and s.config.getboolean("general", "ignore-readonly")):
s.warn("Attempted to modify flags for messages %s in folder %s[%s], but that folder is read-only. No flags have been modified for that message." % \
(str(uidlist), s.getnicename(destfolder), destfolder.getname()))
def flagstoreadonly(self, destfolder, uidlist, flags):
if self.config.has_option('general', 'ignore-readonly') and \
self.config.getboolean('general', 'ignore-readonly'):
return
self.warn("Attempted to modify flags for messages %s in folder %s[%s], "
"but that folder is read-only. No flags have been modified "
"for that message." % (
str(uidlist), self.getnicename(destfolder), destfolder))
def deletereadonly(s, destfolder, uidlist):
if not (s.config.has_option('general', 'ignore-readonly') and s.config.getboolean("general", "ignore-readonly")):
s.warn("Attempted to delete messages %s in folder %s[%s], but that folder is read-only. No messages have been deleted in that folder." % \
(str(uidlist), s.getnicename(destfolder), destfolder.getname()))
def deletereadonly(self, destfolder, uidlist):
if self.config.has_option('general', 'ignore-readonly') and \
self.config.getboolean('general', 'ignore-readonly'):
return
self.warn("Attempted to delete messages %s in folder %s[%s], but that "
"folder is read-only. No messages have been deleted in that "
"folder." % (str(uidlist), self.getnicename(destfolder),
destfolder))
################################################## MESSAGES
def init_banner(s):
def init_banner(self):
"""Called when the UI starts. Must be called before any other UI
call except isusable(). Displays the copyright banner. This is
where the UI should do its setup -- TK, for instance, would
create the application window here."""
if s.verbose >= 0:
s._msg(offlineimap.banner)
pass
def connecting(s, hostname, port):
def connecting(self, hostname, port):
"""Log 'Establishing connection to'"""
if s.verbose < 0: return
if not self.logger.isEnabledFor(logging.info): return
displaystr = ''
hostname = hostname if hostname else ''
port = "%s" % port if port else ''
if hostname:
displaystr = ' to %s:%s' % (hostname, port)
s._msg("Establishing connection%s" % displaystr)
self.logger.info("Establishing connection%s" % displaystr)
def acct(self, account):
"""Output that we start syncing an account (and start counting)"""
self.acct_startimes[account] = time.time()
if self.verbose >= 0:
self._msg("*** Processing account %s" % account)
self.logger.info("*** Processing account %s" % account)
def acctdone(self, account):
"""Output that we finished syncing an account (in which time)"""
@ -252,75 +288,63 @@ class UIBase:
def syncfolders(self, src_repo, dst_repo):
"""Log 'Copying folder structure...'"""
if self.verbose < 0: return
self.debug('', "Copying folder structure from %s to %s" % \
(src_repo, dst_repo))
if self.logger.isEnabledFor(logging.DEBUG):
self.debug('', "Copying folder structure from %s to %s" %\
(src_repo, dst_repo))
############################## Folder syncing
def syncingfolder(s, srcrepos, srcfolder, destrepos, destfolder):
def syncingfolder(self, srcrepos, srcfolder, destrepos, destfolder):
"""Called when a folder sync operation is started."""
if s.verbose >= 0:
s._msg("Syncing %s: %s -> %s" % (srcfolder.getname(),
s.getnicename(srcrepos),
s.getnicename(destrepos)))
self.logger.info("Syncing %s: %s -> %s" % (srcfolder,
self.getnicename(srcrepos),
self.getnicename(destrepos)))
def skippingfolder(s, folder):
def skippingfolder(self, folder):
"""Called when a folder sync operation is started."""
if s.verbose >= 0:
s._msg("Skipping %s (not changed)" % folder.getname())
self.logger.info("Skipping %s (not changed)" % folder)
def validityproblem(s, folder):
s.warn("UID validity problem for folder %s (repo %s) (saved %d; got %d); skipping it" % \
(folder.getname(), folder.getrepository().getname(),
def validityproblem(self, folder):
self.logger.warning("UID validity problem for folder %s (repo %s) "
"(saved %d; got %d); skipping it. Please see FAQ "
"and manual how to handle this." % \
(folder, folder.getrepository(),
folder.getsaveduidvalidity(), folder.getuidvalidity()))
def loadmessagelist(s, repos, folder):
if s.verbose > 0:
s._msg("Loading message list for %s[%s]" % (s.getnicename(repos),
folder.getname()))
def loadmessagelist(self, repos, folder):
self.logger.debug("Loading message list for %s[%s]" % (
self.getnicename(repos),
folder))
def messagelistloaded(s, repos, folder, count):
if s.verbose > 0:
s._msg("Message list for %s[%s] loaded: %d messages" % \
(s.getnicename(repos), folder.getname(), count))
def messagelistloaded(self, repos, folder, count):
self.logger.debug("Message list for %s[%s] loaded: %d messages" % (
self.getnicename(repos), folder, count))
############################## Message syncing
def syncingmessages(s, sr, sf, dr, df):
if s.verbose > 0:
s._msg("Syncing messages %s[%s] -> %s[%s]" % (s.getnicename(sr),
sf.getname(),
s.getnicename(dr),
df.getname()))
def syncingmessages(self, sr, srcfolder, dr, dstfolder):
self.logger.debug("Syncing messages %s[%s] -> %s[%s]" % (
self.getnicename(sr), srcfolder,
self.getnicename(dr), dstfolder))
def copyingmessage(self, uid, num, num_to_copy, src, destfolder):
"""Output a log line stating which message we copy"""
if self.verbose < 0: return
self._msg("Copy message %s (%d of %d) %s:%s -> %s" % (uid, num,
num_to_copy, src.repository, src, destfolder.repository))
self.logger.info("Copy message %s (%d of %d) %s:%s -> %s" % (
uid, num, num_to_copy, src.repository, src,
destfolder.repository))
def deletingmessage(s, uid, destlist):
if s.verbose >= 0:
ds = s.folderlist(destlist)
s._msg("Deleting message %d in %s" % (uid, ds))
def deletingmessages(self, uidlist, destlist):
ds = self.folderlist(destlist)
self.logger.info("Deleting %d messages (%s) in %s" % (
len(uidlist),
offlineimap.imaputil.uid_sequence(uidlist), ds))
def deletingmessages(s, uidlist, destlist):
if s.verbose >= 0:
ds = s.folderlist(destlist)
s._msg("Deleting %d messages (%s) in %s" % \
(len(uidlist),
offlineimap.imaputil.uid_sequence(uidlist),
ds))
def addingflags(self, uidlist, flags, dest):
self.logger.info("Adding flag %s to %d messages on %s" % (
", ".join(flags), len(uidlist), dest))
def addingflags(s, uidlist, flags, dest):
if s.verbose >= 0:
s._msg("Adding flag %s to %d messages on %s" % \
(", ".join(flags), len(uidlist), dest))
def deletingflags(s, uidlist, flags, dest):
if s.verbose >= 0:
s._msg("Deleting flag %s from %d messages on %s" % \
(", ".join(flags), len(uidlist), dest))
def deletingflags(self, uidlist, flags, dest):
self.logger.info("Deleting flag %s from %d messages on %s" % (
", ".join(flags), len(uidlist), dest))
def serverdiagnostics(self, repository, type):
"""Connect to repository and output useful information for debugging"""
@ -371,69 +395,68 @@ class UIBase:
################################################## Threads
def getThreadDebugLog(s, thread):
if s.debugmessages.has_key(thread):
def getThreadDebugLog(self, thread):
if self.debugmessages.has_key(thread):
message = "\nLast %d debug messages logged for %s prior to exception:\n"\
% (len(s.debugmessages[thread]), thread.getName())
message += "\n".join(s.debugmessages[thread])
% (len(self.debugmessages[thread]), thread.getName())
message += "\n".join(self.debugmessages[thread])
else:
message = "\nNo debug messages were logged for %s." % \
thread.getName()
return message
def delThreadDebugLog(s, thread):
if s.debugmessages.has_key(thread):
del s.debugmessages[thread]
def delThreadDebugLog(self, thread):
if thread in self.debugmessages:
del self.debugmessages[thread]
def getThreadExceptionString(s, thread):
def getThreadExceptionString(self, thread):
message = "Thread '%s' terminated with exception:\n%s" % \
(thread.getName(), thread.getExitStackTrace())
message += "\n" + s.getThreadDebugLog(thread)
message += "\n" + self.getThreadDebugLog(thread)
return message
def threadException(s, thread):
def threadException(self, thread):
"""Called when a thread has terminated with an exception.
The argument is the ExitNotifyThread that has so terminated."""
s._msg(s.getThreadExceptionString(thread))
s.delThreadDebugLog(thread)
s.terminate(100)
self.warn(self.getThreadExceptionString(thread))
self.delThreadDebugLog(thread)
self.terminate(100)
def terminate(self, exitstatus = 0, errortitle = None, errormsg = None):
"""Called to terminate the application."""
#print any exceptions that have occurred over the run
if not self.exc_queue.empty():
self._msg("\nERROR: Exceptions occurred during the run!")
self.warn("ERROR: Exceptions occurred during the run!")
while not self.exc_queue.empty():
msg, exc, exc_traceback = self.exc_queue.get()
if msg:
self._msg("ERROR: %s\n %s" % (msg, exc))
self.warn("ERROR: %s\n %s" % (msg, exc))
else:
self._msg("ERROR: %s" % (exc))
self.warn("ERROR: %s" % (exc))
if exc_traceback:
self._msg("\nTraceback:\n%s" %"".join(
self.warn("\nTraceback:\n%s" %"".join(
traceback.format_tb(exc_traceback)))
if errormsg and errortitle:
sys.stderr.write('ERROR: %s\n\n%s\n'%(errortitle, errormsg))
self.warn('ERROR: %s\n\n%s\n'%(errortitle, errormsg))
elif errormsg:
sys.stderr.write('%s\n' % errormsg)
self.warn('%s\n' % errormsg)
sys.exit(exitstatus)
def threadExited(s, thread):
def threadExited(self, thread):
"""Called when a thread has exited normally. Many UIs will
just ignore this."""
s.delThreadDebugLog(thread)
s.unregisterthread(thread)
self.delThreadDebugLog(thread)
self.unregisterthread(thread)
################################################## Hooks
def callhook(s, msg):
if s.verbose >= 0:
s._msg(msg)
def callhook(self, msg):
self.info(msg)
################################################## Other
def sleep(s, sleepsecs, account):
def sleep(self, sleepsecs, account):
"""This function does not actually output anything, but handles
the overall sleep, dealing with updates as necessary. It will,
however, call sleeping() which DOES output something.
@ -446,12 +469,12 @@ class UIBase:
if account.get_abort_event():
abortsleep = True
else:
abortsleep = s.sleeping(10, sleepsecs)
sleepsecs -= 10
s.sleeping(0, 0) # Done sleeping.
abortsleep = self.sleeping(10, sleepsecs)
sleepsecs -= 10
self.sleeping(0, 0) # Done sleeping.
return abortsleep
def sleeping(s, sleepsecs, remainingsecs):
def sleeping(self, sleepsecs, remainingsecs):
"""Sleep for sleepsecs, display remainingsecs to go.
Does nothing if sleepsecs <= 0.
@ -463,6 +486,7 @@ class UIBase:
"""
if sleepsecs > 0:
if remainingsecs//60 != (remainingsecs-sleepsecs)//60:
s._msg("Next refresh in %.1f minutes" % (remainingsecs/60.0))
self.logger.info("Next refresh in %.1f minutes" % (
remainingsecs/60.0))
time.sleep(sleepsecs)
return 0

View File

@ -1,5 +1,5 @@
# UI module
# Copyright (C) 2010 Sebastian Spaeth <Sebastian@SSpaeth.de>
# Copyright (C) 2010-2011 Sebastian Spaeth & contributors
#
# 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