1
votes

I have a python cgi-script that checks if a process is active, and starts it if this process is not found. The process itself is a webserver (based on web.py). After I ensure that the process is running, I try to make a url request to it. The idea is to redirect the results of this request to the requester of my cgi script, basically I want to redirect a query to a local webserver that listens to a different port.

This code works fine if I have started the server first (findImgServerProcess returns True), from a shell, not using cgi requests. But if I try to start the process through the cgi-script below, I do get as far as the urllib2.urlopen call, which throws an exception that the connection is refused. I don't understand why? If I print the list of processes (r in findImgServerProcess()) I can see the process is there, but why does urllib2.urlopen throw an exception? I have the apache2 webserver set up to use suexec.

Here's the code:

#!/usr/bin/python
import cgi, cgitb
cgitb.enable()
import os, re
import sys
import subprocess

import urllib2
urlbase = "http://localhost:8080/getimage"
imgserver = "/home/martin/public_html/cgi-bin/stlimgservermirror.py" # this is based on web.py

def findImgServerProcess():
    r = subprocess.Popen(["ps", "aux"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0]
    return re.match(".*%s" % os.path.split(imgserver)[-1], r, re.DOTALL)

def ensureImgServerProcess():
    if findImgServerProcess():
        return True

    os.environ['LD_LIBRARY_PATH'] = '/home/martin/lib'
    fout = open("/dev/null", "w")
    ferr = fout
    subprocess.Popen([sys.executable, imgserver], stdout=fout, stderr=subprocess.STDOUT)
    # now try and find the process
    return findImgServerProcess() != None

def main():
    if not ensureImgServerProcess():
        print "Content-type: text/plain\n"
        print "image server down!"
        return

    form = cgi.FieldStorage()
    if form.has_key("debug"):
        print "Content-type: text/plain\n"
        print os.environ['QUERY_STRING']
    else:
        try:
            img = urllib2.urlopen("%s?%s" % (urlbase, os.environ['QUERY_STRING'])).read()
        except Exception, e:
            print "Content-type: text/plain\n"
            print e
            sys.exit()
        print "Content-type: image/png\n"
        print img

if __name__ == "__main__":
    main()
1

1 Answers

0
votes

A possibility is that the subprocess hasn't had an opportunity to completely start up before you try to connect to it. To test this, try adding a time.sleep(5) before you call urlopen.

This isn't ideal, but will at least help you figure out if that's the problem. Down the road, you'll probably want to set up a better way to check that the HTTP daemon is running and keep it running.