terrain.py 19 KB

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