<commit_before>import os
import sys
import pwd
import grp
import logging.handlers
import signal
import atexit

# For becoming the daemon django.utils.daemonize.become_daemon() is used.
# The additional daemon-stuff utilities follow:

def drop_privileges(user='nobody', group='nogroup'):
    """
    Drop privileges if we're superuser by changing UID/GID to given user/group.
    """
    if os.geteuid() == 0:
        # Remove group privileges
        os.setgroups([])

        if group != 'root':
            try:
                newgid = grp.getgrnam(group).gr_gid
            except KeyError:
                raise RuntimeError("System group '%s' not found." % group)

            os.setgid(newgid)
            os.setegid(newgid)

        if user != 'root':
            try:
                newuid = pwd.getpwnam(user).pw_uid
            except KeyError:
                raise RuntimeError("System user '%s' not found." % user)

            os.setuid(newuid)
            os.seteuid(newuid)


def install_termination_logging_signal_handlers():
    """
    Install the handler for every reconfigurable signal (except some
    ignorables). On signal, the event is logged and process is terminated.
    """
    def sig_handler(signum, unused_frame):
        signames = [ n for n,v in signal.__dict__.iteritems()
                       if n.startswith('SIG') and v==signum ]
        signame = signames and ' (%s)' % signames[0] or ''
        logging.info("Terminating with signal %d%s." % (signum, signame))
        sys.exit(2)     # calls exit_function

    for s in xrange(100):
        if s not in (signal.SIGCHLD, signal.SIGURG, signal.SIGWINCH):
            try:
                signal.signal(s, sig_handler)
            except:
                pass


def init_syslog(log_level_name, process_ident):
    """
    Set the root logger to be directed to syslog from the given level
    and with given ident string (which will get prepended to every message).
    """
    logging.root.setLevel(logging.getLevelName(log_level_name))
    if len(logging.root.handlers) == 0:
        fmt = '%s %%(levelname)s: %%(message)s' % process_ident
        hdlr = logging.handlers.SysLogHandler(address='/dev/log')
        hdlr.setFormatter(logging.Formatter(fmt))
        logging.root.addHandler(hdlr)


def setup_pidfile(pidfile_path):
    """
    Fails if there is something at the given path. Otherwise, writes
    the current PID to file at that path. Also sets the atexit
    handler to automatically remove the file upon exit.

    Note: The process needs to have file removing privileges in the end.<commit_msg>Fixes to init_syslog for backward compats.<commit_after>import os
import sys
import pwd
import grp
import logging.handlers
import signal
import atexit

# For becoming the daemon django.utils.daemonize.become_daemon() is used.
# The additional daemon-stuff utilities follow:

def drop_privileges(user='nobody', group='nogroup'):
    """
    Drop privileges if we're superuser by changing UID/GID to given user/group.
    """
    if os.geteuid() == 0:
        # Remove group privileges
        os.setgroups([])

        if group != 'root':
            try:
                newgid = grp.getgrnam(group).gr_gid
            except KeyError:
                raise RuntimeError("System group '%s' not found." % group)

            os.setgid(newgid)
            os.setegid(newgid)

        if user != 'root':
            try:
                newuid = pwd.getpwnam(user).pw_uid
            except KeyError:
                raise RuntimeError("System user '%s' not found." % user)

            os.setuid(newuid)
            os.seteuid(newuid)


def install_termination_logging_signal_handlers():
    """
    Install the handler for every reconfigurable signal (except some
    ignorables). On signal, the event is logged and process is terminated.
    """
    def sig_handler(signum, unused_frame):
        signames = [ n for n,v in signal.__dict__.iteritems()
                       if n.startswith('SIG') and v==signum ]
        signame = signames and ' (%s)' % signames[0] or ''
        logging.info("Terminating with signal %d%s." % (signum, signame))
        sys.exit(2)     # calls exit_function

    for s in xrange(100):
        if s not in (signal.SIGCHLD, signal.SIGURG, signal.SIGWINCH):
            try:
                signal.signal(s, sig_handler)
            except:
                pass


def init_syslog(level, process_ident, address='/dev/log', facility='daemon'):
    """
    Set the root logger to be directed to syslog from the given level
    and with given ident string (which will get prepended to every message).
    """
    logging.root.setLevel(level)
    if len(logging.root.handlers) == 0:
        fmt = '%s %%(levelname)s: %%(message)s' % process_ident
        hdlr = logging.handlers.SysLogHandler(address, facility)
        hdlr.setFormatter(logging.Formatter(fmt))
        logging.root.addHandler(hdlr)


def setup_pidfile(pidfile_path):
    """
    Fails if there is something at the given path. Otherwise, writes
    the current PID to file at that path. Also sets the atexit
    handler to automatically remove the file upon exit.

    Note: The process needs to have file removing privileges in the end.
{'fraction_non_alphanumeric': 0.09631186699789795, 'fraction_numerical': 0.0026753296388304986, 'mean_word_length': 2.4321311475409835, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, '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': '3476164', 'n_tokens_mistral': 1575, 'n_tokens_neox': 1504, 'n_words': 473}