UIBase.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. # UI base class
  2. # Copyright (C) 2002-2018 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. from queue import Queue
  25. from collections import deque
  26. import offlineimap
  27. from offlineimap.error import OfflineImapError
  28. debugtypes = {'': 'Other offlineimap related sync messages',
  29. 'imap': 'IMAP protocol debugging',
  30. 'maildir': 'Maildir repository debugging',
  31. 'thread': 'Threading debugging'}
  32. globalui = None
  33. def setglobalui(newui):
  34. """Set the global ui object to be used for logging."""
  35. global globalui
  36. globalui = newui
  37. def getglobalui():
  38. """Return the current ui object."""
  39. global globalui
  40. return globalui
  41. class UIBase:
  42. def __init__(self, config, loglevel=logging.INFO):
  43. self.config = config
  44. # Is this a 'dryrun'?
  45. self.dryrun = config.getdefaultboolean('general', 'dry-run', False)
  46. self.debuglist = []
  47. # list of debugtypes we are supposed to log
  48. self.debugmessages = {}
  49. # debugmessages in a deque(v) per thread(k)
  50. self.debugmsglen = 15
  51. self.threadaccounts = {}
  52. # dict linking active threads (k) to account names (v)
  53. self.acct_startimes = {}
  54. # linking active accounts with the time.time() when sync started
  55. self.logfile = None
  56. self.exc_queue = Queue()
  57. # saves all occuring exceptions, so we can output them at the end
  58. self.uidval_problem = False
  59. # at least one folder skipped due to UID validity problem
  60. # create logger with 'OfflineImap' app
  61. self.logger = logging.getLogger('OfflineImap')
  62. self.logger.setLevel(loglevel)
  63. self._log_con_handler = self.setup_consolehandler()
  64. """The console handler (we need access to be able to lock it)."""
  65. # UTILS
  66. def setup_consolehandler(self):
  67. """Backend specific console handler.
  68. Sets up things and adds them to self.logger.
  69. :returns: The logging.Handler() for console output"""
  70. # create console handler with a higher log level
  71. ch = logging.StreamHandler(sys.stdout)
  72. # ch.setLevel(logging.DEBUG)
  73. # create formatter and add it to the handlers
  74. self.formatter = logging.Formatter("%(message)s")
  75. ch.setFormatter(self.formatter)
  76. # add the handlers to the logger
  77. self.logger.addHandler(ch)
  78. self.logger.info(offlineimap.banner)
  79. return ch
  80. def setup_sysloghandler(self):
  81. """Backend specific syslog handler."""
  82. # create syslog handler
  83. ch = logging.handlers.SysLogHandler('/dev/log')
  84. # create formatter and add it to the handlers
  85. self.formatter = logging.Formatter("offlineimap[%(process)d]: %(message)s")
  86. ch.setFormatter(self.formatter)
  87. # add the handlers to the logger
  88. self.logger.addHandler(ch)
  89. def setlogfile(self, logfile):
  90. """Create file handler which logs to file."""
  91. fh = logging.FileHandler(logfile, 'at')
  92. # fh.setLevel(logging.DEBUG)
  93. file_formatter = logging.Formatter("%(asctime)s %(levelname)s: "
  94. "%(message)s", '%Y-%m-%d %H:%M:%S')
  95. fh.setFormatter(file_formatter)
  96. self.logger.addHandler(fh)
  97. # write out more verbose initial info blurb on the log file
  98. p_ver = ".".join([str(x) for x in sys.version_info[0:3]])
  99. msg = "OfflineImap %s starting...\n Python: %s Platform: %s\n " \
  100. "Args: %s" % (offlineimap.__version__, p_ver, sys.platform,
  101. " ".join(sys.argv))
  102. record = logging.LogRecord('OfflineImap', logging.INFO, __file__,
  103. None, msg, None, None)
  104. fh.emit(record)
  105. def _msg(self, msg):
  106. """Display a message."""
  107. # TODO: legacy function, rip out.
  108. self.info(msg)
  109. def info(self, msg):
  110. """Display a message."""
  111. self.logger.info(msg)
  112. def warn(self, msg, minor=0):
  113. self.logger.warning(msg)
  114. def error(self, exc, exc_traceback=None, msg=None):
  115. """Log a message at severity level ERROR.
  116. Log Exception 'exc' to error log, possibly prepended by a preceding
  117. error "msg", detailing at what point the error occurred.
  118. In debug mode, we also output the full traceback that occurred
  119. if one has been passed in via sys.info()[2].
  120. Also save the Exception to a stack that can be output at the end
  121. of the sync run when offlineiamp exits. It is recommended to
  122. always pass in exceptions if possible, so we can give the user
  123. the best debugging info.
  124. We are always pushing tracebacks to the exception queue to
  125. make them to be output at the end of the run to allow users
  126. pass sensible diagnostics to the developers or to solve
  127. problems by themselves.
  128. One example of such a call might be:
  129. ui.error(exc, sys.exc_info()[2], msg="While syncing Folder %s in "
  130. "repo %s")
  131. """
  132. if msg:
  133. self.logger.error("ERROR: %s\n %s" % (msg, exc))
  134. else:
  135. self.logger.error("ERROR: %s" % exc)
  136. instant_traceback = exc_traceback
  137. if not self.debuglist:
  138. # only output tracebacks in debug mode
  139. instant_traceback = None
  140. # push exc on the queue for later output
  141. self.exc_queue.put((msg, exc, exc_traceback))
  142. if instant_traceback:
  143. self.logger.error(traceback.format_tb(instant_traceback))
  144. def registerthread(self, account):
  145. """Register current thread as being associated with an account name."""
  146. cur_thread = threading.current_thread()
  147. if cur_thread in self.threadaccounts:
  148. # was already associated with an old account, update info
  149. self.debug('thread', "Register thread '%s' (previously '%s', now "
  150. "'%s')" % (cur_thread.name,
  151. self.getthreadaccount(cur_thread), account))
  152. else:
  153. self.debug('thread', "Register new thread '%s' (account '%s')" %
  154. (cur_thread.name, account))
  155. self.threadaccounts[cur_thread] = account
  156. def unregisterthread(self, thr):
  157. """Unregister a thread as being associated with an account name."""
  158. if thr in self.threadaccounts:
  159. del self.threadaccounts[thr]
  160. self.debug('thread', "Unregister thread '%s'" % thr.name)
  161. def getthreadaccount(self, thr=None):
  162. """Get Account() for a thread (current if None)
  163. If no account has been registered with this thread, return 'None'."""
  164. if thr is None:
  165. thr = threading.current_thread()
  166. if thr in self.threadaccounts:
  167. return self.threadaccounts[thr]
  168. return None
  169. def debug(self, debugtype, msg):
  170. cur_thread = threading.current_thread()
  171. if cur_thread not in self.debugmessages:
  172. # deque(..., self.debugmsglen) would be handy but was
  173. # introduced in p2.6 only, so we'll need to work around and
  174. # shorten our debugmsg list manually :-(
  175. self.debugmessages[cur_thread] = deque()
  176. self.debugmessages[cur_thread].append("%s: %s" % (debugtype, msg))
  177. # Shorten queue if needed
  178. if len(self.debugmessages[cur_thread]) > self.debugmsglen:
  179. self.debugmessages[cur_thread].popleft()
  180. if debugtype in self.debuglist: # log if we are supposed to do so
  181. self.logger.debug("[%s]: %s" % (debugtype, msg))
  182. def add_debug(self, debugtype):
  183. global debugtypes
  184. if debugtype in debugtypes:
  185. if debugtype not in self.debuglist:
  186. self.debuglist.append(debugtype)
  187. self.debugging(debugtype)
  188. else:
  189. self.invaliddebug(debugtype)
  190. def is_debugging(self, debugtype):
  191. return (debugtype in self.debuglist)
  192. def debugging(self, debugtype):
  193. global debugtypes
  194. self.logger.debug("Now debugging for %s: %s" % (debugtype,
  195. debugtypes[debugtype]))
  196. def invaliddebug(self, debugtype):
  197. self.warn("Invalid debug type: %s" % debugtype)
  198. def getnicename(self, mobject):
  199. """Return the type of a repository or Folder as string.
  200. (IMAP, Gmail, Maildir, etc...)"""
  201. prelimname = mobject.__class__.__name__.split('.')[-1]
  202. # Strip off extra stuff.
  203. return re.sub('(Folder|Repository)', '', prelimname)
  204. def isusable(self):
  205. """Returns true if this UI object is usable in the current
  206. environment. For instance, an X GUI would return true if it's
  207. being run in X with a valid DISPLAY setting, and false otherwise."""
  208. return True
  209. # INPUT
  210. def getpass(self, username, config, errmsg=None):
  211. raise NotImplementedError("Prompting for a password is not supported"
  212. " in this UI backend.")
  213. def folderlist(self, folder_list):
  214. return ', '.join(["%s[%s]" %
  215. (self.getnicename(x), x.getname()) for x in folder_list])
  216. # WARNINGS
  217. def msgtoreadonly(self, destfolder, uid):
  218. if self.config.has_option('general', 'ignore-readonly') and \
  219. self.config.getboolean('general', 'ignore-readonly'):
  220. return
  221. self.warn("Attempted to synchronize message %d to folder %s[%s], "
  222. "but that folder is read-only. The message will not be "
  223. "copied to that folder." % (
  224. uid, self.getnicename(destfolder), destfolder))
  225. def flagstoreadonly(self, destfolder, uidlist, flags):
  226. if self.config.has_option('general', 'ignore-readonly') and \
  227. self.config.getboolean('general', 'ignore-readonly'):
  228. return
  229. self.warn("Attempted to modify flags for messages %s in folder %s[%s], "
  230. "but that folder is read-only. No flags have been modified "
  231. "for that message." % (
  232. str(uidlist), self.getnicename(destfolder), destfolder))
  233. def labelstoreadonly(self, destfolder, uidlist, labels):
  234. if self.config.has_option('general', 'ignore-readonly') and \
  235. self.config.getboolean('general', 'ignore-readonly'):
  236. return
  237. self.warn("Attempted to modify labels for messages %s in folder %s[%s], "
  238. "but that folder is read-only. No labels have been modified "
  239. "for that message." % (
  240. str(uidlist), self.getnicename(destfolder), destfolder))
  241. def deletereadonly(self, destfolder, uidlist):
  242. if self.config.has_option('general', 'ignore-readonly') and \
  243. self.config.getboolean('general', 'ignore-readonly'):
  244. return
  245. self.warn("Attempted to delete messages %s in folder %s[%s], but that "
  246. "folder is read-only. No messages have been deleted in that "
  247. "folder." % (str(uidlist), self.getnicename(destfolder),
  248. destfolder))
  249. # MESSAGES
  250. def init_banner(self):
  251. """Called when the UI starts. Must be called before any other UI
  252. call except isusable(). Displays the copyright banner. This is
  253. where the UI should do its setup -- TK, for instance, would
  254. create the application window here."""
  255. pass
  256. def connecting(self, reposname, hostname, port):
  257. """Log 'Establishing connection to'."""
  258. if not self.logger.isEnabledFor(logging.INFO):
  259. 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:%s" % (
  322. uid, num, num_to_copy, src.repository, src,
  323. destfolder.repository, destfolder))
  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, rtype):
  352. """Connect to repository and output useful information for debugging."""
  353. conn = None
  354. self._msg("%s repository '%s': type '%s'" % (rtype, 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 rtype != '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:
  392. folders.append("%s%s" % (name,
  393. syncstr))
  394. else:
  395. folders.append("%s -> %s%s" % (name,
  396. visiblename, syncstr))
  397. self._msg("Folderlist:\n %s\n" % "\n ".join(folders))
  398. finally:
  399. if conn: # release any existing IMAP connection
  400. repository.imapserver.close()
  401. def savemessage(self, debugtype, uid, flags, folder):
  402. """Output a log line stating that we save a msg."""
  403. self.debug(debugtype, "Write mail '%s:%d' with flags %s" %
  404. (folder, uid, repr(flags)))
  405. # Threads
  406. def getThreadDebugLog(self, thread):
  407. if thread in self.debugmessages:
  408. message = "\nLast %d debug messages logged for %s prior to exception:\n" \
  409. % (len(self.debugmessages[thread]), thread.name)
  410. message += "\n".join(self.debugmessages[thread])
  411. else:
  412. message = "\nNo debug messages were logged for %s." % \
  413. thread.name
  414. return message
  415. def delThreadDebugLog(self, thread):
  416. if thread in self.debugmessages:
  417. del self.debugmessages[thread]
  418. def getThreadExceptionString(self, thread):
  419. message = "Thread '%s' terminated with exception:\n%s" % \
  420. (thread.name, thread.exit_stacktrace)
  421. message += "\n" + self.getThreadDebugLog(thread)
  422. return message
  423. def threadException(self, thread):
  424. """Called when a thread has terminated with an exception.
  425. The argument is the ExitNotifyThread that has so terminated."""
  426. self.warn(self.getThreadExceptionString(thread))
  427. self.delThreadDebugLog(thread)
  428. self.terminate(100)
  429. def terminate(self, exitstatus=0, errortitle=None, errormsg=None):
  430. """Called to terminate the application."""
  431. # print any exceptions that have occurred over the run
  432. if not self.exc_queue.empty():
  433. self.warn("ERROR: Exceptions occurred during the run!")
  434. if exitstatus == 0:
  435. exitstatus = 1
  436. while not self.exc_queue.empty():
  437. msg, exc, exc_traceback = self.exc_queue.get()
  438. exc_str = "".join(traceback.format_exception_only(type(exc), exc))
  439. if msg:
  440. self.warn("ERROR: %s\n %s" % (msg, exc_str))
  441. else:
  442. self.warn("ERROR: %s" % exc_str)
  443. if exc_traceback:
  444. self.warn("\nTraceback:\n%s" % "".join(
  445. traceback.format_tb(exc_traceback)))
  446. if errormsg and errortitle:
  447. self.warn('ERROR: %s\n\n%s\n' % (errortitle, errormsg))
  448. elif errormsg:
  449. self.warn('%s\n' % errormsg)
  450. if self.uidval_problem:
  451. self.warn('At least one folder skipped due to UID validity problem')
  452. if exitstatus == 0:
  453. exitstatus = 2
  454. sys.exit(exitstatus)
  455. def threadExited(self, thread):
  456. """Called when a thread has exited normally.
  457. Many UIs will just ignore this."""
  458. self.delThreadDebugLog(thread)
  459. self.unregisterthread(thread)
  460. # Hooks
  461. def callhook(self, msg):
  462. if self.dryrun:
  463. self.info("[DRYRUN] {0}".format(msg))
  464. else:
  465. self.info(msg)
  466. # Other
  467. def sleep(self, sleepsecs, account):
  468. """This function does not actually output anything, but handles
  469. the overall sleep, dealing with updates as necessary. It will,
  470. however, call sleeping() which DOES output something.
  471. :returns: 0/False if timeout expired, 1/2/True if there is a
  472. request to cancel the timer.
  473. """
  474. abortsleep = False
  475. while sleepsecs > 0 and not abortsleep:
  476. if account.get_abort_event():
  477. abortsleep = True
  478. else:
  479. abortsleep = self.sleeping(10, sleepsecs)
  480. sleepsecs -= 10
  481. self.sleeping(0, 0) # Done sleeping.
  482. return abortsleep
  483. def sleeping(self, sleepsecs, remainingsecs):
  484. """Sleep for sleepsecs, display remainingsecs to go.
  485. Does nothing if sleepsecs <= 0.
  486. Display a message on the screen if we pass a full minute.
  487. This implementation in UIBase does not support this, but some
  488. implementations return 0 for successful sleep and 1 for an
  489. 'abort', ie a request to sync immediately.
  490. """
  491. if sleepsecs > 0:
  492. if remainingsecs // 60 != (remainingsecs - sleepsecs) // 60:
  493. self.logger.debug("Next refresh in %.1f minutes" % (
  494. remainingsecs / 60.0))
  495. time.sleep(sleepsecs)
  496. return 0