__init__.py 11 KB

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