terrain.py 18 KB

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