[Zope-Checkins] CVS: Zope27/lib/python - Globals.py:1.1.2.1 SignalHandler.py:1.1.2.1 ts_regex.py:1.1.2.1

Jim Fulton jim@zope.com
Tue, 13 Aug 2002 15:33:28 -0400


Update of /cvs-repository/Zope27/lib/python
In directory cvs.zope.org:/tmp/cvs-serv30914/lib/python

Added Files:
      Tag: Zope-2_7-development-branch
	Globals.py SignalHandler.py ts_regex.py 
Log Message:
Added some extra needed files

=== Added File Zope27/lib/python/Globals.py ===
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
# 
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
# 
##############################################################################

"""Global definitions"""

__version__='$Revision: 1.1.2.1 $'[11:-2]

# Global constants: __replaceable__ flags:
NOT_REPLACEABLE = 0
REPLACEABLE = 1
UNIQUE = 2

import Acquisition, ComputedAttribute, App.PersistentExtra, os
import TreeDisplay

from App.FindHomes import INSTANCE_HOME, SOFTWARE_HOME, ZOPE_HOME
from App.Common import package_home, attrget, Dictionary
from Persistence import Persistent, PersistentMapping
from App.special_dtml import HTML, HTMLFile, DTMLFile
from App.class_init import default__class_init__, ApplicationDefaultPermissions

# Nicer alias for class initializer.
InitializeClass = default__class_init__

from App.Dialogs import MessageDialog
from App.ImageFile import ImageFile

VersionNameName='Zope-Version'

data_dir = os.path.join(INSTANCE_HOME, 'var')
opened=[]

# Check,if DEBUG variables are set
DevelopmentMode=None

z1 = os.environ.get('Z_DEBUG_MODE','')
z2 = os.environ.get('BOBO_DEBUG_MODE','')

if z1.lower() in ('yes','y') or z1.isdigit():
    DevelopmentMode=1
elif z2.lower() in ('yes','y') or z2.isdigit():
    DevelopmentMode=1


=== Added File Zope27/lib/python/SignalHandler.py ===
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
# 
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
# 
##############################################################################

"""Signal handling dispatcher."""

__version__='$Revision: 1.1.2.1 $'[11:-2]

from ZServer import asyncore
import sys, os, zdaemon, ZLogger
import signal, zLOG


class SignalHandler:

    def __init__(self):
        self.registry = {}
        self.registerHandler(signal.SIGTERM, self.shutdownHandler)
        self.registerHandler(signal.SIGINT, self.shutdownHandler)
        self.registerHandler(signal.SIGHUP, self.restartHandler)
        self.registerHandler(signal.SIGUSR2, self.sigusr2Handler)

    def registerHandler(self, signum, handler):
        """Register a handler function that will be called when the process
           recieves the signal signum. The signum argument must be a signal
           constant such as SIGTERM. The handler argument must be a function
           or method that takes no arguments. Note that handlers will not
           be called on non-posix platforms."""
        if os.name != 'posix':
            return
        items = self.registry.get(signum)
        if items is None:
            items = self.registry[signum] = []
            signal.signal(signum, self.signalHandler)
            signame = zdaemon.Daemon.get_signal_name(signum)
            zLOG.LOG('Z2', zLOG.BLATHER, "Installed sighandler for %s" % (
                      signame
                      ))
        items.insert(0, handler)

    def getRegisteredSignals(self):
        """Return a list of the signals that have handlers registered. This
           is used to pass the signals through to the ZDaemon code."""
        return self.registry.keys()

    def signalHandler(self, signum, frame):
        """Meta signal handler that dispatches to registered handlers."""
        signame = zdaemon.Daemon.get_signal_name(signum)
        zLOG.LOG('Z2', zLOG.INFO , "Caught signal %s" % signame)

        for handler in self.registry.get(signum, []):
            # Never let a bad handler prevent the standard signal
            # handlers from running.
            try: handler()
            except SystemExit:
                # if we trap SystemExit, we can't restart
                raise
            except:
                zLOG.LOG('Z2', zLOG.WARNING,
                         'A handler for %s failed!' % signame,
                         error=sys.exc_info())

    # Builtin signal handlers for clean shutdown, restart and log rotation.

    def shutdownHandler(self):
        """Shutdown cleanly on SIGTERM, SIGINT. This is registered first,
           so it should be called after all other handlers."""
        self.closeall()
        zLOG.LOG('Z2', zLOG.INFO , "Shutting down")
        sys.exit(0)

    def restartHandler(self):
        """Restart cleanly on SIGHUP. This is registered first, so it
           should be called after all other SIGHUP handlers."""
        self.closeall()
        zLOG.LOG('Z2', zLOG.INFO , "Restarting")
        sys.exit(1)

    def sigusr2Handler(self):
        """Reopen log files on SIGUSR2. This is registered first, so it
           should be called after all other SIGUSR2 handlers."""
        zLOG.LOG('Z2', zLOG.INFO , "Reopening log files")
        reopen = getattr(getattr(sys, '__lg', None), 'reopen', None)
        if reopen is not None:
            reopen()
            zLOG.LOG('Z2', zLOG.BLATHER, "Reopened access log")
        reopen = getattr(getattr(sys, '__detailedlog', None), 'reopen', None)
        if reopen is not None:
            reopen()
            zLOG.LOG('Z2', zLOG.BLATHER,"Reopened detailed request log")
        if hasattr(zLOG, '_set_stupid_dest'):
            zLOG._set_stupid_dest(None)
        else:
            zLOG._stupid_dest = None
        ZLogger.stupidFileLogger._stupid_dest = None
        zLOG.LOG('Z2', zLOG.BLATHER, "Reopened event log")
        zLOG.LOG('Z2', zLOG.INFO, "Log files reopened successfully")
    
    def closeall(self):
        """Helper method to close network and database connections."""
        import Globals
        zLOG.LOG('Z2', zLOG.INFO, "Closing all open network connections")
        for socket in asyncore.socket_map.values():
            try: socket.close()
            except: pass

        zLOG.LOG('Z2', zLOG.INFO, "Closing all open ZODB databases")
        for db in Globals.opened:
            try: db.close()
            finally: pass



# The SignalHandler is actually a singleton.
SignalHandler = SignalHandler()




=== Added File Zope27/lib/python/ts_regex.py ===
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
# 
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
# 
##############################################################################
"""Provide a thread-safe interface to regex
"""
import regex, regsub #, Sync
from regex import *
from regsub import split, sub, gsub, splitx, capwords

try: 
    import thread
except:
    class allocate_lock:
        def acquire(*args): pass
        def release(*args): pass

else:
    class SafeFunction:
        _l=thread.allocate_lock()
        _a=_l.acquire
        _r=_l.release

        def __init__(self, f):
            self._f=f

        def __call__(self, *args, **kw):
            self._a()
            try: return apply(self._f, args, kw)
            finally: self._r()

    split=SafeFunction(split)
    sub=SafeFunction(sub)
    gsub=SafeFunction(gsub)
    splitx=SafeFunction(splitx)
    capwords=SafeFunction(capwords)

    allocate_lock=thread.allocate_lock

class compile:

    _r=None
    groupindex=None

    def __init__(self, *args):
        self._r=r=apply(regex.compile,args)
        self._init(r)

    def _init(self, r):
        lock=allocate_lock()
        self.__a=lock.acquire
        self.__r=lock.release
        self.translate=r.translate
        self.givenpat=r.givenpat
        self.realpat=r.realpat

    def match(self, string, pos=0):
        self.__a()
        try: return self._r.match(string, pos)
        finally: self.__r()

    def search(self, string, pos=0):
        self.__a()
        try: return self._r.search(string, pos)
        finally: self.__r()
        
    def search_group(self, str, group, pos=0):
        """Search a string for a pattern.

        If the pattern was not found, then None is returned,
        otherwise, the location where the pattern was found,
        as well as any specified group are returned.
        """
        self.__a()
        try:
            r=self._r
            l=r.search(str, pos)
            if l < 0: return None
            return l, apply(r.group, group)
        finally: self.__r()

    def match_group(self, str, group, pos=0):
        """Match a pattern against a string

        If the string does not match the pattern, then None is
        returned, otherwise, the length of the match, as well
        as any specified group are returned.
        """
        self.__a()
        try:
            r=self._r
            l=r.match(str, pos)
            if l < 0: return None
            return l, apply(r.group, group)
        finally: self.__r()

    def search_regs(self, str, pos=0):
        """Search a string for a pattern.

        If the pattern was not found, then None is returned,
        otherwise, the 'regs' attribute of the expression is
        returned.
        """
        self.__a()
        try:
            r=self._r
            r.search(str, pos)
            return r.regs
        finally: self.__r()

    def match_regs(self, str, pos=0):
        """Match a pattern against a string

        If the string does not match the pattern, then None is
        returned, otherwise, the 'regs' attribute of the expression is
        returned.
        """
        self.__a()
        try:
            r=self._r
            r.match(str, pos)
            return r.regs
        finally: self.__r()

class symcomp(compile):

    def __init__(self, *args):
        self._r=r=apply(regex.symcomp,args)
        self._init(r)
        self.groupindex=r.groupindex