terrain.py 17 KB

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