view mcserver/mcserver.py @ 5:1adf97ba90c8

added visual client
author gyorgyf
date Thu, 21 Jun 2012 17:14:09 +0100
parents 02b4c5e122e8
children 9d9169751aba
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__

if not os.path.isfile(CONFIG_FILE) :
	print >> sys.stderr, "Config file not found: %s" %CONFIG_FILE
	sys.exit(-1)


class MoodConductor:
	
	def __init__(self):
		self.x = 0.0
		self.y = 0.0
	
	def index(self):
		return ""
	
	@cp.expose
	def mood(self,x,y):
		print "Received coordinates", x,y, "\n"
		self.x, self.y = x,y
		return ""
		
	@cp.expose
	def result(self):
		return "(%s,%s)" %(self.x,self.y)
	



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
	cp.config.update(CONFIG_FILE)
	cp.config.update({'tools.staticdir.root': os.getcwd()})
	cp.tree.mount(MoodConductor(),script_name="/moodconductor",config=CONFIG_FILE)	
	port = int(cp.server.socket_port)
	ip = cp.server.socket_host
	print "Trying to bind: %(ip)s:%(port)s" %locals()
	getProcessPids(port,kill=True)
	cp.quickstart()

if __name__ == "__main__":
	main()