<commit_before>"""Site services for use with a Web Site Process Bus."""

import os
import re
try:
    set
except NameError:
    from sets import Set as set
import signal as _signal
import sys
import time
import threading


class SimplePlugin(object):
    """Plugin base class which auto-subscribes methods for known channels."""
    
    def __init__(self, bus):
        self.bus = bus
    
    def subscribe(self):
        """Register this object as a (multi-channel) listener on the bus."""
        for channel in self.bus.listeners:
            method = getattr(self, channel, None)
            if method is not None:
                self.bus.subscribe(channel, method)
    
    def unsubscribe(self):
        """Unregister this object as a listener on the bus."""
        for channel in self.bus.listeners:
            method = getattr(self, channel, None)
            if method is not None:
                self.bus.unsubscribe(channel, method)



class SignalHandler(object):
    """Register bus channels (and listeners) for system signals.
    
    By default, instantiating this object subscribes the following signals
    and listeners:
    
        TERM: bus.exit
        HUP : bus.restart
        USR1: bus.graceful
    """
    
    # Map from signal numbers to names
    signals = {}
    for k, v in vars(_signal).items():
        if k.startswith('SIG') and not k.startswith('SIG_'):
            signals[v] = k
    del k, v
    
    def __init__(self, bus):
        self.bus = bus
        # Set default handlers
        self.handlers = {'SIGTERM': self.bus.exit,
                         'SIGHUP': self.bus.restart,
                         'SIGUSR1': self.bus.graceful,
                         }
    
    def subscribe(self):
        for sig, func in self.handlers.iteritems():
            try:
                self.set_handler(sig, func)
            except ValueError:
                pass
    
    def set_handler(self, signal, listener=None):
        """Subscribe a handler for the given signal (number or name).
        
        If the optional 'listener' argument is provided, it will be
        subscribed as a listener for the given signal's channel.
        
        If the given signal name or number is not available on the current
        platform, ValueError is raised.
        """
        if isinstance(signal, basestring):
            signum = getattr(_signal, signal, None)
            if signum is None:
                raise ValueError("No such signal: %r" % signal)
            signame = signal
        else:
            try:
                signame = self.signals[signal]
            except KeyError:
                raise ValueError("No such signal: %r" % signal)
            signum = signal
        
        # Should we do something with existing signal handlers?
        # cur = _signal.getsignal(signum)
        _signal.signal(signum, self._handle_signal)
        if listener is not None:
            self.bus.log("Listening for %s." % signame)
            self.bus.subscribe(signame, listener)
    
    def _handle_signal(self, signum=None, frame=None):
        """Python signal handler (self.set_handler subscribes it for you)."""
        signame = self.signals[signum]
        self.bus.log("Caught signal %s." % signame)
        self.bus.publish(signame)



try:
    import pwd, grp
except ImportError:
    pwd, grp = None, None


class DropPrivileges(SimplePlugin):
    """Drop privileges. uid/gid arguments not available on Windows.
    
    Special thanks to <NAME>: http://antonym.org/node/100.
    """
    
    def __init__(self, bus, umask=None, uid=None, gid=None):
        SimplePlugin.__init__(self, bus)
        self.finalized = False
        self.uid = uid
        self.gid = gid
        self.umask = umask
    
    def _get_uid(self):
        return self._uid
    def _set_uid(self, val):
        if val is not None:
            if pwd is None:
                self.bus.log("pwd module not available; ignoring uid.")
                val = None
            elif isinstance(val, basestring):
                val = pwd.getpwnam(val)[2]
        self._uid = val
    uid = property(_get_uid, _set_uid, doc="The uid under which to run.")
    
    def _get_gid(self):
        return self._gid
    def _set_gid(self, val):
        if val is not None:
            if grp is None:
                self.bus.log("grp module not available; ignoring gid.")
                val = None
            elif isinstance(val, basestring):
                val = grp.getgrnam(val)[2]
        self._gid = val
    gid = property(_get_gid, _set_gid, doc="The gid under which to run.")
    
    def _get_umask(self):
        return self._umask
    def _set_umask(self, val):
        if val is not None:
            try:
                os.umask
            except AttributeError:
                self.bus.log("umask function not available; ignoring umask.")
                val = None
        self._umask = val
    umask = property(_get_umask, _set_umask, doc="The umask under which to run.")
    
    def start(self):
        # uid/gid
        def current_ids():
            """Return the current (uid, gid) if available."""
            name, group = None, None
            if pwd:
                name = pwd.getpwuid(os.getuid())[0]
            if grp:
                group = grp.getgrgid(os.getgid())[0]
            return name, group
        
        if self.finalized:
            if not (self.uid is None and self.gid is None):
                self.bus.log('Already running as uid: %r gid: %r' %
                             current_ids())
        else:
            if self.uid is None and self.gid is None:
                self.bus.log('uid/gid not set')
            else:
                self.bus.log('Started as uid: %r gid: %r' % current_ids())
                if self.gid is not None:
                    os.setgid(gid)
                if self.uid is not None:
                    os.setuid(uid)
                self.bus.log('Running as uid: %r gid: %r' % current_ids())
        
        # umask
        if self.finalized:
            if self.umask is not None:
                self.bus.log('umask already set to: %03o' % self.umask)
        else:
            if self.umask is None:
                self.bus.log('umask not set')
            else:
                old_umask = os.umask(self.umask)
                self.bus.log('umask old: %03o, new: %03o' %
                             (old_umask, self.umask))
        
        self.finalized = True
    start.priority = 75


class Daemonizer(SimplePlugin):
    """Daemonize the running script.
    <commit_msg>On Windows, no need to log "uid/gid not set".<commit_after>"""Site services for use with a Web Site Process Bus."""

import os
import re
try:
    set
except NameError:
    from sets import Set as set
import signal as _signal
import sys
import time
import threading


class SimplePlugin(object):
    """Plugin base class which auto-subscribes methods for known channels."""
    
    def __init__(self, bus):
        self.bus = bus
    
    def subscribe(self):
        """Register this object as a (multi-channel) listener on the bus."""
        for channel in self.bus.listeners:
            method = getattr(self, channel, None)
            if method is not None:
                self.bus.subscribe(channel, method)
    
    def unsubscribe(self):
        """Unregister this object as a listener on the bus."""
        for channel in self.bus.listeners:
            method = getattr(self, channel, None)
            if method is not None:
                self.bus.unsubscribe(channel, method)



class SignalHandler(object):
    """Register bus channels (and listeners) for system signals.
    
    By default, instantiating this object subscribes the following signals
    and listeners:
    
        TERM: bus.exit
        HUP : bus.restart
        USR1: bus.graceful
    """
    
    # Map from signal numbers to names
    signals = {}
    for k, v in vars(_signal).items():
        if k.startswith('SIG') and not k.startswith('SIG_'):
            signals[v] = k
    del k, v
    
    def __init__(self, bus):
        self.bus = bus
        # Set default handlers
        self.handlers = {'SIGTERM': self.bus.exit,
                         'SIGHUP': self.bus.restart,
                         'SIGUSR1': self.bus.graceful,
                         }
    
    def subscribe(self):
        for sig, func in self.handlers.iteritems():
            try:
                self.set_handler(sig, func)
            except ValueError:
                pass
    
    def set_handler(self, signal, listener=None):
        """Subscribe a handler for the given signal (number or name).
        
        If the optional 'listener' argument is provided, it will be
        subscribed as a listener for the given signal's channel.
        
        If the given signal name or number is not available on the current
        platform, ValueError is raised.
        """
        if isinstance(signal, basestring):
            signum = getattr(_signal, signal, None)
            if signum is None:
                raise ValueError("No such signal: %r" % signal)
            signame = signal
        else:
            try:
                signame = self.signals[signal]
            except KeyError:
                raise ValueError("No such signal: %r" % signal)
            signum = signal
        
        # Should we do something with existing signal handlers?
        # cur = _signal.getsignal(signum)
        _signal.signal(signum, self._handle_signal)
        if listener is not None:
            self.bus.log("Listening for %s." % signame)
            self.bus.subscribe(signame, listener)
    
    def _handle_signal(self, signum=None, frame=None):
        """Python signal handler (self.set_handler subscribes it for you)."""
        signame = self.signals[signum]
        self.bus.log("Caught signal %s." % signame)
        self.bus.publish(signame)



try:
    import pwd, grp
except ImportError:
    pwd, grp = None, None


class DropPrivileges(SimplePlugin):
    """Drop privileges. uid/gid arguments not available on Windows.
    
    Special thanks to <NAME>: http://antonym.org/node/100.
    """
    
    def __init__(self, bus, umask=None, uid=None, gid=None):
        SimplePlugin.__init__(self, bus)
        self.finalized = False
        self.uid = uid
        self.gid = gid
        self.umask = umask
    
    def _get_uid(self):
        return self._uid
    def _set_uid(self, val):
        if val is not None:
            if pwd is None:
                self.bus.log("pwd module not available; ignoring uid.")
                val = None
            elif isinstance(val, basestring):
                val = pwd.getpwnam(val)[2]
        self._uid = val
    uid = property(_get_uid, _set_uid, doc="The uid under which to run.")
    
    def _get_gid(self):
        return self._gid
    def _set_gid(self, val):
        if val is not None:
            if grp is None:
                self.bus.log("grp module not available; ignoring gid.")
                val = None
            elif isinstance(val, basestring):
                val = grp.getgrnam(val)[2]
        self._gid = val
    gid = property(_get_gid, _set_gid, doc="The gid under which to run.")
    
    def _get_umask(self):
        return self._umask
    def _set_umask(self, val):
        if val is not None:
            try:
                os.umask
            except AttributeError:
                self.bus.log("umask function not available; ignoring umask.")
                val = None
        self._umask = val
    umask = property(_get_umask, _set_umask, doc="The umask under which to run.")
    
    def start(self):
        # uid/gid
        def current_ids():
            """Return the current (uid, gid) if available."""
            name, group = None, None
            if pwd:
                name = pwd.getpwuid(os.getuid())[0]
            if grp:
                group = grp.getgrgid(os.getgid())[0]
            return name, group
        
        if self.finalized:
            if not (self.uid is None and self.gid is None):
                self.bus.log('Already running as uid: %r gid: %r' %
                             current_ids())
        else:
            if self.uid is None and self.gid is None:
                if pwd or grp:
                    self.bus.log('uid/gid not set')
            else:
                self.bus.log('Started as uid: %r gid: %r' % current_ids())
                if self.gid is not None:
                    os.setgid(gid)
                if self.uid is not None:
                    os.setuid(uid)
                self.bus.log('Running as uid: %r gid: %r' % current_ids())
        
        # umask
        if self.finalized:
            if self.umask is not None:
                self.bus.log('umask already set to: %03o' % self.umask)
        else:
            if self.umask is None:
                self.bus.log('umask not set')
            else:
                old_umask = os.umask(self.umask)
                self.bus.log('umask old: %03o, new: %03o' %
                             (old_umask, self.umask))
        
        self.finalized = True
    start.priority = 75


class Daemonizer(SimplePlugin):
    """Daemonize the running script.
    
{'fraction_non_alphanumeric': 0.0932478310071671, 'fraction_numerical': 0.0025650697849867975, 'mean_word_length': 1.6538538538538539, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5366190', 'n_tokens_mistral': 3869, 'n_tokens_neox': 3722, 'n_words': 1188}