services.rst 11 KB

  1. External Services
  2. =================
  3. Up to now, everything was contained in the Modelverse.
  4. Nonetheless, this is not always possible, or desired: sometimes we want to run an activity using an external tool, or a service.
  5. There are two main reasons why we would like this: performance and feasability.
  6. For performance, an external service is likely to be faster than a Modelverse-based implementation.
  7. Not only because the action language execution of the Modelverse is comparatively slow, but also because of the optimized implementation of the external tool.
  8. It is clear that a specialized tool will be much faster than a naive implementation, even if the naive implementation were to be done in an efficient language.
  9. For example, PythonPDEVS uses many non-trivial algorithms to speed up DEVS simulation, which are not easily mimicked in a new implementation.
  10. While not impossible, of course, it seems wasteful to spend a significant amount of time to reimplement a tool.
  11. For feasability, an external service can offer operations that the Modelverse would otherwise not be able to execute.
  12. This links back to performance, but also to the algorithms required for the operation.
  13. For example, reimplementing a differential equation solver is wasteful, knowing that specialized tools have spent many man-years to implement and optimize it.
  14. We can never dream to come even close to these implementations.
  15. Both go hand-in-hand: a naive implementation is often possible, but there is always the tradeoff between spending more time in developing the algorithm, and more time in using the algorithm.
  16. The ideal solution would be to use an existing tool, thereby relying on the expertise of other developers, and merely making it available in the Modelverse.
  17. When making this available in the Modelverse, we strife to minimize the difference between an internal and external operation.
  18. This can be done using services: instead of modelling the activity, we model the communication with a tool that does the actual activity.
  19. While there remains a big difference, as we cannot alter the semantics of the external tool, we come fairly close, abstracting away from the tool that is actually used for the operation.
  20. In this section, we will illustrate this operation through the use of a *Fibonacci* service, which takes a single integer, and returns the Fibonacci number corresponding to it.
  21. Modelverse-side
  22. ---------------
  23. On the Modelverse, users can use the *comm* operations to communicate with external tools.
  24. This is highly similar to communication for input and output to the designated user.
  25. Code on the Modelverse can set up a connection to a registered service as follows::
  26. Integer function fibonacci(n : Integer):
  27. String port
  28. // Set up a dedicated communication port to the service
  29. port = comm_connect("fibonacci")
  30. // Send some data: the integer we got ourselves
  31. comm_send(port, n)
  32. // The external service computes the result
  33. // The comm_get function is blocking
  34. Integer result
  35. result = comm_get(port)!
  36. // Close the communication port from our side
  37. comm_close(port)
  38. return result!
  39. In this example, we send an integer parameter to the external service, and expect it to reply with another integer, containing the final result.
  40. When we got our result, we should always call *comm_close* to close the port at the Modelverse side.
  41. Multiple calls to *comm_send* and *comm_get* are possible, depending on the communication protocol devised between the Modelverse and the external service.
  42. For example, if we want to wait for the service to accept the result (e.g., the service can give an error on non-integer input)::
  43. Integer function fibonacci(n : Integer):
  44. String port
  45. port = comm_connect("fibonacci")
  46. comm_send(port, n)
  47. String response
  48. response = comm_get(port)
  49. if (response == "OK"):
  50. Integer result
  51. result = comm_get(port)
  52. comm_close(port)
  53. return result!
  54. elif (response == "Integer value expected!"):
  55. // error out, as it is not an integer!
  56. log("Non-integer input to fibonacci function!")
  57. comm_close(port)
  58. return -1!
  59. Sometimes, for example when coupled to Statecharts, we want to poll whether or not there is input from the service.
  60. This can be done using the *comm_poll* function, whose signature is identical to *comm_get*, though it returns a boolean and returns immediately.
  61. As expected, it does not consume the value itself, which can subsequently be read out using *comm_get*, which will now return immediately if *comm_poll* was True.
  62. Service-side
  63. ------------
  64. The external service itself should be slightly augmented with a minimal wrapper.
  65. This wrapper is responsible for the communication with the Modelverse, by importing the Modelverse wrapper, deserializing the input from the Modelverse, and serializing the output from the tool.
  66. For our fibonacci example, where the fibonacci code is written in Python as well, we can code this as follows::
  67. >>> def fibonacci_service(port):
  68. ... def fibonacci(n):
  69. ... if n <= 2:
  70. ... return 1
  71. ... else:
  72. ... return fibonacci(n - 1) + fibonacci(n - 2)
  73. ... mv_input = service_get(port)
  74. ... result = fibonacci(mv_input)
  75. ... service_set(port, result)
  76. >>> service_register("fibonacci", fibonacci_service)
  77. >>> try:
  78. ... while raw_input() != "STOP":
  79. ... pass
  80. ... finally:
  81. ... service_stop()
  82. In this simple piece of code, we define the actual fibonacci code in the function *fibonacci*, which is totally unrelated to the Modelverse and is just pure Python code.
  83. To wrap it, we define *fibonacci_service*, which is a function taking the communication port.
  84. This function is responsible for communication with the Modelverse, through the operations *service_get* and *service_set*.
  85. Both functions have the expected signature.
  86. The service function is invoked on a thread, and therefore runs concurrently with other invocations of this same service.
  87. Upon termination of the function, the thread ceases to exist.
  88. All threads are daemon threads, such that, if the service wants to exit, it can immediately exit without first finishing up the processing of tasks in the Modelverse.
  89. It is up to the Modelverse tasks to be resilient to such service failure or termination anyway, possibly through the use of a statechart that contains timeouts.
  90. When the service is registered, we have to specify the name of the service to be used in the Modelverse on a *comm_connect* call.
  91. The second parameter is the function to invoke when a connection is made, and must take one parameter: the communication port to be used.
  92. After the service is registered, the main thread simply continues.
  93. This makes it possible for the administrators of the service to maintain full control over their service.
  94. If the main thread terminates, all currently running services are terminated.
  95. Note that, after registration, this program is not able to do any other operations, until the *service_stop* operation is sent.
  96. When doing type checking first, we can do multiple *service_set* operations::
  97. >>> def fibonacci_service(port):
  98. ... def fibonacci(n):
  99. ... if n <= 2:
  100. ... return 1
  101. ... else:
  102. ... return fibonacci(n - 1) + fibonacci(n - 2)
  103. ... mv_input = service_get(port)
  104. ... if isinstance(mv_input, int):
  105. ... service_set(port, "OK")
  106. ... result = fibonacci(mv_input)
  107. ... service_set(port, result)
  108. ... else:
  109. ... service_set(port, "Integer value expected!")
  110. >>> service_register("fibonacci", fibonacci_service)
  111. >>> try:
  112. ... while raw_input() != "STOP":
  113. ... pass
  114. ... finally:
  115. ... service_stop()
  116. The invoked function is in this case other Python code, though this does not need to be that way.
  117. It would also be possible to invoke another executable, such as a *fibonacci* program, as long as the program can be used in an automated way.
  118. Therefore, the external services are not limited to Python in any way, and we merely use Python as a convencience, since we already have a wrapper for it.
  119. Using an external program happens through the *subprocess* Python module::
  120. >>> def fibonacci_service(port):
  121. ... def fibonacci(n):
  122. ... import subprocess
  123. ... result = subprocess.check_output(["./fibonacci", str(n)])
  124. ... return int(result)
  125. ... mv_input = service_get(port)
  126. ... result = fibonacci(mv_input)
  127. ... service_set(port, result)
  128. >>> service_register("fibonacci", fibonacci_service)
  129. >>> try:
  130. ... while raw_input() != "STOP":
  131. ... pass
  132. ... finally:
  133. ... service_stop()
  134. HUTN compiler
  135. -------------
  136. While it might not be obvious, some of the internal Modelverse operations are implemented using external services already.
  137. This is the case for the *compile_code* and *compile_model* functions.
  138. These functions rely on a HUTN compiler running as a service: the string is sent there, and the service sends back the list of operations to execute on the Modelverse (i.e., the compiled data).
  139. This was done to prevent a complete implementation of a parser in the Modelverse.
  140. While this would certainly be possible, at the moment it is not of high priority, and it is easy to shift it externally.
  141. Also, by using external services, it becomes possible to rely on trusted parsers, such as ANTLR or Ply, instead of building one from scratch as well.
  142. Users of the *compile_code* and *compile_model* functions are never exposed to the use of an external service: it looks exactly like any other function call.
  143. Nonetheless, there is a small difference: when the external service encounters a problem, or is simply not running, the functions will not be able to operate, even though the input is correct.
  144. In any case, the compile_code and compile_model operations return a string value if they encounter a problem.
  145. This problem could be anything, such as a syntax error or a semantical analysis error.
  146. Otherwise, the functions return the action language function and model, respectively.
  147. Before you can execute these functions, the HUTN compilation service must be running, which can be done by executing::
  148. >>> python scripts/
  149. The service will connect to the Modelverse specified in its configuration (i.e., the *init* call).
  150. It stays connected until the *STOP* input is given on *stdin*.
  151. Others
  152. ------
  153. Many other services have been defined and are automatically ran by the Modelverse.
  154. This includes a JSON service (serialization and deserialization), a file server (persistent storage to files), a DEVS simulation server (both interactive and batch execution), and a PetriNet analysis service.
  155. New services can easily be defined by putting a Python file in the *services* folder of the Modelverse.
  156. All its subfolders are traversed and for each the ** file is executed upon starting the Modelverse.
  157. Upon starting the Modelverse, a log is printed to stdout of which services have started up.
  158. When the Modelverse terminates, all services also quit.