terrain.py 17 KB

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