设置重启Django服务器Apache的Webhook最佳方法
我最开始尝试使用django,然后用django-webhooks来调用一个shell脚本,目的是重启服务器。但这个方法不行,因为当调用重启服务器时,网页会卡住,因为django正在重新加载。
之后,我用fastcgi和python单独创建了一个网址来调用这个shell脚本。我知道在服务器上直接运行这个python脚本是没问题的,但通过网址运行时却不行。
Apache的设置如下:
<VirtualHost *:80>
ServerName webhooks.myserver.com
DocumentRoot /home/ubuntu/web/common/www
<Directory />
Options FollowSymLinks +ExecCGI
AllowOverride All
</Directory>
<Files post.py>
SetHandler fastcgi-script
</Files>
FastCgiServer /home/ubuntu/web/common/www/post.py -processes 2 -socket /tmp/fcgi.sock
</VirtualHost>
Apache调用的python代码是:
#!/usr/bin/python
import fcgi, warnings, os, subprocess
BASE_DIR = os.getcwd()
def app(environ, start_response):
cmd = "sudo %s/../deploy/postwebhook.sh >> /var/log/votizen/webhooks_run.log 2>> /var/log/votizen/webhooks_error.log &" % BASE_DIR
warnings.warn("Running cmd=%s" % cmd)
bufsize = -1
PIPE = subprocess.PIPE
subprocess.Popen(cmd, shell=isinstance(cmd, basestring),
bufsize=bufsize, stdin=PIPE, stdout=PIPE,
stderr=PIPE, close_fds=True)
warnings.warn("Post deployment webhook completed")
start_response('200 OK', [('Content-Type', 'text/html')])
return('Hello World!')
fcgi.WSGIServer(app, bindAddress = '/tmp/fcgi.sock').run()
而shell脚本是:
#!/bin/bash
# restart the apache server
echo ' '
echo 'post webhooks started'
date '+%H:%M:%S %d-%m-%y'
apache2ctl -t; sudo /etc/init.d/apache2 stop; sudo /etc/init.d/apache2 start
# todo: check if apache failed
# copy media files for apps
echo "moving SC to S3"
python /home/ubuntu/web/corporate/manage.py sync_media_s3 -p sc
date '+%H:%M:%S %d-%m-%y'
echo 'post webhooks completed'
我在apache的日志里没有看到任何错误,访问日志显示触发的网址确实被调用了。不过,我只在重启后第一次调用这个网址时看到python的警告,但服务器并没有真正重启。
2 个回答
0
我没有使用django,不过用简单的python,下面的代码对我来说是有效的。
import os
os.system('apachectl -k restart')
0
我正在使用webfaction,下面这个脚本对我来说是有效的:
import time
import os
BASE_DIR = "/path/to/your/app/"
def stopit(app):
os.popen( os.path.join(BASE_DIR, "apache2", "bin", "stop") )
def startit(app):
os.popen( os.path.join(BASE_DIR, "apache2", "bin", "start") )
def restart(app):
stopit(app)
time.sleep(1)
startit(app)
然后“停止”脚本看起来是这样的:
#!/usr/local/bin/python
import os
lines = os.popen('ps -u username -o pid,command').readlines()
running = False
for line in lines:
if '/path/to/app/apache2/conf/httpd.conf' in line:
running = True
proc_id = line.split()[0]
os.system('kill %s 2> /dev/null' % proc_id)
if not running:
print "Not running"
else:
print "Stopped"
而“启动”脚本是:
/path/to/app/apache2/bin/httpd -f /path/to/app/apache2/conf/httpd.conf