import xmlconfig
configFile = "config.xml"
configOptions = {}
-opts, args = getopt.getopt(sys.argv[1:], "bc:o:dDgtl:h", ["background", "config=", "option=", "debug", "Debug", "garbage", "traceback", "log=", "help"])
+opts, args = getopt.getopt(sys.argv[1:], "bc:o:dDgtlp:h", ["background", "config=", "option=", "debug", "Debug", "garbage", "traceback", "log=", "pid=", "help"])
for o, v in opts:
if o in ("-c", "--config"):
configFile = v
config.debugLevel = "1"
elif o in ("-l", "--log"):
config.debugFile = v
+ elif o in ("-p", "--pid"):
+ config.pid = v
elif o in ("-o", "--option"):
var, setting = v.split("=", 2)
configOptions[var] = setting
print " -g print garbage collection output"
print " -t print debugging only on traceback"
print " -l <file> write debugging output to file"
+ print " -p <file> write process ID to file"
print " -o <var>=<setting> set config var to setting"
sys.exit(0)
class App:
def __init__(self):
# Check for any other instances
+ if config.pid and os.name != "posix":
+ config.pid = ""
if config.pid:
- self.checkPID()
+ twistd.checkPID(config.pid)
# Do any auto-update stuff
housekeep.init()
# Daemonise the process and write the PID file
- if config.background:
- self.daemonise()
+ if config.background and os.name == "posix":
+ twistd.daemonize()
if config.pid:
self.writePID()
self.c.startService()
reactor.addSystemEventTrigger('before', 'shutdown', self.shuttingDown)
- def checkPID(self):
- # Check that we're not already running
- if os.path.isfile(config.pid):
- if os.name == "posix":
- pf = open(config.pid)
- pid = int(str(pf.readline().strip()))
- pf.close()
- try:
- os.kill(pid, signal.SIGHUP)
- self.alreadyRunning()
- except OSError:
- pass
- else:
- self.alreadyRunning()
-
def writePID(self):
# Create a PID file
pid = str(os.getpid())
sys.__stdout__.write("There is already a transport instance running with this configuration.\nExiting...\n\n")
sys.exit(1)
- def daemonise(self):
- try:
- pid = os.fork()
- if pid > 0:
- sys.exit(0)
- except OSError, e:
- sys.stderr.write("Daemonise failed: (%d) %s\n" % (e.errno, e.strerror))
- sys.exit(1)
-
def shuttingDown(self):
self.transportSvc.removeMe()
# Keep the transport running for another 3 seconds
def cb(ignored=None):
if config.pid:
- os.remove(config.pid)
+ twistd.removePID(config.pid)
d = Deferred()
d.addCallback(cb)
reactor.callLater(3.0, d.callback, None)
def SIGHUPstuff(*args):
global configFile, configOptions
xmlconfig.reloadConfig(configFile, configOptions)
+ if config.pid and os.name != "posix":
+ config.pid = ""
debug.reloadConfig()
legacy.reloadConfig()
import signal
# Set SIGHUP to reload the config file & close & open debug file
signal.signal(signal.SIGHUP, SIGHUPstuff)
+ # Load some scripts for PID and daemonising
+ from twisted.scripts import twistd
def main():