Skip to content

Instantly share code, notes, and snippets.

@ckazzku
Created May 26, 2015 18:26
Show Gist options
  • Save ckazzku/c31ff14271a82c345bee to your computer and use it in GitHub Desktop.
Save ckazzku/c31ff14271a82c345bee to your computer and use it in GitHub Desktop.
Simple web server for управления процессом
#!/usr/bin/env python2
import bottle
import os
import signal
import subprocess
import time
process = None
args = ['./start.sh']
def terminate_handler(signum, frame):
do_stop()
exit()
#--------------------#
def get_pid():
global process
pid = -1
if process:
pid = process.pid
return pid
def is_running():
pid = get_pid()
try:
os.killpg(pid, 0)
return True
except:
pass
return False
#--------------------#
@bottle.get('/')
def index():
html = '''<!DOCTYPE html>
<html>
<head><title>{{ title }}</title>{{ !script }}</head>
<body>
{{ !content }}
</body>
</html>
'''
script = '''<script>
function post(location) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
console.log(xmlhttp.responseText);
document.getElementById("result").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST", "/" + location, true);
xmlhttp.send();
}
</script>'''
button = '''<p><button onclick="post('{0}')">{0}</button></p>'''
res = '<hr/><p><div id="result"></div></p>'
content = button.format('start') + button.format('stop') + button.format('restart') + res
return bottle.template(html, title='process control', content=content, script=script)
@bottle.get('/status')
def get_status():
if is_running():
pid = get_pid()
return '{0} IS RUNNING'.format(pid)
return 'NOT RUNNING'
@bottle.post('/start')
def do_start():
global process
global args
if not process:
print 'start...'
process = subprocess.Popen(args, shell=True, preexec_fn=os.setsid)
return get_status()
@bottle.post('/restart')
def do_restart():
do_stop()
return do_start()
@bottle.post('/stop')
def do_stop():
global process
if process:
os.killpg(process.pid, signal.SIGTERM)
while process.poll() is None:
print '.',
time.sleep(1)
print 'stop.'
process = None
return get_status()
if __name__ == '__main__':
signal.signal(signal.SIGINT, terminate_handler)
signal.signal(signal.SIGTERM, terminate_handler)
bottle.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment