[Spambayes-checkins] spambayes/windows pop3proxy_service.py, 1.18, 1.19

Tony Meyer anadelonbrin at users.sourceforge.net
Tue Mar 29 07:50:11 CEST 2005


Update of /cvsroot/spambayes/spambayes/windows
In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv17728/windows

Modified Files:
	pop3proxy_service.py 
Log Message:
Don't log to text files, but to the service log, as is appropriate.

Work around a problem that occurs if thetre is a zlib.dll in the SYSTEM32
directory.

When installing, create a directory for the data, unless there is already a configuration
 file.  This directory is called "SpamBayesData" and is in the same directory as the
install script.  When running, if this directory exists, then use it.  This is preferable
behaviour for a service.

Index: pop3proxy_service.py
===================================================================
RCS file: /cvsroot/spambayes/spambayes/windows/pop3proxy_service.py,v
retrieving revision 1.18
retrieving revision 1.19
diff -C2 -d -r1.18 -r1.19
*** pop3proxy_service.py	16 Jul 2004 02:02:33 -0000	1.18
--- pop3proxy_service.py	29 Mar 2005 05:50:06 -0000	1.19
***************
*** 11,15 ****
  # * To remove the service: "pop3proxy_service.py remove"
  
! # This module is part of the spambayes project, which is Copyright 2002
  # The Python Software Foundation and is covered by the Python Software
  # Foundation license.
--- 11,15 ----
  # * To remove the service: "pop3proxy_service.py remove"
  
! # This module is part of the spambayes project, which is Copyright 2002-4
  # The Python Software Foundation and is covered by the Python Software
  # Foundation license.
***************
*** 17,21 ****
  # Originally written by Mark Hammond.
  
! import sys, os
  
  # Messages from pop3proxy will go nowhere when executed as a service
--- 17,110 ----
  # Originally written by Mark Hammond.
  
! import os
! import sys
! import logging
! 
! import servicemanager
! try:
!     servicemanager.LogInfoMsg(os.getcwd())
!     servicemanager.LogInfoMsg(__file__)
!     servicemanager.LogInfoMsg(sys.argv[0])
! except:
!     pass
! 
! class ServiceEventLogHandler(logging.Handler):
!     """Dispatches logging events to the win32 services event log.
! 
!     Requires pywin32.    
!     """
!     import servicemanager
!     def emit(self, record):
!         """Emit a record.
! 
!         If a formatter is specified, it is used to format the record.
!         This record is then written to the win32 services event log,
!         with the type set to the appropriate type based on the level.
!         """
!         try:
!             servicemgr = self.servicemanager
!             level = record.levelno
!             msg = self.format(record)
!             if level >= logging.ERROR:
!                 servicemgr.LogErrorMsg(msg)
!             elif level >= logging.WARNING:
!                 servicemgr.LogWarningMsg(msg)
!             elif level >= logging.INFO:
!                 servicemgr.LogInfoMsg(msg)
!             elif level >= logging.DEBUG:
!                 # What should we do with this?  It's very low-level
!                 # to be going into the log, but then it only gets
!                 # added if the logger's level is set low enough.
!                 # For now, nothing (absorb), and reconsider this
!                 # when we are actually using the logging module properly.
!                 pass
!             else:
!                 # Really low; just absorb these for now.
!                 pass
!         except:
!             self.handleError(record)
! 
!     def handleError(self, record):
!         """
!         Handle errors which occur during an emit() call.
! 
!         sys.stderr does nowwhere, so redirect this into the event log, too.
!         """
!         if raiseExceptions:
!             try:
!                 import cStringIO as StringIO
!             except ImportError:
!                 import StringIO
!             import traceback
!             ei = sys.exc_info()
!             msg = StringIO.StringIO()
!             traceback.print_exception(ei[0], ei[1], ei[2], None, msg)
!             msg.seek(0)
!             self.servicemanager.LogErrorMsg(msg)
!             del ei
! 
! 
! class ServiceEventLogHandlerWrapper(object):
!     """Pretend that the ServiceEventLogHandler is a file-like object,
!     so we can use it while we don't use the proper logging module."""
!     def __init__(self, service_name, level=logging.INFO):
!         self.log = ServiceEventLogHandler()
!         self.name = service_name
!         self.level = level
!         self.data = ""
!     def write(self, data):
!         # This could use the higher-up stuff, but don't for now.
!         # Buffer until newline.
!         self.data += data
!         if '\n' not in data:
!             return
!         # Skip blank lines
!         if not self.data.strip():
!             return
!         record = logging.LogRecord(self.name, self.level, "", "",
!                                    self.data, None, None)
!         self.log.emit(record)
!         self.data = ""
! 
  
  # Messages from pop3proxy will go nowhere when executed as a service
***************
*** 28,48 ****
      # No console - if we are running from Python sources,
      # redirect to win32traceutil, but if running from a binary
!     # install, redirect to a log file.
      # Want to move to logging module later, so for now, we
      # hack together a simple logging strategy.
      if hasattr(sys, "frozen"):
!         temp_dir = win32api.GetTempPath()
!         for i in range(3,0,-1):
!             try: os.unlink(os.path.join(temp_dir, "SpamBayesService%d.log" % (i+1)))
!             except os.error: pass
!             try:
!                 os.rename(
!                     os.path.join(temp_dir, "SpamBayesService%d.log" % i),
!                     os.path.join(temp_dir, "SpamBayesService%d.log" % (i+1))
!                     )
!             except os.error: pass
!         # Open this log, as unbuffered so crashes still get written.
!         sys.stdout = open(os.path.join(temp_dir,"SpamBayesService1.log"), "wt", 0)
!         sys.stderr = sys.stdout
      else:
          import win32traceutil
--- 117,131 ----
      # No console - if we are running from Python sources,
      # redirect to win32traceutil, but if running from a binary
!     # install, redirect to the services event log.
!     # We used to redirect to log files (in the temp folder, in
!     # the form SpamBayesService%d.log), but that is apparently
!     # not necessarily a good place, so we moved to the official
!     # location.
      # Want to move to logging module later, so for now, we
      # hack together a simple logging strategy.
      if hasattr(sys, "frozen"):
!         sys.stdout = ServiceEventLogHandlerWrapper("pop3proxy")
!         sys.stderr = ServiceEventLogHandlerWrapper("pop3proxy",
!                                                    logging.ERROR)
      else:
          import win32traceutil
***************
*** 70,76 ****
      sys.path.insert(0, sb_dir)
      sys.path.insert(-1, sb_scripts_dir)
!     # and change directory here, so pop3proxy uses the default
      # config file etc
!     os.chdir(sb_dir)
  
  # Rest of the standard Python modules we use.
--- 153,180 ----
      sys.path.insert(0, sb_dir)
      sys.path.insert(-1, sb_scripts_dir)
!     # and change directory here, so sb_server uses the correct
      # config file etc
!     # If the "SpamBayesData" directory that we create exists, change to
!     # that, otherwise into the spambayes directory itself.
!     if os.path.exists(os.path.join(sb_dir, "SpamBayesData")):
!         os.chdir(os.path.join(sb_dir, "SpamBayesData"))
!     else:
!         os.chdir(sb_dir)
! 
!     # Fix to handle problem if there is a zlib.dll in the SYSTEM32 directory.
!     # (The Python DLL directory must come before that in sys.path)
!     # This is a bit hackish, but shouldn't do any real harm.
!     from win32com.shell import shell, shellcon
!     sys32path = shell.SHGetFolderPath(0, shellcon.CSIDL_SYSTEM, 0, 0)
!     for path in sys.path[:-1]:
!         if path == sys32path:
!             sys.path.remove(path)
!             assert path not in sys.path, \
!                    "Please remove multiple copies of windows\system32 in path"
!             sys.path.append(path) # put it at the *end*
!     del sys32path
!     del shell
!     del shellcon
!     del path
  
  # Rest of the standard Python modules we use.
***************
*** 115,119 ****
              errCode = winerror.ERROR_SERVICE_SPECIFIC_ERROR
              self.ReportServiceStatus(win32service.SERVICE_STOPPED,
!                                      win32ExitCode=errCode, svcExitCode = 1)
              return
          assert not sb_server.state.launchUI, "Service can't launch a UI"
--- 219,223 ----
              errCode = winerror.ERROR_SERVICE_SPECIFIC_ERROR
              self.ReportServiceStatus(win32service.SERVICE_STOPPED,
!                                      win32ExitCode=errCode, svcExitCode=1)
              return
          assert not sb_server.state.launchUI, "Service can't launch a UI"
***************
*** 191,193 ****
--- 295,309 ----
  
  if __name__=='__main__':
+     if "install" in sys.argv:
+         # Installing the service also creates a directory (if it does not
+         # already exist) in which the data will be placed, unless an
+         # existing configuration file can be found.
+         from spambayes.Options import optionsPathname
+         if not os.path.exists(optionsPathname):
+             data_directory = os.path.join(os.path.dirname(sys.argv[0]),
+                                           "..", "SpamBayesData")
+             data_directory = os.path.abspath(data_directory)
+             if not os.path.exists(data_directory):
+                 print "Creating data directory at", data_directory
+                 os.makedirs(data_directory)
      win32serviceutil.HandleCommandLine(Service)



More information about the Spambayes-checkins mailing list