2010-09-15 61 views
2

我首先嚐試使用django,然後使用django-webhooks調用重新啓動服務器的shell腳本。這是行不通的,因爲當重新加載django時,在重新啓動服務器時網頁會掛起。設置webhook爲django服務器重新啓動apache的最佳方式

然後,我單獨使用fastcgi和python創建一個調用shell腳本的URL。我知道python腳本在服務器上運行時工作,但不知道它是從URL運行的。

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日誌和訪問日誌中的錯誤表明正在調用觸發URL。但是,我只會在重新啓動後第一次調用URL時纔會看到python警告,並且它從不真正重新啓動服務器。

回答

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 
+0

Ryan,這對我不起作用。沒有通過Apache提供此腳本?我看到的是Apache停止運行時,整個腳本停止運行,因此Apache再也不會重新啓動。 – 2010-09-15 20:14:20

+0

運行「開始」腳本不起作用?您可能需要等待1秒以上才能關閉Apache。可靠的方法是檢查您的流程列表... – 2010-09-16 07:26:44

0

我沒有使用django,但簡單的python下面的代碼適用於我。

import os 
os.system('apachectl -k restart')