在BaseHTTPServer中启动守护进程

0 投票
1 回答
1122 浏览
提问于 2025-04-18 03:00

为了让客服能够重启Oracle实例,我们正在尝试实现一个小的Python网络服务器,这个服务器会启动一个shell脚本来启动Oracle实例。

代码已经写好了,能够成功启动实例,但出现了一个问题:这个实例和网络服务器是连接在一起的,所以在实例停止之前,浏览器的缓冲区不会关闭,并且有一个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函数)。这个脚本启动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()

你们能帮我一下吗?

1 个回答

0

你的问题和HTTP服务器关系不大。看起来你在用Python控制Oracle守护进程时遇到了一些普遍的问题。

首先,试着写一个简单的Python脚本,看看能否完成你想要的功能。

我猜测,你在尝试读取守护进程控制脚本的输出时遇到了麻烦。

你可以查看一下 Popen.communicate(),这个方法可以帮助你读取命令的输出。另一种选择是使用subprocess.call()。

网上有很多关于如何从Python调用系统命令的教程,比如 这个

除了Python本身的问题,你可能还会遇到权限问题——如果运行脚本或HTTP服务器的用户没有权限调用Oracle控制脚本,那你就会遇到另一个问题(在Linux上,可以通过把该用户添加到sudoers来解决)。

解决了调用脚本的问题后,让它在你的HTTP服务器中正常工作就会简单多了。

撰写回答