__init__.py 11 KB

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