UIBase.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. # UI base class
  2. # Copyright (C) 2002-2016 John Goerzen & contributors.
  3. #
  4. # This program is free software; you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License as published by
  6. # the Free Software Foundation; either version 2 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  17. import logging
  18. import logging.handlers
  19. import re
  20. import time
  21. import sys
  22. import traceback
  23. import threading
  24. try:
  25. from Queue import Queue
  26. except ImportError: # python3
  27. from queue import Queue
  28. from collections import deque
  29. import offlineimap
  30. from offlineimap.error import OfflineImapError
  31. debugtypes = {'':'Other offlineimap related sync messages',
  32. 'imap': 'IMAP protocol debugging',
  33. 'maildir': 'Maildir repository debugging',
  34. 'thread': 'Threading debugging'}
  35. globalui = None
  36. def setglobalui(newui):
  37. """Set the global ui object to be used for logging."""
  38. global globalui
  39. globalui = newui
  40. def getglobalui():
  41. """Return the current ui object."""
  42. global globalui
  43. return globalui
  44. class UIBase(object):
  45. def __init__(self, config, loglevel=logging.INFO):
  46. self.config = config
  47. # Is this a 'dryrun'?
  48. self.dryrun = config.getdefaultboolean('general', 'dry-run', False)
  49. self.debuglist = []
  50. # list of debugtypes we are supposed to log
  51. self.debugmessages = {}
  52. # debugmessages in a deque(v) per thread(k)
  53. self.debugmsglen = 15
  54. self.threadaccounts = {}
  55. # dict linking active threads (k) to account names (v)
  56. self.acct_startimes = {}
  57. # linking active accounts with the time.time() when sync started
  58. self.logfile = None
  59. self.exc_queue = Queue()
  60. # saves all occuring exceptions, so we can output them at the end
  61. self.uidval_problem = False
  62. # at least one folder skipped due to UID validity problem
  63. # create logger with 'OfflineImap' app
  64. self.logger = logging.getLogger('OfflineImap')
  65. self.logger.setLevel(loglevel)
  66. self._log_con_handler = self.setup_consolehandler()
  67. """The console handler (we need access to be able to lock it)."""
  68. ################################################## UTILS
  69. def setup_consolehandler(self):
  70. """Backend specific console handler.
  71. Sets up things and adds them to self.logger.
  72. :returns: The logging.Handler() for console output"""
  73. # create console handler with a higher log level
  74. ch = logging.StreamHandler(sys.stdout)
  75. #ch.setLevel(logging.DEBUG)
  76. # create formatter and add it to the handlers
  77. self.formatter = logging.Formatter("%(message)s")
  78. ch.setFormatter(self.formatter)
  79. # add the handlers to the logger
  80. self.logger.addHandler(ch)
  81. self.logger.info(offlineimap.banner)
  82. return ch
  83. def setup_sysloghandler(self):
  84. """Backend specific syslog handler."""
  85. # create syslog handler
  86. ch = logging.handlers.SysLogHandler('/dev/log')
  87. # create formatter and add it to the handlers
  88. self.formatter = logging.Formatter("%(message)s")
  89. ch.setFormatter(self.formatter)
  90. # add the handlers to the logger
  91. self.logger.addHandler(ch)
  92. def setlogfile(self, logfile):
  93. """Create file handler which logs to file."""
  94. fh = logging.FileHandler(logfile, 'at')
  95. #fh.setLevel(logging.DEBUG)
  96. file_formatter = logging.Formatter("%(asctime)s %(levelname)s: "
  97. "%(message)s", '%Y-%m-%d %H:%M:%S')
  98. fh.setFormatter(file_formatter)
  99. self.logger.addHandler(fh)
  100. # write out more verbose initial info blurb on the log file
  101. p_ver = ".".join([str(x) for x in sys.version_info[0:3]])
  102. msg = "OfflineImap %s starting...\n Python: %s Platform: %s\n "\
  103. "Args: %s"% (offlineimap.__version__, p_ver, sys.platform,
  104. " ".join(sys.argv))
  105. record = logging.LogRecord('OfflineImap', logging.INFO, __file__,
  106. None, msg, None, None)
  107. fh.emit(record)
  108. def _msg(self, msg):
  109. """Display a message."""
  110. # TODO: legacy function, rip out.
  111. self.info(msg)
  112. def info(self, msg):
  113. """Display a message."""
  114. self.logger.info(msg)
  115. def warn(self, msg, minor=0):
  116. self.logger.warning(msg)
  117. def error(self, exc, exc_traceback=None, msg=None):
  118. """Log a message at severity level ERROR.
  119. Log Exception 'exc' to error log, possibly prepended by a preceding
  120. error "msg", detailing at what point the error occurred.
  121. In debug mode, we also output the full traceback that occurred
  122. if one has been passed in via sys.info()[2].
  123. Also save the Exception to a stack that can be output at the end
  124. of the sync run when offlineiamp exits. It is recommended to
  125. always pass in exceptions if possible, so we can give the user
  126. the best debugging info.
  127. We are always pushing tracebacks to the exception queue to
  128. make them to be output at the end of the run to allow users
  129. pass sensible diagnostics to the developers or to solve
  130. problems by themselves.
  131. One example of such a call might be:
  132. ui.error(exc, sys.exc_info()[2], msg="While syncing Folder %s in "
  133. "repo %s")
  134. """
  135. if msg:
  136. self.logger.error("ERROR: %s\n %s"% (msg, exc))
  137. else:
  138. self.logger.error("ERROR: %s"% (exc))
  139. instant_traceback = exc_traceback
  140. if not self.debuglist:
  141. # only output tracebacks in debug mode
  142. instant_traceback = None
  143. # push exc on the queue for later output
  144. self.exc_queue.put((msg, exc, exc_traceback))
  145. if instant_traceback:
  146. self.logger.error(traceback.format_tb(instant_traceback))
  147. def registerthread(self, account):
  148. """Register current thread as being associated with an account name."""
  149. cur_thread = threading.currentThread()
  150. if cur_thread in self.threadaccounts:
  151. # was already associated with an old account, update info
  152. self.debug('thread', "Register thread '%s' (previously '%s', now "
  153. "'%s')"% (cur_thread.getName(),
  154. self.getthreadaccount(cur_thread), account))
  155. else:
  156. self.debug('thread', "Register new thread '%s' (account '%s')"%
  157. (cur_thread.getName(), account))
  158. self.threadaccounts[cur_thread] = account
  159. def unregisterthread(self, thr):
  160. """Unregister a thread as being associated with an account name."""
  161. if thr in self.threadaccounts:
  162. del self.threadaccounts[thr]
  163. self.debug('thread', "Unregister thread '%s'"% thr.getName())
  164. def getthreadaccount(self, thr=None):
  165. """Get Account() for a thread (current if None)
  166. If no account has been registered with this thread, return 'None'."""
  167. if thr == None:
  168. thr = threading.currentThread()
  169. if thr in self.threadaccounts:
  170. return self.threadaccounts[thr]
  171. return None
  172. def debug(self, debugtype, msg):
  173. cur_thread = threading.currentThread()
  174. if not cur_thread in self.debugmessages:
  175. # deque(..., self.debugmsglen) would be handy but was
  176. # introduced in p2.6 only, so we'll need to work around and
  177. # shorten our debugmsg list manually :-(
  178. self.debugmessages[cur_thread] = deque()
  179. self.debugmessages[cur_thread].append("%s: %s" % (debugtype, msg))
  180. # Shorten queue if needed
  181. if len(self.debugmessages[cur_thread]) > self.debugmsglen:
  182. self.debugmessages[cur_thread].popleft()
  183. if debugtype in self.debuglist: # log if we are supposed to do so
  184. self.logger.debug("[%s]: %s" % (debugtype, msg))
  185. def add_debug(self, debugtype):
  186. global debugtypes
  187. if debugtype in debugtypes:
  188. if not debugtype in self.debuglist:
  189. self.debuglist.append(debugtype)
  190. self.debugging(debugtype)
  191. else:
  192. self.invaliddebug(debugtype)
  193. def debugging(self, debugtype):
  194. global debugtypes
  195. self.logger.debug("Now debugging for %s: %s" % (debugtype,
  196. debugtypes[debugtype]))
  197. def invaliddebug(self, debugtype):
  198. self.warn("Invalid debug type: %s" % debugtype)
  199. def getnicename(self, object):
  200. """Return the type of a repository or Folder as string.
  201. (IMAP, Gmail, Maildir, etc...)"""
  202. prelimname = object.__class__.__name__.split('.')[-1]
  203. # Strip off extra stuff.
  204. return re.sub('(Folder|Repository)', '', prelimname)
  205. def isusable(self):
  206. """Returns true if this UI object is usable in the current
  207. environment. For instance, an X GUI would return true if it's
  208. being run in X with a valid DISPLAY setting, and false otherwise."""
  209. return True
  210. ################################################## INPUT
  211. def getpass(self, accountname, config, errmsg = None):
  212. raise NotImplementedError("Prompting for a password is not supported"
  213. " in this UI backend.")
  214. def folderlist(self, folder_list):
  215. return ', '.join(["%s[%s]"% \
  216. (self.getnicename(x), x.getname()) for x in folder_list])
  217. ################################################## WARNINGS
  218. def msgtoreadonly(self, destfolder, uid, content, flags):
  219. if self.config.has_option('general', 'ignore-readonly') and \
  220. self.config.getboolean('general', 'ignore-readonly'):
  221. return
  222. self.warn("Attempted to synchronize message %d to folder %s[%s], "
  223. "but that folder is read-only. The message will not be "
  224. "copied to that folder."% (
  225. uid, self.getnicename(destfolder), destfolder))
  226. def flagstoreadonly(self, destfolder, uidlist, flags):
  227. if self.config.has_option('general', 'ignore-readonly') and \
  228. self.config.getboolean('general', 'ignore-readonly'):
  229. return
  230. self.warn("Attempted to modify flags for messages %s in folder %s[%s], "
  231. "but that folder is read-only. No flags have been modified "
  232. "for that message."% (
  233. str(uidlist), self.getnicename(destfolder), destfolder))
  234. def labelstoreadonly(self, destfolder, uidlist, labels):
  235. if self.config.has_option('general', 'ignore-readonly') and \
  236. self.config.getboolean('general', 'ignore-readonly'):
  237. return
  238. self.warn("Attempted to modify labels for messages %s in folder %s[%s], "
  239. "but that folder is read-only. No labels have been modified "
  240. "for that message."% (
  241. str(uidlist), self.getnicename(destfolder), destfolder))
  242. def deletereadonly(self, destfolder, uidlist):
  243. if self.config.has_option('general', 'ignore-readonly') and \
  244. self.config.getboolean('general', 'ignore-readonly'):
  245. return
  246. self.warn("Attempted to delete messages %s in folder %s[%s], but that "
  247. "folder is read-only. No messages have been deleted in that "
  248. "folder."% (str(uidlist), self.getnicename(destfolder),
  249. destfolder))
  250. ################################################## MESSAGES
  251. def init_banner(self):
  252. """Called when the UI starts. Must be called before any other UI
  253. call except isusable(). Displays the copyright banner. This is
  254. where the UI should do its setup -- TK, for instance, would
  255. create the application window here."""
  256. pass
  257. def connecting(self, reposname, hostname, port):
  258. """Log 'Establishing connection to'."""
  259. if not self.logger.isEnabledFor(logging.INFO): return
  260. displaystr = ''
  261. hostname = hostname if hostname else ''
  262. port = "%s"% port if port else ''
  263. if hostname:
  264. displaystr = ' to %s:%s' % (hostname, port)
  265. self.logger.info("Establishing connection%s (%s)"%
  266. (displaystr, reposname))
  267. def acct(self, account):
  268. """Output that we start syncing an account (and start counting)."""
  269. self.acct_startimes[account] = time.time()
  270. self.logger.info("*** Processing account %s"% account)
  271. def acctdone(self, account):
  272. """Output that we finished syncing an account (in which time)."""
  273. sec = time.time() - self.acct_startimes[account]
  274. del self.acct_startimes[account]
  275. self.logger.info("*** Finished account '%s' in %d:%02d"%
  276. (account, sec // 60, sec % 60))
  277. def syncfolders(self, src_repo, dst_repo):
  278. """Log 'Copying folder structure...'."""
  279. if self.logger.isEnabledFor(logging.DEBUG):
  280. self.debug('', "Copying folder structure from %s to %s" %\
  281. (src_repo, dst_repo))
  282. ############################## Folder syncing
  283. def makefolder(self, repo, foldername):
  284. """Called when a folder is created."""
  285. prefix = "[DRYRUN] " if self.dryrun else ""
  286. self.info(("{0}Creating folder {1}[{2}]".format(
  287. prefix, foldername, repo)))
  288. def syncingfolder(self, srcrepos, srcfolder, destrepos, destfolder):
  289. """Called when a folder sync operation is started."""
  290. self.logger.info("Syncing %s: %s -> %s"% (srcfolder,
  291. self.getnicename(srcrepos),
  292. self.getnicename(destrepos)))
  293. def skippingfolder(self, folder):
  294. """Called when a folder sync operation is started."""
  295. self.logger.info("Skipping %s (not changed)" % folder)
  296. def validityproblem(self, folder):
  297. self.uidval_problem = True
  298. self.logger.warning("UID validity problem for folder %s (repo %s) "
  299. "(saved %d; got %d); skipping it. Please see FAQ "
  300. "and manual on how to handle this."% \
  301. (folder, folder.getrepository(),
  302. folder.get_saveduidvalidity(), folder.get_uidvalidity()))
  303. def loadmessagelist(self, repos, folder):
  304. self.logger.debug("Loading message list for %s[%s]"% (
  305. self.getnicename(repos),
  306. folder))
  307. def messagelistloaded(self, repos, folder, count):
  308. self.logger.debug("Message list for %s[%s] loaded: %d messages" % (
  309. self.getnicename(repos), folder, count))
  310. ############################## Message syncing
  311. def syncingmessages(self, sr, srcfolder, dr, dstfolder):
  312. self.logger.debug("Syncing messages %s[%s] -> %s[%s]" % (
  313. self.getnicename(sr), srcfolder,
  314. self.getnicename(dr), dstfolder))
  315. def ignorecopyingmessage(self, uid, src, destfolder):
  316. """Output a log line stating which message is ignored."""
  317. self.logger.info("IGNORED: Copy message UID %s %s:%s -> %s"% (
  318. uid, src.repository, src, destfolder.repository))
  319. def copyingmessage(self, uid, num, num_to_copy, src, destfolder):
  320. """Output a log line stating which message we copy."""
  321. self.logger.info("Copy message UID %s (%d/%d) %s:%s -> %s"% (
  322. uid, num, num_to_copy, src.repository, src,
  323. destfolder.repository))
  324. def deletingmessages(self, uidlist, destlist):
  325. ds = self.folderlist(destlist)
  326. prefix = "[DRYRUN] " if self.dryrun else ""
  327. self.info("{0}Deleting {1} messages ({2}) in {3}".format(
  328. prefix, len(uidlist),
  329. offlineimap.imaputil.uid_sequence(uidlist), ds))
  330. def addingflags(self, uidlist, flags, dest):
  331. self.logger.info("Adding flag %s to %d messages on %s" % (
  332. ", ".join(flags), len(uidlist), dest))
  333. def deletingflags(self, uidlist, flags, dest):
  334. self.logger.info("Deleting flag %s from %d messages on %s" % (
  335. ", ".join(flags), len(uidlist), dest))
  336. def addinglabels(self, uidlist, label, dest):
  337. self.logger.info("Adding label %s to %d messages on %s" % (
  338. label, len(uidlist), dest))
  339. def deletinglabels(self, uidlist, label, dest):
  340. self.logger.info("Deleting label %s from %d messages on %s" % (
  341. label, len(uidlist), dest))
  342. def settinglabels(self, uid, num, num_to_set, labels, dest):
  343. self.logger.info("Setting labels to message %d on %s (%d of %d): %s" % (
  344. uid, dest, num, num_to_set, ", ".join(labels)))
  345. def collectingdata(self, uidlist, source):
  346. if uidlist:
  347. self.logger.info("Collecting data from %d messages on %s"% (
  348. len(uidlist), source))
  349. else:
  350. self.logger.info("Collecting data from messages on %s"% source)
  351. def serverdiagnostics(self, repository, type):
  352. """Connect to repository and output useful information for debugging."""
  353. conn = None
  354. self._msg("%s repository '%s': type '%s'" % (type, repository.name,
  355. self.getnicename(repository)))
  356. try:
  357. if hasattr(repository, 'gethost'): # IMAP
  358. self._msg("Host: %s Port: %s SSL: %s"% (repository.gethost(),
  359. repository.getport(), repository.getssl()))
  360. try:
  361. conn = repository.imapserver.acquireconnection()
  362. except OfflineImapError as e:
  363. self._msg("Failed to connect. Reason %s" % e)
  364. else:
  365. if 'ID' in conn.capabilities:
  366. self._msg("Server supports ID extension.")
  367. #TODO: Debug and make below working, it hangs Gmail
  368. #res_type, response = conn.id((
  369. # 'name', offlineimap.__productname__,
  370. # 'version', offlineimap.__version__))
  371. #self._msg("Server ID: %s %s" % (res_type, response[0]))
  372. self._msg("Server welcome string: %s" % str(conn.welcome))
  373. self._msg("Server capabilities: %s\n" % str(conn.capabilities))
  374. repository.imapserver.releaseconnection(conn)
  375. if type != 'Status':
  376. folderfilter = repository.getconf('folderfilter', None)
  377. if folderfilter:
  378. self._msg("folderfilter= %s\n" % folderfilter)
  379. folderincludes = repository.getconf('folderincludes', None)
  380. if folderincludes:
  381. self._msg("folderincludes= %s\n" % folderincludes)
  382. nametrans = repository.getconf('nametrans', None)
  383. if nametrans:
  384. self._msg("nametrans= %s\n" % nametrans)
  385. folders = repository.getfolders()
  386. foldernames = [(f.name, f.getvisiblename(), f.sync_this)
  387. for f in folders]
  388. folders = []
  389. for name, visiblename, sync_this in foldernames:
  390. syncstr = "" if sync_this else " (disabled)"
  391. if name == visiblename: folders.append("%s%s" % (name,
  392. syncstr))
  393. else: folders.append("%s -> %s%s" % (name,
  394. visiblename, syncstr))
  395. self._msg("Folderlist:\n %s\n" % "\n ".join(folders))
  396. finally:
  397. if conn: #release any existing IMAP connection
  398. repository.imapserver.close()
  399. def savemessage(self, debugtype, uid, flags, folder):
  400. """Output a log line stating that we save a msg."""
  401. self.debug(debugtype, "Write mail '%s:%d' with flags %s"%
  402. (folder, uid, repr(flags)))
  403. ################################################## Threads
  404. def getThreadDebugLog(self, thread):
  405. if thread in self.debugmessages:
  406. message = "\nLast %d debug messages logged for %s prior to exception:\n"\
  407. % (len(self.debugmessages[thread]), thread.getName())
  408. message += "\n".join(self.debugmessages[thread])
  409. else:
  410. message = "\nNo debug messages were logged for %s."% \
  411. thread.getName()
  412. return message
  413. def delThreadDebugLog(self, thread):
  414. if thread in self.debugmessages:
  415. del self.debugmessages[thread]
  416. def getThreadExceptionString(self, thread):
  417. message = "Thread '%s' terminated with exception:\n%s"% \
  418. (thread.getName(), thread.exit_stacktrace)
  419. message += "\n" + self.getThreadDebugLog(thread)
  420. return message
  421. def threadException(self, thread):
  422. """Called when a thread has terminated with an exception.
  423. The argument is the ExitNotifyThread that has so terminated."""
  424. self.warn(self.getThreadExceptionString(thread))
  425. self.delThreadDebugLog(thread)
  426. self.terminate(100)
  427. def terminate(self, exitstatus = 0, errortitle = None, errormsg = None):
  428. """Called to terminate the application."""
  429. #print any exceptions that have occurred over the run
  430. if not self.exc_queue.empty():
  431. self.warn("ERROR: Exceptions occurred during the run!")
  432. if exitstatus == 0:
  433. exitstatus = 1
  434. while not self.exc_queue.empty():
  435. msg, exc, exc_traceback = self.exc_queue.get()
  436. if msg:
  437. self.warn("ERROR: %s\n %s"% (msg, exc))
  438. else:
  439. self.warn("ERROR: %s"% (exc))
  440. if exc_traceback:
  441. self.warn("\nTraceback:\n%s"% "".join(
  442. traceback.format_tb(exc_traceback)))
  443. if errormsg and errortitle:
  444. self.warn('ERROR: %s\n\n%s\n'% (errortitle, errormsg))
  445. elif errormsg:
  446. self.warn('%s\n'% errormsg)
  447. if self.uidval_problem:
  448. self.warn('At least one folder skipped due to UID validity problem')
  449. if exitstatus == 0:
  450. exitstatus = 2
  451. sys.exit(exitstatus)
  452. def threadExited(self, thread):
  453. """Called when a thread has exited normally.
  454. Many UIs will just ignore this."""
  455. self.delThreadDebugLog(thread)
  456. self.unregisterthread(thread)
  457. ################################################## Hooks
  458. def callhook(self, msg):
  459. if self.dryrun:
  460. self.info("[DRYRUN] {0}".format(msg))
  461. else:
  462. self.info(msg)
  463. ################################################## Other
  464. def sleep(self, sleepsecs, account):
  465. """This function does not actually output anything, but handles
  466. the overall sleep, dealing with updates as necessary. It will,
  467. however, call sleeping() which DOES output something.
  468. :returns: 0/False if timeout expired, 1/2/True if there is a
  469. request to cancel the timer.
  470. """
  471. abortsleep = False
  472. while sleepsecs > 0 and not abortsleep:
  473. if account.get_abort_event():
  474. abortsleep = True
  475. else:
  476. abortsleep = self.sleeping(10, sleepsecs)
  477. sleepsecs -= 10
  478. self.sleeping(0, 0) # Done sleeping.
  479. return abortsleep
  480. def sleeping(self, sleepsecs, remainingsecs):
  481. """Sleep for sleepsecs, display remainingsecs to go.
  482. Does nothing if sleepsecs <= 0.
  483. Display a message on the screen if we pass a full minute.
  484. This implementation in UIBase does not support this, but some
  485. implementations return 0 for successful sleep and 1 for an
  486. 'abort', ie a request to sync immediately.
  487. """
  488. if sleepsecs > 0:
  489. if remainingsecs//60 != (remainingsecs-sleepsecs)//60:
  490. self.logger.debug("Next refresh in %.1f minutes" % (
  491. remainingsecs/60.0))
  492. time.sleep(sleepsecs)
  493. return 0