docker-offlineimap/offlineimap/ui/UIBase.py

377 lines
14 KiB
Python
Raw Normal View History

2002-06-21 07:29:12 +02:00
# UI base class
# Copyright (C) 2002 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.
2002-06-21 07:29:12 +02:00
#
# 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
2006-08-12 06:15:55 +02:00
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
2002-06-21 07:29:12 +02:00
import re
import time
import sys
import traceback
import threading
from StringIO import StringIO
Patch for signal handling to start a sync by Jim Pryor Here's the way I'd like to use offlineimap on my laptop: 1. Have a regular cron job running infrequently. The cron job checks to see if I'm online, plugged in, and that no other copy of offlineimap is running. If all of these conditions are satisfied, it runs offlineimap just once: "offlineimap -o -u Noninteractive.Quiet" 2. When I start up mutt, I do it by calling a wrapper script that delays until cron-started copies of offlineimap have finished, then starts offlineimap on its regular, stay-alive and keep checking schedule. When I quit mutt, the wrapper script tells offlineimap to stop. This way I get frequent regular checks while I have mutt running, but I don't waste my battery/cpu checking frequently for mail when I'm not interested in it. To make this work, though, it'd be nicer if it were easier to tell offlineimap, from the outside, things like "terminate cleanly now" and "when you've finished synching, then terminate instead of sleeping and synching again." OK, to put my money where my mouth is, I attach two patches against offlineimap 6.0.3. The first, "cleanup.patch", cleans up a few spots that tend to throw exceptions for me as offlineimap is exiting from a KeyboardInterrupt. The second adds signaling capabilities to offlineimap. * sending a SIGTERM tells offlineimap to terminate immediately but cleanly, just as if "q" had been pressed in the GUI interface * sending a SIGUSR1 tells every account to do a full sync asap: if it's sleeping, then wake up and do the sync now. If it's mid-sync, then re-synch any folders whose syncing has already been started or completed, and continue to synch the other, queued but not-yet-synched folders. * sending a SIGHUP tells every account to die as soon as it can (but not immediately: only after finishing any synch it's now engaged in) * sending a SIGUSR2 tells every account to do a full sync asap (as with SIGUSR1), then die It's tricky to mix signals with threads, but I think I've done this correctly. I've been using it now for a few weeks without any obvious problems. But I'm passing it on so that others can review the code and test it out on their systems. I developed the patch when I was running Python 2.5.2, but to my knowledge I don't use any Python 2.5-specific code. Now I'm using the patch with Python 2.6. Although I said "without any obvious problems," let me confess that I'm seeing offlineimap regularly choke when I do things like this: start up my offlineimap-wrapped copy of mutt, wait a while, put the machine to sleep (not sure if offlineimap is active in the background or idling), move to a different spot, wake the machine up again and it acquires a new network, sometimes a wired network instead of wifi. Offlineimap doesn't like that so much. I don't yet have any reason to think the problems here come from my patches. But I'm just acknowledging them, so that if others are able to use offlineimap without any difficulty in situations like I described, then maybe the fault is with my patches.
2008-12-01 23:13:16 +01:00
from Queue import Empty
import offlineimap
2002-06-21 07:29:12 +02:00
debugtypes = {'':'Other offlineimap related sync messages',
'imap': 'IMAP protocol debugging',
'maildir': 'Maildir repository debugging',
'thread': 'Threading debugging'}
2007-07-05 15:49:54 +02:00
globalui = None
def setglobalui(newui):
"""Set the global ui object to be used for logging"""
2007-07-05 15:49:54 +02:00
global globalui
globalui = newui
def getglobalui():
"""Return the current ui object"""
2007-07-05 15:49:54 +02:00
global globalui
return globalui
2002-06-21 07:29:12 +02:00
class UIBase:
def __init__(s, config, verbose = 0):
s.verbose = verbose
s.config = config
s.debuglist = []
2007-07-05 15:49:54 +02:00
s.debugmessages = {}
s.debugmsglen = 50
s.threadaccounts = {}
s.logfile = None
2002-06-21 07:29:12 +02:00
################################################## UTILS
def _msg(s, msg):
"""Generic tool called when no other works."""
s._log(msg)
s._display(msg)
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
def setlogfd(s, logfd):
s.logfile = logfd
2006-10-19 03:04:28 +02:00
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 _display(s, msg):
"""Display a message."""
raise NotImplementedError
2002-06-21 07:29:12 +02:00
2002-10-30 05:26:49 +01:00
def warn(s, msg, minor = 0):
if minor:
s._msg("warning: " + msg)
else:
s._msg("WARNING: " + msg)
2002-06-21 07:29:12 +02:00
2007-07-05 15:49:54 +02:00
def registerthread(s, account):
"""Provides a hint to UIs about which account this particular
thread is processing."""
2007-07-05 15:49:54 +02:00
if s.threadaccounts.has_key(threading.currentThread()):
raise ValueError, "Thread %s already registered (old %s, new %s)" %\
2007-07-05 15:49:54 +02:00
(threading.currentThread().getName(),
s.getthreadaccount(s), account)
2007-07-05 15:49:54 +02:00
s.threadaccounts[threading.currentThread()] = account
s.debug('thread', "Register new thread '%s' (account '%s')" %\
(threading.currentThread().getName(), account))
2007-07-05 15:49:54 +02:00
def unregisterthread(s, thr):
"""Recognizes a thread has exited."""
2007-07-05 15:49:54 +02:00
if s.threadaccounts.has_key(thr):
del s.threadaccounts[thr]
s.debug('thread', "Unregister thread '%s'" % thr.getName())
def getthreadaccount(s, thr = None):
if not thr:
thr = threading.currentThread()
if s.threadaccounts.has_key(thr):
return s.threadaccounts[thr]
return '*Control'
2007-07-05 15:49:54 +02:00
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)]
while len(s.debugmessages[thisthread]) > s.debugmsglen:
s.debugmessages[thisthread] = s.debugmessages[thisthread][1:]
if debugtype in s.debuglist:
if not s._log("DEBUG[%s]: %s" % (debugtype, msg)):
s._display("DEBUG[%s]: %s" % (debugtype, msg))
def add_debug(s, debugtype):
global debugtypes
if debugtype in debugtypes:
if not debugtype in s.debuglist:
s.debuglist.append(debugtype)
s.debugging(debugtype)
else:
s.invaliddebug(debugtype)
def debugging(s, debugtype):
global debugtypes
s._msg("Now debugging for %s: %s" % (debugtype, debugtypes[debugtype]))
2007-07-05 15:49:54 +02:00
def invaliddebug(s, debugtype):
s.warn("Invalid debug type: %s" % debugtype)
def locked(s):
raise Exception, "Another OfflineIMAP is running with the same metadatadir; exiting."
2007-07-05 15:49:54 +02:00
def getnicename(s, object):
prelimname = str(object.__class__).split('.')[-1]
# Strip off extra stuff.
return re.sub('(Folder|Repository)', '', prelimname)
def isusable(s):
"""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
2002-06-21 07:29:12 +02:00
################################################## INPUT
2007-07-05 15:49:54 +02:00
def getpass(s, accountname, config, errmsg = None):
raise NotImplementedError
2002-06-21 07:29:12 +02:00
2002-06-21 08:51:21 +02:00
def folderlist(s, list):
return ', '.join(["%s[%s]" % (s.getnicename(x), x.getname()) for x in list])
################################################## WARNINGS
2007-07-05 15:49:54 +02:00
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." % \
2007-07-05 15:49:54 +02:00
(uid, s.getnicename(destfolder), destfolder.getname()))
2007-07-05 15:49:54 +02:00
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 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()))
2002-06-21 07:29:12 +02:00
################################################## MESSAGES
def init_banner(s):
"""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)
2002-06-21 07:29:12 +02:00
def connecting(s, hostname, port):
if s.verbose < 0:
return
if hostname == None:
hostname = ''
if port != None:
port = ":%s" % str(port)
displaystr = ' to %s%s.' % (hostname, port)
if hostname == '' and port == None:
displaystr = '.'
s._msg("Establishing connection" + displaystr)
2002-06-21 07:29:12 +02:00
def acct(s, accountname):
if s.verbose >= 0:
s._msg("***** Processing account %s" % accountname)
2002-06-21 07:29:12 +02:00
def acctdone(s, accountname):
if s.verbose >= 0:
s._msg("***** Finished processing account " + accountname)
2002-06-21 07:29:12 +02:00
def syncfolders(s, srcrepos, destrepos):
if s.verbose >= 0:
s._msg("Copying folder structure from %s to %s" % \
(s.getnicename(srcrepos), s.getnicename(destrepos)))
2002-06-21 07:29:12 +02:00
############################## Folder syncing
def syncingfolder(s, 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)))
2002-06-21 07:29:12 +02:00
Daniel Jacobowitz patches fixes deb#433732 Date: Sun, 30 Sep 2007 13:54:56 -0400 From: Daniel Jacobowitz <drow@false.org> To: offlineimap@complete.org Subject: Assorted patches Here's the result of a lazy Sunday hacking on offlineimap. Sorry for not breaking this into multiple patches. They're mostly logically independent so just ask if that would make a difference. First, a new -q (quick) option. The quick option means to only update folders that seem to have had significant changes. For Maildir, any change to any message UID or flags is significant, because checking the flags doesn't add a significant cost. For IMAP, only a change to the total number of messages or a change in the UID of the most recent message is significant. This should catch everything except for flags changes. The difference in bandwidth is astonishing: a quick sync takes 80K instead of 5.3MB, and 28 seconds instead of 90. There's a configuration variable that lets you say every tenth sync should update flags, but let all the intervening ones be lighter. Second, a fix to the UID validity problems many people have been reporting with Courier. As discussed in Debian bug #433732, I changed the UID validity check to use SELECT unless the server complains that the folder is read-only. This avoids the Courier bug (see the Debian log for more details). This won't fix existing validity errors, you need to remove the local status and validity files by hand and resync. Third, some speedups in Maildir checking. It's still pretty slow due to a combination of poor performance in os.listdir (never reads more than 4K of directory entries at a time) and some semaphore that leads to lots of futex wake operations, but at least this saves 20% or so of the CPU time running offlineimap on a single folder: Time with quick refresh and md5 in loop: 4.75s user 0.46s system 12% cpu 41.751 total Time with quick refresh and md5 out of loop: 4.38s user 0.50s system 14% cpu 34.799 total Time using string compare to check folder: 4.11s user 0.47s system 13% cpu 34.788 total And fourth, some display fixes for Curses.Blinkenlights. I made warnings more visible, made the new quick sync message cyan, and made all not explicitly colored messages grey. That last one was really bugging me. Any time OfflineIMAP printed a warning in this UI, it had even odds of coming out black on black! Anyway, I hope these are useful. I'm happy to revise them if you see a problem. -- Daniel Jacobowitz CodeSourcery
2007-10-01 23:20:37 +02:00
def skippingfolder(s, folder):
"""Called when a folder sync operation is started."""
if s.verbose >= 0:
s._msg("Skipping %s (not changed)" % folder.getname())
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(),
folder.getsaveduidvalidity(), folder.getuidvalidity()))
2002-06-21 07:29:12 +02:00
def loadmessagelist(s, repos, folder):
if s.verbose > 0:
s._msg("Loading message list for %s[%s]" % (s.getnicename(repos),
folder.getname()))
2002-06-21 07:29:12 +02:00
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))
2002-06-21 07:29:12 +02:00
############################## 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()))
2002-06-21 07:29:12 +02:00
def copyingmessage(s, uid, src, destlist):
if s.verbose >= 0:
ds = s.folderlist(destlist)
s._msg("Copy message %d %s[%s] -> %s" % (uid, s.getnicename(src),
src.getname(), ds))
2002-06-21 07:29:12 +02:00
def deletingmessage(s, uid, destlist):
if s.verbose >= 0:
ds = s.folderlist(destlist)
s._msg("Deleting message %d in %s" % (uid, ds))
2002-06-21 07:29:12 +02:00
def deletingmessages(s, uidlist, destlist):
if s.verbose >= 0:
ds = s.folderlist(destlist)
s._msg("Deleting %d messages (%s) in %s" % \
(len(uidlist),
", ".join([str(u) for u in uidlist]),
ds))
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))
2002-06-21 07:29:12 +02:00
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))
2002-06-21 07:29:12 +02:00
################################################## Threads
def getThreadDebugLog(s, thread):
if s.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])
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 getThreadExceptionString(s, thread):
message = "Thread '%s' terminated with exception:\n%s" % \
(thread.getName(), thread.getExitStackTrace())
message += "\n" + s.getThreadDebugLog(thread)
return message
def threadException(s, 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)
def getMainExceptionString(s):
sbuf = StringIO()
traceback.print_exc(file = sbuf)
return "Main program terminated with exception:\n" + \
sbuf.getvalue() + "\n" + \
s.getThreadDebugLog(threading.currentThread())
def mainException(s):
s._msg(s.getMainExceptionString())
def terminate(s, exitstatus = 0, errortitle = None, errormsg = None):
"""Called to terminate the application."""
if errormsg <> None:
if errortitle <> None:
sys.stderr.write('ERROR: %s\n\n%s\n'%(errortitle, errormsg))
else:
sys.stderr.write('%s\n' % errormsg)
sys.exit(exitstatus)
def threadExited(s, thread):
"""Called when a thread has exited normally. Many UIs will
just ignore this."""
s.delThreadDebugLog(thread)
s.unregisterthread(thread)
################################################## Hooks
def callhook(s, msg):
if s.verbose >= 0:
s._msg(msg)
2002-06-21 09:25:24 +02:00
################################################## Other
2002-06-21 07:29:12 +02:00
Patch for signal handling to start a sync by Jim Pryor Here's the way I'd like to use offlineimap on my laptop: 1. Have a regular cron job running infrequently. The cron job checks to see if I'm online, plugged in, and that no other copy of offlineimap is running. If all of these conditions are satisfied, it runs offlineimap just once: "offlineimap -o -u Noninteractive.Quiet" 2. When I start up mutt, I do it by calling a wrapper script that delays until cron-started copies of offlineimap have finished, then starts offlineimap on its regular, stay-alive and keep checking schedule. When I quit mutt, the wrapper script tells offlineimap to stop. This way I get frequent regular checks while I have mutt running, but I don't waste my battery/cpu checking frequently for mail when I'm not interested in it. To make this work, though, it'd be nicer if it were easier to tell offlineimap, from the outside, things like "terminate cleanly now" and "when you've finished synching, then terminate instead of sleeping and synching again." OK, to put my money where my mouth is, I attach two patches against offlineimap 6.0.3. The first, "cleanup.patch", cleans up a few spots that tend to throw exceptions for me as offlineimap is exiting from a KeyboardInterrupt. The second adds signaling capabilities to offlineimap. * sending a SIGTERM tells offlineimap to terminate immediately but cleanly, just as if "q" had been pressed in the GUI interface * sending a SIGUSR1 tells every account to do a full sync asap: if it's sleeping, then wake up and do the sync now. If it's mid-sync, then re-synch any folders whose syncing has already been started or completed, and continue to synch the other, queued but not-yet-synched folders. * sending a SIGHUP tells every account to die as soon as it can (but not immediately: only after finishing any synch it's now engaged in) * sending a SIGUSR2 tells every account to do a full sync asap (as with SIGUSR1), then die It's tricky to mix signals with threads, but I think I've done this correctly. I've been using it now for a few weeks without any obvious problems. But I'm passing it on so that others can review the code and test it out on their systems. I developed the patch when I was running Python 2.5.2, but to my knowledge I don't use any Python 2.5-specific code. Now I'm using the patch with Python 2.6. Although I said "without any obvious problems," let me confess that I'm seeing offlineimap regularly choke when I do things like this: start up my offlineimap-wrapped copy of mutt, wait a while, put the machine to sleep (not sure if offlineimap is active in the background or idling), move to a different spot, wake the machine up again and it acquires a new network, sometimes a wired network instead of wifi. Offlineimap doesn't like that so much. I don't yet have any reason to think the problems here come from my patches. But I'm just acknowledging them, so that if others are able to use offlineimap without any difficulty in situations like I described, then maybe the fault is with my patches.
2008-12-01 23:13:16 +01:00
def sleep(s, sleepsecs, siglistener):
"""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.
Returns 0 if timeout expired, 1 if there is a request to cancel
the timer, and 2 if there is a request to abort the program."""
abortsleep = 0
while sleepsecs > 0 and not abortsleep:
Patch for signal handling to start a sync by Jim Pryor Here's the way I'd like to use offlineimap on my laptop: 1. Have a regular cron job running infrequently. The cron job checks to see if I'm online, plugged in, and that no other copy of offlineimap is running. If all of these conditions are satisfied, it runs offlineimap just once: "offlineimap -o -u Noninteractive.Quiet" 2. When I start up mutt, I do it by calling a wrapper script that delays until cron-started copies of offlineimap have finished, then starts offlineimap on its regular, stay-alive and keep checking schedule. When I quit mutt, the wrapper script tells offlineimap to stop. This way I get frequent regular checks while I have mutt running, but I don't waste my battery/cpu checking frequently for mail when I'm not interested in it. To make this work, though, it'd be nicer if it were easier to tell offlineimap, from the outside, things like "terminate cleanly now" and "when you've finished synching, then terminate instead of sleeping and synching again." OK, to put my money where my mouth is, I attach two patches against offlineimap 6.0.3. The first, "cleanup.patch", cleans up a few spots that tend to throw exceptions for me as offlineimap is exiting from a KeyboardInterrupt. The second adds signaling capabilities to offlineimap. * sending a SIGTERM tells offlineimap to terminate immediately but cleanly, just as if "q" had been pressed in the GUI interface * sending a SIGUSR1 tells every account to do a full sync asap: if it's sleeping, then wake up and do the sync now. If it's mid-sync, then re-synch any folders whose syncing has already been started or completed, and continue to synch the other, queued but not-yet-synched folders. * sending a SIGHUP tells every account to die as soon as it can (but not immediately: only after finishing any synch it's now engaged in) * sending a SIGUSR2 tells every account to do a full sync asap (as with SIGUSR1), then die It's tricky to mix signals with threads, but I think I've done this correctly. I've been using it now for a few weeks without any obvious problems. But I'm passing it on so that others can review the code and test it out on their systems. I developed the patch when I was running Python 2.5.2, but to my knowledge I don't use any Python 2.5-specific code. Now I'm using the patch with Python 2.6. Although I said "without any obvious problems," let me confess that I'm seeing offlineimap regularly choke when I do things like this: start up my offlineimap-wrapped copy of mutt, wait a while, put the machine to sleep (not sure if offlineimap is active in the background or idling), move to a different spot, wake the machine up again and it acquires a new network, sometimes a wired network instead of wifi. Offlineimap doesn't like that so much. I don't yet have any reason to think the problems here come from my patches. But I'm just acknowledging them, so that if others are able to use offlineimap without any difficulty in situations like I described, then maybe the fault is with my patches.
2008-12-01 23:13:16 +01:00
try:
abortsleep = siglistener.get_nowait()
# retrieved signal while sleeping: 1 means immediately resynch, 2 means immediately die
except Empty:
# no signal
abortsleep = s.sleeping(10, sleepsecs)
sleepsecs -= 10
s.sleeping(0, 0) # Done sleeping.
return abortsleep
2002-06-21 09:25:24 +02:00
def sleeping(s, sleepsecs, remainingsecs):
"""Sleep for sleepsecs, display remainingsecs to go.
2002-06-21 09:25:24 +02:00
Does nothing if sleepsecs <= 0.
Display a message on the screen every 10 seconds.
This implementation in UIBase does not support this, but some
implementations return 0 for successful sleep and 1 for an
'abort', ie a request to sync immediately.
"""
2002-06-21 09:25:24 +02:00
if sleepsecs > 0:
if remainingsecs % 10 == 0:
s._msg("Next refresh in %d seconds" % remainingsecs)
2002-06-21 09:25:24 +02:00
time.sleep(sleepsecs)
return 0