terrain.py 18 KB

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