terrain.py 17 KB

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