【问题标题】:Start daemon process within BaseHTTPServer在 BaseHTTPServer 中启动守护进程
【发布时间】:2014-04-16 15:29:47
【问题描述】:

为了允许帮助台重新启动 Oracle 实例,我们正在尝试实现一个小型 Python 网络服务器,该服务器将启动一个用于启动 Oracle 实例的 shell 脚本。

代码完成,它启动了实例,但有一个问题:实例连接到网络服务器,所以直到实例停止后浏览器的缓冲区才关闭,并且有一个ora_pmon_INSTANCE进程监听网络服务器端口。

我尝试使用以下命令启动脚本:

process = os.system("/home/oracle/scripts/webservice/prueba.sh TFINAN")

process = subprocess.Popen(["/home/oracle/scripts/webservice/prueba.sh", "TFINAN"], shell=False, stdout=subprocess.PIPE)`

但它发生了同样的事情。

我还尝试使用 daemon 启动脚本(使用 redhat 的 init 脚本中的 daemon 函数)。该脚本以相同的结果启动 Oracle 实例。

这是我的代码:

#!/usr/bin/python

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from SocketServer import ThreadingMixIn
import threading
import argparse, urlparse
import re
import cgi, sys, time
import os, subprocess

class HTTPRequestHandler(BaseHTTPRequestHandler):

    def do_POST(self):
        self.send_response(403)
        self.send_header('Content-Type', 'text/html')
        self.end_headers()

        return

    def do_GET(self):
        ko = False
        respuesta = ""
        params = {}
        myProc = -1
        parsed_path = urlparse.urlparse(self.path)
        try:
            params = dict([p.split('=') for p in parsed_path[4].split('&')])
        except:
            params = {}

        elif None != re.search('/prueba/*', self.path):
            self.send_response(200)
            respuesta = "Hola Mundo! -->" + str( params['database'] )

        elif None != re.search('/startup/*', self.path):
            self.send_response(200)
            self.send_header('Content-Type', 'text/html')
            self.end_headers()
            cmd = """ <html>
                        <body><H2> Iniciando instancia oracle: """ + str( params["database"]) + '. Espere un momento, por favor ...</H2>'

            self.wfile.write(cmd)

            #process = os.system("/home/oracle/scripts/webservice/prueba.sh INSTANCE")
            process = subprocess.Popen(["/home/oracle/scripts/webservice/prueba.sh", "INSTANCE"], shell=False, stdout=subprocess.PIPE)
            # wait for the process to terminate
            out, err = process.communicate()
            errcode = process.returncode
            if errcode == 0:
                self.wfile.write("""<H1> Instancia iniciada correctamente
                                </H1>
                            </body> </html>""")
                self.wfile.close()
            else:
                respuestaok = "Error inicializando la instancia: " + str( params['database']) + " Intentelo de nuevo pasados unos minutos y si vuelve a fallar escale la incidencia al siguiente nivel de soporte"

        else:
            self.send_response(403, 'Bad Request: pagina no existe')
            respuesta = "Solicitud no autorizada"

        if respuesta != "":
            self.send_response(200)
            self.send_header('Content-Type', 'text/html')
            self.end_headers()
            self.wfile.write(respuesta)
            self.wfile.close()

        if ko:
            server.stop()           

        return


class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    allow_reuse_address = True

    def shutdown(self):
        self.socket.close()
        sys.exit(0)

class SimpleHttpServer(object):
    def __init__(self, ip, port):
        self.server = ThreadedHTTPServer((ip,port), HTTPRequestHandler)

    def start(self):
        self.server_thread = threading.Thread(target=self.server.serve_forever)
        self.server_thread.daemon = True
        self.server_thread.start()

    def waitForThread(self):
        self.server_thread.join()

    def stop(self):
        self.server.shutdown()

if __name__=='__main__':
    parser = argparse.ArgumentParser(description='HTTP Server')
    parser.add_argument('port', type=int, help='Listening port for HTTP Server')
    parser.add_argument('ip', help='HTTP Server IP')
    args = parser.parse_args()

    server = SimpleHttpServer(args.ip, args.port)
    print 'HTTP Server Running...........'
    server.start()
    server.waitForThread()

有谁能帮帮我吗?

【问题讨论】:

    标签: python linux bash basehttpserver


    【解决方案1】:

    您的问题与 HTTP 服务器无关。从 Python 代码控制 Oracle 守护程序似乎有一般问题。

    首先尝试编写一个简单的 python 脚本,它可以满足您的需求。

    我的猜测是,您的尝试在读取守护程序控制脚本的输出时遇到了问题。

    另请参阅Popen.communicate() 以读取命令的输出。其他选项可能是调用 subprocess.call()

    有很多关于从 Python 调用系统命令的教程,例如this one

    除了纯粹的 Python 相关问题之外,您可能会遇到权限问题 - 如果您的用户运行脚本/HTTP 服务器不允许调用 oracle 控制脚本,那么您还有另一个问题(可能有解决方案,在 Linux 上添加该用户进入 sudoers)。

    在您解决调用脚本的问题后,应该很容易让它在您的 HTTP 服务器内工作。

    【讨论】:

      猜你喜欢
      • 2010-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-21
      • 2012-01-13
      • 2011-08-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多