python 写的一个Ice服务端在linux下面的守护进程程序

framework基本都是开发的远程调用方法

DBUtils.PooledDB 是一个python的mysql数据连接池。后期都改为SQLAlchemy的连接池了


 

#coding=utf-8
import sys,Ice,logging
from framework.ProspectEvent import *
from framework.ProductEvent import *
from framework.OrderEvent import *
from DBUtils.PooledDB import PooledDB
import MySQLdb
import settings
import time
import sys,os
from signal import SIGINT,SIGTERM,SIGKILL
def daemonize(stdout='/dev/null',stderr=None,stdin='/dev/nnull',pidfile=None,startmsg='started with pid $d'):
    sys.stdout.flush()
    sys.stderr.flush()
    pid=None
    try:
        pid=os.fork()
        if pid>0:
            sys.exit(0)
    except OSError,e:
        sys.stderr.write("fork #1 failed:(%d) %s/n"%(e.errno,e.strerror))
        sys.exit(1)
    os.chdir('/')
    os.umask(0)
    os.setsid()
    try:
        pid=os.fork()
        if pid>0:
            sys.exit(0)
    except OSError,e:
        sys.stderr.write("fork #2 failed:(%d) %s/n"%(e.errno,e.strerror))
        sys.exit(1)
    if not stderr:
        stderr=stdout
    si=file(stdin,'r')
    so=file(stdout,'a+')
    se=file(stderr,'a+',0)
    pid=str(os.getpid())
    sys.stderr.write("/n%s/n" % startmsg % pid)
    sys.stderr.flush()
    if pidfile:
        file(pidfile,'w+').write("%s/n" % pid)
    os.dup2(si.fileno(), sys.stdin.fileno())
    os.dup2(so.fileno(), sys.stdout.fileno())
    os.dup2(se.fileno(), sys.stderr.fileno())
class DaemonizeError(Exception):
    pass
def startstop(stdout='/dev/null', stderr=None, stdin='/dev/null',pidfile='pid.txt', startmsg = 'started with pid %s', action=None ):
    if not action and len(sys.argv)>1:
        action = sys.argv[1]
    if action:
        try:
            pf  = file(pidfile,'r')
            pid = int(pf.read().strip())
            pf.close()
        except IOError:
            pid = None
        if 'stop' == action or 'restart' == action:
            if not pid:
                mess = "Could not stop, pid file '%s' missing./n"
                raise DaemonizeError(mess % pidfile)
            try:
               while 1:
                   print "sending SIGINT to",pid
                   os.kill(pid,SIGINT)
                   time.sleep(2)
                   print "sending SIGTERM to",pid
                   os.kill(pid,SIGTERM)
                   time.sleep(2)
                   print "sending SIGKILL to",pid
                   os.kill(pid,SIGKILL)
                   time.sleep(1)
            except OSError, err:
               print "进程被成功终止..."
               os.remove(pidfile)
               if 'stop' == action:
                   return
               action='start'#ÖØÐÂÆô¶¯½ø³Ì
               pid =None
        if 'start'== action:
            if pid:
                mess =u"进程:'%s'已存在,请确认服务器是否在运行?/n"
                raise DaemonizeError(mess % pidfile)
            daemonize(stdout,stderr,stdin,pidfile,startmsg)
            return
    print "ÃüÁî: %s start|stop|restart" % sys.argv[0]
    raise DaemonizeError(u"输入命令无效...")
def run():
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                        datefmt='%a, %d %b %Y %H:%M:%S',
                        filename='server.log',
                        filemode='w')
    communicator = Ice.initialize(sys.argv)
    adapter = communicator.createObjectAdapterWithEndpoints('Poto','tcp -h 192.168.1.20 -p 10000')
    pool = PooledDB(MySQLdb,settings.SRV_DB_MAX,host=settings.SRV_DB_HOST,user=settings.SRV_DB_USER,
                    passwd=settings.SRV_DB_PASSWORD,db=settings.SRV_DB_NAME,charset=settings.SRV_DB_CHARSETS)
    iprospect=IProspectDirectory(pool)
    iproduct=IProductDirectory(pool)
    iorder=IOrderDirectory(pool)
    adapter.add(iprospect,communicator.stringToIdentity('Prospect'))
    adapter.add(iproduct,communicator.stringToIdentity('Product'))
    adapter.add(iorder,communicator.stringToIdentity('Order'))
    adapter.activate()
    communicator.waitForShutdown()
    sys.stdout.write(u"server is stop:%s",time.ctime(time.time()))
    communicator.destroy()
    pool.close()
if __name__=="__main__":
    startstop(stdout='/tmp/potoserver.log',pidfile='/tmp/daemonize.pid')
    if sys.argv[1]in ('start','restart'):
        run()

posted on 2010-03-22 11:10  reck for zhou  阅读(502)  评论(0编辑  收藏  举报

导航