terrain.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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 sys
  30. import time
  31. # In order to make sure we start all tests with a 'clean' environment,
  32. # We perform a number of initialization steps, like restoring configuration
  33. # files, and removing generated data files.
  34. # This approach may not scale; if so we should probably provide specific
  35. # initialization steps for scenarios. But until that is shown to be a problem,
  36. # It will keep the scenarios cleaner.
  37. # This is a list of files that are freshly copied before each scenario
  38. # The first element is the original, the second is the target that will be
  39. # used by the tests that need them
  40. copylist = [
  41. ["configurations/bindctl_commands.config.orig",
  42. "configurations/bindctl_commands.config"],
  43. ["configurations/example.org.config.orig",
  44. "configurations/example.org.config"],
  45. ["configurations/resolver/resolver_basic.config.orig",
  46. "configurations/resolver/resolver_basic.config"],
  47. ["configurations/multi_instance/multi_auth.config.orig",
  48. "configurations/multi_instance/multi_auth.config"]
  49. ]
  50. # This is a list of files that, if present, will be removed before a scenario
  51. removelist = [
  52. "data/test_nonexistent_db.sqlite3"
  53. ]
  54. # When waiting for output data of a running process, use OUTPUT_WAIT_INTERVAL
  55. # as the interval in which to check again if it has not been found yet.
  56. # If we have waited OUTPUT_WAIT_MAX_INTERVALS times, we will abort with an
  57. # error (so as not to hang indefinitely)
  58. OUTPUT_WAIT_INTERVAL = 0.5
  59. OUTPUT_WAIT_MAX_INTERVALS = 20
  60. # class that keeps track of one running process and the files
  61. # we created for it.
  62. class RunningProcess:
  63. def __init__(self, step, process_name, args):
  64. # set it to none first so destructor won't error if initializer did
  65. """
  66. Initialize the long-running process structure, and start the process.
  67. Parameters:
  68. step: The scenario step it was called from. This is used for
  69. determining the output files for redirection of stdout
  70. and stderr.
  71. process_name: The name to refer to this running process later.
  72. args: Array of arguments to pass to Popen().
  73. """
  74. self.process = None
  75. self.step = step
  76. self.process_name = process_name
  77. self.remove_files_on_exit = True
  78. self._check_output_dir()
  79. self._create_filenames()
  80. self._start_process(args)
  81. def _start_process(self, args):
  82. """
  83. Start the process.
  84. Parameters:
  85. args:
  86. Array of arguments to pass to Popen().
  87. """
  88. stderr_write = open(self.stderr_filename, "w")
  89. stdout_write = open(self.stdout_filename, "w")
  90. self.process = subprocess.Popen(args, 1, None, subprocess.PIPE,
  91. stdout_write, stderr_write)
  92. # open them again, this time for reading
  93. self.stderr = open(self.stderr_filename, "r")
  94. self.stdout = open(self.stdout_filename, "r")
  95. def mangle_filename(self, filebase, extension):
  96. """
  97. Remove whitespace and non-default characters from a base string,
  98. and return the substituted value. Whitespace is replaced by an
  99. underscore. Any other character that is not an ASCII letter, a
  100. number, a dot, or a hyphen or underscore is removed.
  101. Parameter:
  102. filebase: The string to perform the substitution and removal on
  103. extension: An extension to append to the result value
  104. Returns the modified filebase with the given extension
  105. """
  106. filebase = re.sub("\s+", "_", filebase)
  107. filebase = re.sub("[^a-zA-Z0-9.\-_]", "", filebase)
  108. return filebase + "." + extension
  109. def _check_output_dir(self):
  110. # We may want to make this overridable by the user, perhaps
  111. # through an environment variable. Since we currently expect
  112. # lettuce to be run from our lettuce dir, we shall just use
  113. # the relative path 'output/'
  114. """
  115. Make sure the output directory for stdout/stderr redirection
  116. exists.
  117. Fails if it exists but is not a directory, or if it does not
  118. and we are unable to create it.
  119. """
  120. self._output_dir = os.getcwd() + os.sep + "output"
  121. if not os.path.exists(self._output_dir):
  122. os.mkdir(self._output_dir)
  123. assert os.path.isdir(self._output_dir),\
  124. self._output_dir + " is not a directory."
  125. def _create_filenames(self):
  126. """
  127. Derive the filenames for stdout/stderr redirection from the
  128. feature, scenario, and process name. The base will be
  129. "<Feature>-<Scenario>-<process name>.[stdout|stderr]"
  130. """
  131. filebase = self.step.scenario.feature.name + "-" +\
  132. self.step.scenario.name + "-" + self.process_name
  133. self.stderr_filename = self._output_dir + os.sep +\
  134. self.mangle_filename(filebase, "stderr")
  135. self.stdout_filename = self._output_dir + os.sep +\
  136. self.mangle_filename(filebase, "stdout")
  137. def stop_process(self):
  138. """
  139. Stop this process by calling terminate(). Blocks until process has
  140. exited. If remove_files_on_exit is True, redirected output files
  141. are removed.
  142. """
  143. if self.process is not None:
  144. self.process.terminate()
  145. self.process.wait()
  146. self.process = None
  147. if self.remove_files_on_exit:
  148. self._remove_files()
  149. def _remove_files(self):
  150. """
  151. Remove the files created for redirection of stdout/stderr output.
  152. """
  153. os.remove(self.stderr_filename)
  154. os.remove(self.stdout_filename)
  155. def _wait_for_output_str(self, filename, running_file, strings, only_new, matches = 1):
  156. """
  157. Wait for a line of output in this process. This will (if only_new is
  158. False) first check all previous output from the process, and if not
  159. found, check all output since the last time this method was called.
  160. For each line in the output, the given strings array is checked. If
  161. any output lines checked contains one of the strings in the strings
  162. array, that string (not the line!) is returned.
  163. Parameters:
  164. filename: The filename to read previous output from, if applicable.
  165. running_file: The open file to read new output from.
  166. strings: Array of strings to look for.
  167. only_new: If true, only check output since last time this method was
  168. called. If false, first check earlier output.
  169. matches: Check for the string this many times.
  170. Returns a tuple containing the matched string, and the complete line
  171. it was found in.
  172. Fails if none of the strings was read after 10 seconds
  173. (OUTPUT_WAIT_INTERVAL * OUTPUT_WAIT_MAX_INTERVALS).
  174. """
  175. match_count = 0
  176. if not only_new:
  177. full_file = open(filename, "r")
  178. for line in full_file:
  179. for string in strings:
  180. if line.find(string) != -1:
  181. match_count += 1
  182. if match_count >= matches:
  183. full_file.close()
  184. return (string, line)
  185. wait_count = 0
  186. while wait_count < OUTPUT_WAIT_MAX_INTERVALS:
  187. where = running_file.tell()
  188. line = running_file.readline()
  189. if line:
  190. for string in strings:
  191. if line.find(string) != -1:
  192. match_count += 1
  193. if match_count >= matches:
  194. return (string, line)
  195. else:
  196. wait_count += 1
  197. time.sleep(OUTPUT_WAIT_INTERVAL)
  198. running_file.seek(where)
  199. assert False, "Timeout waiting for process output: " + str(strings)
  200. def wait_for_stderr_str(self, strings, only_new = True, matches = 1):
  201. """
  202. Wait for one of the given strings in this process's stderr 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. matches: Check for the string this many times.
  208. Returns a tuple containing the matched string, and the complete line
  209. it was found in.
  210. Fails if none of the strings was read after 10 seconds
  211. (OUTPUT_WAIT_INTERVAL * OUTPUT_WAIT_MAX_INTERVALS).
  212. """
  213. return self._wait_for_output_str(self.stderr_filename, self.stderr,
  214. strings, only_new, matches)
  215. def wait_for_stdout_str(self, strings, only_new = True, matches = 1):
  216. """
  217. Wait for one of the given strings in this process's stdout output.
  218. Parameters:
  219. strings: Array of strings to look for.
  220. only_new: If true, only check output since last time this method was
  221. called. If false, first check earlier output.
  222. matches: Check for the string this many times.
  223. Returns a tuple containing the matched string, and the complete line
  224. it was found in.
  225. Fails if none of the strings was read after 10 seconds
  226. (OUTPUT_WAIT_INTERVAL * OUTPUT_WAIT_MAX_INTERVALS).
  227. """
  228. return self._wait_for_output_str(self.stdout_filename, self.stdout,
  229. strings, only_new, matches)
  230. # Container class for a number of running processes
  231. # i.e. servers like bind10, etc
  232. # one-shot programs like dig or bindctl are started and closed separately
  233. class RunningProcesses:
  234. def __init__(self):
  235. """
  236. Initialize with no running processes.
  237. """
  238. self.processes = {}
  239. def add_process(self, step, process_name, args):
  240. """
  241. Start a process with the given arguments, and store it under the given
  242. name.
  243. Parameters:
  244. step: The scenario step it was called from. This is used for
  245. determining the output files for redirection of stdout
  246. and stderr.
  247. process_name: The name to refer to this running process later.
  248. args: Array of arguments to pass to Popen().
  249. Fails if a process with the given name is already running.
  250. """
  251. assert process_name not in self.processes,\
  252. "Process " + process_name + " already running"
  253. self.processes[process_name] = RunningProcess(step, process_name, args)
  254. def get_process(self, process_name):
  255. """
  256. Return the Process with the given process name.
  257. Parameters:
  258. process_name: The name of the process to return.
  259. Fails if the process is not running.
  260. """
  261. assert process_name in self.processes,\
  262. "Process " + name + " unknown"
  263. return self.processes[process_name]
  264. def stop_process(self, process_name):
  265. """
  266. Stop the Process with the given process name.
  267. Parameters:
  268. process_name: The name of the process to return.
  269. Fails if the process is not running.
  270. """
  271. assert process_name in self.processes,\
  272. "Process " + name + " unknown"
  273. self.processes[process_name].stop_process()
  274. del self.processes[process_name]
  275. def stop_all_processes(self):
  276. """
  277. Stop all running processes.
  278. """
  279. for process in self.processes.values():
  280. process.stop_process()
  281. def keep_files(self):
  282. """
  283. Keep the redirection files for stdout/stderr output of all processes
  284. instead of removing them when they are stopped later.
  285. """
  286. for process in self.processes.values():
  287. process.remove_files_on_exit = False
  288. def wait_for_stderr_str(self, process_name, strings, only_new = True, matches = 1):
  289. """
  290. Wait for one of the given strings in the given process's stderr output.
  291. Parameters:
  292. process_name: The name of the process to check the stderr output of.
  293. strings: Array of strings to look for.
  294. only_new: If true, only check output since last time this method was
  295. called. If false, first check earlier output.
  296. matches: Check for the string this many times.
  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_stderr_str(strings,
  305. only_new,
  306. matches)
  307. def wait_for_stdout_str(self, process_name, strings, only_new = True, matches = 1):
  308. """
  309. Wait for one of the given strings in the given process's stdout output.
  310. Parameters:
  311. process_name: The name of the process to check the stdout output of.
  312. strings: Array of strings to look for.
  313. only_new: If true, only check output since last time this method was
  314. called. If false, first check earlier output.
  315. matches: Check for the string this many times.
  316. Returns the matched string.
  317. Fails if none of the strings was read after 10 seconds
  318. (OUTPUT_WAIT_INTERVAL * OUTPUT_WAIT_MAX_INTERVALS).
  319. Fails if the process is unknown.
  320. """
  321. assert process_name in self.processes,\
  322. "Process " + process_name + " unknown"
  323. return self.processes[process_name].wait_for_stdout_str(strings,
  324. only_new,
  325. matches)
  326. @before.each_scenario
  327. def initialize(scenario):
  328. """
  329. Global initialization for each scenario.
  330. """
  331. # Keep track of running processes
  332. world.processes = RunningProcesses()
  333. # Convenience variable to access the last query result from querying.py
  334. world.last_query_result = None
  335. # For slightly better errors, initialize a process_pids for the relevant
  336. # steps
  337. world.process_pids = None
  338. # Some tests can modify the settings. If the tests fail half-way, or
  339. # don't clean up, this can leave configurations or data in a bad state,
  340. # so we copy them from originals before each scenario
  341. for item in copylist:
  342. shutil.copy(item[0], item[1])
  343. for item in removelist:
  344. if os.path.exists(item):
  345. os.remove(item)
  346. @after.each_scenario
  347. def cleanup(scenario):
  348. """
  349. Global cleanup for each scenario.
  350. """
  351. # Keep output files if the scenario failed
  352. if not scenario.passed:
  353. world.processes.keep_files()
  354. # Stop any running processes we may have had around
  355. world.processes.stop_all_processes()
  356. # Environment check
  357. # Checks if LETTUCE_SETUP_COMPLETED is set in the environment
  358. # If not, abort with an error to use the run-script
  359. if 'LETTUCE_SETUP_COMPLETED' not in os.environ:
  360. print("Environment check failure; LETTUCE_SETUP_COMPLETED not set")
  361. print("Please use the run_lettuce.sh script. If you want to test an")
  362. print("installed version of bind10 with these tests, use")
  363. print("run_lettuce.sh -I [lettuce arguments]")
  364. sys.exit(1)