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()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章