__init__.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. # -*- coding: utf-8 -*-
  2. """!@package grass.pygrass.massages
  3. @brief PyGRASS message interface
  4. Fast and exit-safe interface to GRASS C-library message functions
  5. (C) 2013 by the GRASS Development Team
  6. This program is free software under the GNU General Public
  7. License (>=v2). Read the file COPYING that comes with GRASS
  8. for details.
  9. @author Soeren Gebbert
  10. """
  11. import sys
  12. import grass.lib.gis as libgis
  13. from multiprocessing import Process, Lock, Pipe
  14. class FatalError(Exception):
  15. """!This error will be raised in case raise_on_error was set True
  16. when creating the messenger object.
  17. """
  18. def __init__(self, msg):
  19. self.value = msg
  20. def __str__(self):
  21. return self.value
  22. def message_server(lock, conn):
  23. """!The GRASS message server function designed to be a target for
  24. multiprocessing.Process
  25. @param lock A multiprocessing.Lock
  26. @param conn A multiprocessing.Pipe
  27. This function will use the G_* message C-functions from grass.lib.gis
  28. to provide an interface to the GRASS C-library messaging system.
  29. The data that is send through the pipe must provide an
  30. identifier string to specify which C-function should be called.
  31. The following identifers are supported:
  32. - "INFO" Prints an info message, see G_message() for details
  33. - "IMPORTANT" Prints an important info message,
  34. see G_important_message() for details
  35. - "VERBOSE" Prints a verbose message if the verbosity level is
  36. set accordingly, see G_verbose_message() for details
  37. - "WARNING" Prints a warning message, see G_warning() for details
  38. - "ERROR" Prints a message with a leading "ERROR: " string,
  39. see G_important_message() for details
  40. - "PERCENT" Prints a percent value based on three integer values: n, d and s
  41. see G_percent() for details
  42. - "STOP" Stops the server function and closes the pipe
  43. - "FATAL" Calls G_fatal_error(), this functions is only for
  44. testing purpose
  45. The that is end through the pipe must be a list of values:
  46. - Messages: ["INFO|VERBOSE|WARNING|ERROR|FATAL", "MESSAGE"]
  47. - Debug: ["DEBUG", level, "MESSAGE"]
  48. - Percent: ["PERCENT", n, d, s]
  49. """
  50. while True:
  51. # Avoid busy waiting
  52. conn.poll(None)
  53. data = conn.recv()
  54. message_type = data[0]
  55. # Only one process is allowed to write to stderr
  56. lock.acquire()
  57. # Stop the pipe and the infinite loop
  58. if message_type == "STOP":
  59. conn.close()
  60. lock.release()
  61. return
  62. message = data[1]
  63. if message_type == "PERCENT":
  64. n = int(data[1])
  65. d = int(data[2])
  66. s = int(data[3])
  67. libgis.G_percent(n, d, s)
  68. elif message_type == "DEBUG":
  69. level = data[1]
  70. message = data[2]
  71. libgis.G_debug(level, message)
  72. elif message_type == "VERBOSE":
  73. libgis.G_verbose_message(message)
  74. elif message_type == "INFO":
  75. libgis.G_message(message)
  76. elif message_type == "IMPORTANT":
  77. libgis.G_important_message(message)
  78. elif message_type == "WARNING":
  79. libgis.G_warning(message)
  80. elif message_type == "ERROR":
  81. libgis.G_important_message("ERROR: %s"%message)
  82. # This is for testing only
  83. elif message_type == "FATAL":
  84. libgis.G_fatal_error(message)
  85. lock.release()
  86. class Messenger(object):
  87. """!Fast and exit-safe interface to GRASS C-library message functions
  88. This class implements a fast and exit-safe interface to the GRASS
  89. C-library message functions like: G_message(), G_warning(),
  90. G_important_message(), G_verbose_message(), G_percent() and G_debug().
  91. Note:
  92. The C-library message functions a called via ctypes in a subprocess
  93. using a pipe (multiprocessing.Pipe) to transfer the text messages.
  94. Hence, the process that uses the Messenger interface will not be
  95. exited, if a G_fatal_error() was invoked in the subprocess.
  96. In this case the Messenger object will simply start a new subprocess
  97. and restarts the pipeline.
  98. Usage:
  99. @code
  100. >>> msgr = Messenger()
  101. >>> msgr.debug(0, "debug 0")
  102. >>> msgr.verbose("verbose message")
  103. >>> msgr.message("message")
  104. >>> msgr.important("important message")
  105. >>> msgr.percent(1, 1, 1)
  106. >>> msgr.warning("Ohh")
  107. >>> msgr.error("Ohh no")
  108. D0/0: debug 0
  109. message
  110. important message
  111. 100%
  112. WARNING: Ohh
  113. ERROR: Ohh no
  114. >>> msgr = Messenger()
  115. >>> msgr.fatal("Ohh no no no!")
  116. Traceback (most recent call last):
  117. File "__init__.py", line 239, in fatal
  118. sys.exit(1)
  119. SystemExit: 1
  120. >>> msgr = Messenger(raise_on_error=True)
  121. >>> msgr.fatal("Ohh no no no!")
  122. Traceback (most recent call last):
  123. File "__init__.py", line 241, in fatal
  124. raise FatalError(message)
  125. FatalError: Ohh no no no!
  126. @endcode
  127. """
  128. def __init__(self, raise_on_error=False):
  129. self.client_conn = None
  130. self.server_conn = None
  131. self.server = None
  132. self.raise_on_error = raise_on_error
  133. self.start_server()
  134. def __del__(self):
  135. self.stop()
  136. def start_server(self):
  137. self.client_conn, self.server_conn = Pipe()
  138. self.lock = Lock()
  139. self.server = Process(target=message_server, args=(self.lock,
  140. self.server_conn))
  141. self.server.daemon = True
  142. self.server.start()
  143. def _check_restart_server(self):
  144. """!Restart the server if it was terminated
  145. """
  146. if self.server.is_alive() is True:
  147. return
  148. self.client_conn.close()
  149. self.server_conn.close()
  150. self.start_server()
  151. self.warning("Needed to restart the messenger server")
  152. def message(self, message):
  153. """!Send a message to stderr
  154. G_message() will be called in the messenger server process
  155. """
  156. self._check_restart_server()
  157. self.client_conn.send(["INFO", message])
  158. def verbose(self, message):
  159. """!Send a verbose message to stderr
  160. G_verbose_message() will be called in the messenger server process
  161. """
  162. self._check_restart_server()
  163. self.client_conn.send(["VERBOSE", message])
  164. def important(self, message):
  165. """!Send an important message to stderr
  166. G_important_message() will be called in the messenger server process
  167. """
  168. self._check_restart_server()
  169. self.client_conn.send(["IMPORTANT", message])
  170. def warning(self, message):
  171. """!Send a warning message to stderr
  172. G_warning() will be called in the messenger server process
  173. """
  174. self._check_restart_server()
  175. self.client_conn.send(["WARNING", message])
  176. def error(self, message):
  177. """!Send an error message to stderr
  178. G_important_message() with an additional "ERROR:" string at
  179. the start will be called in the messenger server process
  180. """
  181. self._check_restart_server()
  182. self.client_conn.send(["ERROR", message])
  183. def fatal(self, message):
  184. """!Send an error message to stderr, call sys.exit(1) or raise FatalError
  185. This function emulates the behavior of G_fatal_error(). It prints
  186. an error message to stderr and calls sys.exit(1). If raise_on_error
  187. is set True while creating the messenger object, a FatalError
  188. exception will be raised instead of calling sys.exit(1).
  189. """
  190. self._check_restart_server()
  191. self.client_conn.send(["ERROR", message])
  192. self.stop()
  193. if self.raise_on_error is True:
  194. raise FatalError(message)
  195. else:
  196. sys.exit(1)
  197. def debug(self, level, message):
  198. """!Send a debug message to stderr
  199. G_debug() will be called in the messenger server process
  200. """
  201. self._check_restart_server()
  202. self.client_conn.send(["DEBUG", level, message])
  203. def percent(self, n, d, s):
  204. """!Send a percentage to stderr
  205. G_percent() will be called in the messenger server process
  206. """
  207. self._check_restart_server()
  208. self.client_conn.send(["PERCENT", n, d, s])
  209. def stop(self):
  210. """!Stop the messenger server and close the pipe
  211. """
  212. if self.server is not None and self.server.is_alive():
  213. self.client_conn.send(["STOP",])
  214. self.server.join(5)
  215. self.server.terminate()
  216. if self.client_conn is not None:
  217. self.client_conn.close()
  218. def test_fatal_error(self, message):
  219. """!Force the messenger server to call G_fatal_error()
  220. """
  221. import time
  222. self._check_restart_server()
  223. self.client_conn.send(["FATAL", message])
  224. time.sleep(1)
  225. if __name__ == "__main__":
  226. import doctest
  227. doctest.testmod()