Пример #1
0
    def testMessageSend(self):
        
        class MSG_PONG(Message): pass
        class MSG_PING(Message): pass

        def c(parent):
            for msg, args, kwargs in Tasklet.receive():     
                if msg.match(MSG_PING):
                    self.assertEquals((10, ), args)
                    MSG_PONG.send(parent)(20)

        parent = Tasklet.current()
        child = Tasklet.new(c)(parent)
        i = 0
        MSG_PING.send(child)(10)
        for msg, args, kwargs in Tasklet.receive():
            if msg.match(MSG_PONG):
                self.assertEquals((20, ), args)
                i += 1
                if i > 5: break
                MSG_PING.send(child)(10)

        self.assertEquals(6, i)

        try:
            start = time.time()
            for msg, args, kwargs in Tasklet.receive(2.0):
                self.fail('expected timeout error')            
        except TimeoutError:
            end = time.time()
            self.assertAlmostEqual(2.0, end - start, places = 1)

        child.kill()
Пример #2
0
    def testMessageSend(self):
        class MSG_PONG(Message):
            pass

        class MSG_PING(Message):
            pass

        def c(parent):
            for msg, args, kwargs in Tasklet.receive():
                if msg.match(MSG_PING):
                    self.assertEquals((10, ), args)
                    MSG_PONG.send(parent)(20)

        parent = Tasklet.current()
        child = Tasklet.new(c)(parent)
        i = 0
        MSG_PING.send(child)(10)
        for msg, args, kwargs in Tasklet.receive():
            if msg.match(MSG_PONG):
                self.assertEquals((20, ), args)
                i += 1
                if i > 5: break
                MSG_PING.send(child)(10)

        self.assertEquals(6, i)

        try:
            start = time.time()
            for msg, args, kwargs in Tasklet.receive(2.0):
                self.fail('expected timeout error')
        except TimeoutError:
            end = time.time()
            self.assertAlmostEqual(2.0, end - start, places=1)

        child.kill()
Пример #3
0
 def server():
     server_endpoint = None
     try:
         remote_server = RemoteServer()
         server_endpoint = remote_server.serve(('localhost', 9081))
         remote_server.register('testing123')
         for msg, args, kwargs in Tasklet.receive():
             if msg.match(MSG_SUM):
                 server_results.append('s')
                 msg.reply(sum(args))
             elif msg.match(MSG_TEST):
                 server_results.append('t')
             elif msg.match(MSG_QUIT):
                 server_results.append('q')
                 break
             elif msg.match(MSG_SLEEP):
                 server_results.append('sl')
                 Tasklet.sleep(args[0])
                 msg.reply(True)
     except Exception:
         logging.exception("")
         self.fail("")
     finally:
         if server_endpoint is not None:
             server_endpoint.close()
Пример #4
0
 def server():
     server_endpoint = None
     try:
         remote_server = RemoteServer()
         server_endpoint = remote_server.serve(('localhost', 9081))
         remote_server.register('testing123')
         for msg, args, kwargs in Tasklet.receive():
             if msg.match(MSG_SUM):
                 server_results.append('s')
                 msg.reply(sum(args))
             elif msg.match(MSG_TEST):
                 server_results.append('t')
             elif msg.match(MSG_QUIT):
                 server_results.append('q')
                 break
             elif msg.match(MSG_SLEEP):
                 server_results.append('sl')
                 Tasklet.sleep(args[0])
                 msg.reply(True)
     except Exception:
         logging.exception("")
         self.fail("")
     finally:
         if server_endpoint is not None: 
             server_endpoint.close()
Пример #5
0
    def waitForActions(self, jobguids):
        """
        Wait for some background jobs to finish.

        @param jobguids:  A list containing the jobguids of the jobs you want to wait for.
        @type jobguids:   array of jobguids
        """
        for jobguid in jobguids:
            q.workflowengine.jobmanager.registerJobFinishedCallback(jobguid)

        out = {}
        while len(jobguids) > 0:
            (msg, args, kwargs) = Tasklet.receive().next()
            if msg.match(MSG_JOB_FINISHED):
                (jobguid, status, result) = args
                jobguids.remove(jobguid)
                out[jobguid] = (status, result)

        failed = filter(lambda jobguid: out[jobguid][0] == 'ERROR', out)

        if failed:
            raise WFLException.createCombo(
                map(lambda jobguid: out[jobguid][1], failed))
        else:
            return dict(
                zip(map(lambda jobguid: jobguid, out),
                    map(lambda jobguid: out[jobguid][1], out)))
 def sendToDrp(self, name, *args, **kwargs):
     MSG_DRP_CALL.send(self.__tasklet)(Tasklet.current(), name, *args, **kwargs)
     (msg, args, kwargs) = Tasklet.receive().next()
     if msg.match(MSG_DRP_RETURN):
         return args[0]
     elif msg.match(MSG_DRP_EXCEPTION):
         raise args[0]
Пример #7
0
    def handle(self, socket, application):
        stream = BufferedStream(socket)
        #implements http1.1 keep alive handler
        #there are several concurrent tasks for each connection;
        #1 for reading requests, 1 or more for handling requests and 1 for writing responses
        #the current task (the one created to handle the socket connection) is the controller task,
        #e.g. it coordinates the actions of it's children by message passing
        control = Tasklet.current()

        #writes responses back to the client when they are ready:
        response_writer = Tasklet.new(self.write_responses,
                                      name='response_writer')(control, stream)
        #reads requests from clients:
        request_reader = Tasklet.new(self.read_requests,
                                     name='request_reader')(control, stream)

        #typical flow:
        #1. reader reads in request, sends notification to control (MSG_REQUEST_READ)
        #2. control starts handler for the request
        #3. handler works on request and sends notification to control when finished (MSG_REQUEST_HANDLED)
        #4. control sends message to writer to start writing the response (MSG_WRITE_RESPONSE)
        #5. writer notififies control when response is wriiten (MSG_RESPONSE_WRITTEN)

        #control wait for msgs to arrive:
        for msg, (request, response), kwargs in Tasklet.receive():
            if msg.match(self.MSG_REQUEST_READ):
                #we use reque to be able to send the responses back in the correct order later
                self._reque.start(request)
                Tasklet.new(self.handle_request,
                            name='request_handler')(control, request,
                                                    application)

            elif msg.match(self.MSG_REQUEST_HANDLED):
                #we use reque to retire (send out) the responses in the correct order
                for request, response in self._reque.finish(request, response):
                    self.MSG_WRITE_RESPONSE.send(response_writer)(request,
                                                                  response)

            elif msg.match(self.MSG_RESPONSE_WRITTEN):
                if request.version == 'HTTP/1.0':
                    break  #no keep-alive support in http 1.0
                elif request.get_response_header('Connection') == 'close':
                    break  #response indicated to close after response
                elif request.get_request_header('Connection') == 'close':
                    break  #request indicated to close after response
            elif msg.match(self.MSG_READ_ERROR):
                break  #stop and close the connection
            elif msg.match(self.MSG_WRITE_ERROR):
                break  #stop and close the connection
            else:
                assert False, "unexpected msg in control loop"

        #kill reader and writer
        #any outstanding request will continue, but will exit by themselves
        response_writer.kill()
        request_reader.kill()

        #close our side of the socket
        stream.close()
Пример #8
0
def printer():
    for msg, args, kwargs in Tasklet.receive():
        if msg.match(MSG_GREETING):
            print 'Hello', args[0]
        elif msg.match(MSG_FAREWELL):
            print 'Goodbye', args[0]
        else:
            pass #unknown msg
Пример #9
0
 def sendToDrp(self, name, *args, **kwargs):
     MSG_DRP_CALL.send(self.__tasklet)(Tasklet.current(), name, *args,
                                       **kwargs)
     (msg, args, kwargs) = Tasklet.receive().next()
     if msg.match(MSG_DRP_RETURN):
         return args[0]
     elif msg.match(MSG_DRP_EXCEPTION):
         raise args[0]
Пример #10
0
 def write_responses(self, control, stream):
     try:
         for msg, (request, response), kwargs in Tasklet.receive():
             request.write_response(response, stream.writer)
             self.MSG_RESPONSE_WRITTEN.send(control)(request, response)
     except Exception, e:
         self.log.exception("Exception in writer")
         self.MSG_WRITE_ERROR.send(control)(None, None)
Пример #11
0
 def write_responses(self, control, stream):
     try:
         for msg, (request, response), kwargs in Tasklet.receive():
             request.write_response(response, stream.writer)
             self.MSG_RESPONSE_WRITTEN.send(control)(request, response)
     except Exception, e:
         self.log.exception("Exception in writer")
         self.MSG_WRITE_ERROR.send(control)(None, None)
Пример #12
0
 def c():
     for msg, args, kwargs in Tasklet.receive():
         if msg.match(MSG_TEST_SUM):
             msg.reply(sum(args))
         elif msg.match(MSG_TEST_MAX):
             msg.reply(max(args))
         elif msg.match(MSG_TEST_SLEEP):     
             Tasklet.sleep(args[0])
             msg.reply(True)
Пример #13
0
 def c():
     for msg, args, kwargs in Tasklet.receive():
         if msg.match(MSG_TEST_SUM):
             msg.reply(sum(args))
         elif msg.match(MSG_TEST_MAX):
             msg.reply(max(args))
         elif msg.match(MSG_TEST_SLEEP):
             Tasklet.sleep(args[0])
             msg.reply(True)
Пример #14
0
 def _bootstrap_service(self):
     while True:
         for msg, args, kwargs in Tasklet.receive():
             if msg.match(MSG_LOOKUP):
                 name = args[0]
                 if name in self._task_by_name:
                     task_id = self._task_id_by_task.get(self._task_by_name[name], 0)
                 else:
                     task_id = 0
                 msg.reply(task_id)
Пример #15
0
    def handle(self, socket, application):
        stream = BufferedStream(socket)
        #implements http1.1 keep alive handler
        #there are several concurrent tasks for each connection;
        #1 for reading requests, 1 or more for handling requests and 1 for writing responses
        #the current task (the one created to handle the socket connection) is the controller task,
        #e.g. it coordinates the actions of it's children by message passing
        control = Tasklet.current()

        #writes responses back to the client when they are ready:
        response_writer = Tasklet.new(self.write_responses, name = 'response_writer')(control, stream)
        #reads requests from clients:
        request_reader = Tasklet.new(self.read_requests, name = 'request_reader')(control, stream)

        #typical flow:
        #1. reader reads in request, sends notification to control (MSG_REQUEST_READ)
        #2. control starts handler for the request
        #3. handler works on request and sends notification to control when finished (MSG_REQUEST_HANDLED)
        #4. control sends message to writer to start writing the response (MSG_WRITE_RESPONSE)
        #5. writer notififies control when response is wriiten (MSG_RESPONSE_WRITTEN)

        #control wait for msgs to arrive:
        for msg, (request, response), kwargs in Tasklet.receive():
            if msg.match(self.MSG_REQUEST_READ):
                #we use reque to be able to send the responses back in the correct order later
                self._reque.start(request)
                Tasklet.new(self.handle_request, name = 'request_handler')(control, request, application)

            elif msg.match(self.MSG_REQUEST_HANDLED):
                #request.environ["wsgi.input"].read(request.environ["wsgi.input"]._n)
                #we use reque to retire (send out) the responses in the correct order
                for request, response in self._reque.finish(request, response):
                    self.MSG_WRITE_RESPONSE.send(response_writer)(request, response)

            elif msg.match(self.MSG_RESPONSE_WRITTEN):
                if request.version == 'HTTP/1.0':
                    break #no keep-alive support in http 1.0
                elif request.get_response_header('Connection') == 'close':
                    break #response indicated to close after response
                elif request.get_request_header('Connection') == 'close':
                    break #request indicated to close after response
            elif msg.match(self.MSG_READ_ERROR):
                break #stop and close the connection
            elif msg.match(self.MSG_WRITE_ERROR):
                break #stop and close the connection
            else:
                assert False, "unexpected msg in control loop"

        #kill reader and writer
        #any outstanding request will continue, but will exit by themselves
        response_writer.kill()
        request_reader.kill()

        #close our side of the socket
        stream.close()
    def startRootobjectAction(self, rootobjectname, actionname, params, executionparams={}, jobguid=None):
        """
        Starts a given RootObject Action. Uses the tasklet engine to run the matching tasklets.

        The current job will be determined automatically, it can however be overriden by setting jobguid.
        The action will be executed in a new job that is the newest child of the current job, the new job will inherit the following properties of the job: name, description, userErrormsg, internalErrormsg and maxduration.

        The executionparams passed to the function will override the properties of the job (if provided).
        .
        The guid of the job in which the action is executed, will be added to params: params['jobguid'].
        The tasklets executing in the Actor Action have to add their result in params['result']. The dictionary returned by startActorAction contains this result, under the 'result' key.

        @param rootobjectname:                 Name of the rootobject of the root object action.
        @type type:                            string

        @param actionnmame:                    Name of the action to execute on the rootobject.
        @type actionname:                      string

        @param params:                         Dictionary containing all parameters required to execute this actions.
        @type params:                          dictionary

        @param executionParams:                Dictionary can following keys: name, description, userErrormsg, internalErrormsg, maxduration, wait, timetostart, priority, clouduserguid, rootobjecttype, rootobjectguid
        @type executionParams:                 dictionary

        @param jobguid:                        Optional parameter, can be used to override the current job.
        @type jobguid:                         guid

        @return:                               dictionary with action result as result and the action's jobguid: {'result': <result>, 'jobguid': guid}
        @rtype:                                dictionary

        @raise ActionNotFoundException:        In case no actions are found for the specified rootobjectname and actoraction
        @raise e:                              In case an error occurred, exception is raised
        """
        if len(self.__taskletEngine.find(tags=(rootobjectname, actionname), path=RootobjectActionTaskletPath)) == 0:
            raise ActionNotFoundException("RootobjectAction", rootobjectname, actionname)
        #SETUP THE JOB AND THE PARAMS
        currentjobguid = jobguid or (hasattr(Tasklet.current(), 'jobguid') and Tasklet.current().jobguid) or None
        if q.workflowengine.jobmanager.isKilled(currentjobguid):
           raise Exception("Can't create child jobs: the job is killed !")
        
        params['jobguid'] = jobguid = q.workflowengine.jobmanager.createJob(currentjobguid, rootobjectname+"."+actionname, executionparams, params=params)
        #START A NEW TASKLET FOR THE JOB
        q.workflowengine.jobmanager.startJob(jobguid)

        tasklet = Tasklet.new(self.__execute)(Tasklet.current(), jobguid, params, (rootobjectname, actionname), RootobjectActionTaskletPath)

        #WAIT FOR THE ANSWER
        (msg, args, kwargs) = Tasklet.receive().next()

        if msg.match(MSG_ACTION_NOWAIT):
            return { 'jobguid':jobguid, 'result':None }
        if msg.match(MSG_ACTION_RETURN):
            return { 'jobguid':jobguid, 'result':params.get('result')}
        elif msg.match(MSG_ACTION_EXCEPTION):
            raise args[0]
Пример #17
0
 def _bootstrap_service(self):
     while True:
         for msg, args, kwargs in Tasklet.receive():
             if msg.match(MSG_LOOKUP):
                 name = args[0]
                 if name in self._task_by_name:
                     task_id = self._task_id_by_task.get(
                         self._task_by_name[name], 0)
                 else:
                     task_id = 0
                 msg.reply(task_id)
    def __send(self):
        # Started in the sending tasklet
        writer = self.__stream.writer

        for msg, args, kwargs in Tasklet.receive():
            if msg.match(MSG_SOCKET_SEND):
                message = self.__yaml_message(args[0])
                q.logger.log("[SocketTaskHandler] Sending message: " + message, 5)
                writer.write_bytes(message)
                writer.flush()
            elif msg.match(MSG_SOCKET_CLOSE):
                return
 def __run(self):
     for msg, args, kwargs in Tasklet.receive():
         if msg.match(MSG_DRP_CALL):
             (caller, rootobject, action) = args[0:3]
             q.logger.log("[DRPTasklet] Received task: ro=" + str(rootobject) + " action=" + str(action), 5)
             try:
                 #If you want to add transaction support, this is the place to be.
                 result = getattr(getattr(self.connection, rootobject), action)(*args[3:], **kwargs)
             except Exception, e:
                 q.logger.log("[DRPTasklet] Exception occured on DRP action: " + str(e), 1)
                 MSG_DRP_EXCEPTION.send(caller)(WFLException.create(e))
             else:
                 MSG_DRP_RETURN.send(caller)(result)
    def __send(self):
        # Started in the sending tasklet
        writer = self.__stream.writer

        for msg, args, kwargs in Tasklet.receive():
            if msg.match(MSG_SOCKET_SEND):
                message = self.__yaml_message(args[0])
                q.logger.log("[SocketTaskHandler] Sending message: " + message,
                             5)
                writer.write_bytes(message)
                writer.flush()
            elif msg.match(MSG_SOCKET_CLOSE):
                return
    def executeScript(self, agentguid, actionname, scriptpath, params, executionparams={}, jobguid=None):
        """
        Execute a script on an agent. The action will be executed in a new job that is the newest child of the current job.
        The new job will inherit the following properties of the job: name, description, userErrormsg, internalErrormsg, maxduration and customerguid.
        The executionparams passed to the function will override the properties of the job (if provided).

        @param agentguid:                      Guid of the agent on which the script will be executed.
        @type agentguid:                       guid

        @param actionname:                     The name of the action, will filled in, in the job
        @param actionname:                     string

        @param scriptpath:                     The path of the script, on the server.
        @type scriptpath:                      string

        @param params:                         Dictionary containing all parameters required to execute this script.
        @type params:                          dictionary

        @param executionParams:                Dictionary can following keys: name, description, userErrormsg, internalErrormsg, maxduration, wait, timetostart, priority
        @type executionParams:                 dictionary

        @param jobguid:                        Optional parameter, can be used to override the current job.
        @type jobguid:                         guid

        @return:                               Dictionary with action result as result and the action's jobguid: {'result': <result>, 'jobguid': guid}
        @rtype:                                dictionary

        @raise IOError:                        If the scriptpath can't be read.
        @raise TimeOutException:               If the agent did not respond within the maxduration: the script will be killed and the exception will be raised.
        @raise AgentNotAvailableException:     If the agent is not available when starting the script, the script is not be started.
        @raise ScriptFailedException:          If an exception occurres on the agent while executing the script.
        """
        #SETUP THE JOB AND THE PARAMS
        currentjobguid = jobguid or Tasklet.current().jobguid
        if q.workflowengine.jobmanager.isKilled(currentjobguid):
            raise Exception("Can't create child jobs: the job is killed !")

        params['jobguid'] = jobguid = q.workflowengine.jobmanager.createJob(currentjobguid, actionname, executionparams, agentguid, params=params)
        #START A NEW TASKLET FOR THE JOB
        q.workflowengine.jobmanager.startJob(jobguid)
        tasklet = Tasklet.new(self.__execute)(Tasklet.current(), jobguid, agentguid, scriptpath, params)
        #WAIT FOR THE ANSWER
        (msg, args, kwargs) = Tasklet.receive().next()
        if msg.match(MSG_ACTION_NOWAIT):
            return { 'jobguid':jobguid, 'result':None }
        if msg.match(MSG_ACTION_RETURN):
            return args[0]
        elif msg.match(MSG_ACTION_EXCEPTION):
            raise args[0]
Пример #22
0
 def __run(self):
     for msg, args, kwargs in Tasklet.receive():
         if msg.match(MSG_DRP_CALL):
             (caller, rootobject, action) = args[0:3]
             q.logger.log(
                 "[DRPTasklet] Received task: ro=" + str(rootobject) +
                 " action=" + str(action), 5)
             try:
                 #If you want to add transaction support, this is the place to be.
                 result = getattr(getattr(self.connection, rootobject),
                                  action)(*args[3:], **kwargs)
             except Exception, e:
                 q.logger.log(
                     "[DRPTasklet] Exception occured on DRP action: " +
                     str(e), 1)
                 MSG_DRP_EXCEPTION.send(caller)(WFLException.create(e))
             else:
                 MSG_DRP_RETURN.send(caller)(result)
Пример #23
0
def handle(client_socket):
    """handles a single client connected to the chat server"""
    stream = BufferedStream(client_socket)

    client_task = Tasklet.current() #this is the current task as started by server
    connected_clients.add(client_task)
    
    def writer():
        for msg, args, kwargs in Tasklet.receive():
            if msg.match(MSG_WRITE_LINE):
                stream.writer.write_bytes(args[0] + '\n')
                stream.writer.flush()
            
    def reader():
        for line in stream.reader.read_lines():
            line = line.strip()
            if line == 'quit': 
                MSG_QUIT.send(client_task)()
            else:
                MSG_LINE_READ.send(client_task)(line)
    
    reader_task = Tasklet.new(reader)()
    writer_task = Tasklet.new(writer)()

    MSG_WRITE_LINE.send(writer_task)("type 'quit' to exit..")
    
    for msg, args, kwargs in Tasklet.receive():
        if msg.match(MSG_QUIT):
            break
        elif msg.match(MSG_LINE_READ):
            #a line was recv from our client, multicast it to the other clients
            for task in connected_clients:
                if task != client_task: #don't echo the line back to myself
                    MSG_WRITE_LINE.send(task)(args[0])
        elif msg.match(MSG_WRITE_LINE):
            MSG_WRITE_LINE.send(writer_task)(args[0])
        
    connected_clients.remove(client_task)
    reader_task.kill()
    writer_task.kill()
    client_socket.close()
    def waitForActions(self, jobguids):
        """
        Wait for some background jobs to finish.

        @param jobguids:  A list containing the jobguids of the jobs you want to wait for.
        @type jobguids:   array of jobguids
        """
        for jobguid in jobguids:
            q.workflowengine.jobmanager.registerJobFinishedCallback(jobguid)

        out = {}
        while len(jobguids) > 0:
            (msg, args, kwargs) = Tasklet.receive().next()
            if msg.match(MSG_JOB_FINISHED):
                (jobguid, status, result) = args
                jobguids.remove(jobguid)
                out[jobguid] = (status, result)

        failed = filter(lambda jobguid: out[jobguid][0] == 'ERROR', out)

        if failed:
            raise WFLException.createCombo(map(lambda jobguid: out[jobguid][1], failed))
        else:
            return dict(zip(map(lambda jobguid: jobguid, out), map(lambda jobguid: out[jobguid][1], out)))
Пример #25
0
 def _message_writer(self):
     object_writer = ObjectWriter(self._stream.writer)
     for msg, (remote_task_id, args), kwargs in Tasklet.receive():
         object_writer.write_object((remote_task_id, msg.__class__, id(msg), args, kwargs))
         object_writer.flush()
Пример #26
0
    def startActorAction(self,
                         actorname,
                         actionname,
                         params,
                         executionparams={},
                         jobguid=None):
        """
        Starts a given Actor Action. Uses the tasklet engine to run the matching tasklets.

        The current job will be determined automatically, it can however be overriden by setting jobguid.
        The action will be executed in a new job that is the newest child of the current job, the new job will inherit the following properties of the job: name, description, userErrormsg, internalErrormsg and maxduration.

        The executionparams passed to the function will override the properties of the job (if provided).

        The guid of the job in which the action is executed, will be added to params: params['jobguid'].
        The tasklets executing in the Actor Action have to add their result in params['result']. The dictionary returned by startActorAction contains this result, under the 'result' key.

        @param actorname:                      Name of the actor of the actor action.
        @type actorname:                       string

        @param actionnmame:                    Name of the action of the actor action.
        @type actionname:                      string

        @param params:                         Dictionary containing all parameters required to execute this actions.
        @type params:                          dictionary

        @param executionParams:                Dictionary can following keys: name, description, userErrormsg, internalErrormsg, maxduration, wait, timetostart, priority
        @type executionParams:                 dictionary

        @param jobguid:                        Optional parameter, can be used to override the current job.
        @type jobguid:                         guid

        @return:                               Dictionary with action result as result and the action's jobguid: {'result': <result>, 'jobguid': guid}
        @rtype:                                dictionary

        @raise ActionNotFoundException:        In case no actions are found for the specified actorname and actoraction
        @raise e:                              In case an error occurred, exception is raised
        """
        if len(
                self.__taskletEngine.find(tags=(actorname, actionname),
                                          path=ActorActionTaskletPath)) == 0:
            raise ActionNotFoundException("ActorAction", actorname, actionname)
        #SETUP THE JOB AND THE PARAMS
        currentjobguid = jobguid or Tasklet.current().jobguid
        if q.workflowengine.jobmanager.isKilled(currentjobguid):
            raise Exception("Can't create child jobs: the job is killed !")

        params['jobguid'] = jobguid = q.workflowengine.jobmanager.createJob(
            currentjobguid,
            actorname + "." + actionname,
            executionparams,
            params=params)
        #START A NEW TASKLET FOR THE JOB

        q.workflowengine.jobmanager.startJob(jobguid)
        tasklet = Tasklet.new(self.__execute)(Tasklet.current(), jobguid,
                                              params, (actorname, actionname),
                                              ActorActionTaskletPath)
        #WAIT FOR THE ANSWER
        (msg, args, kwargs) = Tasklet.receive().next()
        if msg.match(MSG_ACTION_NOWAIT):
            return {'jobguid': jobguid, 'result': None}
        if msg.match(MSG_ACTION_RETURN):
            return {'jobguid': jobguid, 'result': params.get('result')}
        elif msg.match(MSG_ACTION_EXCEPTION):
            raise args[0]
Пример #27
0
 def _message_writer(self):
     object_writer = ObjectWriter(self._stream.writer)
     for msg, (remote_task_id, args), kwargs in Tasklet.receive():
         object_writer.write_object(
             (remote_task_id, msg.__class__, id(msg), args, kwargs))
         object_writer.flush()
Пример #28
0
 def writer():
     for msg, args, kwargs in Tasklet.receive():
         if msg.match(MSG_WRITE_LINE):
             stream.writer.write_bytes(args[0] + '\n')
             stream.writer.flush()
Пример #29
0
 def c(parent):
     for msg, args, kwargs in Tasklet.receive():     
         if msg.match(MSG_PING):
             self.assertEquals((10, ), args)
             MSG_PONG.send(parent)(20)
    def executeScript(self,
                      agentguid,
                      actionname,
                      scriptpath,
                      params,
                      executionparams={},
                      jobguid=None):
        """
        Execute a script on an agent. The action will be executed in a new job that is the newest child of the current job.
        The new job will inherit the following properties of the job: name, description, userErrormsg, internalErrormsg, maxduration and customerguid.
        The executionparams passed to the function will override the properties of the job (if provided).

        @param agentguid:                      Guid of the agent on which the script will be executed.
        @type agentguid:                       guid

        @param actionname:                     The name of the action, will filled in, in the job
        @param actionname:                     string

        @param scriptpath:                     The path of the script, on the server.
        @type scriptpath:                      string

        @param params:                         Dictionary containing all parameters required to execute this script.
        @type params:                          dictionary

        @param executionParams:                Dictionary can following keys: name, description, userErrormsg, internalErrormsg, maxduration, wait, timetostart, priority
        @type executionParams:                 dictionary

        @param jobguid:                        Optional parameter, can be used to override the current job.
        @type jobguid:                         guid

        @return:                               Dictionary with action result as result and the action's jobguid: {'result': <result>, 'jobguid': guid}
        @rtype:                                dictionary

        @raise IOError:                        If the scriptpath can't be read.
        @raise TimeOutException:               If the agent did not respond within the maxduration: the script will be killed and the exception will be raised.
        @raise AgentNotAvailableException:     If the agent is not available when starting the script, the script is not be started.
        @raise ScriptFailedException:          If an exception occurres on the agent while executing the script.
        """
        #SETUP THE JOB AND THE PARAMS
        currentjobguid = jobguid or Tasklet.current().jobguid
        if q.workflowengine.jobmanager.isKilled(currentjobguid):
            raise Exception("Can't create child jobs: the job is killed !")

        params['jobguid'] = jobguid = q.workflowengine.jobmanager.createJob(
            currentjobguid,
            actionname,
            executionparams,
            agentguid,
            params=params)
        #START A NEW TASKLET FOR THE JOB
        q.workflowengine.jobmanager.startJob(jobguid)
        tasklet = Tasklet.new(self.__execute)(Tasklet.current(), jobguid,
                                              agentguid, scriptpath, params)
        #WAIT FOR THE ANSWER
        (msg, args, kwargs) = Tasklet.receive().next()
        if msg.match(MSG_ACTION_NOWAIT):
            return {'jobguid': jobguid, 'result': None}
        if msg.match(MSG_ACTION_RETURN):
            return args[0]
        elif msg.match(MSG_ACTION_EXCEPTION):
            raise args[0]
Пример #31
0
 def c(parent):
     for msg, args, kwargs in Tasklet.receive():
         if msg.match(MSG_PING):
             self.assertEquals((10, ), args)
             MSG_PONG.send(parent)(20)