Beispiel #1
0
    def _dispatch(self, method, args=None):
        if args is not None:
            data = [method, args]
        else:
            data = method

        try:
            self.lock.acquire()
            message_id = self._get_message_id()
            message = {'id': message_id, 'data': data}
            message = "{0}{1}".format(json.dumps(message), self.delimiter)
            self.sim_agent.stdin.write(message.encode('utf-8'))
            self.sim_agent.stdin.flush()
            buff = bytearray()
            c = self.sim_agent.stdout.read(1)
            while c != self.delimiter.encode('utf-8') and c:
                buff.extend(c)
                c = self.sim_agent.stdout.read(1)
            response = json.loads(buff.decode('utf-8'))
            if response["id"] != message_id:
                raise KappaError("expect id {0} got {1}".format(
                    response["id"], message_id))
            else:
                return self.projection(response["data"])[1]

        finally:
            self.lock.release()
Beispiel #2
0
 def projection(self, response):
     result_data = response["data"]["result_data"]
     data = result_data[1]
     if result_data[0] == "Ok":
         return data[1]
     else:
         raise KappaError(data)
Beispiel #3
0
 def simulation_start(self, simulation_parameter=None):
     if simulation_parameter is None:
         simulation_parameter = self.get_default_sim_param()
     if self.project_ast is None:
         raise KappaError("Project not parsed since last modification")
     return self._post(self.in_project('simulation'),
                       simulation_parameter.toJSON())
Beispiel #4
0
def find_websim():
    # Look bellow the KAPPY_DIR first, then KASIM_DIR
    up_two = path.normpath(
        path.join(path.dirname(path.abspath(__file__)), '..', '..'))
    sim_path = find_path(up_two, 'WebSim')
    if sim_path is not None:
        return sim_path
    raise KappaError('WebSim could not be found.')
Beispiel #5
0
 def _dispatch(self, method, sub_url=None, data=None):
     if sub_url is not None:
         url = path.join(self.url, sub_url)
     else:
         url = self.url
     if data is not None:
         data = json.dumps(data)
     try:
         r = request(method, url, data=data)
     except exceptions.HTTPError as e:
         msg = e.read()
         raise KappaError(json.loads(msg, encoding='utf-8'))
     details = r.json(encoding='utf-8')
     if 400 <= r.status_code < 500:
         raise KappaError(details)
     else:
         return details
Beispiel #6
0
 def _analyses_init(self):
     """
     Initialize the static analyser thanks to the result of project_parse
     """
     if self.project_ast is None:
         raise KappaError("Project not parsed since last modification")
     result = self._dispatch_sa(["INIT", self.project_ast])
     self.analyses_to_init = False
     return result
Beispiel #7
0
    def shutdown(self, key):
        """Shut down kappa instance.

        Given a key to a kappa service shutdown a running kappa instance.
        """
        parse_url = "{0}/shutdown".format(self.url)
        try:
            r = request("POST", parse_url, data=key.encode('utf-8'))
        except exceptions.HTTPError as exception:
            raise KappaError(exception.reason)
        if r.status_code == 200:
            return r.text
        elif r.status_code == 400:
            print(r.text, r.reason)
            raise KappaError(r.text)
        elif r.status_code == 401:
            raise KappaError(r.text)
        else:
            raise KappaError(r.reason)
Beispiel #8
0
    def simulation_start(self, simulation_parameter):
        """Start the simulation from the last parsed model.

        Inputs
        ------
        simulation_parameter -- is described in kappa_common.SimulationParameter
        """
        if self.project_ast is None:
            raise KappaError("Project not parsed since last modification")
        return self._dispatch("SimulationStart", simulation_parameter.toJSON())
Beispiel #9
0
def find_agent_bin():
    agent_names = ['KaSimAgent', 'KaSaAgent']
    for potential_dir in [KAPPY_DIR, KASIM_DIR]:
        bin_dir = path.join(potential_dir, 'bin')
        if not path.exists(bin_dir):
            continue
        contents = listdir(bin_dir)
        if all([agent in contents for agent in agent_names]):
            break
    else:
        raise KappaError("Could not find directory with agents.")
    return bin_dir
Beispiel #10
0
    def _dispatch_model(self, data):
        try:
            self.lock.acquire()
            message_id = self._get_message_id()
            message = [ message_id, data]
            message = "{0}{1}".format(json.dumps(message), self.delimiter)
            self.model_agent.stdin.write(message.encode('utf-8'))
            self.model_agent.stdin.flush()
            buff = self.read_stdout(self.model_agent)
            response = json.loads(buff.decode('utf-8'))
            if isinstance(response,str):
                raise KappaError(response)
            elif response[0] != message_id:
                raise KappaError(
                        "expect id {0} got {1}".format(response[0],
                                                       message_id)
                        )
            else:
                return self.projection(response[1])

        finally:
            self.lock.release()
Beispiel #11
0
 def __init__(self, kappa_bin_path=None, delimiter='\x1e', args=None):
     self.delimiter = delimiter
     self.project_ast = None
     self.analyses_to_init = True
     if kappa_bin_path is None:
         if BIN_DIR is None:
             # binaries must either exist in kappy directory or
             # their location must be passed to this class
             raise KappaError("Kappa binaries not found.")
         kappa_bin_path = BIN_DIR
     sim_args = [
         path.join(kappa_bin_path, "KaSimAgent"),
         "--delimiter",
         "\\x{:02x}".format(ord(self.delimiter)),
         "--log",
         "-",
     ]
     if args:
         sim_args = sim_args + args
     self.lock = threading.Lock()
     self.message_id = 0
     self.sim_agent = subprocess.Popen(sim_args,
                                       stdin=subprocess.PIPE,
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.STDOUT)
     sa_args = [
         path.join(kappa_bin_path, "KaSaAgent"),
         "--delimiter",
         "\\x{:02x}".format(ord(self.delimiter)),
     ]
     if args:
         sa_args = sa_args + args
     self.sa_agent = subprocess.Popen(sa_args,
                                      stdin=subprocess.PIPE,
                                      stdout=subprocess.PIPE,
                                      stderr=subprocess.STDOUT)
     model_args = [
         path.join(kappa_bin_path, "KaMoHa"),
         "--delimiter",
         "\\x{:02x}".format(ord(self.delimiter)),
     ]
     if args:
         model_args = model_args + args
     self.model_agent = subprocess.Popen(model_args,
                                         stdin=subprocess.PIPE,
                                         stdout=subprocess.PIPE,
                                         stderr=subprocess.STDOUT)
     return
Beispiel #12
0
    def _dispatch_sa(self, data):
        try:
            self.lock.acquire()
            message_id = self._get_message_id()
            message = {'id': message_id, 'data': data}
            message = "{0}{1}".format(json.dumps(message), self.delimiter)
            self.sa_agent.stdin.write(message.encode('utf-8'))
            self.sa_agent.stdin.flush()
            buff = self.read_stdout(self.sa_agent)
            response = json.loads(buff.decode('utf-8'))
            if response['code'] == "SUCCESS":
                return response['data']
            else:
                raise KappaError(response['data'])

        finally:
            self.lock.release()
Beispiel #13
0
 def projection(self, result_data):
     data = result_data[1]
     if result_data[0] == "Ok":
         return data
     else:
         raise KappaError(data)
Beispiel #14
0
 def _analyses_init(self):
     if self.project_ast is None:
         raise KappaError("Project not parsed since last modification")
     result = self._put(self.in_project('analyses'), self.project_ast)
     self.analyses_to_init = False
     return result