__init__.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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. from multiprocessing import Process, Lock, Pipe
  13. import grass.lib.gis as libgis
  14. from grass.exceptions import FatalError
  15. def message_server(lock, conn):
  16. """The GRASS message server function designed to be a target for
  17. multiprocessing.Process
  18. :param lock: A multiprocessing.Lock
  19. :param conn: A multiprocessing.Pipe
  20. This function will use the G_* message C-functions from grass.lib.gis
  21. to provide an interface to the GRASS C-library messaging system.
  22. The data that is send through the pipe must provide an
  23. identifier string to specify which C-function should be called.
  24. The following identifers are supported:
  25. - "INFO" Prints an info message, see G_message() for details
  26. - "IMPORTANT" Prints an important info message,
  27. see G_important_message() for details
  28. - "VERBOSE" Prints a verbose message if the verbosity level is
  29. set accordingly, see G_verbose_message() for details
  30. - "WARNING" Prints a warning message, see G_warning() for details
  31. - "ERROR" Prints a message with a leading "ERROR: " string,
  32. see G_important_message() for details
  33. - "PERCENT" Prints a percent value based on three integer values: n, d and s
  34. see G_percent() for details
  35. - "STOP" Stops the server function and closes the pipe
  36. - "FATAL" Calls G_fatal_error(), this functions is only for
  37. testing purpose
  38. The that is end through the pipe must be a list of values:
  39. - Messages: ["INFO|VERBOSE|WARNING|ERROR|FATAL", "MESSAGE"]
  40. - Debug: ["DEBUG", level, "MESSAGE"]
  41. - Percent: ["PERCENT", n, d, s]
  42. """
  43. libgis.G_debug(1, "Start messenger server")
  44. while True:
  45. # Avoid busy waiting
  46. conn.poll(None)
  47. data = conn.recv()
  48. message_type = data[0]
  49. # Only one process is allowed to write to stderr
  50. lock.acquire()
  51. # Stop the pipe and the infinite loop
  52. if message_type == "STOP":
  53. conn.close()
  54. lock.release()
  55. libgis.G_debug(1, "Stop messenger server")
  56. sys.exit()
  57. message = data[1]
  58. if message_type == "PERCENT":
  59. n = int(data[1])
  60. d = int(data[2])
  61. s = int(data[3])
  62. libgis.G_percent(n, d, s)
  63. elif message_type == "DEBUG":
  64. level = data[1]
  65. message = data[2]
  66. libgis.G_debug(level, message)
  67. elif message_type == "VERBOSE":
  68. libgis.G_verbose_message(message)
  69. elif message_type == "INFO":
  70. libgis.G_message(message)
  71. elif message_type == "IMPORTANT":
  72. libgis.G_important_message(message)
  73. elif message_type == "WARNING":
  74. libgis.G_warning(message)
  75. elif message_type == "ERROR":
  76. libgis.G_important_message("ERROR: %s"%message)
  77. # This is for testing only
  78. elif message_type == "FATAL":
  79. libgis.G_fatal_error(message)
  80. lock.release()
  81. class Messenger(object):
  82. """Fast and exit-safe interface to GRASS C-library message functions
  83. This class implements a fast and exit-safe interface to the GRASS
  84. C-library message functions like: G_message(), G_warning(),
  85. G_important_message(), G_verbose_message(), G_percent() and G_debug().
  86. Note:
  87. The C-library message functions a called via ctypes in a subprocess
  88. using a pipe (multiprocessing.Pipe) to transfer the text messages.
  89. Hence, the process that uses the Messenger interface will not be
  90. exited, if a G_fatal_error() was invoked in the subprocess.
  91. In this case the Messenger object will simply start a new subprocess
  92. and restarts the pipeline.
  93. Usage:
  94. >>> msgr = Messenger()
  95. >>> msgr.debug(0, "debug 0")
  96. >>> msgr.verbose("verbose message")
  97. >>> msgr.message("message")
  98. >>> msgr.important("important message")
  99. >>> msgr.percent(1, 1, 1)
  100. >>> msgr.warning("Ohh")
  101. >>> msgr.error("Ohh no")
  102. D0/0: debug 0
  103. message
  104. important message
  105. 100%
  106. WARNING: Ohh
  107. ERROR: Ohh no
  108. >>> msgr = Messenger()
  109. >>> msgr.fatal("Ohh no no no!")
  110. Traceback (most recent call last):
  111. File "__init__.py", line 239, in fatal
  112. sys.exit(1)
  113. SystemExit: 1
  114. >>> msgr = Messenger(raise_on_error=True)
  115. >>> msgr.fatal("Ohh no no no!")
  116. Traceback (most recent call last):
  117. File "__init__.py", line 241, in fatal
  118. raise FatalError(message)
  119. FatalError: Ohh no no no!
  120. >>> msgr = Messenger(raise_on_error=True)
  121. >>> msgr.set_raise_on_error(False)
  122. >>> msgr.fatal("Ohh no no no!")
  123. Traceback (most recent call last):
  124. File "__init__.py", line 239, in fatal
  125. sys.exit(1)
  126. SystemExit: 1
  127. >>> msgr = Messenger(raise_on_error=False)
  128. >>> msgr.set_raise_on_error(True)
  129. >>> msgr.fatal("Ohh no no no!")
  130. Traceback (most recent call last):
  131. File "__init__.py", line 241, in fatal
  132. raise FatalError(message)
  133. FatalError: Ohh no no no!
  134. """
  135. def __init__(self, raise_on_error=False):
  136. self.client_conn = None
  137. self.server_conn = None
  138. self.server = None
  139. self.raise_on_error = raise_on_error
  140. self.start_server()
  141. def start_server(self):
  142. """Start the messenger server and open the pipe
  143. """
  144. self.client_conn, self.server_conn = Pipe()
  145. self.lock = Lock()
  146. self.server = Process(target=message_server, args=(self.lock,
  147. self.server_conn))
  148. self.server.daemon = True
  149. self.server.start()
  150. def _check_restart_server(self):
  151. """Restart the server if it was terminated
  152. """
  153. if self.server.is_alive() is True:
  154. return
  155. self.client_conn.close()
  156. self.server_conn.close()
  157. self.start_server()
  158. self.warning("Needed to restart the messenger server")
  159. def message(self, message):
  160. """Send a message to stderr
  161. :param message: the text of message
  162. :type message: str
  163. G_message() will be called in the messenger server process
  164. """
  165. self._check_restart_server()
  166. self.client_conn.send(["INFO", message])
  167. def verbose(self, message):
  168. """Send a verbose message to stderr
  169. :param message: the text of message
  170. :type message: str
  171. G_verbose_message() will be called in the messenger server process
  172. """
  173. self._check_restart_server()
  174. self.client_conn.send(["VERBOSE", message])
  175. def important(self, message):
  176. """Send an important message to stderr
  177. :param message: the text of message
  178. :type message: str
  179. G_important_message() will be called in the messenger server process
  180. """
  181. self._check_restart_server()
  182. self.client_conn.send(["IMPORTANT", message])
  183. def warning(self, message):
  184. """Send a warning message to stderr
  185. :param message: the text of message
  186. :type message: str
  187. G_warning() will be called in the messenger server process
  188. """
  189. self._check_restart_server()
  190. self.client_conn.send(["WARNING", message])
  191. def error(self, message):
  192. """Send an error message to stderr
  193. :param message: the text of message
  194. :type message: str
  195. G_important_message() with an additional "ERROR:" string at
  196. the start will be called in the messenger server process
  197. """
  198. self._check_restart_server()
  199. self.client_conn.send(["ERROR", message])
  200. def fatal(self, message):
  201. """Send an error message to stderr, call sys.exit(1) or raise FatalError
  202. :param message: the text of message
  203. :type message: str
  204. This function emulates the behavior of G_fatal_error(). It prints
  205. an error message to stderr and calls sys.exit(1). If raise_on_error
  206. is set True while creating the messenger object, a FatalError
  207. exception will be raised instead of calling sys.exit(1).
  208. """
  209. self._check_restart_server()
  210. self.client_conn.send(["ERROR", message])
  211. self.stop()
  212. if self.raise_on_error is True:
  213. raise FatalError(message)
  214. else:
  215. sys.exit(1)
  216. def debug(self, level, message):
  217. """Send a debug message to stderr
  218. :param message: the text of message
  219. :type message: str
  220. G_debug() will be called in the messenger server process
  221. """
  222. self._check_restart_server()
  223. self.client_conn.send(["DEBUG", level, message])
  224. def percent(self, n, d, s):
  225. """Send a percentage to stderr
  226. :param message: the text of message
  227. :type message: str
  228. G_percent() will be called in the messenger server process
  229. """
  230. self._check_restart_server()
  231. self.client_conn.send(["PERCENT", n, d, s])
  232. def stop(self):
  233. """Stop the messenger server and close the pipe
  234. """
  235. if self.server is not None and self.server.is_alive():
  236. self.client_conn.send(["STOP", ])
  237. self.server.join(5)
  238. self.server.terminate()
  239. if self.client_conn is not None:
  240. self.client_conn.close()
  241. def set_raise_on_error(self, raise_on_error=True):
  242. """Set the fatal error behavior
  243. :param raise_on_error: if True a FatalError exception will be
  244. raised instead of calling sys.exit(1)
  245. :type raise_on_error: bool
  246. - If raise_on_error == True, a FatalError exception will be raised
  247. if fatal() is called
  248. - If raise_on_error == False, sys.exit(1) will be invoked if
  249. fatal() is called
  250. """
  251. self.raise_on_error = raise_on_error
  252. def get_raise_on_error(self):
  253. """Get the fatal error behavior
  254. :returns: True if a FatalError exception will be raised or False if
  255. sys.exit(1) will be called in case of invoking fatal()
  256. """
  257. return self.raise_on_error
  258. def test_fatal_error(self, message):
  259. """Force the messenger server to call G_fatal_error()
  260. """
  261. import time
  262. self._check_restart_server()
  263. self.client_conn.send(["FATAL", message])
  264. time.sleep(1)
  265. def get_msgr(_instance=[None, ], *args, **kwargs):
  266. """Return a Messenger instance.
  267. :returns: the Messenger instance.
  268. >>> msgr0 = get_msgr()
  269. >>> msgr1 = get_msgr()
  270. >>> msgr2 = Messenger()
  271. >>> msgr0 is msgr1
  272. True
  273. >>> msgr0 is msgr2
  274. False
  275. """
  276. if not _instance[0]:
  277. _instance[0] = Messenger(*args, **kwargs)
  278. return _instance[0]
  279. if __name__ == "__main__":
  280. import doctest
  281. doctest.testmod()