terrain.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. # Copyright (C) 2011 Internet Systems Consortium.
  2. #
  3. # Permission to use, copy, modify, and distribute this software for any
  4. # purpose with or without fee is hereby granted, provided that the above
  5. # copyright notice and this permission notice appear in all copies.
  6. #
  7. # THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SYSTEMS CONSORTIUM
  8. # DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
  9. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
  10. # INTERNET SYSTEMS CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
  11. # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
  12. # FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  13. # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
  14. # WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. #
  16. # This is the 'terrain' in which the lettuce lives. By convention, this is
  17. # where global setup and teardown is defined.
  18. #
  19. # We declare some attributes of the global 'world' variables here, so the
  20. # tests can safely assume they are present.
  21. #
  22. # We also use it to provide scenario invariants, such as resetting data.
  23. #
  24. from lettuce import *
  25. import subprocess
  26. import os.path
  27. import shutil
  28. import re
  29. import time
  30. # In order to make sure we start all tests with a 'clean' environment,
  31. # We perform a number of initialization steps, like restoring configuration
  32. # files, and removing generated data files.
  33. # This approach may not scale; if so we should probably provide specific
  34. # initialization steps for scenarios. But until that is shown to be a problem,
  35. # It will keep the scenarios cleaner.
  36. # This is a list of files that are freshly copied before each scenario
  37. # The first element is the original, the second is the target that will be
  38. # used by the tests that need them
  39. copylist = [
  40. ["configurations/example.org.config.orig", "configurations/example.org.config"]
  41. ]
  42. # This is a list of files that, if present, will be removed before a scenario
  43. removelist = [
  44. "data/test_nonexistent_db.sqlite3"
  45. ]
  46. # When waiting for output data of a running process, use OUTPUT_WAIT_INTERVAL
  47. # as the interval in which to check again if it has not been found yet.
  48. # If we have waited OUTPUT_WAIT_MAX_INTERVALS times, we will abort with an
  49. # error (so as not to hang indefinitely)
  50. OUTPUT_WAIT_INTERVAL = 0.5
  51. OUTPUT_WAIT_MAX_INTERVALS = 20
  52. # class that keeps track of one running process and the files
  53. # we created for it.
  54. class RunningProcess:
  55. def __init__(self, step, process_name, args):
  56. # set it to none first so destructor won't error if initializer did
  57. """
  58. Initialize the long-running process structure, and start the process.
  59. Parameters:
  60. step: The scenario step it was called from. This is used for
  61. determining the output files for redirection of stdout
  62. and stderr.
  63. process_name: The name to refer to this running process later.
  64. args: Array of arguments to pass to Popen().
  65. """
  66. self.process = None
  67. self.step = step
  68. self.process_name = process_name
  69. self.remove_files_on_exit = True
  70. self._check_output_dir()
  71. self._create_filenames()
  72. self._start_process(args)
  73. def _start_process(self, args):
  74. """
  75. Start the process.
  76. Parameters:
  77. args:
  78. Array of arguments to pass to Popen().
  79. """
  80. stderr_write = open(self.stderr_filename, "w")
  81. stdout_write = open(self.stdout_filename, "w")
  82. self.process = subprocess.Popen(args, 1, None, subprocess.PIPE,
  83. stdout_write, stderr_write)
  84. # open them again, this time for reading
  85. self.stderr = open(self.stderr_filename, "r")
  86. self.stdout = open(self.stdout_filename, "r")
  87. def mangle_filename(self, filebase, extension):
  88. """
  89. Remove whitespace and non-default characters from a base string,
  90. and return the substituted value. Whitespace is replaced by an
  91. underscore. Any other character that is not an ASCII letter, a
  92. number, a dot, or a hyphen or underscore is removed.
  93. Parameter:
  94. filebase: The string to perform the substitution and removal on
  95. extension: An extension to append to the result value
  96. Returns the modified filebase with the given extension
  97. """
  98. filebase = re.sub("\s+", "_", filebase)
  99. filebase = re.sub("[^a-zA-Z0-9.\-_]", "", filebase)
  100. return filebase + "." + extension
  101. def _check_output_dir(self):
  102. # We may want to make this overridable by the user, perhaps
  103. # through an environment variable. Since we currently expect
  104. # lettuce to be run from our lettuce dir, we shall just use
  105. # the relative path 'output/'
  106. """
  107. Make sure the output directory for stdout/stderr redirection
  108. exists.
  109. Fails if it exists but is not a directory, or if it does not
  110. and we are unable to create it.
  111. """
  112. self._output_dir = os.getcwd() + os.sep + "output"
  113. if not os.path.exists(self._output_dir):
  114. os.mkdir(self._output_dir)
  115. assert os.path.isdir(self._output_dir),\
  116. self._output_dir + " is not a directory."
  117. def _create_filenames(self):
  118. """
  119. Derive the filenames for stdout/stderr redirection from the
  120. feature, scenario, and process name. The base will be
  121. "<Feature>-<Scenario>-<process name>.[stdout|stderr]"
  122. """
  123. filebase = self.step.scenario.feature.name + "-" +\
  124. self.step.scenario.name + "-" + self.process_name
  125. self.stderr_filename = self._output_dir + os.sep +\
  126. self.mangle_filename(filebase, "stderr")
  127. self.stdout_filename = self._output_dir + os.sep +\
  128. self.mangle_filename(filebase, "stdout")
  129. def stop_process(self):
  130. """
  131. Stop this process by calling terminate(). Blocks until process has
  132. exited. If remove_files_on_exit is True, redirected output files
  133. are removed.
  134. """
  135. if self.process is not None:
  136. self.process.terminate()
  137. self.process.wait()
  138. self.process = None
  139. if self.remove_files_on_exit:
  140. self._remove_files()
  141. def _remove_files(self):
  142. """
  143. Remove the files created for redirection of stdout/stderr output.
  144. """
  145. os.remove(self.stderr_filename)
  146. os.remove(self.stdout_filename)
  147. def _wait_for_output_str(self, filename, running_file, strings, only_new):
  148. """
  149. Wait for a line of output in this process. This will (if only_new is
  150. False) first check all previous output from the process, and if not
  151. found, check all output since the last time this method was called.
  152. For each line in the output, the given strings array is checked. If
  153. any output lines checked contains one of the strings in the strings
  154. array, that string (not the line!) is returned.
  155. Parameters:
  156. filename: The filename to read previous output from, if applicable.
  157. running_file: The open file to read new output from.
  158. strings: Array of strings to look for.
  159. only_new: If true, only check output since last time this method was
  160. called. If false, first check earlier output.
  161. Returns a tuple containing the matched string, and the complete line
  162. it was found in.
  163. Fails if none of the strings was read after 10 seconds
  164. (OUTPUT_WAIT_INTERVAL * OUTPUT_WAIT_MAX_INTERVALS).
  165. """
  166. if not only_new:
  167. full_file = open(filename, "r")
  168. for line in full_file:
  169. for string in strings:
  170. if line.find(string) != -1:
  171. full_file.close()
  172. return (string, line)
  173. wait_count = 0
  174. while wait_count < OUTPUT_WAIT_MAX_INTERVALS:
  175. where = running_file.tell()
  176. line = running_file.readline()
  177. if line:
  178. for string in strings:
  179. if line.find(string) != -1:
  180. return (string, line)
  181. else:
  182. wait_count += 1
  183. time.sleep(OUTPUT_WAIT_INTERVAL)
  184. running_file.seek(where)
  185. assert False, "Timeout waiting for process output: " + str(strings)
  186. def wait_for_stderr_str(self, strings, only_new = True):
  187. """
  188. Wait for one of the given strings in this process's stderr output.
  189. Parameters:
  190. strings: Array of strings to look for.
  191. only_new: If true, only check output since last time this method was
  192. called. If false, first check earlier output.
  193. Returns a tuple containing the matched string, and the complete line
  194. it was found in.
  195. Fails if none of the strings was read after 10 seconds
  196. (OUTPUT_WAIT_INTERVAL * OUTPUT_WAIT_MAX_INTERVALS).
  197. """
  198. return self._wait_for_output_str(self.stderr_filename, self.stderr,
  199. strings, only_new)
  200. def wait_for_stdout_str(self, strings, only_new = True):
  201. """
  202. Wait for one of the given strings in this process's stdout output.
  203. Parameters:
  204. strings: Array of strings to look for.
  205. only_new: If true, only check output since last time this method was
  206. called. If false, first check earlier output.
  207. Returns a tuple containing the matched string, and the complete line
  208. it was found in.
  209. Fails if none of the strings was read after 10 seconds
  210. (OUTPUT_WAIT_INTERVAL * OUTPUT_WAIT_MAX_INTERVALS).
  211. """
  212. return self._wait_for_output_str(self.stdout_filename, self.stdout,
  213. strings, only_new)
  214. # Container class for a number of running processes
  215. # i.e. servers like bind10, etc
  216. # one-shot programs like dig or bindctl are started and closed separately
  217. class RunningProcesses:
  218. def __init__(self):
  219. """
  220. Initialize with no running processes.
  221. """
  222. self.processes = {}
  223. def add_process(self, step, process_name, args):
  224. """
  225. Start a process with the given arguments, and store it under the given
  226. name.
  227. Parameters:
  228. step: The scenario step it was called from. This is used for
  229. determining the output files for redirection of stdout
  230. and stderr.
  231. process_name: The name to refer to this running process later.
  232. args: Array of arguments to pass to Popen().
  233. Fails if a process with the given name is already running.
  234. """
  235. assert process_name not in self.processes,\
  236. "Process " + process_name + " already running"
  237. self.processes[process_name] = RunningProcess(step, process_name, args)
  238. def get_process(self, process_name):
  239. """
  240. Return the Process with the given process name.
  241. Parameters:
  242. process_name: The name of the process to return.
  243. Fails if the process is not running.
  244. """
  245. assert process_name in self.processes,\
  246. "Process " + name + " unknown"
  247. return self.processes[process_name]
  248. def stop_process(self, process_name):
  249. """
  250. Stop the Process with the given process name.
  251. Parameters:
  252. process_name: The name of the process to return.
  253. Fails if the process is not running.
  254. """
  255. assert process_name in self.processes,\
  256. "Process " + name + " unknown"
  257. self.processes[process_name].stop_process()
  258. del self.processes[process_name]
  259. def stop_all_processes(self):
  260. """
  261. Stop all running processes.
  262. """
  263. for process in self.processes.values():
  264. process.stop_process()
  265. def keep_files(self):
  266. """
  267. Keep the redirection files for stdout/stderr output of all processes
  268. instead of removing them when they are stopped later.
  269. """
  270. for process in self.processes.values():
  271. process.remove_files_on_exit = False
  272. def wait_for_stderr_str(self, process_name, strings, only_new = True):
  273. """
  274. Wait for one of the given strings in the given process's stderr output.
  275. Parameters:
  276. process_name: The name of the process to check the stderr output of.
  277. strings: Array of strings to look for.
  278. only_new: If true, only check output since last time this method was
  279. called. If false, first check earlier output.
  280. Returns the matched string.
  281. Fails if none of the strings was read after 10 seconds
  282. (OUTPUT_WAIT_INTERVAL * OUTPUT_WAIT_MAX_INTERVALS).
  283. Fails if the process is unknown.
  284. """
  285. assert process_name in self.processes,\
  286. "Process " + process_name + " unknown"
  287. return self.processes[process_name].wait_for_stderr_str(strings,
  288. only_new)
  289. def wait_for_stdout_str(self, process_name, strings, only_new = True):
  290. """
  291. Wait for one of the given strings in the given process's stdout output.
  292. Parameters:
  293. process_name: The name of the process to check the stdout output of.
  294. strings: Array of strings to look for.
  295. only_new: If true, only check output since last time this method was
  296. called. If false, first check earlier output.
  297. Returns the matched string.
  298. Fails if none of the strings was read after 10 seconds
  299. (OUTPUT_WAIT_INTERVAL * OUTPUT_WAIT_MAX_INTERVALS).
  300. Fails if the process is unknown.
  301. """
  302. assert process_name in self.processes,\
  303. "Process " + process_name + " unknown"
  304. return self.processes[process_name].wait_for_stdout_str(strings,
  305. only_new)
  306. @before.each_scenario
  307. def initialize(scenario):
  308. """
  309. Global initialization for each scenario.
  310. """
  311. # Keep track of running processes
  312. world.processes = RunningProcesses()
  313. # Convenience variable to access the last query result from querying.py
  314. world.last_query_result = None
  315. # Some tests can modify the settings. If the tests fail half-way, or
  316. # don't clean up, this can leave configurations or data in a bad state,
  317. # so we copy them from originals before each scenario
  318. for item in copylist:
  319. shutil.copy(item[0], item[1])
  320. for item in removelist:
  321. if os.path.exists(item):
  322. os.remove(item)
  323. @after.each_scenario
  324. def cleanup(scenario):
  325. """
  326. Global cleanup for each scenario.
  327. """
  328. # Keep output files if the scenario failed
  329. if not scenario.passed:
  330. world.processes.keep_files()
  331. # Stop any running processes we may have had around
  332. world.processes.stop_all_processes()