From: Vincent Le Gallic Date: Wed, 18 Jul 2012 19:25:33 +0000 (+0200) Subject: C'est cool d'être daemonizable X-Git-Url: http://gitweb.pimeys.fr/?a=commitdiff_plain;h=bc481af86a1c451def138702bb565929492be53b;p=bots%2Fthemis.git C'est cool d'être daemonizable --- diff --git a/themis.py b/themis.py index 5062e50..64212f7 100755 --- a/themis.py +++ b/themis.py @@ -4,8 +4,6 @@ # Un bot IRC pour kicker à tour de bras de #déprime -import irclib -import ircbot import threading import random import time @@ -13,6 +11,13 @@ import socket, ssl, json import pickle import re import os +import signal +import sys + +# Oui, j'ai recodé ma version d'irclib pour pouvoir rattrapper les SIGHUP +sys.path.insert(0, "/home/vincent/scripts/python-myirclib") +import irclib +import ircbot import sys config_debug_stdout=True @@ -680,18 +685,48 @@ class Themis(ircbot.SingleServerIRCBot): def _getnick(self): return self.serv.get_nickname() nick=property(_getnick) + + def start_as_daemon(self, outfile): + sys.stderr = Logger(outfile) + self.start() + + +class Logger(object): + """Pour écrire ailleurs que sur stdout""" + def __init__(self, filename="themis.full.log"): + self.filename = filename + + def write(self, message): + f = open(self.filename, "a") + f.write(message) + f.close() if __name__=="__main__": import sys if len(sys.argv)==1: - print "Usage : themis.py [--debug]" + print "Usage : themis.py [--debug] [--no-output] [--daemon [--pidfile]] [--outfile]" + print " --outfile sans --no-output ni --daemon n'a aucun effet" exit(1) serveur=sys.argv[1] + if "--daemon" in sys.argv: + thisfile = os.path.realpath(__file__) + thisdirectory = thisfile.rsplit("/", 1)[0] + os.chdir(thisdirectory) + daemon = True + else: + daemon = False if "debug" in sys.argv or "--debug" in sys.argv: debug=True else: debug=False + if "--no-output" in sys.argv or "--daemon" in sys.argv: + outfile = "/var/log/bots/themis.full.log" + for arg in sys.argv: + arg = arg.split("=") + if arg[0].strip('-') in ["out", "outfile", "logfile"]: + outfile = arg[1] + sys.stdout = Logger(outfile) serveurs={"a♡":"acoeur.crans.org","acoeur":"acoeur.crans.org","acoeur.crans.org":"acoeur.crans.org", "irc":"irc.crans.org","crans":"irc.crans.org","irc.crans.org":"irc.crans.org"} try: @@ -700,4 +735,21 @@ if __name__=="__main__": print "Server Unknown : %s"%(serveur) exit(404) themis=Themis(serveur,debug) - themis.start() + if daemon: + child_pid = os.fork() + if child_pid == 0: + os.setsid() + themis.start_as_daemon(outfile) + else: + # on enregistre le pid de themis + pidfile = "/var/run/bots/themis.pid" + for arg in sys.argv: + arg = arg.split("=") + if arg[0].strip('-') in ["pidfile"]: + pidfile = arg[1] + f = open(pidfile, "w") + f.write("%s\n" % child_pid) + f.close() + else: + themis.start() +