0

In order to allow helpdesk to restart an Oracle Instance, we are trying to implement a small python webserver that would start a shell script that starts the Oracle instance.

The code is done and it starts the instance but there is a problem: the instance is connected to the webserver, so the buffer to the browser is not closed until the instance has been stopped, and there is a ora_pmon_INSTANCE process listening on the webserver port.

I tried to launch the script with:

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

and

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

but it happens the same.

I also tried to launch a script with daemon (using daemon function from redhat's init scripts). The script starts the Oracle instance with the same result.

This is my code:

#!/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()

Can any of you help me?

4

1 回答 1

0

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

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

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

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

有很多从 Python 调用系统命令的教程,例如这个

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

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

于 2014-04-17T20:00:34.000 回答