__init__.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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 __del__(self):
  142. self.stop()
  143. def start_server(self):
  144. """Start the messenger server and open the pipe
  145. """
  146. self.client_conn, self.server_conn = Pipe()
  147. self.lock = Lock()
  148. self.server = Process(target=message_server, args=(self.lock,
  149. self.server_conn))
  150. self.server.daemon = True
  151. self.server.start()
  152. def _check_restart_server(self):
  153. """Restart the server if it was terminated
  154. """
  155. if self.server.is_alive() is True:
  156. return
  157. self.client_conn.close()
  158. self.server_conn.close()
  159. self.start_server()
  160. self.warning("Needed to restart the messenger server")
  161. def message(self, message):
  162. """Send a message to stderr
  163. :param message: the text of message
  164. :type message: str
  165. G_message() will be called in the messenger server process
  166. """
  167. self._check_restart_server()
  168. self.client_conn.send(["INFO", message])
  169. def verbose(self, message):
  170. """Send a verbose message to stderr
  171. :param message: the text of message
  172. :type message: str
  173. G_verbose_message() will be called in the messenger server process
  174. """
  175. self._check_restart_server()
  176. self.client_conn.send(["VERBOSE", message])
  177. def important(self, message):
  178. """Send an important message to stderr
  179. :param message: the text of message
  180. :type message: str
  181. G_important_message() will be called in the messenger server process
  182. """
  183. self._check_restart_server()
  184. self.client_conn.send(["IMPORTANT", message])
  185. def warning(self, message):
  186. """Send a warning message to stderr
  187. :param message: the text of message
  188. :type message: str
  189. G_warning() will be called in the messenger server process
  190. """
  191. self._check_restart_server()
  192. self.client_conn.send(["WARNING", message])
  193. def error(self, message):
  194. """Send an error message to stderr
  195. :param message: the text of message
  196. :type message: str
  197. G_important_message() with an additional "ERROR:" string at
  198. the start will be called in the messenger server process
  199. """
  200. self._check_restart_server()
  201. self.client_conn.send(["ERROR", message])
  202. def fatal(self, message):
  203. """Send an error message to stderr, call sys.exit(1) or raise FatalError
  204. :param message: the text of message
  205. :type message: str
  206. This function emulates the behavior of G_fatal_error(). It prints
  207. an error message to stderr and calls sys.exit(1). If raise_on_error
  208. is set True while creating the messenger object, a FatalError
  209. exception will be raised instead of calling sys.exit(1).
  210. """
  211. self._check_restart_server()
  212. self.client_conn.send(["ERROR", message])
  213. self.stop()
  214. if self.raise_on_error is True:
  215. raise FatalError(message)
  216. else:
  217. sys.exit(1)
  218. def debug(self, level, message):
  219. """Send a debug message to stderr
  220. :param message: the text of message
  221. :type message: str
  222. G_debug() will be called in the messenger server process
  223. """
  224. self._check_restart_server()
  225. self.client_conn.send(["DEBUG", level, message])
  226. def percent(self, n, d, s):
  227. """Send a percentage to stderr
  228. :param message: the text of message
  229. :type message: str
  230. G_percent() will be called in the messenger server process
  231. """
  232. self._check_restart_server()
  233. self.client_conn.send(["PERCENT", n, d, s])
  234. def stop(self):
  235. """Stop the messenger server and close the pipe
  236. """
  237. if self.server is not None and self.server.is_alive():
  238. self.client_conn.send(["STOP", ])
  239. self.server.join(5)
  240. self.server.terminate()
  241. if self.client_conn is not None:
  242. self.client_conn.close()
  243. def set_raise_on_error(self, raise_on_error=True):
  244. """Set the fatal error behavior
  245. :param raise_on_error: if True a FatalError exception will be
  246. raised instead of calling sys.exit(1)
  247. :type raise_on_error: bool
  248. - If raise_on_error == True, a FatalError exception will be raised
  249. if fatal() is called
  250. - If raise_on_error == False, sys.exit(1) will be invoked if
  251. fatal() is called
  252. """
  253. self.raise_on_error = raise_on_error
  254. def get_raise_on_error(self):
  255. """Get the fatal error behavior
  256. :returns: True if a FatalError exception will be raised or False if
  257. sys.exit(1) will be called in case of invoking fatal()
  258. """
  259. return self.raise_on_error
  260. def test_fatal_error(self, message):
  261. """Force the messenger server to call G_fatal_error()
  262. """
  263. import time
  264. self._check_restart_server()
  265. self.client_conn.send(["FATAL", message])
  266. time.sleep(1)
  267. def get_msgr(_instance=[None, ], *args, **kwargs):
  268. """Return a Messenger instance.
  269. :returns: the Messenger instance.
  270. >>> msgr0 = get_msgr()
  271. >>> msgr1 = get_msgr()
  272. >>> msgr2 = Messenger()
  273. >>> msgr0 is msgr1
  274. True
  275. >>> msgr0 is msgr2
  276. False
  277. """
  278. if not _instance[0]:
  279. _instance[0] = Messenger(*args, **kwargs)
  280. return _instance[0]
  281. if __name__ == "__main__":
  282. import doctest
  283. doctest.testmod()