Mercurial > hg > mood-conductor
view mcserver/mcserver.py @ 2:60e254d948c2
some server confic mods
author | gyorgyf |
---|---|
date | Sat, 16 Jun 2012 21:59:05 +0100 |
parents | 71cea958c8a2 |
children | 0aa5f9e5c24e |
line wrap: on
line source
#!/usr/bin/env python # encoding: utf-8 """ mcserver.py Created by George Fazekas on 2012-06-16. Copyright (c) 2012 . All rights reserved. """ import os,sys,optparse,signal import cherrypy as cp from cherrypy.lib import static import subprocess as sp from subprocess import Popen as spopen op = optparse.OptionParser() op.add_option('-u', '--user', action="store", dest="USER", default="server", type="str") options, args = op.parse_args() CONFIG_FILE = "mc%(USER)s.cfg" %options.__dict__ print CONFIG_FILE if not os.path.isfile(CONFIG_FILE) : print >> sys.stderr, "Config file not found." sys.exit(-1) class MoodConductor: # @cp.expose def index(self): return "Hello world!" # index.exposed = True @cp.expose def mood(self,x,y): print x,y return "OK" def getProcessPids(port,kill=False): '''Get the pid of the offending Python process given a port after an unsuccessful restart.''' print "Running lsof -i :"+str(port)," ...\n\n" command = "lsof -i :"+str(port) w = spopen(command,stdout=sp.PIPE,stderr=sp.PIPE,shell=True) se = w.stderr.readlines() result = w.stdout.readlines() exitcode = w.wait() if not result : print "getProcessPid:: Unable to obtain process pid. (lsof returned nothing. exitcode: %s)" %str(exitcode) return False import pprint pprint.pprint(result) # get heading: ix = None head = result[0].upper() if 'PID' in head: head = filter(lambda x: x != str(), head.split(' ')) head = map(lambda x: x.strip().replace(' ',''), head) if 'PID' in head : ix = head.index('PID') # get process pid pids = [] for line in result : if 'python' in line.lower() : line = filter(lambda x: x != str(), line.split(' ')) line = map(lambda x: x.strip().replace(' ',''), line) try : if ix : pids.append(int(line[ix])) else: numbers = filter(lambda x: x.isdigit(), line) pids.append(int(numbers[0])) except: print 'Error parsing lsof results.' return False print 'Pids found: ',pids # kill if specified if kill : pids_killed = [] import signal for pid in pids: print 'Killing process: ',pid try : os.kill(pid,signal.SIGKILL) pids_killed.append(pid) except : print 'Failed: ',pid if pids_killed : print 'Processes killed:',pids_killed,' Waiting 10 secods...' import time time.sleep(10) return True return False def main(argv=None): # Configure and start # port = 8030 # cp.config.update({'server.socket_host': '127.0.0.1'}) # cp.config.update({'server.socket_port': port}) cp.config.update({'tools.staticdir.root': os.getcwd()}) port = int(cp.server.socket_port) getProcessPids(port,kill=True) cp.tree.mount(MoodConductor(),script_name="/moodconductor",config=CONFIG_FILE) cp.quickstart() if __name__ == "__main__": main()