示例#1
0
 def __init__(self, argv):
     # Call the constructor of TripsModule
     super(Kappa_Module, self).__init__(argv)
     self.tasks = [
         'KAPPA-VERSION', 'KAPPA-PARSE', 'KAPPA-START', 'KAPPA-STATUS',
         'KAPPA-STOP'
     ]
     parser = argparse.ArgumentParser()
     parser.add_argument("--kappa_url", help="kappa endpoint")
     args = parser.parse_args()
     if args.kappa_url:
         self.kappa_url = args.kappa_url
     else:
         logging.error('No Kappa URL given.')
         sys.exit()
     # Send subscribe messages
     for task in self.tasks:
         msg_txt =\
             '(subscribe :content (request &key :content (%s . *)))' % task
         self.send(KQMLPerformative.from_string(msg_txt))
     # Instantiate a kappa runtime
     self.kappa = KappaRuntime(self.kappa_url)
     # Send ready message
     self.ready()
     super(Kappa_Module, self).start()
示例#2
0
 def test_info(self):
     """ the the ability of the server to return
         information about the service.
     """
     runtime = KappaRuntime(self.endpoint)
     info = runtime.info()
     self.assertIsNotNone('environment_simulations' in info)
     self.assertEqual(info['environment_simulations'], 0)
     self.assertIsNotNone('environment_projects' in info)
     self.assertEqual(info['environment_projects'], 0)
     self.assertIsNotNone('environment_build' in info)
示例#3
0
 def test_info(self):
     """ the the ability of the server to return
         information about the service.
     """
     runtime = KappaRuntime(self.endpoint)
     info = runtime.info()
     self.assertIsNotNone('sessions' in info)
     self.assertEqual(info['sessions'], 0)
     self.assertIsNotNone('processes' in info)
     self.assertEqual(info['processes'], 0)
     self.assertIsNotNone('build' in info)
示例#4
0
    def __init__(self, **kwargs):
        # Call the constructor of TripsModule
        parser = argparse.ArgumentParser()
        parser.add_argument("--kappa_url", help="kappa endpoint")
        args = parser.parse_args()
        if args.kappa_url:
            self.kappa_url = args.kappa_url
        else:
            logger.error('No Kappa URL given.')
            sys.exit()

        # Instantiate a kappa runtime
        self.kappa = KappaRuntime(self.kappa_url)

        super(Kappa_Module, self).__init__(**kwargs)
        return
示例#5
0
 def init(self):
     '''
     Initialize Kappa module
     '''
     super(Kappa_Module, self).init()
     # Send subscribe messages
     for task, subtasks in self.tasks.iteritems():
         for subtask in subtasks:
             msg_txt = '(subscribe :content (request &key :content ' +\
                 '(%s &key :content (%s . *))))' % (task, subtask)
             self.send(KQMLPerformative.fromString(msg_txt))
     # Instantiate a kappa runtime
     self.kappa = KappaRuntime(self.kappa_url)
     # Send ready message
     self.ready()
示例#6
0
 def __init__(self, argv):
     # Call the constructor of TripsModule
     super(Kappa_Module, self).__init__(argv)
     self.tasks = ['KAPPA-VERSION', 'KAPPA-PARSE', 'KAPPA-START',
                   'KAPPA-STATUS', 'KAPPA-STOP']
     parser = argparse.ArgumentParser()
     parser.add_argument("--kappa_url", help="kappa endpoint")
     args = parser.parse_args()
     if args.kappa_url:
         self.kappa_url = args.kappa_url
     else:
         logger.error('No Kappa URL given.')
         sys.exit()
     # Send subscribe messages
     for task in self.tasks:
         msg_txt =\
             '(subscribe :content (request &key :content (%s . *)))' % task
         self.send(KQMLPerformative.from_string(msg_txt))
     # Instantiate a kappa runtime
     self.kappa = KappaRuntime(self.kappa_url)
     # Send ready message
     self.ready()
     super(Kappa_Module, self).start()
示例#7
0
class Kappa_Module(TripsModule):
    '''
    The Kappa module is a TRIPS module built around the Kappa client. Its role
    is to receive and decode messages and send responses from and to other
    agents in the system.
    '''
    def __init__(self, argv):
        # Call the constructor of TripsModule
        super(Kappa_Module, self).__init__(argv)
        self.tasks = [
            'KAPPA-VERSION', 'KAPPA-PARSE', 'KAPPA-START', 'KAPPA-STATUS',
            'KAPPA-STOP'
        ]
        parser = argparse.ArgumentParser()
        parser.add_argument("--kappa_url", help="kappa endpoint")
        args = parser.parse_args()
        if args.kappa_url:
            self.kappa_url = args.kappa_url
        else:
            logging.error('No Kappa URL given.')
            sys.exit()
        # Send subscribe messages
        for task in self.tasks:
            msg_txt =\
                '(subscribe :content (request &key :content (%s . *)))' % task
            self.send(KQMLPerformative.from_string(msg_txt))
        # Instantiate a kappa runtime
        self.kappa = KappaRuntime(self.kappa_url)
        # Send ready message
        self.ready()
        super(Kappa_Module, self).start()

    def receive_request(self, msg, content):
        '''
        If a "request" message is received, decode the task and the content
        and call the appropriate function to prepare the response. A reply
        "tell" message is then sent back.
        '''
        content_list = content
        task_str = content_list[0].to_string().upper()
        arguments = self.request_arguments(content_list)
        if task_str == 'KAPPA-VERSION':
            try:
                reply_content = self.respond_version()
            except Exception as e:
                message = 'Could not get Kappa version: (%s)' % e
                self.error_reply(msg, message)
                return
        elif task_str == 'KAPPA-PARSE':
            try:
                reply_content = self.respond_parse(arguments)
            except Exception as e:
                message = 'Could not parse Kappa model: (%s)' % e
                self.error_reply(msg, message)
                return
        elif task_str == 'KAPPA-START':
            try:
                reply_content = self.respond_start(arguments)
            except Exception as e:
                message = 'Could not start Kappa simulation: (%s)' % e
                self.error_reply(msg, message)
                return
        elif task_str == 'KAPPA-STATUS':
            try:
                reply_content = self.respond_status(arguments)
            except Exception as e:
                message = 'Could not get Kappa status: (%s)' % e
                self.error_reply(msg, message)
                return
        elif task_str == 'KAPPA-STOP':
            try:
                reply_content = self.respond_stop(arguments)
            except Exception as e:
                message = 'Could not stop Kappa simulation: (%s)' % e
                self.error_reply(msg, message)
                return
        else:
            message = '"unknown request task ' + task_str + '"'
            self.error_reply(msg, message)
            return
        reply_msg = KQMLPerformative('reply')
        reply_msg.set_parameter(':content', reply_content)
        logger.debug(reply_content.to_string())
        self.reply(msg, reply_msg)

    def respond_version(self):
        '''
        Response content to version message
        '''
        response = self.kappa.version()
        reply_content = KQMLList.from_string(
            '(SUCCESS ' + ':VERSION "%s" ' % response['version'] +
            ':BUILD   "%s")' % response['build'])
        logger.debug(reply_content.to_string())
        return reply_content

    def response_error(self, error):
        reply_content = KQMLList()
        for e in error:
            error_msg = '"%s"' %\
                str(e).encode('string-escape').replace('"', '\\"')
            reply_content.add(error_msg)
        return self.format_error(reply_content.to_string())

    def request_arguments(self, arguments):
        request = {}
        arg_list = [arguments[index] for index in range(arguments.length())]
        for i, a in enumerate(arg_list):
            arg_str = a.to_string()
            if arg_str.startswith(':'):
                key = arg_str[1:].upper()
                val = arg_list[i + 1].to_string()
                request[key] = val
        logger.debug(request)
        return request

    def respond_parse(self, arguments):
        '''
        Response content to parse message
        '''
        if "CODE" not in arguments:
            reply_content = self.response_error(["Missing code"])
        else:
            request_code = arguments["CODE"]
            request_code = request_code[1:-1]
            logger.debug('raw {0}'.format(request_code))
            request_code = request_code.decode('string_escape')
            logger.debug('respond_parse {0}'.format(request_code))
            reply_content = KQMLList()
            try:
                response = self.kappa.parse(request_code)
                logger.debug(response)
                reply_content = KQMLList.from_string('(SUCCESS)')
            except RuntimeError as e:
                logger.debug(e.errors)
                reply_content = self.response_error(e.errors)
        return reply_content

    def format_error(self, message):
        response_content = KQMLList.from_string('(FAILURE :reason %s)' %
                                                message)
        return response_content

    def respond_start(self, arguments):
        '''
        Response content to start message
        '''
        if "CODE" not in arguments:
            response_content = self.response_error(["Missing code"])
        elif "NB_PLOT" not in arguments:
            response_content =\
                self.response_error(["Missing number of plot points"])
        else:
            try:
                parameter = {}
                parameter["nb_plot"] = arguments["NB_PLOT"]
                if "MAX_TIME" in arguments:
                    parameter["max_time"] = float(arguments["MAX_TIME"])
                if "MAX_EVENTS" in arguments:
                    parameter["max_events"] = int(arguments["MAX_EVENTS"])
                request_code = arguments["CODE"]
                request_code = request_code[1:-1]
                request_code = request_code.decode('string_escape')
                parameter["code"] = request_code
                try:
                    logger.debug(parameter)
                    response = self.kappa.start(parameter)
                    response_message = '(SUCCESS :id %d)' % response
                    response_content = KQMLList.from_string(response_message)
                except RuntimeError as e:
                    response_content = self.response_error(e.errors)
            except ValueError as e:
                response_content = self.response_error([str(e)])
        return response_content

    def respond_status(self, arguments):
        if "ID" not in arguments:
            response_content = self.response_error(["Missing simulation id"])
        else:
            try:
                token = int(arguments["ID"])
                status = self.kappa.status(token)
                response_content = render_status(status)
            except ValueError as e:
                response_content = self.response_error([str(e)])
            except RuntimeError as e:
                response_content = self.response_error(e.errors)
        return response_content

    def respond_stop(self, arguments):
        if "ID" not in arguments:
            response_content = self.response_error(["Missing simulation id"])
        else:
            try:
                token = int(arguments["ID"])
                status = self.kappa.stop(token)
                response_content = KQMLList.from_string('(SUCCESS)')
            except RuntimeError as e:
                response_content = self.response_error(e.errors)
        return response_content
示例#8
0
class Kappa_Module(KQMLModule):
    '''
    The Kappa module is a TRIPS module built around the Kappa client. Its role
    is to receive and decode messages and send responses from and to other
    agents in the system.
    '''
    def __init__(self, argv):
        # Call the constructor of TripsModule
        super(Kappa_Module, self).__init__(argv)
        self.tasks = ['KAPPA-VERSION', 'KAPPA-PARSE', 'KAPPA-START',
                      'KAPPA-STATUS', 'KAPPA-STOP']
        parser = argparse.ArgumentParser()
        parser.add_argument("--kappa_url", help="kappa endpoint")
        args = parser.parse_args()
        if args.kappa_url:
            self.kappa_url = args.kappa_url
        else:
            logger.error('No Kappa URL given.')
            sys.exit()
        # Send subscribe messages
        for task in self.tasks:
            msg_txt =\
                '(subscribe :content (request &key :content (%s . *)))' % task
            self.send(KQMLPerformative.from_string(msg_txt))
        # Instantiate a kappa runtime
        self.kappa = KappaRuntime(self.kappa_url)
        # Send ready message
        self.ready()
        super(Kappa_Module, self).start()

    def receive_request(self, msg, content):
        '''
        If a "request" message is received, decode the task and the content
        and call the appropriate function to prepare the response. A reply
        "tell" message is then sent back.
        '''
        content_list = content
        task_str = content_list[0].to_string().upper()
        arguments = self.request_arguments(content_list)
        if task_str == 'KAPPA-VERSION':
            try:
                reply_content = self.respond_version()
            except Exception as e:
                message = 'Could not get Kappa version: (%s)' % e
                self.error_reply(msg, message)
                return
        elif task_str == 'KAPPA-PARSE':
            try:
                reply_content = self.respond_parse(arguments)
            except Exception as e:
                message = 'Could not parse Kappa model: (%s)' % e
                self.error_reply(msg, message)
                return
        elif task_str == 'KAPPA-START':
            try:
                reply_content = self.respond_start(arguments)
            except Exception as e:
                message = 'Could not start Kappa simulation: (%s)' % e
                self.error_reply(msg, message)
                return
        elif task_str == 'KAPPA-STATUS':
            try:
                reply_content = self.respond_status(arguments)
            except Exception as e:
                message = 'Could not get Kappa status: (%s)' % e
                self.error_reply(msg, message)
                return
        elif task_str == 'KAPPA-STOP':
            try:
                reply_content = self.respond_stop(arguments)
            except Exception as e:
                message = 'Could not stop Kappa simulation: (%s)' % e
                self.error_reply(msg, message)
                return
        else:
            message = '"unknown request task ' + task_str + '"'
            self.error_reply(msg, message)
            return
        reply_msg = KQMLPerformative('reply')
        reply_msg.set_parameter(':content', reply_content)
        logger.debug(reply_content.to_string())
        self.reply(msg, reply_msg)

    def respond_version(self):
        '''
        Response content to version message
        '''
        response = self.kappa.version()
        reply_content = KQMLList.from_string(
                        '(SUCCESS ' +
                             ':VERSION "%s" ' % response['version'] +
                             ':BUILD   "%s")' % response['build'])
        logger.debug(reply_content.to_string())
        return reply_content

    def response_error(self, error):
        reply_content = KQMLList()
        for e in error:
            error_msg = '"%s"' %\
                str(e).encode('string-escape').replace('"', '\\"')
            reply_content.add(error_msg)
        return self.format_error(reply_content.to_string())

    def request_arguments(self, arguments):
        request = {}
        arg_list = [arguments[index] for index in
                    range(arguments.length())]
        for i, a in enumerate(arg_list):
            arg_str = a.to_string()
            if arg_str.startswith(':'):
                key = arg_str[1:].upper()
                val = arg_list[i+1].to_string()
                request[key] = val
        logger.debug(request)
        return request

    def respond_parse(self, arguments):
        '''
        Response content to parse message
        '''
        if "CODE" not in arguments:
            reply_content = self.response_error(["Missing code"])
        else:
            request_code = arguments["CODE"]
            request_code = request_code[1:-1]
            logger.debug('raw {0}'.format(request_code))
            request_code = request_code.decode('string_escape')
            logger.debug('respond_parse {0}'.format(request_code))
            reply_content = KQMLList()
            try:
                response = self.kappa.parse(request_code)
                logger.debug(response)
                reply_content = KQMLList.from_string('(SUCCESS)')
            except RuntimeError as e:
                logger.debug(e.errors)
                reply_content = self.response_error(e.errors)
        return reply_content

    def format_error(self, message):
        response_content = KQMLList.from_string(
                            '(FAILURE :reason %s)' % message)
        return response_content

    def respond_start(self, arguments):
        '''
        Response content to start message
        '''
        if "CODE" not in arguments:
            response_content = self.response_error(["Missing code"])
        elif "NB_PLOT" not in arguments:
            response_content =\
                self.response_error(["Missing number of plot points"])
        else:
            try:
                parameter = {}
                parameter["nb_plot"] = arguments["NB_PLOT"]
                if "MAX_TIME" in arguments:
                    parameter["max_time"] = float(arguments["MAX_TIME"])
                if "MAX_EVENTS" in arguments:
                    parameter["max_events"] = int(arguments["MAX_EVENTS"])
                request_code = arguments["CODE"]
                request_code = request_code[1:-1]
                request_code = request_code.decode('string_escape')
                parameter["code"] = request_code
                try:
                    logger.debug(parameter)
                    response = self.kappa.start(parameter)
                    response_message = '(SUCCESS :id %d)' % response
                    response_content = KQMLList.from_string(response_message)
                except RuntimeError as e:
                    response_content = self.response_error(e.errors)
            except ValueError as e:
                response_content = self.response_error([str(e)])
        return response_content

    def respond_status(self, arguments):
        if "ID" not in arguments:
            response_content = self.response_error(["Missing simulation id"])
        else:
            try:
                token = int(arguments["ID"])
                status = self.kappa.status(token)
                response_content = render_status(status)
            except ValueError as e:
                response_content = self.response_error([str(e)])
            except RuntimeError as e:
                response_content = self.response_error(e.errors)
        return response_content

    def respond_stop(self, arguments):
        if "ID" not in arguments:
            response_content = self.response_error(["Missing simulation id"])
        else:
            try:
                token = int(arguments["ID"])
                status = self.kappa.stop(token)
                response_content = KQMLList.from_string('(SUCCESS)')
            except RuntimeError as e:
                response_content = self.response_error(e.errors)
        return response_content
示例#9
0
 def tearDownClass(cls):
     """ tear down test by shutting down"""
     runtime = KappaRuntime(cls.endpoint)
     print runtime.shutdown(cls.key)
示例#10
0
class Kappa_Module(trips_module.TripsModule):
    '''
    The Kappa module is a TRIPS module built around the Kappa client. Its role
    is to receive and decode messages and send responses from and to other
    agents in the system.
    '''
    def __init__(self, argv):
        # Call the constructor of TripsModule
        super(Kappa_Module, self).__init__(argv)
        self.tasks = {'ONT::PERFORM': ['ONT::VERSION']}
        parser = argparse.ArgumentParser()
        parser.add_argument("--kappa_url"
                           ,help="kappa endpoint")
        args = parser.parse_args()
        if args.kappa_url:
            self.kappa_url=args.kappa_url

    def init(self):
        '''
        Initialize Kappa module
        '''
        super(Kappa_Module, self).init()
        # Send subscribe messages
        for task, subtasks in self.tasks.iteritems():
            for subtask in subtasks:
                msg_txt = '(subscribe :content (request &key :content ' +\
                    '(%s &key :content (%s . *))))' % (task, subtask)
                self.send(KQMLPerformative.fromString(msg_txt))
        # Instantiate a kappa runtime
        self.kappa = KappaRuntime(self.kappa_url)
        # Send ready message
        self.ready()

    def receive_request(self, msg, content):
        '''
        If a "request" message is received, decode the task and the content
        and call the appropriate function to prepare the response. A reply
        "tell" message is then sent back.
        '''
        print msg
        content_list = cast(KQMLList, content)
        task_str = content_list.get(0).toString().upper()
        if task_str == 'ONT::PERFORM':
            subtask = cast(KQMLList,content_list.getKeywordArg(':content'))
            subtask_str = subtask.get(0).toString().upper()
            subtask.remove(0)
            arguments = self.request_arguments(subtask)
            if subtask_str == 'ONT::VERSION':
                reply_content = self.respond_version()
            elif subtask_str == 'ONT::PARSE':
                reply_content = self.respond_parse(arguments)
            elif subtask_str == 'ONT::START':
                reply_content = self.respond_start(arguments)
            elif subtask_str == 'ONT::STATUS':
                reply_content = self.respond_status(arguments)
            elif subtask_str == 'ONT::STOP':
                reply_content = self.respond_stop(arguments)
            else:
                message = '"'+'unknown request subtask ' + subtask_str + '"'
                self.error_reply(msg,message)
                return
        else:
            message = '"'+'unknown request task ' + task_str + '"'
            self.error_reply(msg,message)
            return
        reply_msg = KQMLPerformative('reply')
        reply_msg.setParameter(':content', cast(KQMLObject, reply_content))
        self.reply(msg, reply_msg)

    def respond_version(self):
        '''
        Response content to version message
        '''
        reply_content = KQMLList()
        response = self.kappa.version()
        response_content = KQMLList.fromString( '' +\
                        '(ONT::KAPPA ' +\
                             '( ONT::VERSION "%s") ' % response['version'] +\
                             '( ONT::BUILD   "%s") ' % response['build']   +\
                        ')')
        reply_content.add(KQMLList(response_content))
        return reply_content
    def response_error(self,error):
        reply_content = KQMLList()
        for e in error:
            error_msg = '"%s"' % str(e).encode('string-escape').replace('"', '\\"')
            reply_content.add(error_msg)
        return self.format_error(reply_content.toString())

    def request_arguments(self,arguments):
        request = dict()
        for index in range(arguments.size()):
            key_value = arguments.get(index)
            key_value = cast(KQMLList, key_value)
            if key_value.size() > 1:
                request[key_value.get(0).toString()] = key_value.get(1).toString()
        return request

    def respond_parse(self,arguments):
        '''
        Response content to parse message
        '''
        if not "ONT::CODE" in arguments:
            reply_content = self.response_error(["Missing code"])
        else:
            request_code = arguments["ONT::CODE"]
            request_code = request_code[1:-1]
            print 'raw {0}'.format(request_code)
            request_code = request_code.decode('string_escape')
            print 'respond_parse {0}'.format(request_code)
            reply_content = KQMLList()
            try: 
                response = self.kappa.parse(request_code)
                print response
                response_content = KQMLList.fromString('(ONT::KAPPA ( ONT::OK ) )')
                reply_content.add(KQMLList(response_content))
            except RuntimeError as e:
                print e.errors
                reply_content = self.response_error(e.errors)
        return reply_content

    def format_error(self,message):
        response_content = KQMLList.fromString( '' +\
                        '(ONT::KAPPA ' +\
                             '( ONT::ERRORS %s) ' % message +\
                        ')')
        return response_content
    
    def respond_start(self,arguments):
        '''
        Response content to start message
        '''
        if not "ONT::CODE" in arguments:
            response_content = self.response_error(["Missing code"])
        elif not "ONT::NB_PLOT" in arguments:
            response_content = self.response_error(["Missing number of plot points"])
        else:
            try:
                parameter = dict()
                parameter["nb_plot"] = arguments["ONT::NB_PLOT"]
                if "ONT::MAX_TIME" in arguments:
                    parameter["max_time"] = float(arguments["ONT::MAX_TIME"])
                if "ONT::MAX_EVENTS" in arguments:
                    parameter["max_events"] = int(arguments["ONT::MAX_EVENTS"])
                request_code = arguments["ONT::CODE"]
                request_code = request_code[1:-1]
                request_code = request_code.decode('string_escape')
                parameter["code"] = request_code
                try: 
                    print parameter
                    response = self.kappa.start(parameter)
                    response_message = '(ONT::KAPPA ( ONT::TOKEN %d ) )' % response
                    response_content = KQMLList.fromString(response_message)
                except RuntimeError as e:
                    response_content = self.response_error(e.errors)
            except ValueError as e:
                response_content = self.response_error([str(e)])
        return response_content

    def respond_status(self,arguments):
        if not "ONT::TOKEN" in arguments:
            response_content = self.response_error(["Missing token"])
        else:
            try:
                token = int(arguments["ONT::TOKEN"])
                status = self.kappa.status(token)
                response_content = render_status(status)
            except ValueError as e:
                response_content = self.response_error([str(e)])
            except RuntimeError as e:
                response_content = self.response_error(e.errors)
        return response_content

    def respond_stop(self,arguments):
        if not "ONT::TOKEN" in arguments:
            response_content = self.response_error(["Missing token"])
        else:
            try:
                token = int(arguments["ONT::TOKEN"])
                status = self.kappa.stop(token)
                response_content = KQMLList.fromString('(ONT::KAPPA ( ONT::OK ) )')
            except RuntimeError as e:
                response_content = self.response_error(e.errors)
        return response_content
示例#11
0
            raise e

from jnius import autoclass, cast
from TripsModule import trips_module
from kappa_client import KappaRuntime, RuntimeError
from time import sleep

# Declare KQML java classes
KQMLPerformative = autoclass('TRIPS.KQML.KQMLPerformative')
KQMLList = autoclass('TRIPS.KQML.KQMLList')
KQMLObject = autoclass('TRIPS.KQML.KQMLObject')


if __name__ == "__main__":
    with open("../abc-pert.ka") as f:
        try:
            subprocess.Popen('../WebSim.native --shutdown-key 6666 --port 6666'.split())
            sleep(1)
            data = f.read()
            runtime = KappaRuntime("http://localhost:6666")
            token = runtime.start({ 'code': data
                                  , 'nb_plot': 10
                                  , 'max_events' : 10000 })
            sleep(10)
            status = runtime.status(token)
            print status
            print render_status(status).toString()
            print runtime.shutdown('6666')
        except RuntimeError as e:
            print e.errors