Skip to content

Instantly share code, notes, and snippets.

@progrium
Created May 18, 2010 02:47
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save progrium/404549 to your computer and use it in GitHub Desktop.
Save progrium/404549 to your computer and use it in GitHub Desktop.
twistd-style nodejs daemonizer
#!/usr/bin/env python
# Copyright (c) 2010 Jeff Lindsay
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# Usage: noded.py [options] script
#
# Daemonizes a node.js script with various options
#
# Options:
# -h, --help show this help message and exit
# -l LOGFILE, --logfile=LOGFILE
# log stdout to a file [default: noded.log]
# -p PIDFILE, --pidfile=PIDFILE
# write the PID to a file [default: noded.pid]
# -u UID, --uid=UID set the process user
# -g GID, --gid=GID set the process group
# -c CHROOT, --chroot=CHROOT
# chroot the process
# -b BINARY, --binary=BINARY
# path to node binary [default: node]
import sys, os, pwd, grp, tempfile
from optparse import OptionParser
wrapper = """var fs = require('fs'), script = process.binding('evals').Script;
fs.writeFileSync('%(pidfile)s', process.pid.toString());
global['exports'] = exports;
global['require'] = require;
global['module'] = module;
global['__filename']= __filename;
global['__dirname'] = __dirname;
script.runInThisContext(fs.readFileSync('%(script)s'), global, '%(script)s');
if (%(uid)s) { process.setuid(%(uid)s); }
if (%(gid)s) { process.setgid(%(gid)s); }"""
def daemonize (stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
'''Originally from: http://www.noah.org/wiki/Daemonize_Python'''
try:
pid = os.fork()
if pid > 0:
sys.exit(0) # Exit first parent.
except OSError, e:
sys.stderr.write ("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror) )
sys.exit(1)
os.umask(0)
os.setsid()
try:
pid = os.fork()
if pid > 0:
sys.exit(0) # Exit second parent.
except OSError, e:
sys.stderr.write ("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror) )
sys.exit(1)
si = open(stdin, 'r')
so = open(stdout, 'a+')
se = open(stderr, 'a+', 0)
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
if __name__ == "__main__":
parser = OptionParser("usage: %prog [options] script", description="Daemonizes a node.js script with various options")
parser.add_option("-l", "--logfile", dest="logfile", help="log stdout to a file [default: noded.log]", default='noded.log')
parser.add_option("-p", "--pidfile", dest="pidfile", help="write the PID to a file [default: noded.pid]", default='noded.pid')
parser.add_option("-u", "--uid", dest="uid", help="set the process user")
parser.add_option("-g", "--gid", dest="gid", help="set the process group")
parser.add_option("-c", "--chroot", dest="chroot", help="chroot the process")
parser.add_option("-b", "--binary", dest="binary", help="path to node binary [default: node]", default='node')
(options, args) = parser.parse_args()
if len(args) == 0:
parser.print_help()
exit()
daemonize('/dev/null', options.logfile, options.logfile)
if options.uid: options.uid = pwd.getpwnam(options.uid)[2]
if options.gid: options.gid = grp.getgrnam(options.gid)[2]
with tempfile.NamedTemporaryFile(delete=False,suffix='.'+args[0].replace('/', '-')) as f:
f.write(wrapper % dict(
pidfile=options.pidfile,
script=args[0],
uid=options.uid or 'null',
gid=options.gid or 'null'))
script = f.name
if options.chroot:
os.execvp('chroot', ['chroot', options.chroot, options.binary, script])
else:
os.execvp(options.binary, [options.binary, script])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment