Start daemon process within BaseHTTPServer
Question: 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?


Answer: Your problem is not related much to HTTP server. You seem to have general
problem to control Oracle daemon from Python code.

Try first writing a simple python script, which does what you need.

My guess is, that your attempts are having problems with reading output from
daemon control script.

See also
[Popen.communicate()](https://docs.python.org/2/library/subprocess.html#subprocess.Popen.communicate)
for reading output from the command. Other option could be to call
subrocess.call()

There are many tutorials for calling system command from Python, e.g. [this
one](http://www.pythonforbeginners.com/os/subprocess-for-system-
administrators)

Apart of purely Python related problems you may run into problems with
permission - if your user, running the script/HTTP server is not allowed to
call oracle control script, you have another problem (which might have a
solution, on Linux adding that user into sudoers).

After you resolve problems with calling the script, it shall be easy to make
it working inside of your HTTP server.

