bind10_control.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. # Copyright (C) 2011-2012 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. from lettuce import *
  16. import time
  17. import subprocess
  18. import re
  19. import json
  20. @step('sleep for (\d+) seconds')
  21. def wait_seconds(step, seconds):
  22. """Sleep for some seconds.
  23. Parameters:
  24. seconds number of seconds to sleep for.
  25. """
  26. time.sleep(float(seconds))
  27. @step('start bind10(?: with configuration (\S+))?' +\
  28. '(?: with cmdctl port (\d+))?' +\
  29. '(?: with msgq socket file (\S+))?' +\
  30. '(?: as (\S+))?')
  31. def start_bind10(step, config_file, cmdctl_port, msgq_sockfile, process_name):
  32. """
  33. Start BIND 10 with the given optional config file, cmdctl port, and
  34. store the running process in world with the given process name.
  35. Parameters:
  36. config_file ('with configuration <file>', optional): this configuration
  37. will be used. The path is relative to the base lettuce
  38. directory.
  39. cmdctl_port ('with cmdctl port <portnr>', optional): The port on which
  40. b10-cmdctl listens for bindctl commands. Defaults to 56175.
  41. msgq_sockfile ('with msgq socket file', optional): The msgq socket file
  42. that will be used for internal communication
  43. process_name ('as <name>', optional). This is the name that can be used
  44. in the following steps of the scenario to refer to this
  45. BIND 10 instance. Defaults to 'bind10'.
  46. This call will block until BIND10_STARTUP_COMPLETE or BIND10_STARTUP_ERROR
  47. is logged. In the case of the latter, or if it times out, the step (and
  48. scenario) will fail.
  49. It will also fail if there is a running process with the given process_name
  50. already.
  51. """
  52. args = [ 'bind10', '-v' ]
  53. if config_file is not None:
  54. args.append('-p')
  55. args.append("configurations/")
  56. args.append('-c')
  57. args.append(config_file)
  58. if cmdctl_port is None:
  59. args.append('--cmdctl-port=56175')
  60. else:
  61. args.append('--cmdctl-port=' + cmdctl_port)
  62. if process_name is None:
  63. process_name = "bind10"
  64. else:
  65. args.append('-m')
  66. args.append(process_name + '_msgq.socket')
  67. world.processes.add_process(step, process_name, args)
  68. # check output to know when startup has been completed
  69. (message, line) = world.processes.wait_for_stderr_str(process_name,
  70. ["BIND10_STARTUP_COMPLETE",
  71. "BIND10_STARTUP_ERROR"])
  72. assert message == "BIND10_STARTUP_COMPLETE", "Got: " + str(line)
  73. @step('wait for bind10 auth (?:of (\w+) )?to start')
  74. def wait_for_auth(step, process_name):
  75. """Wait for b10-auth to run. This is done by blocking until the message
  76. AUTH_SERVER_STARTED is logged.
  77. Parameters:
  78. process_name ('of <name', optional): The name of the BIND 10 instance
  79. to wait for. Defaults to 'bind10'.
  80. """
  81. if process_name is None:
  82. process_name = "bind10"
  83. world.processes.wait_for_stderr_str(process_name, ['AUTH_SERVER_STARTED'],
  84. False)
  85. @step('wait for bind10 xfrout (?:of (\w+) )?to start')
  86. def wait_for_xfrout(step, process_name):
  87. """Wait for b10-xfrout to run. This is done by blocking until the message
  88. XFROUT_NEW_CONFIG_DONE is logged.
  89. Parameters:
  90. process_name ('of <name', optional): The name of the BIND 10 instance
  91. to wait for. Defaults to 'bind10'.
  92. """
  93. if process_name is None:
  94. process_name = "bind10"
  95. world.processes.wait_for_stderr_str(process_name,
  96. ['XFROUT_NEW_CONFIG_DONE'],
  97. False)
  98. @step('have bind10 running(?: with configuration ([\S]+))?' +\
  99. '(?: with cmdctl port (\d+))?' +\
  100. '(?: as ([\S]+))?')
  101. def have_bind10_running(step, config_file, cmdctl_port, process_name):
  102. """
  103. Compound convenience step for running bind10, which consists of
  104. start_bind10.
  105. Currently only supports the 'with configuration' option.
  106. """
  107. start_step = 'start bind10 with configuration ' + config_file
  108. if cmdctl_port is not None:
  109. start_step += ' with cmdctl port ' + str(cmdctl_port)
  110. if process_name is not None:
  111. start_step += ' as ' + process_name
  112. step.given(start_step)
  113. # function to send lines to bindctl, and store the result
  114. def run_bindctl(commands, cmdctl_port=None, ignore_failure=False):
  115. """Run bindctl.
  116. Parameters:
  117. commands: a sequence of strings which will be sent.
  118. cmdctl_port: a port number on which cmdctl is listening, is converted
  119. to string if necessary. If not provided, or None, defaults
  120. to 56175
  121. ignore_failure(bool): if set to True, don't examin the result code
  122. of bindctl and assert it succeeds.
  123. bindctl's stdout and stderr streams are stored (as one multiline string
  124. in world.last_bindctl_stdout/stderr.
  125. Fails if the return code is not 0
  126. """
  127. if cmdctl_port is None:
  128. cmdctl_port = 56175
  129. args = ['bindctl', '-p', str(cmdctl_port), '--csv-file-dir=configurations/' ]
  130. bindctl = subprocess.Popen(args, 1, None, subprocess.PIPE,
  131. subprocess.PIPE, None)
  132. for line in commands:
  133. bindctl.stdin.write(line + "\n")
  134. (stdout, stderr) = bindctl.communicate()
  135. if ignore_failure:
  136. return
  137. result = bindctl.returncode
  138. world.last_bindctl_stdout = stdout
  139. world.last_bindctl_stderr = stderr
  140. assert result == 0, "bindctl exit code: " + str(result) +\
  141. "\nstdout:\n" + str(stdout) +\
  142. "stderr:\n" + str(stderr)
  143. @step('last bindctl( stderr)? output should( not)? contain (\S+)( exactly)?')
  144. def check_bindctl_output(step, stderr, notv, string, exactly):
  145. """Checks the stdout (or stderr) stream of the last run of bindctl,
  146. fails if the given string is not found in it (or fails if 'not' was
  147. set and it is found
  148. Parameters:
  149. stderr ('stderr'): Check stderr instead of stdout output
  150. notv ('not'): reverse the check (fail if string is found)
  151. string ('contain <string>') string to look for
  152. exactly ('exactly'): Make an exact match delimited by whitespace
  153. """
  154. if stderr is None:
  155. output = world.last_bindctl_stdout
  156. else:
  157. output = world.last_bindctl_stderr
  158. found = False
  159. if exactly is None:
  160. if string in output:
  161. found = True
  162. else:
  163. if re.search(r'^\s+' + string + r'\s+', output, re.IGNORECASE | re.MULTILINE) is not None:
  164. found = True
  165. if notv is None:
  166. assert found == True, "'" + string +\
  167. "' was not found in bindctl output:\n" +\
  168. output
  169. else:
  170. assert not found, "'" + string +\
  171. "' was found in bindctl output:\n" +\
  172. output
  173. def parse_bindctl_output_as_data_structure():
  174. """Helper function for data-related command tests: evaluates the
  175. last output of bindctl as a data structure that can then be
  176. inspected.
  177. If the bindctl output is not valid (json) data, this call will
  178. fail with an assertion failure.
  179. If it is valid, it is parsed and returned as whatever data
  180. structure it represented.
  181. """
  182. # strip any extra output after a character that commonly terminates a valid
  183. # JSON expression, i.e., ']', '}' and '"'. (The extra output would
  184. # contain 'Exit from bindctl' message, and depending on environment some
  185. # other control-like characters...but why is this message even there?)
  186. # Note that this filter is not perfect. For example, it cannot recognize
  187. # a simple expression of true/false/null.
  188. output = re.sub("(.*)([^]}\"]*$)", r"\1", world.last_bindctl_stdout)
  189. try:
  190. return json.loads(output)
  191. except ValueError as ve:
  192. assert False, "Last bindctl output does not appear to be a " +\
  193. "parseable data structure: '" + output + "': " + str(ve)
  194. def find_process_pid(step, process_name):
  195. """Helper function to request the running processes from Init, and
  196. return the pid of the process with the given process_name.
  197. Fails with an assert if the response from b10-init is not valid JSON,
  198. or if the process with the given name is not found.
  199. """
  200. # show_processes output is a list of lists, where the inner lists
  201. # are of the form [ pid, "name" ]
  202. # Not checking data form; errors will show anyway (if these turn
  203. # out to be too vague, we can change this)
  204. step.given('send bind10 the command Init show_processes')
  205. running_processes = parse_bindctl_output_as_data_structure()
  206. for process in running_processes:
  207. if process[1] == process_name:
  208. return process[0]
  209. assert False, "Process named " + process_name +\
  210. " not found in output of Init show_processes";
  211. @step("remember the pid of process ([\S]+)")
  212. def remember_pid(step, process_name):
  213. """Stores the PID of the process with the given name as returned by
  214. Init show_processes command.
  215. Fails if the process with the given name does not appear to exist.
  216. Stores the component_name->pid value in the dict world.process_pids.
  217. This should only be used by the related step
  218. 'the pid of process <name> should (not) have changed'
  219. Arguments:
  220. process name ('process <name>') the name of the component to store
  221. the pid of.
  222. """
  223. if world.process_pids is None:
  224. world.process_pids = {}
  225. world.process_pids[process_name] = find_process_pid(step, process_name)
  226. @step('pid of process ([\S]+) should not have changed')
  227. def check_pid(step, process_name):
  228. """Checks the PID of the process with the given name as returned by
  229. Init show_processes command.
  230. Fails if the process with the given name does not appear to exist.
  231. Fails if the process with the given name exists, but has a different
  232. pid than it had when the step 'remember the pid of process' was
  233. called.
  234. Fails if that step has not been called (since world.process_pids
  235. does not exist).
  236. """
  237. assert world.process_pids is not None, "No process pids stored"
  238. assert process_name in world.process_pids, "Process named " +\
  239. process_name +\
  240. " was not stored"
  241. pid = find_process_pid(step, process_name)
  242. assert world.process_pids[process_name] == pid,\
  243. "Expected pid: " + str(world.process_pids[process_name]) +\
  244. " Got pid: " + str(pid)
  245. @step('set bind10 configuration (\S+) to (.*)(?: with cmdctl port (\d+))?')
  246. def config_set_command(step, name, value, cmdctl_port):
  247. """
  248. Run bindctl, set the given configuration to the given value, and commit it.
  249. Parameters:
  250. name ('configuration <name>'): Identifier of the configuration to set
  251. value ('to <value>'): value to set it to.
  252. cmdctl_port ('with cmdctl port <portnr>', optional): cmdctl port to send
  253. the command to. Defaults to 56175.
  254. Fails if cmdctl does not exit with status code 0.
  255. """
  256. commands = ["config set " + name + " " + value,
  257. "config commit",
  258. "quit"]
  259. run_bindctl(commands, cmdctl_port)
  260. @step('send bind10 the following commands(?: with cmdctl port (\d+))?')
  261. def send_multiple_commands(step, cmdctl_port):
  262. """
  263. Run bindctl, and send it the given multiline set of commands.
  264. A quit command is always appended.
  265. cmdctl_port ('with cmdctl port <portnr>', optional): cmdctl port to send
  266. the command to. Defaults to 56175.
  267. Fails if cmdctl does not exit with status code 0.
  268. """
  269. commands = step.multiline.split("\n")
  270. # Always add quit
  271. commands.append("quit")
  272. run_bindctl(commands, cmdctl_port)
  273. @step('remove bind10 configuration (\S+)(?: value (\S+))?(?: with cmdctl port (\d+))?')
  274. def config_remove_command(step, name, value, cmdctl_port):
  275. """
  276. Run bindctl, remove the given configuration item, and commit it.
  277. Parameters:
  278. name ('configuration <name>'): Identifier of the configuration to remove
  279. value ('value <value>'): if name is a named set, use value to identify
  280. item to remove
  281. cmdctl_port ('with cmdctl port <portnr>', optional): cmdctl port to send
  282. the command to. Defaults to 56175.
  283. Fails if cmdctl does not exit with status code 0.
  284. """
  285. cmd = "config remove " + name
  286. if value is not None:
  287. cmd = cmd + " " + value
  288. commands = [cmd,
  289. "config commit",
  290. "quit"]
  291. run_bindctl(commands, cmdctl_port)
  292. @step('send bind10(?: with cmdctl port (\d+))?( ignoring failure)? the command (.+)')
  293. def send_command(step, cmdctl_port, ignore_failure, command):
  294. """
  295. Run bindctl, send the given command, and exit bindctl.
  296. Parameters:
  297. command ('the command <command>'): The command to send.
  298. cmdctl_port ('with cmdctl port <portnr>', optional): cmdctl port to send
  299. the command to. Defaults to 56175.
  300. ignore_failure ('ignoring failure', optional): set to None if bindctl
  301. is expected to succeed (normal case, which is the default); if it is
  302. not None, it means bindctl is expected to fail (and it's acceptable).
  303. Fails if bindctl does not exit with status code 0 and ignore_failure
  304. is not None.
  305. """
  306. commands = [command,
  307. "quit"]
  308. run_bindctl(commands, cmdctl_port, ignore_failure is not None)
  309. @step('bind10 module (\S+) should( not)? be running')
  310. def module_is_running(step, name, not_str):
  311. """
  312. Convenience step to check if a module is running; can only work with
  313. default cmdctl port; sends a 'help' command with bindctl, then
  314. checks if the output contains the given name.
  315. Parameters:
  316. name ('module <name>'): The name of the module (case sensitive!)
  317. not ('not'): Reverse the check (fail if it is running)
  318. """
  319. if not_str is None:
  320. not_str = ""
  321. step.given('send bind10 the command help')
  322. step.given('last bindctl output should' + not_str + ' contain ' + name + ' exactly')
  323. @step('Configure BIND10 to run DDNS')
  324. def configure_ddns_on(step):
  325. """
  326. Convenience compound step to enable the b10-ddns module.
  327. """
  328. step.behave_as("""
  329. When I send bind10 the following commands
  330. \"\"\"
  331. config add Init/components b10-ddns
  332. config set Init/components/b10-ddns/kind dispensable
  333. config set Init/components/b10-ddns/address DDNS
  334. config commit
  335. \"\"\"
  336. """)
  337. @step('Configure BIND10 to stop running DDNS')
  338. def configure_ddns_off(step):
  339. """
  340. Convenience compound step to disable the b10-ddns module.
  341. """
  342. step.behave_as("""
  343. When I send bind10 the following commands
  344. \"\"\"
  345. config remove Init/components b10-ddns
  346. config commit
  347. \"\"\"
  348. """)
  349. @step('query statistics(?: (\S+))? of bind10 module (\S+)(?: with cmdctl port (\d+))?')
  350. def query_statistics(step, statistics, name, cmdctl_port):
  351. """
  352. query statistics data via bindctl.
  353. Parameters:
  354. statistics ('statistics <statistics>', optional) : The queried statistics name.
  355. name ('module <name>'): The name of the module (case sensitive!)
  356. cmdctl_port ('with cmdctl port <portnr>', optional): cmdctl port to send
  357. the command to.
  358. """
  359. port_str = ' with cmdctl port %s' % cmdctl_port \
  360. if cmdctl_port else ''
  361. step.given('send bind10%s the command Stats show owner=%s%s'\
  362. % (port_str, name,\
  363. ' name=%s' % statistics if statistics else ''))
  364. @step('statistics counters are 0 in category (\S+)( except for the' + \
  365. ' following items)?')
  366. def check_statistics_items(step, category, has_except_for):
  367. """
  368. check the output of bindctl for statistics of specified counter.
  369. Parameters:
  370. category ('category <category>'): The category of counter.
  371. has_except_for ('except for the following items'): checks values of items
  372. with the multiline part.
  373. Expected values of items are taken from the multiline part of the step in
  374. the scenario. The multiline part has at most four columns: item_name,
  375. item_value, min_value, and max_value. item_name is a relative name
  376. to category. item_value is an expected value for
  377. item_name. min_value and max_value are expected to be used when
  378. item_value cannot be specified to be item_value. min_value is the
  379. minimum value in the expected range, and max_value is the maximum
  380. value in the expected range. Values would be examined if they are
  381. in columns corresponding to these.
  382. """
  383. def flatten(dictionary, prefix=''):
  384. h = {}
  385. for k, v in dictionary.items():
  386. if type(v) is dict:
  387. h.update(flatten(v, prefix+'.'+k))
  388. else:
  389. h[prefix+'.'+k] = v
  390. return h
  391. stats = flatten(parse_bindctl_output_as_data_structure())
  392. if has_except_for:
  393. # fetch step tables in the scnario as hashes
  394. for item in step.hashes:
  395. name = category+'.'+item['item_name']
  396. assert stats.has_key(name), \
  397. 'Statistics item %s was not found' % (name)
  398. found = stats[name]
  399. if 'item_value' in item and item['item_value']:
  400. value = item['item_value']
  401. assert int(found) == int(value), \
  402. 'Statistics item %s has unexpected value %s (expect %s)' % \
  403. (name, found, value)
  404. if 'min_value' in item and item['min_value']:
  405. value = item['min_value']
  406. assert float(value) <= float(found), \
  407. 'Statistics item %s has unexpected value %s (expect %s or greater than)' % \
  408. (name, found, value)
  409. if 'max_value' in item and item['max_value']:
  410. value = item['max_value']
  411. assert float(found) <= float(value), \
  412. 'Statistics item %s has unexpected value %s (expect %s or less than)' % \
  413. (name, found, value)
  414. del(stats[name])
  415. for name, found in stats.items():
  416. assert int(found) == 0, \
  417. 'Statistics item %s has unexpected value %s (expect %s)' % \
  418. (name, found, 0)
  419. @step('check initial statistics(?:( not)? containing (\S+))? for (\S+)'
  420. '( with cmdctl port \d+)?( except for the following items)?')
  421. def check_init_statistics(step, notv, string, name, cmdctl_port, has_except_for):
  422. """Checks the initial statistics for the module. Also checks a
  423. string is contained or not contained in them. Statistics counters
  424. other than zero can follow below.
  425. Parameters:
  426. notv ('not'): reverse the check (fail if string is found)
  427. string ('containing <string>') string to look for
  428. name ('module <name>'): The name of the module (case sensitive!)
  429. cmdctl_port ('with cmdctl port <portnr>', optional): cmdctl port to send
  430. the command to.
  431. has_except_for ('except for the following items'): checks values of items
  432. with the multiline part.
  433. """
  434. query_str = 'query statistics of bind10 module ' + name
  435. if cmdctl_port:
  436. query_str = query_str + cmdctl_port
  437. notcontain_str = 'last bindctl output should%s contain "%s"'
  438. check_str = 'statistics counters are 0 in category .' + name
  439. if has_except_for:
  440. check_str = check_str + has_except_for + "\n" \
  441. + step.represent_hashes()
  442. step.given(query_str)
  443. step.given(notcontain_str % (' not', 'error'))
  444. if string is not None:
  445. step.given(notcontain_str % (notv, string))
  446. step.given(check_str)