コード例 #1
0
 def _setPickle(self, data):
     tmppath = self._picklepath + '.tmp'
     try:
         cPickle.dump(data, open(tmppath, 'w'), 1)
         os.rename(tmppath, self._picklepath)
     except:
         logException()
コード例 #2
0
 def _setPickle(self, data):
     tmppath = self._picklepath + '.tmp'
     try:
         cPickle.dump(data, open(tmppath, 'w'), 1)
         os.rename(tmppath, self._picklepath)
     except:
         logException()
コード例 #3
0
 def __parseComponentName(self, name):
     """
     I expect a name of the following sort: host[:port]absolutePath,
     where absolutePath begins with a slash, and contains no colons,
     and port is an integer, and host contains neither a colon nor a slash.
     """
     DEBUG(REMOTE_CLIENT, "in __parseComponentName with name %s" % name)
     try:
         slashIndex = name.find("/")
         assert slashIndex > 0
         path = name[1 + slashIndex :]
         DEBUG(REMOTE_CLIENT, "path is %s" % path)
         colonIndex = name.find(":")
         assert colonIndex < slashIndex
         if colonIndex > -1:
             assert colonIndex > 0
             host = name[:colonIndex]
             DEBUG(REMOTE_CLIENT, "host is %s" % host)
             port = int(name[1 + colonIndex : slashIndex])
         else:
             host = name[:slashIndex]
             port = DEFAULT_PORT
     except:
         logException()
         raise ValueError, "component name could not be parsed"
     return host, port, path
コード例 #4
0
def _processRequest(conn, sessionDict):
    DEBUG(EXTCGI, 'extcgi Processing Request')
    #dict of environ, headers, stdin
    kid_stdin, parent_to_kid_stdin = os.pipe()
    parent_to_kid_stdout, kid_stdout = os.pipe()
    parent_to_kid_stderr, kid_stderr = os.pipe()
    pid = os.fork()
    try:
        if pid: #ok I'm the parent
            DEBUG(EXTCGI, 'child pid is %d' % pid)
            #close kid sides
            os.close(kid_stdin)
            os.close(kid_stdout)
            os.close(kid_stderr)

            stdin = conn._stdin

            return _doCGI(conn, pid, parent_to_kid_stdin,
                          parent_to_kid_stdout,
                          parent_to_kid_stderr, stdin)

        else: #I'm the kid
            #close parent side of pipes
            os.close(parent_to_kid_stdin)
            os.close(parent_to_kid_stdout)
            os.close(parent_to_kid_stderr)
            #dup kid sides to my stdin/out/err
            os.dup2(kid_stdin, 0)
            os.dup2(kid_stdout, 1)
            os.dup2(kid_stderr, 2)
            env = _fix(conn.env)
            if DEBUGIT(EXTCGI):
                DEBUG(EXTCGI, "environment is %s" % _dispenv(env))
            prog = Configuration.CGIProgram
            args = ( (prog,) + (prog,) +
                     Configuration.CGIProgramArgs +(env,))
            DEBUG(EXTCGI, 'args is %s' % repr(args))
            oldpwd = os.getcwd()
            try:
                os.chdir(os.path.split(env["PATH_TRANSLATED"])[0])
                os.execle(*args)

            finally:
                os.chdir(oldpwd)
    except:
        if pid == 0: #I'm the kid
            logException()
            #give the parent some info as to why I died
            os.write(kid_stderr, "exception executing CGI : %s %s" % (
                sys.exc_info()[0], sys.exc_info()[1]))
            DEBUG(EXTCGI, "I'm still here! killing self");
            os.kill(os.getpid(), 9)

        else: #I'm the parent
            e, t, tb = sys.exc_info()
            try:
                os.kill(pid, 9) # we screwed up, kill kid
            except: #in event that it's already dead, that's ok too
                pass
            raise e, t, tb
コード例 #5
0
def _beginSession(sock, sessionDict):
    # capture the ip & port (or path, for a unix socket)
    # on which the request came, for scoping of configuration
    # data on their basis
    ip, port, unixpath=None, None, None
    try:      
        addr=sock.getsockname()
        if type(addr)==types.TupleType:
            ip, port=addr
        else:
            unixpath=addr
    except:
        ERROR("failed to read addr off socket!")
        logException()
        raise

    if ip and port:
        sessionDict[constants.IP]=ip
        sessionDict[constants.PORT]=port
    else:
        sessionDict[constants.UNIXPATH]=unixpath
    
    # get configuration data for the job
    Configuration.scope(sessionDict)
    
    # job must be defined, or else die here
    if Configuration.job==None:
        message="No job specified for service on %s:%d, "\
                 "request cannot be processed!" % (ip, port)
        ERROR(message)
        raise SkunkCriticalError, message
    
    BeginSession(Configuration.job, sock, sessionDict)
コード例 #6
0
def getConfiguredSlots(path=None, slotfilename=None):
    """
    get the slots configured for given path.
    """
    if path is None:
        path = current_component()
    if slotfilename is None:
        slotfilename = C.slotConfigFilename
    elif not path.endswith('/'):
        path = path + '/'
    slots = {}
    conffiles=[pathjoin(path[:(x or 1)], slotfilename) \
               for x, y in enumerate(path) if y=='/']

    for c in conffiles:
        try:
            newslots = datacomp(c, path=path)
        except FileNotFoundException:
            continue
        except VFSException:
            logException()
            continue
        else:
            slots.update(newslots)
    return slots
コード例 #7
0
def getConfiguredSlots(path=None, slotfilename=None):
    """
    get the slots configured for given path.
    """
    if path is None:
        path=current_component()
    if slotfilename is None:
        slotfilename=C.slotConfigFilename
    elif not path.endswith('/'):
        path=path+'/'
    slots={}
    conffiles=[pathjoin(path[:(x or 1)], slotfilename) \
               for x, y in enumerate(path) if y=='/']
        
    for c in conffiles:
        try:
            newslots=datacomp(c, path=path)
        except FileNotFoundException:
            continue
        except VFSException:
            logException()
            continue
        else:
            slots.update(newslots)
    return slots
コード例 #8
0
def _processRequest(conn, sessionDict):
    DEBUG(EXTCGI, 'extcgi Processing Request')
    #dict of environ, headers, stdin
    kid_stdin, parent_to_kid_stdin = os.pipe()
    parent_to_kid_stdout, kid_stdout = os.pipe()
    parent_to_kid_stderr, kid_stderr = os.pipe()
    pid = os.fork()
    try:
        if pid:  #ok I'm the parent
            DEBUG(EXTCGI, 'child pid is %d' % pid)
            #close kid sides
            os.close(kid_stdin)
            os.close(kid_stdout)
            os.close(kid_stderr)

            stdin = conn._stdin

            return _doCGI(conn, pid, parent_to_kid_stdin, parent_to_kid_stdout,
                          parent_to_kid_stderr, stdin)

        else:  #I'm the kid
            #close parent side of pipes
            os.close(parent_to_kid_stdin)
            os.close(parent_to_kid_stdout)
            os.close(parent_to_kid_stderr)
            #dup kid sides to my stdin/out/err
            os.dup2(kid_stdin, 0)
            os.dup2(kid_stdout, 1)
            os.dup2(kid_stderr, 2)
            env = _fix(conn.env)
            if DEBUGIT(EXTCGI):
                DEBUG(EXTCGI, "environment is %s" % _dispenv(env))
            prog = Configuration.CGIProgram
            args = ((prog, ) + (prog, ) + Configuration.CGIProgramArgs +
                    (env, ))
            DEBUG(EXTCGI, 'args is %s' % repr(args))
            oldpwd = os.getcwd()
            try:
                os.chdir(os.path.split(env["PATH_TRANSLATED"])[0])
                os.execle(*args)

            finally:
                os.chdir(oldpwd)
    except:
        if pid == 0:  #I'm the kid
            logException()
            #give the parent some info as to why I died
            os.write(
                kid_stderr, "exception executing CGI : %s %s" %
                (sys.exc_info()[0], sys.exc_info()[1]))
            DEBUG(EXTCGI, "I'm still here! killing self")
            os.kill(os.getpid(), 9)

        else:  #I'm the parent
            e, t, tb = sys.exc_info()
            try:
                os.kill(pid, 9)  # we screwed up, kill kid
            except:  #in event that it's already dead, that's ok too
                pass
            raise e, t, tb
コード例 #9
0
def _processRequest(conn, sessionDict):
    DEBUG(PYCGI, "pycgi processing request")
    try:
        env=_fix(conn.env, conn.uri)
    except vfs.FileNotFoundException:
        DEBUG(PYCGI, "file not found!")
        return fourOhFourHandler(conn, sessionDict)
    DEBUG(PYCGI, "file evidently exists")
    oldpwd=os.getcwd()
    os.environ.update(env)
    # what to do with argv?
    save_argv=sys.argv
    sys.argv=[env['SCRIPT_NAME']]
    saved=_swap_streams(conn)
    try:
        try:
            (directory, file) = os.path.split(env['SCRIPT_FILENAME'])
            os.chdir(directory)
            DEBUG(PYCGI, "about to execfile %s" % file)
            execfile(file)
        except SystemExit:
            pass
        except:
            logException()
            raise
    finally:
        os.chdir(oldpwd)
        sys.argv=save_argv
        new=_swap_streams(conn, saved)
    new[0].seek(0)
    respp = rfc822.Message(new[0])
    for k,v in respp.items():
        conn.responseHeaders[k] = v
    conn.write(new[0].read())        
    return conn.response()
コード例 #10
0
 def _getPickle(self):
     if os.path.exists(self._picklepath):
         try:
             data=cPickle.load(open(self._picklepath))
         except:
             logException()
             data={}
         return data
コード例 #11
0
 def __readManifest(self):
     try:
         data=self.__fsclass(self.file).open(os.path.join('/', manifest.MANIFEST_FILE)).read()
     except vfs.VFSException:
         ERROR("error in reading product manifest: %s" % self.file)
         logException()
         raise
     self.manifest=manifest.read_manifest(data)
コード例 #12
0
 def _getPickle(self):
     if os.path.exists(self._picklepath):
         try:
             data = cPickle.load(open(self._picklepath))
         except:
             logException()
             data = {}
         return data
コード例 #13
0
 def _initCookies(self):
     self.requestCookie = Cookie.SimpleCookie()
     if self.requestHeaders.has_key('Cookie'):
         try:
             self.requestCookie.load(self.requestHeaders['Cookie'])
         except Cookie.CookieError:
             logException()
     self.responseCookie = Cookie.SimpleCookie()        
コード例 #14
0
 def __readManifest(self):
     try:
         data=self.__fsclass(self.file).open(os.path.join('/', manifest.MANIFEST_FILE)).read()
     except vfs.VFSException:
         ERROR("error in reading product manifest: %s" % self.file)
         logException()
         raise
     self.manifest=manifest.read_manifest(data)
コード例 #15
0
 def _initCookies(self):
     self.requestCookie = Cookie.SimpleCookie()
     if self.requestHeaders.has_key('Cookie'):
         try:
             self.requestCookie.load(self.requestHeaders['Cookie'])
         except Cookie.CookieError:
             logException()
     self.responseCookie = Cookie.SimpleCookie()
コード例 #16
0
def _sendResponse(sock,
                  responseData,                 
                  requestData,
                  sessionDict):
    try:
        SocketScience.send_it_all(sock, responseData)
    except IOError, en:  #ignore broken pipes
        if en != errno.EPIPE:
            logException()
コード例 #17
0
def _sendResponse(sock,
                  responseData,                 
                  requestData,
                  sessionDict):
    try:
        SocketScience.send_it_all(sock, responseData)
    except IOError, en:  #ignore broken pipes
        if en != errno.EPIPE:
            logException()
コード例 #18
0
def _resolve_string(controllerName):
    try:
        c=_import_a_class(controllerName)
    except ImportError:
        logException()
        return None
    else:
        # do we need to instantiate one?
        # who says this needs to be a instance anyway?
        return c
コード例 #19
0
def _resolve_string(controllerName):
    try:
        c = _import_a_class(controllerName)
    except ImportError:
        logException()
        return None
    else:
        # do we need to instantiate one?
        # who says this needs to be a instance anyway?
        return c
コード例 #20
0
 def __setPickle(self, data):
     f=open(self._picklepath, 'w')
     fd=f.fileno()
     fcntl.flock(fd, fcntl.LOCK_EX)
     try:
         cPickle.dump(data, f, 1)
     except:
         logException()
     fcntl.flock(fd, fcntl.LOCK_UN)
     f.close()
コード例 #21
0
 def __getPickle(self):
     if os.path.exists(self._picklepath):
         f=open(self._picklepath)
         fd=f.fileno()
         # let reads coexist
         fcntl.flock(fd, fcntl.LOCK_SH)
         try:
             data=cPickle.load(f)
         except:
             logException()
             data={}
         fcntl.flock(fd, fcntl.LOCK_UN)
         f.close()
         return data
コード例 #22
0
 def execSql(self, sql, args=None):
     try:
         db=self.getConnection()
         cursor=db.cursor()
         cursor.execute(sql, args)
         retval=cursor.fetchall()
         cursor.close()
         db.commit()
         return retval
     except Exception, e:
         DEBUG(SESSIONHANDLER, "sql exception -- see error log")
         logException()
         try:
             db.rollback()
         except:
             pass
コード例 #23
0
 def authFailed(self, conn):
     try:
         page=AE.Component.callComponent(
             self.loginPage, {'CONNECTION':conn})
     # string exception left here for backwards compatibility
     except ("OK", OK):
         #this is the magical "do whatever you would've done" bit
         AE.Component.resetComponentStack()
         return
     
     except:
         DEBUG(AUTH, 'ACK! exception rendering login page')
         logException()
         page = "error occurred rendering login page"
         
     conn._output.write(page)
     resp = conn.response()
     DEBUG(AUTH, "page is %s" % resp)
     raise PreemptiveResponse, resp
コード例 #24
0
    def authFailed(self, conn):
        try:
            page = AE.Component.callComponent(self.loginPage,
                                              {'CONNECTION': conn})
        # string exception left here for backwards compatibility
        except ("OK", OK):
            #this is the magical "do whatever you would've done" bit
            AE.Component.resetComponentStack()
            return

        except:
            DEBUG(AUTH, 'ACK! exception rendering login page')
            logException()
            page = "error occurred rendering login page"

        conn._output.write(page)
        resp = conn.response()
        DEBUG(AUTH, "page is %s" % resp)
        raise PreemptiveResponse, resp
コード例 #25
0
    def _initArgs(self, requestData):
        stdin = cStringIO.StringIO(requestData['stdin'])
        env = requestData['environ']
        try:
            query = cgi.FieldStorage(fp = stdin, environ = env,
                                     keep_blank_values = 1)
            self.args=self._convertArgs(query)
            ok=1
        except:
            # may be some exotic content-type
            logException()
            DEBUG(WEB, "content-type: %s" % self.requestHeaders.get("content-type"))
            self.args={}
            ok=0

        if ok and Configuration.mergeQueryStringWithPostData and \
               env.get("REQUEST_METHOD")=='POST':
            #if POST, see if any GET args too
            environ = env.copy()
            environ["REQUEST_METHOD"] = 'GET'            
            query = cgi.FieldStorage(fp = stdin, environ = environ,
                                     keep_blank_values = 1)
            self.args.update(self._convertArgs(query))
コード例 #26
0
def _sendResponse(sock,
                  responseData,                 
                  requestData,
                  sessionDict):
    try:
        SocketScience.send_it_all(sock, responseData)
    except:
        logException()

    # reset alarm
    signal.alarm(Configuration.PostResponseTimeout)
    
    try:
        DEBUG(REQUESTHANDLER, 'post request hook')
        PostRequest(Configuration.job, requestData, sessionDict)
    except:
        logException()                
    try:
        DEBUG(REQUESTHANDLER, "cleaning up")
        CleanupRequest(Configuration.job, requestData, sessionDict)
    except:
        logException()
コード例 #27
0
        HaveConnection(Configuration.job, connection, sessionDict)
        # DEBUG(WEB, 'survived HaveConnection hook')

        # overlay of config information
        Configuration.trim()
        Configuration.scope(sessionDict)
        #Configuration.saveMash()

        # DEBUG(WEB, 'executing PreHandleConnection hook')
        PreHandleConnection(Configuration.job, connection, sessionDict)
                
    except PreemptiveResponse, pr:
        # DEBUG(WEB, 'got preemptive response')
        response=pr.responseData
    except:
        logException()
    else:
        RouteConnection(Configuration.job, connection, sessionDict)
        # DEBUG(WEB, 'handling connection')
        response=HandleConnection(Configuration.job, connection, sessionDict)

    # so the response can be further processed, add it to the sessionDict temporarily
    sessionDict['RESPONSE']=response
    ProcessResponse(connection, sessionDict)
    response=sessionDict['RESPONSE']
    del sessionDict['RESPONSE']
    
    # the connection should be available to postResponse and cleanup hooks.
    sessionDict[constants.CONNECTION]=connection
    # DEBUG(WEB, 'returning response: %s' % response)
    #if response!=None:
コード例 #28
0
def _endSession(sessionDict):
    try:
        EndSession(Configuration.job, sessionDict)
    except:
        logException()
    Configuration.trim()
コード例 #29
0
                else:
#                    DEBUG(REQUESTHANDLER, 'handling request')
                    rawResponse=HandleRequest(Configuration.job,
                                              requestData,
                                              sessionDict)

#                    DEBUG(REQUESTHANDLER, 'response returned: %s' % str(rawResponse))
#                    DEBUG(REQUESTHANDLER, 'marshalling response')
                    responseData=protocolImpl.marshalResponse(rawResponse,
                                                              sessionDict)
            except:
                try:
                    # the current exception is available anyway, so is not passed;
                    # perhaps nothing should be
#                    DEBUG(REQUESTHANDLER, 'marshalling exception')
                    responseData=protocolImpl.marshalException(logException(),
                                                               sessionDict)
                except:
                    logException()
        finally:     
#            DEBUG(REQUESTHANDLER, 'sending response')
            _sendResponse(sock,
                          responseData,
                          requestData,
                          sessionDict)
        
            signal.alarm(0)
            signal_plus.unblockTERM()

        # the protocol can close the connection by return a negative timeout;
        # sessionDict allows it to reference state that has been stored there.