app/django/utils/daemonize.py
author Daniel Bentley <dbentley@google.com>
Sun, 12 Apr 2009 09:06:45 +0000
branchgae-fetch-limitation-fix
changeset 2313 c39a81bce1bd
parent 323 ff1a9aa48cfd
permissions -rw-r--r--
Use offset_linkid instead of offset to scan >1000 entities. this is a first-cut. It works in all the ways I could make earlier versions fail. It passes link_id as URL parameters. It also has a new class LinkCreator which makes the main body of getListContents even easier to write. I wasn't sure if link_id's could have non alphanumeric characters; if so, they need to be URL encoded/decoded. I also need to go and remove any mention of raw offsets now, because we don't use them. I believe I've talked about this approach with a few of you and it sounded reasonable. Feel free to roll-back/fix/amend/comment-for-me-to-fix. This is my first big-logic-change to Melange. Patch by: Dan Bentley

import os
import sys

if os.name == 'posix':
    def become_daemon(our_home_dir='.', out_log='/dev/null',
                      err_log='/dev/null', umask=022):
        "Robustly turn into a UNIX daemon, running in our_home_dir."
        # First fork
        try:
            if os.fork() > 0:
                sys.exit(0)     # kill off parent
        except OSError, e:
            sys.stderr.write("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror))
            sys.exit(1)
        os.setsid()
        os.chdir(our_home_dir)
        os.umask(umask)

        # Second fork
        try:
            if os.fork() > 0:
                os._exit(0)
        except OSError, e:
            sys.stderr.write("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror))
            os._exit(1)

        si = open('/dev/null', 'r')
        so = open(out_log, 'a+', 0)
        se = open(err_log, 'a+', 0)
        os.dup2(si.fileno(), sys.stdin.fileno())
        os.dup2(so.fileno(), sys.stdout.fileno())
        os.dup2(se.fileno(), sys.stderr.fileno())
        # Set custom file descriptors so that they get proper buffering.
        sys.stdout, sys.stderr = so, se
else:
    def become_daemon(our_home_dir='.', out_log=None, err_log=None, umask=022):
        """
        If we're not running under a POSIX system, just simulate the daemon
        mode by doing redirections and directory changing.
        """
        os.chdir(our_home_dir)
        os.umask(umask)
        sys.stdin.close()
        sys.stdout.close()
        sys.stderr.close()
        if err_log:
            sys.stderr = open(err_log, 'a', 0)
        else:
            sys.stderr = NullDevice()
        if out_log:
            sys.stdout = open(out_log, 'a', 0)
        else:
            sys.stdout = NullDevice()

    class NullDevice:
        "A writeable object that writes to nowhere -- like /dev/null."
        def write(self, s):
            pass