bind10_test.py.in 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  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. from bind10_src import ProcessInfo, BoB, parse_args, dump_pid, unlink_pid_file, _BASETIME
  16. # XXX: environment tests are currently disabled, due to the preprocessor
  17. # setup that we have now complicating the environment
  18. import unittest
  19. import sys
  20. import os
  21. import copy
  22. import signal
  23. import socket
  24. from isc.net.addr import IPAddr
  25. import time
  26. import isc
  27. import isc.log
  28. from isc.testutils.parse_args import TestOptParser, OptsError
  29. class TestProcessInfo(unittest.TestCase):
  30. def setUp(self):
  31. # redirect stdout to a pipe so we can check that our
  32. # process spawning is doing the right thing with stdout
  33. self.old_stdout = os.dup(sys.stdout.fileno())
  34. self.pipes = os.pipe()
  35. os.dup2(self.pipes[1], sys.stdout.fileno())
  36. os.close(self.pipes[1])
  37. # note that we use dup2() to restore the original stdout
  38. # to the main program ASAP in each test... this prevents
  39. # hangs reading from the child process (as the pipe is only
  40. # open in the child), and also insures nice pretty output
  41. def tearDown(self):
  42. # clean up our stdout munging
  43. os.dup2(self.old_stdout, sys.stdout.fileno())
  44. os.close(self.pipes[0])
  45. def test_init(self):
  46. pi = ProcessInfo('Test Process', [ '/bin/echo', 'foo' ])
  47. pi.spawn()
  48. os.dup2(self.old_stdout, sys.stdout.fileno())
  49. self.assertEqual(pi.name, 'Test Process')
  50. self.assertEqual(pi.args, [ '/bin/echo', 'foo' ])
  51. # self.assertEqual(pi.env, { 'PATH': os.environ['PATH'],
  52. # 'PYTHON_EXEC': os.environ['PYTHON_EXEC'] })
  53. self.assertEqual(pi.dev_null_stdout, False)
  54. self.assertEqual(os.read(self.pipes[0], 100), b"foo\n")
  55. self.assertNotEqual(pi.process, None)
  56. self.assertTrue(type(pi.pid) is int)
  57. # def test_setting_env(self):
  58. # pi = ProcessInfo('Test Process', [ '/bin/true' ], env={'FOO': 'BAR'})
  59. # os.dup2(self.old_stdout, sys.stdout.fileno())
  60. # self.assertEqual(pi.env, { 'PATH': os.environ['PATH'],
  61. # 'PYTHON_EXEC': os.environ['PYTHON_EXEC'],
  62. # 'FOO': 'BAR' })
  63. def test_setting_null_stdout(self):
  64. pi = ProcessInfo('Test Process', [ '/bin/echo', 'foo' ],
  65. dev_null_stdout=True)
  66. pi.spawn()
  67. os.dup2(self.old_stdout, sys.stdout.fileno())
  68. self.assertEqual(pi.dev_null_stdout, True)
  69. self.assertEqual(os.read(self.pipes[0], 100), b"")
  70. def test_respawn(self):
  71. pi = ProcessInfo('Test Process', [ '/bin/echo', 'foo' ])
  72. pi.spawn()
  73. # wait for old process to work...
  74. self.assertEqual(os.read(self.pipes[0], 100), b"foo\n")
  75. # respawn it
  76. old_pid = pi.pid
  77. pi.respawn()
  78. os.dup2(self.old_stdout, sys.stdout.fileno())
  79. # make sure the new one started properly
  80. self.assertEqual(pi.name, 'Test Process')
  81. self.assertEqual(pi.args, [ '/bin/echo', 'foo' ])
  82. # self.assertEqual(pi.env, { 'PATH': os.environ['PATH'],
  83. # 'PYTHON_EXEC': os.environ['PYTHON_EXEC'] })
  84. self.assertEqual(pi.dev_null_stdout, False)
  85. self.assertEqual(os.read(self.pipes[0], 100), b"foo\n")
  86. self.assertNotEqual(pi.process, None)
  87. self.assertTrue(type(pi.pid) is int)
  88. self.assertNotEqual(pi.pid, old_pid)
  89. class TestBoB(unittest.TestCase):
  90. def test_init(self):
  91. bob = BoB()
  92. self.assertEqual(bob.verbose, False)
  93. self.assertEqual(bob.msgq_socket_file, None)
  94. self.assertEqual(bob.cc_session, None)
  95. self.assertEqual(bob.ccs, None)
  96. self.assertEqual(bob.components, {})
  97. self.assertEqual(bob.dead_processes, {})
  98. self.assertEqual(bob.runnable, False)
  99. self.assertEqual(bob.uid, None)
  100. self.assertEqual(bob.username, None)
  101. self.assertEqual(bob.nocache, False)
  102. self.assertEqual(bob.cfg_start_auth, True)
  103. self.assertEqual(bob.cfg_start_resolver, False)
  104. self.assertEqual(bob.cfg_start_dhcp4, False)
  105. self.assertEqual(bob.cfg_start_dhcp6, False)
  106. def test_init_alternate_socket(self):
  107. bob = BoB("alt_socket_file")
  108. self.assertEqual(bob.verbose, False)
  109. self.assertEqual(bob.msgq_socket_file, "alt_socket_file")
  110. self.assertEqual(bob.cc_session, None)
  111. self.assertEqual(bob.ccs, None)
  112. self.assertEqual(bob.components, {})
  113. self.assertEqual(bob.dead_processes, {})
  114. self.assertEqual(bob.runnable, False)
  115. self.assertEqual(bob.uid, None)
  116. self.assertEqual(bob.username, None)
  117. self.assertEqual(bob.nocache, False)
  118. self.assertEqual(bob.cfg_start_auth, True)
  119. self.assertEqual(bob.cfg_start_resolver, False)
  120. self.assertEqual(bob.cfg_start_dhcp4, False)
  121. self.assertEqual(bob.cfg_start_dhcp6, False)
  122. def test_command_handler(self):
  123. class DummySession():
  124. def group_sendmsg(self, msg, group):
  125. (self.msg, self.group) = (msg, group)
  126. def group_recvmsg(self, nonblock, seq): pass
  127. class DummyModuleCCSession():
  128. module_spec = isc.config.module_spec.ModuleSpec({
  129. "module_name": "Boss",
  130. "statistics": [
  131. {
  132. "item_name": "boot_time",
  133. "item_type": "string",
  134. "item_optional": False,
  135. "item_default": "1970-01-01T00:00:00Z",
  136. "item_title": "Boot time",
  137. "item_description": "A date time when bind10 process starts initially",
  138. "item_format": "date-time"
  139. }
  140. ]
  141. })
  142. def get_module_spec(self):
  143. return self.module_spec
  144. bob = BoB()
  145. bob.verbose = True
  146. bob.cc_session = DummySession()
  147. bob.ccs = DummyModuleCCSession()
  148. # a bad command
  149. self.assertEqual(bob.command_handler(-1, None),
  150. isc.config.ccsession.create_answer(1, "bad command"))
  151. # "shutdown" command
  152. self.assertEqual(bob.command_handler("shutdown", None),
  153. isc.config.ccsession.create_answer(0))
  154. self.assertFalse(bob.runnable)
  155. # "getstats" command
  156. self.assertEqual(bob.command_handler("getstats", None),
  157. isc.config.ccsession.create_answer(0,
  158. { "owner": "Boss",
  159. "data": {
  160. 'boot_time': time.strftime('%Y-%m-%dT%H:%M:%SZ', _BASETIME)
  161. }}))
  162. # "sendstats" command
  163. self.assertEqual(bob.command_handler("sendstats", None),
  164. isc.config.ccsession.create_answer(0))
  165. self.assertEqual(bob.cc_session.group, "Stats")
  166. self.assertEqual(bob.cc_session.msg,
  167. isc.config.ccsession.create_command(
  168. "set", { "owner": "Boss",
  169. "data": {
  170. "boot_time": time.strftime("%Y-%m-%dT%H:%M:%SZ", _BASETIME)
  171. }}))
  172. # "ping" command
  173. self.assertEqual(bob.command_handler("ping", None),
  174. isc.config.ccsession.create_answer(0, "pong"))
  175. # "show_processes" command
  176. self.assertEqual(bob.command_handler("show_processes", None),
  177. isc.config.ccsession.create_answer(0,
  178. bob.get_processes()))
  179. # an unknown command
  180. self.assertEqual(bob.command_handler("__UNKNOWN__", None),
  181. isc.config.ccsession.create_answer(1, "Unknown command"))
  182. # Class for testing the BoB without actually starting processes.
  183. # This is used for testing the start/stop components routines and
  184. # the BoB commands.
  185. #
  186. # Testing that external processes start is outside the scope
  187. # of the unit test, by overriding the process start methods we can check
  188. # that the right processes are started depending on the configuration
  189. # options.
  190. class MockBob(BoB):
  191. def __init__(self):
  192. BoB.__init__(self)
  193. # Set flags as to which of the overridden methods has been run.
  194. self.msgq = False
  195. self.cfgmgr = False
  196. self.ccsession = False
  197. self.auth = False
  198. self.resolver = False
  199. self.xfrout = False
  200. self.xfrin = False
  201. self.zonemgr = False
  202. self.stats = False
  203. self.stats_httpd = False
  204. self.cmdctl = False
  205. self.dhcp6 = False
  206. self.dhcp4 = False
  207. self.c_channel_env = {}
  208. self.components = { }
  209. self.creator = False
  210. class MockSockCreator(isc.bind10.component.Component):
  211. def __init__(self, process, boss, kind, address=None, params=None):
  212. isc.bind10.component.Component.__init__(self, process, boss,
  213. kind, 'SockCreator')
  214. self._start_func = boss.start_creator
  215. specials = isc.bind10.special_component.get_specials()
  216. specials['sockcreator'] = MockSockCreator
  217. self._component_configurator = \
  218. isc.bind10.component.Configurator(self, specials)
  219. def start_creator(self):
  220. self.creator = True
  221. procinfo = ProcessInfo('b10-sockcreator', ['/bin/false'])
  222. procinfo.pid = 1
  223. return procinfo
  224. def stop_creator(self, kill=False):
  225. self.creator = False
  226. def read_bind10_config(self):
  227. # Configuration options are set directly
  228. pass
  229. def start_msgq(self):
  230. self.msgq = True
  231. procinfo = ProcessInfo('b10-msgq', ['/bin/false'])
  232. procinfo.pid = 2
  233. return procinfo
  234. def start_ccsession(self, c_channel_env):
  235. # this is not a process, don't have to do anything with procinfo
  236. self.ccsession = True
  237. def start_cfgmgr(self):
  238. self.cfgmgr = True
  239. procinfo = ProcessInfo('b10-cfgmgr', ['/bin/false'])
  240. procinfo.pid = 3
  241. return procinfo
  242. def start_auth(self):
  243. self.auth = True
  244. procinfo = ProcessInfo('b10-auth', ['/bin/false'])
  245. procinfo.pid = 5
  246. return procinfo
  247. def start_resolver(self):
  248. self.resolver = True
  249. procinfo = ProcessInfo('b10-resolver', ['/bin/false'])
  250. procinfo.pid = 6
  251. return procinfo
  252. def start_simple(self, name):
  253. procmap = { 'b10-xfrout': self.start_xfrout,
  254. 'b10-xfrin': self.start_xfrin,
  255. 'b10-zonemgr': self.start_zonemgr,
  256. 'b10-stats': self.start_stats,
  257. 'b10-stats-httpd': self.start_stats_httpd,
  258. 'b10-cmdctl': self.start_cmdctl,
  259. 'b10-dhcp6': self.start_dhcp6,
  260. 'b10-dhcp4': self.start_dhcp4 }
  261. return procmap[name]()
  262. def start_xfrout(self):
  263. self.xfrout = True
  264. procinfo = ProcessInfo('b10-xfrout', ['/bin/false'])
  265. procinfo.pid = 7
  266. return procinfo
  267. def start_xfrin(self):
  268. self.xfrin = True
  269. procinfo = ProcessInfo('b10-xfrin', ['/bin/false'])
  270. procinfo.pid = 8
  271. return procinfo
  272. def start_zonemgr(self):
  273. self.zonemgr = True
  274. procinfo = ProcessInfo('b10-zonemgr', ['/bin/false'])
  275. procinfo.pid = 9
  276. return procinfo
  277. def start_stats(self):
  278. self.stats = True
  279. procinfo = ProcessInfo('b10-stats', ['/bin/false'])
  280. procinfo.pid = 10
  281. return procinfo
  282. def start_stats_httpd(self):
  283. self.stats_httpd = True
  284. procinfo = ProcessInfo('b10-stats-httpd', ['/bin/false'])
  285. procinfo.pid = 11
  286. return procinfo
  287. def start_cmdctl(self):
  288. self.cmdctl = True
  289. procinfo = ProcessInfo('b10-cmdctl', ['/bin/false'])
  290. procinfo.pid = 12
  291. return procinfo
  292. def start_dhcp6(self):
  293. self.stats = True
  294. procinfo = ProcessInfo('b10-dhcp6', ['/bin/false'])
  295. procinfo.pid = 13
  296. return procinfo
  297. def start_dhcp4(self):
  298. self.stats = True
  299. procinfo = ProcessInfo('b10-dhcp4', ['/bin/false'])
  300. procinfo.pid = 14
  301. return procinfo
  302. def stop_process(self, process, recipient):
  303. procmap = { 'b10-auth': self.stop_auth,
  304. 'b10-resolver': self.stop_resolver,
  305. 'b10-xfrout': self.stop_xfrout,
  306. 'b10-xfrin': self.stop_xfrin,
  307. 'b10-zonemgr': self.stop_zonemgr,
  308. 'b10-stats': self.stop_stats,
  309. 'b10-stats-httpd': self.stop_stats_httpd,
  310. 'b10-cmdctl': self.stop_cmdctl }
  311. procmap[process]()
  312. # We don't really use all of these stop_ methods. But it might turn out
  313. # someone would add some stop_ method to BoB and we want that one overriden
  314. # in case he forgets to update the tests.
  315. def stop_msgq(self):
  316. if self.msgq:
  317. del self.components[2]
  318. self.msgq = False
  319. def stop_cfgmgr(self):
  320. if self.cfgmgr:
  321. del self.components[3]
  322. self.cfgmgr = False
  323. def stop_auth(self):
  324. if self.auth:
  325. del self.components[5]
  326. self.auth = False
  327. def stop_resolver(self):
  328. if self.resolver:
  329. del self.components[6]
  330. self.resolver = False
  331. def stop_xfrout(self):
  332. if self.xfrout:
  333. del self.components[7]
  334. self.xfrout = False
  335. def stop_xfrin(self):
  336. if self.xfrin:
  337. del self.components[8]
  338. self.xfrin = False
  339. def stop_zonemgr(self):
  340. if self.zonemgr:
  341. del self.components[9]
  342. self.zonemgr = False
  343. def stop_stats(self):
  344. if self.stats:
  345. del self.components[10]
  346. self.stats = False
  347. def stop_stats_httpd(self):
  348. if self.stats_httpd:
  349. del self.components[11]
  350. self.stats_httpd = False
  351. def stop_cmdctl(self):
  352. if self.cmdctl:
  353. del self.components[12]
  354. self.cmdctl = False
  355. class TestStartStopProcessesBob(unittest.TestCase):
  356. """
  357. Check that the start_all_components method starts the right combination
  358. of components and that the right components are started and stopped
  359. according to changes in configuration.
  360. """
  361. def check_environment_unchanged(self):
  362. # Check whether the environment has not been changed
  363. self.assertEqual(original_os_environ, os.environ)
  364. def check_started(self, bob, core, auth, resolver):
  365. """
  366. Check that the right sets of services are started. The ones that
  367. should be running are specified by the core, auth and resolver parameters
  368. (they are groups of processes, eg. auth means b10-auth, -xfrout, -xfrin
  369. and -zonemgr).
  370. """
  371. self.assertEqual(bob.msgq, core)
  372. self.assertEqual(bob.cfgmgr, core)
  373. self.assertEqual(bob.ccsession, core)
  374. self.assertEqual(bob.creator, core)
  375. self.assertEqual(bob.auth, auth)
  376. self.assertEqual(bob.resolver, resolver)
  377. self.assertEqual(bob.xfrout, auth)
  378. self.assertEqual(bob.xfrin, auth)
  379. self.assertEqual(bob.zonemgr, auth)
  380. self.assertEqual(bob.stats, core)
  381. self.assertEqual(bob.stats_httpd, core)
  382. self.assertEqual(bob.cmdctl, core)
  383. self.check_environment_unchanged()
  384. def check_preconditions(self, bob):
  385. self.check_started(bob, False, False, False)
  386. def check_started_none(self, bob):
  387. """
  388. Check that the situation is according to configuration where no servers
  389. should be started. Some components still need to be running.
  390. """
  391. self.check_started(bob, True, False, False)
  392. self.check_environment_unchanged()
  393. def check_started_both(self, bob):
  394. """
  395. Check the situation is according to configuration where both servers
  396. (auth and resolver) are enabled.
  397. """
  398. self.check_started(bob, True, True, True)
  399. self.check_environment_unchanged()
  400. def check_started_auth(self, bob):
  401. """
  402. Check the set of components needed to run auth only is started.
  403. """
  404. self.check_started(bob, True, True, False)
  405. self.check_environment_unchanged()
  406. def check_started_resolver(self, bob):
  407. """
  408. Check the set of components needed to run resolver only is started.
  409. """
  410. self.check_started(bob, True, False, True)
  411. self.check_environment_unchanged()
  412. def check_started_dhcp(self, bob, v4, v6):
  413. """
  414. Check if proper combinations of DHCPv4 and DHCpv6 can be started
  415. """
  416. v4found = 'b10-dhcp4' in bob.component_config
  417. v6found = 'b10-dhcp6' in bob.component_config
  418. # there should be exactly one DHCPv4 daemon (if v4==True)
  419. # there should be exactly one DHCPv6 daemon (if v6==True)
  420. self.assertEqual(v4==True, v4found==1)
  421. self.assertEqual(v6==True, v6found==1)
  422. self.check_environment_unchanged()
  423. # Checks the components started when starting neither auth nor resolver
  424. # is specified.
  425. def test_start_none(self):
  426. # Create BoB and ensure correct initialization
  427. bob = MockBob()
  428. self.check_preconditions(bob)
  429. # Start components and check what was started
  430. bob.cfg_start_auth = False
  431. bob.cfg_start_resolver = False
  432. bob.start_all_components()
  433. self.check_started_none(bob)
  434. # Checks the components started when starting only the auth process
  435. def test_start_auth(self):
  436. # Create BoB and ensure correct initialization
  437. bob = MockBob()
  438. self.check_preconditions(bob)
  439. # Start components and check what was started
  440. bob.cfg_start_auth = True
  441. bob.cfg_start_resolver = False
  442. bob.start_all_components()
  443. self.check_started_auth(bob)
  444. # Checks the components started when starting only the resolver process
  445. def test_start_resolver(self):
  446. # Create BoB and ensure correct initialization
  447. bob = MockBob()
  448. self.check_preconditions(bob)
  449. # Start components and check what was started
  450. bob.cfg_start_auth = False
  451. bob.cfg_start_resolver = True
  452. bob.start_all_components()
  453. self.check_started_resolver(bob)
  454. # Checks the components started when starting both auth and resolver process
  455. def test_start_both(self):
  456. # Create BoB and ensure correct initialization
  457. bob = MockBob()
  458. self.check_preconditions(bob)
  459. # Start components and check what was started
  460. bob.cfg_start_auth = True
  461. bob.cfg_start_resolver = True
  462. bob.start_all_components()
  463. self.check_started_both(bob)
  464. def test_config_start(self):
  465. """
  466. Test that the configuration starts and stops components according
  467. to configuration changes.
  468. """
  469. # Create BoB and ensure correct initialization
  470. bob = MockBob()
  471. self.check_preconditions(bob)
  472. # Start components (nothing much should be started, as in
  473. # test_start_none)
  474. bob.cfg_start_auth = False
  475. bob.cfg_start_resolver = False
  476. bob.start_all_components()
  477. bob.runnable = True
  478. self.check_started_none(bob)
  479. # Enable both at once
  480. bob.config_handler({'start_auth': True, 'start_resolver': True})
  481. self.check_started_both(bob)
  482. # Not touched by empty change
  483. bob.config_handler({})
  484. self.check_started_both(bob)
  485. # Not touched by change to the same configuration
  486. bob.config_handler({'start_auth': True, 'start_resolver': True})
  487. self.check_started_both(bob)
  488. # Turn them both off again
  489. bob.config_handler({'start_auth': False, 'start_resolver': False})
  490. self.check_started_none(bob)
  491. # Not touched by empty change
  492. bob.config_handler({})
  493. self.check_started_none(bob)
  494. # Not touched by change to the same configuration
  495. bob.config_handler({'start_auth': False, 'start_resolver': False})
  496. self.check_started_none(bob)
  497. # Start and stop auth separately
  498. bob.config_handler({'start_auth': True})
  499. self.check_started_auth(bob)
  500. bob.config_handler({'start_auth': False})
  501. self.check_started_none(bob)
  502. # Start and stop resolver separately
  503. bob.config_handler({'start_resolver': True})
  504. self.check_started_resolver(bob)
  505. bob.config_handler({'start_resolver': False})
  506. self.check_started_none(bob)
  507. # Alternate
  508. bob.config_handler({'start_auth': True})
  509. self.check_started_auth(bob)
  510. bob.config_handler({'start_auth': False, 'start_resolver': True})
  511. self.check_started_resolver(bob)
  512. bob.config_handler({'start_auth': True, 'start_resolver': False})
  513. self.check_started_auth(bob)
  514. def test_config_start_once(self):
  515. """
  516. Tests that a process is started only once.
  517. """
  518. # Create BoB and ensure correct initialization
  519. bob = MockBob()
  520. self.check_preconditions(bob)
  521. # Start components (both)
  522. bob.cfg_start_auth = True
  523. bob.cfg_start_resolver = True
  524. bob.start_all_components()
  525. bob.runnable = True
  526. self.check_started_both(bob)
  527. bob.start_auth = lambda: self.fail("Started auth again")
  528. bob.start_xfrout = lambda: self.fail("Started xfrout again")
  529. bob.start_xfrin = lambda: self.fail("Started xfrin again")
  530. bob.start_zonemgr = lambda: self.fail("Started zonemgr again")
  531. bob.start_resolver = lambda: self.fail("Started resolver again")
  532. # Send again we want to start them. Should not do it, as they are.
  533. bob.config_handler({'start_auth': True})
  534. bob.config_handler({'start_resolver': True})
  535. def test_config_not_started_early(self):
  536. """
  537. Test that components are not started by the config handler before
  538. startup.
  539. """
  540. bob = MockBob()
  541. self.check_preconditions(bob)
  542. bob.start_auth = lambda: self.fail("Started auth again")
  543. bob.start_xfrout = lambda: self.fail("Started xfrout again")
  544. bob.start_xfrin = lambda: self.fail("Started xfrin again")
  545. bob.start_zonemgr = lambda: self.fail("Started zonemgr again")
  546. bob.start_resolver = lambda: self.fail("Started resolver again")
  547. bob.config_handler({'start_auth': True, 'start_resolver': True})
  548. # Checks that DHCP (v4 and v6) components are started when expected
  549. def test_start_dhcp(self):
  550. # Create BoB and ensure correct initialization
  551. bob = MockBob()
  552. self.check_preconditions(bob)
  553. # don't care about DNS stuff
  554. bob.cfg_start_auth = False
  555. bob.cfg_start_resolver = False
  556. # v4 and v6 disabled
  557. bob.cfg_start_dhcp6 = False
  558. bob.cfg_start_dhcp4 = False
  559. bob.start_all_components()
  560. self.check_started_dhcp(bob, False, False)
  561. def test_start_dhcp_v6only(self):
  562. # Create BoB and ensure correct initialization
  563. bob = MockBob()
  564. self.check_preconditions(bob)
  565. # don't care about DNS stuff
  566. bob.cfg_start_auth = False
  567. bob.cfg_start_resolver = False
  568. # v6 only enabled
  569. bob.cfg_start_dhcp6 = True
  570. bob.cfg_start_dhcp4 = False
  571. bob.start_all_components()
  572. self.check_started_dhcp(bob, False, True)
  573. # uncomment when dhcpv4 becomes implemented
  574. # v4 only enabled
  575. #bob.cfg_start_dhcp6 = False
  576. #bob.cfg_start_dhcp4 = True
  577. #self.check_started_dhcp(bob, True, False)
  578. # both v4 and v6 enabled
  579. #bob.cfg_start_dhcp6 = True
  580. #bob.cfg_start_dhcp4 = True
  581. #self.check_started_dhcp(bob, True, True)
  582. class MockComponent:
  583. def __init__(self, name, pid):
  584. self.name = lambda: name
  585. self.pid = lambda: pid
  586. class TestBossCmd(unittest.TestCase):
  587. def test_ping(self):
  588. """
  589. Confirm simple ping command works.
  590. """
  591. bob = MockBob()
  592. answer = bob.command_handler("ping", None)
  593. self.assertEqual(answer, {'result': [0, 'pong']})
  594. def test_show_processes_empty(self):
  595. """
  596. Confirm getting a list of processes works.
  597. """
  598. bob = MockBob()
  599. answer = bob.command_handler("show_processes", None)
  600. self.assertEqual(answer, {'result': [0, []]})
  601. def test_show_processes(self):
  602. """
  603. Confirm getting a list of processes works.
  604. """
  605. bob = MockBob()
  606. bob.register_process(1, MockComponent('first', 1))
  607. bob.register_process(2, MockComponent('second', 2))
  608. answer = bob.command_handler("show_processes", None)
  609. processes = [[1, 'first'],
  610. [2, 'second']]
  611. self.assertEqual(answer, {'result': [0, processes]})
  612. class TestParseArgs(unittest.TestCase):
  613. """
  614. This tests parsing of arguments of the bind10 master process.
  615. """
  616. #TODO: Write tests for the original parsing, bad options, etc.
  617. def test_no_opts(self):
  618. """
  619. Test correct default values when no options are passed.
  620. """
  621. options = parse_args([], TestOptParser)
  622. self.assertEqual(None, options.data_path)
  623. self.assertEqual(None, options.config_file)
  624. self.assertEqual(None, options.cmdctl_port)
  625. def test_data_path(self):
  626. """
  627. Test it can parse the data path.
  628. """
  629. self.assertRaises(OptsError, parse_args, ['-p'], TestOptParser)
  630. self.assertRaises(OptsError, parse_args, ['--data-path'],
  631. TestOptParser)
  632. options = parse_args(['-p', '/data/path'], TestOptParser)
  633. self.assertEqual('/data/path', options.data_path)
  634. options = parse_args(['--data-path=/data/path'], TestOptParser)
  635. self.assertEqual('/data/path', options.data_path)
  636. def test_config_filename(self):
  637. """
  638. Test it can parse the config switch.
  639. """
  640. self.assertRaises(OptsError, parse_args, ['-c'], TestOptParser)
  641. self.assertRaises(OptsError, parse_args, ['--config-file'],
  642. TestOptParser)
  643. options = parse_args(['-c', 'config-file'], TestOptParser)
  644. self.assertEqual('config-file', options.config_file)
  645. options = parse_args(['--config-file=config-file'], TestOptParser)
  646. self.assertEqual('config-file', options.config_file)
  647. def test_cmdctl_port(self):
  648. """
  649. Test it can parse the command control port.
  650. """
  651. self.assertRaises(OptsError, parse_args, ['--cmdctl-port=abc'],
  652. TestOptParser)
  653. self.assertRaises(OptsError, parse_args, ['--cmdctl-port=100000000'],
  654. TestOptParser)
  655. self.assertRaises(OptsError, parse_args, ['--cmdctl-port'],
  656. TestOptParser)
  657. options = parse_args(['--cmdctl-port=1234'], TestOptParser)
  658. self.assertEqual(1234, options.cmdctl_port)
  659. def test_brittle(self):
  660. """
  661. Test we can use the "brittle" flag.
  662. """
  663. options = parse_args([], TestOptParser)
  664. self.assertFalse(options.brittle)
  665. options = parse_args(['--brittle'], TestOptParser)
  666. self.assertTrue(options.brittle)
  667. class TestPIDFile(unittest.TestCase):
  668. def setUp(self):
  669. self.pid_file = '@builddir@' + os.sep + 'bind10.pid'
  670. if os.path.exists(self.pid_file):
  671. os.unlink(self.pid_file)
  672. def tearDown(self):
  673. if os.path.exists(self.pid_file):
  674. os.unlink(self.pid_file)
  675. def check_pid_file(self):
  676. # dump PID to the file, and confirm the content is correct
  677. dump_pid(self.pid_file)
  678. my_pid = os.getpid()
  679. self.assertEqual(my_pid, int(open(self.pid_file, "r").read()))
  680. def test_dump_pid(self):
  681. self.check_pid_file()
  682. # make sure any existing content will be removed
  683. open(self.pid_file, "w").write('dummy data\n')
  684. self.check_pid_file()
  685. def test_unlink_pid_file_notexist(self):
  686. dummy_data = 'dummy_data\n'
  687. open(self.pid_file, "w").write(dummy_data)
  688. unlink_pid_file("no_such_pid_file")
  689. # the file specified for unlink_pid_file doesn't exist,
  690. # and the original content of the file should be intact.
  691. self.assertEqual(dummy_data, open(self.pid_file, "r").read())
  692. def test_dump_pid_with_none(self):
  693. # Check the behavior of dump_pid() and unlink_pid_file() with None.
  694. # This should be no-op.
  695. dump_pid(None)
  696. self.assertFalse(os.path.exists(self.pid_file))
  697. dummy_data = 'dummy_data\n'
  698. open(self.pid_file, "w").write(dummy_data)
  699. unlink_pid_file(None)
  700. self.assertEqual(dummy_data, open(self.pid_file, "r").read())
  701. def test_dump_pid_failure(self):
  702. # the attempt to open file will fail, which should result in exception.
  703. self.assertRaises(IOError, dump_pid,
  704. 'nonexistent_dir' + os.sep + 'bind10.pid')
  705. # TODO: Do we want brittle mode? Probably yes. So we need to re-enable to after that.
  706. @unittest.skip("Brittle mode temporarily broken")
  707. class TestBrittle(unittest.TestCase):
  708. def test_brittle_disabled(self):
  709. bob = MockBob()
  710. bob.start_all_components()
  711. bob.runnable = True
  712. bob.reap_children()
  713. self.assertTrue(bob.runnable)
  714. def simulated_exit(self):
  715. ret_val = self.exit_info
  716. self.exit_info = (0, 0)
  717. return ret_val
  718. def test_brittle_enabled(self):
  719. bob = MockBob()
  720. bob.start_all_components()
  721. bob.runnable = True
  722. bob.brittle = True
  723. self.exit_info = (5, 0)
  724. bob._get_process_exit_status = self.simulated_exit
  725. old_stdout = sys.stdout
  726. sys.stdout = open("/dev/null", "w")
  727. bob.reap_children()
  728. sys.stdout = old_stdout
  729. self.assertFalse(bob.runnable)
  730. if __name__ == '__main__':
  731. # store os.environ for test_unchanged_environment
  732. original_os_environ = copy.deepcopy(os.environ)
  733. isc.log.resetUnitTestRootLogger()
  734. unittest.main()