__init__.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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 limitation
  67. if len(message) >= 2000:
  68. messgae = message[:1999]
  69. libgis.G_debug(level, message)
  70. elif message_type == "VERBOSE":
  71. # libgis limitation
  72. if len(message) >= 2000:
  73. messgae = message[:1999]
  74. libgis.G_verbose_message(message)
  75. elif message_type == "INFO":
  76. # libgis limitation
  77. if len(message) >= 2000:
  78. messgae = message[:1999]
  79. libgis.G_message(message)
  80. elif message_type == "IMPORTANT":
  81. # libgis limitation
  82. if len(message) >= 2000:
  83. messgae = message[:1999]
  84. libgis.G_important_message(message)
  85. elif message_type == "WARNING":
  86. # libgis limitation
  87. if len(message) >= 2000:
  88. messgae = message[:1999]
  89. libgis.G_warning(message)
  90. elif message_type == "ERROR":
  91. # libgis limitation
  92. if len(message) >= 2000:
  93. messgae = message[:1999]
  94. libgis.G_important_message("ERROR: %s"%message)
  95. # This is for testing only
  96. elif message_type == "FATAL":
  97. # libgis limitation
  98. if len(message) >= 2000:
  99. messgae = message[:1999]
  100. libgis.G_fatal_error(message)
  101. lock.release()
  102. class Messenger(object):
  103. """Fast and exit-safe interface to GRASS C-library message functions
  104. This class implements a fast and exit-safe interface to the GRASS
  105. C-library message functions like: G_message(), G_warning(),
  106. G_important_message(), G_verbose_message(), G_percent() and G_debug().
  107. Note:
  108. The C-library message functions a called via ctypes in a subprocess
  109. using a pipe (multiprocessing.Pipe) to transfer the text messages.
  110. Hence, the process that uses the Messenger interface will not be
  111. exited, if a G_fatal_error() was invoked in the subprocess.
  112. In this case the Messenger object will simply start a new subprocess
  113. and restarts the pipeline.
  114. Usage:
  115. >>> msgr = Messenger()
  116. >>> msgr.debug(0, "debug 0")
  117. >>> msgr.verbose("verbose message")
  118. >>> msgr.message("message")
  119. >>> msgr.important("important message")
  120. >>> msgr.percent(1, 1, 1)
  121. >>> msgr.warning("Ohh")
  122. >>> msgr.error("Ohh no")
  123. >>> msgr = Messenger()
  124. >>> msgr.fatal("Ohh no no no!")
  125. Traceback (most recent call last):
  126. File "__init__.py", line 239, in fatal
  127. sys.exit(1)
  128. SystemExit: 1
  129. >>> msgr = Messenger(raise_on_error=True)
  130. >>> msgr.fatal("Ohh no no no!")
  131. Traceback (most recent call last):
  132. File "__init__.py", line 241, in fatal
  133. raise FatalError(message)
  134. FatalError: Ohh no no no!
  135. >>> msgr = Messenger(raise_on_error=True)
  136. >>> msgr.set_raise_on_error(False)
  137. >>> msgr.fatal("Ohh no no no!")
  138. Traceback (most recent call last):
  139. File "__init__.py", line 239, in fatal
  140. sys.exit(1)
  141. SystemExit: 1
  142. >>> msgr = Messenger(raise_on_error=False)
  143. >>> msgr.set_raise_on_error(True)
  144. >>> msgr.fatal("Ohh no no no!")
  145. Traceback (most recent call last):
  146. File "__init__.py", line 241, in fatal
  147. raise FatalError(message)
  148. FatalError: Ohh no no no!
  149. """
  150. def __init__(self, raise_on_error=False):
  151. self.client_conn = None
  152. self.server_conn = None
  153. self.server = None
  154. self.raise_on_error = raise_on_error
  155. self.start_server()
  156. def start_server(self):
  157. """Start the messenger server and open the pipe
  158. """
  159. self.client_conn, self.server_conn = Pipe()
  160. self.lock = Lock()
  161. self.server = Process(target=message_server, args=(self.lock,
  162. self.server_conn))
  163. self.server.daemon = True
  164. self.server.start()
  165. def _check_restart_server(self):
  166. """Restart the server if it was terminated
  167. """
  168. if self.server.is_alive() is True:
  169. return
  170. self.client_conn.close()
  171. self.server_conn.close()
  172. self.start_server()
  173. self.warning("Needed to restart the messenger server")
  174. def message(self, message):
  175. """Send a message to stderr
  176. :param message: the text of message
  177. :type message: str
  178. G_message() will be called in the messenger server process
  179. """
  180. self._check_restart_server()
  181. self.client_conn.send(["INFO", message])
  182. def verbose(self, message):
  183. """Send a verbose message to stderr
  184. :param message: the text of message
  185. :type message: str
  186. G_verbose_message() will be called in the messenger server process
  187. """
  188. self._check_restart_server()
  189. self.client_conn.send(["VERBOSE", message])
  190. def important(self, message):
  191. """Send an important message to stderr
  192. :param message: the text of message
  193. :type message: str
  194. G_important_message() will be called in the messenger server process
  195. """
  196. self._check_restart_server()
  197. self.client_conn.send(["IMPORTANT", message])
  198. def warning(self, message):
  199. """Send a warning message to stderr
  200. :param message: the text of message
  201. :type message: str
  202. G_warning() will be called in the messenger server process
  203. """
  204. self._check_restart_server()
  205. self.client_conn.send(["WARNING", message])
  206. def error(self, message):
  207. """Send an error message to stderr
  208. :param message: the text of message
  209. :type message: str
  210. G_important_message() with an additional "ERROR:" string at
  211. the start will be called in the messenger server process
  212. """
  213. self._check_restart_server()
  214. self.client_conn.send(["ERROR", message])
  215. def fatal(self, message):
  216. """Send an error message to stderr, call sys.exit(1) or raise FatalError
  217. :param message: the text of message
  218. :type message: str
  219. This function emulates the behavior of G_fatal_error(). It prints
  220. an error message to stderr and calls sys.exit(1). If raise_on_error
  221. is set True while creating the messenger object, a FatalError
  222. exception will be raised instead of calling sys.exit(1).
  223. """
  224. self._check_restart_server()
  225. self.client_conn.send(["ERROR", message])
  226. self.stop()
  227. if self.raise_on_error is True:
  228. raise FatalError(message)
  229. else:
  230. sys.exit(1)
  231. def debug(self, level, message):
  232. """Send a debug message to stderr
  233. :param message: the text of message
  234. :type message: str
  235. G_debug() will be called in the messenger server process
  236. """
  237. self._check_restart_server()
  238. self.client_conn.send(["DEBUG", level, message])
  239. def percent(self, n, d, s):
  240. """Send a percentage to stderr
  241. :param message: the text of message
  242. :type message: str
  243. G_percent() will be called in the messenger server process
  244. """
  245. self._check_restart_server()
  246. self.client_conn.send(["PERCENT", n, d, s])
  247. def stop(self):
  248. """Stop the messenger server and close the pipe
  249. """
  250. if self.server is not None and self.server.is_alive():
  251. self.client_conn.send(["STOP", ])
  252. self.server.join(5)
  253. self.server.terminate()
  254. if self.client_conn is not None:
  255. self.client_conn.close()
  256. def set_raise_on_error(self, raise_on_error=True):
  257. """Set the fatal error behavior
  258. :param raise_on_error: if True a FatalError exception will be
  259. raised instead of calling sys.exit(1)
  260. :type raise_on_error: bool
  261. - If raise_on_error == True, a FatalError exception will be raised
  262. if fatal() is called
  263. - If raise_on_error == False, sys.exit(1) will be invoked if
  264. fatal() is called
  265. """
  266. self.raise_on_error = raise_on_error
  267. def get_raise_on_error(self):
  268. """Get the fatal error behavior
  269. :returns: True if a FatalError exception will be raised or False if
  270. sys.exit(1) will be called in case of invoking fatal()
  271. """
  272. return self.raise_on_error
  273. def test_fatal_error(self, message):
  274. """Force the messenger server to call G_fatal_error()
  275. """
  276. import time
  277. self._check_restart_server()
  278. self.client_conn.send(["FATAL", message])
  279. time.sleep(1)
  280. def get_msgr(_instance=[None, ], *args, **kwargs):
  281. """Return a Messenger instance.
  282. :returns: the Messenger instance.
  283. >>> msgr0 = get_msgr()
  284. >>> msgr1 = get_msgr()
  285. >>> msgr2 = Messenger()
  286. >>> msgr0 is msgr1
  287. True
  288. >>> msgr0 is msgr2
  289. False
  290. """
  291. if not _instance[0]:
  292. _instance[0] = Messenger(*args, **kwargs)
  293. return _instance[0]
  294. if __name__ == "__main__":
  295. import doctest
  296. doctest.testmod()