bind10_test.py.in 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  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.processes, {})
  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.processes, {})
  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.processes = { }
  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-zonemgr': self.start_zonemgr,
  255. 'b10-stats': self.start_stats,
  256. 'b10-stats-httpd': self.start_stats_httpd,
  257. 'b10-cmdctl': self.start_cmdctl,
  258. 'b10-dhcp6': self.start_dhcp6,
  259. 'b10-dhcp4': self.start_dhcp4 }
  260. return procmap[name]()
  261. def start_xfrout(self):
  262. self.xfrout = True
  263. procinfo = ProcessInfo('b10-xfrout', ['/bin/false'])
  264. procinfo.pid = 7
  265. return procinfo
  266. def start_xfrin(self):
  267. self.xfrin = True
  268. procinfo = ProcessInfo('b10-xfrin', ['/bin/false'])
  269. procinfo.pid = 8
  270. return procinfo
  271. def start_zonemgr(self):
  272. self.zonemgr = True
  273. procinfo = ProcessInfo('b10-zonemgr', ['/bin/false'])
  274. procinfo.pid = 9
  275. return procinfo
  276. def start_stats(self):
  277. self.stats = True
  278. procinfo = ProcessInfo('b10-stats', ['/bin/false'])
  279. procinfo.pid = 10
  280. return procinfo
  281. def start_stats_httpd(self):
  282. self.stats_httpd = True
  283. procinfo = ProcessInfo('b10-stats-httpd', ['/bin/false'])
  284. procinfo.pid = 11
  285. return procinfo
  286. def start_cmdctl(self):
  287. self.cmdctl = True
  288. procinfo = ProcessInfo('b10-cmdctl', ['/bin/false'])
  289. procinfo.pid = 12
  290. return procinfo
  291. def start_dhcp6(self):
  292. self.dhcp6 = True
  293. procinfo = ProcessInfo('b10-dhcp6', ['/bin/false'])
  294. procinfo.pid = 13
  295. return procinfo
  296. def start_dhcp4(self):
  297. self.dhcp4 = True
  298. procinfo = ProcessInfo('b10-dhcp4', ['/bin/false'])
  299. procinfo.pid = 14
  300. return procinfo
  301. def stop_process(self, process, recipient):
  302. procmap = { 'b10-auth': self.stop_auth,
  303. 'b10-resolver': self.stop_resolver,
  304. 'b10-xfrout': self.stop_xfrout,
  305. 'b10-xfrin': self.stop_xfrin,
  306. 'b10-zonemgr': self.stop_zonemgr,
  307. 'b10-stats': self.stop_stats,
  308. 'b10-stats-httpd': self.stop_stats_httpd,
  309. 'b10-cmdctl': self.stop_cmdctl }
  310. procmap[process]()
  311. # Some functions to pretend we stop processes, use by stop_process
  312. def stop_msgq(self):
  313. if self.msgq:
  314. del self.processes[2]
  315. self.msgq = False
  316. def stop_cfgmgr(self):
  317. if self.cfgmgr:
  318. del self.processes[3]
  319. self.cfgmgr = False
  320. def stop_auth(self):
  321. if self.auth:
  322. del self.processes[5]
  323. self.auth = False
  324. def stop_resolver(self):
  325. if self.resolver:
  326. del self.processes[6]
  327. self.resolver = False
  328. def stop_xfrout(self):
  329. if self.xfrout:
  330. del self.processes[7]
  331. self.xfrout = False
  332. def stop_xfrin(self):
  333. if self.xfrin:
  334. del self.processes[8]
  335. self.xfrin = False
  336. def stop_zonemgr(self):
  337. if self.zonemgr:
  338. del self.processes[9]
  339. self.zonemgr = False
  340. def stop_stats(self):
  341. if self.stats:
  342. del self.processes[10]
  343. self.stats = False
  344. def stop_stats_httpd(self):
  345. if self.stats_httpd:
  346. del self.processes[11]
  347. self.stats_httpd = False
  348. def stop_cmdctl(self):
  349. if self.cmdctl:
  350. del self.processes[12]
  351. self.cmdctl = False
  352. class TestStartStopProcessesBob(unittest.TestCase):
  353. """
  354. Check that the start_all_processes method starts the right combination
  355. of processes and that the right processes are started and stopped
  356. according to changes in configuration.
  357. """
  358. def check_environment_unchanged(self):
  359. # Check whether the environment has not been changed
  360. self.assertEqual(original_os_environ, os.environ)
  361. def check_started(self, bob, core, auth, resolver):
  362. """
  363. Check that the right sets of services are started. The ones that
  364. should be running are specified by the core, auth and resolver parameters
  365. (they are groups of processes, eg. auth means b10-auth, -xfrout, -xfrin
  366. and -zonemgr).
  367. """
  368. self.assertEqual(bob.msgq, core)
  369. self.assertEqual(bob.cfgmgr, core)
  370. self.assertEqual(bob.ccsession, core)
  371. self.assertEqual(bob.creator, core)
  372. self.assertEqual(bob.auth, auth)
  373. self.assertEqual(bob.resolver, resolver)
  374. self.assertEqual(bob.xfrout, auth)
  375. self.assertEqual(bob.xfrin, auth)
  376. self.assertEqual(bob.zonemgr, auth)
  377. self.assertEqual(bob.stats, core)
  378. self.assertEqual(bob.stats_httpd, core)
  379. self.assertEqual(bob.cmdctl, core)
  380. self.check_environment_unchanged()
  381. def check_preconditions(self, bob):
  382. self.check_started(bob, False, False, False)
  383. def check_started_none(self, bob):
  384. """
  385. Check that the situation is according to configuration where no servers
  386. should be started. Some processes still need to be running.
  387. """
  388. self.check_started(bob, True, False, False)
  389. self.check_environment_unchanged()
  390. def check_started_both(self, bob):
  391. """
  392. Check the situation is according to configuration where both servers
  393. (auth and resolver) are enabled.
  394. """
  395. self.check_started(bob, True, True, True)
  396. self.check_environment_unchanged()
  397. def check_started_auth(self, bob):
  398. """
  399. Check the set of processes needed to run auth only is started.
  400. """
  401. self.check_started(bob, True, True, False)
  402. self.check_environment_unchanged()
  403. def check_started_resolver(self, bob):
  404. """
  405. Check the set of processes needed to run resolver only is started.
  406. """
  407. self.check_started(bob, True, False, True)
  408. self.check_environment_unchanged()
  409. def check_started_dhcp(self, bob, v4, v6):
  410. """
  411. Check if proper combinations of DHCPv4 and DHCpv6 can be started
  412. """
  413. self.assertEqual(v4, bob.dhcp4)
  414. self.assertEqual(v6, bob.dhcp6)
  415. self.check_environment_unchanged()
  416. def construct_config(self, start_auth, start_resolver):
  417. # The things that are common, not turned on an off
  418. config = {}
  419. config['b10-stats'] = { 'kind': 'dispensable', 'address': 'Stats' }
  420. config['b10-stats-httpd'] = { 'kind': 'dispensable',
  421. 'address': 'StatsHttpd' }
  422. config['b10-cmdctl'] = { 'kind': 'needed', 'special': 'cmdctl' }
  423. if start_auth:
  424. config['b10-auth'] = { 'kind': 'needed', 'special': 'auth' }
  425. config['b10-xfrout'] = { 'kind': 'dispensable',
  426. 'address': 'Xfrout' }
  427. config['b10-xfrin'] = { 'kind': 'dispensable', 'special': 'xfrin' }
  428. config['b10-zonemgr'] = { 'kind': 'dispensable',
  429. 'address': 'Zonemgr' }
  430. if start_resolver:
  431. config['b10-resolver'] = { 'kind': 'needed',
  432. 'special': 'resolver' }
  433. return {'components': config}
  434. def test_config_start(self):
  435. """
  436. Test that the configuration starts and stops processes according
  437. to configuration changes.
  438. """
  439. # Create BoB and ensure correct initialization
  440. bob = MockBob()
  441. self.check_preconditions(bob)
  442. bob.start_all_processes()
  443. bob.runnable = True
  444. bob._BoB_started = True
  445. bob.config_handler(self.construct_config(False, False))
  446. self.check_started_none(bob)
  447. # Enable both at once
  448. bob.config_handler(self.construct_config(True, True))
  449. self.check_started_both(bob)
  450. # Not touched by empty change
  451. bob.config_handler({})
  452. self.check_started_both(bob)
  453. # Not touched by change to the same configuration
  454. bob.config_handler(self.construct_config(True, True))
  455. self.check_started_both(bob)
  456. # Turn them both off again
  457. bob.config_handler(self.construct_config(False, False))
  458. self.check_started_none(bob)
  459. # Not touched by empty change
  460. bob.config_handler({})
  461. self.check_started_none(bob)
  462. # Not touched by change to the same configuration
  463. bob.config_handler(self.construct_config(False, False))
  464. self.check_started_none(bob)
  465. # Start and stop auth separately
  466. bob.config_handler(self.construct_config(True, False))
  467. self.check_started_auth(bob)
  468. bob.config_handler(self.construct_config(False, False))
  469. self.check_started_none(bob)
  470. # Start and stop resolver separately
  471. bob.config_handler(self.construct_config(False, True))
  472. self.check_started_resolver(bob)
  473. bob.config_handler(self.construct_config(False, False))
  474. self.check_started_none(bob)
  475. # Alternate
  476. bob.config_handler(self.construct_config(True, False))
  477. self.check_started_auth(bob)
  478. bob.config_handler(self.construct_config(False, True))
  479. self.check_started_resolver(bob)
  480. bob.config_handler(self.construct_config(True, False))
  481. self.check_started_auth(bob)
  482. def test_config_start_once(self):
  483. """
  484. Tests that a process is started only once.
  485. """
  486. # Create BoB and ensure correct initialization
  487. bob = MockBob()
  488. self.check_preconditions(bob)
  489. bob.start_all_processes()
  490. bob._BoB_started = True
  491. bob.runnable = True
  492. bob.config_handler(self.construct_config(True, True))
  493. self.check_started_both(bob)
  494. bob.start_auth = lambda: self.fail("Started auth again")
  495. bob.start_xfrout = lambda: self.fail("Started xfrout again")
  496. bob.start_xfrin = lambda: self.fail("Started xfrin again")
  497. bob.start_zonemgr = lambda: self.fail("Started zonemgr again")
  498. bob.start_resolver = lambda: self.fail("Started resolver again")
  499. # Send again we want to start them. Should not do it, as they are.
  500. bob.config_handler(self.construct_config(True, True))
  501. def test_config_not_started_early(self):
  502. """
  503. Test that processes are not started by the config handler before
  504. startup.
  505. """
  506. bob = MockBob()
  507. self.check_preconditions(bob)
  508. bob.start_auth = lambda: self.fail("Started auth again")
  509. bob.start_xfrout = lambda: self.fail("Started xfrout again")
  510. bob.start_xfrin = lambda: self.fail("Started xfrin again")
  511. bob.start_zonemgr = lambda: self.fail("Started zonemgr again")
  512. bob.start_resolver = lambda: self.fail("Started resolver again")
  513. bob.config_handler({'start_auth': True, 'start_resolver': True})
  514. # Checks that DHCP (v4 and v6) processes are started when expected
  515. def test_start_dhcp(self):
  516. # Create BoB and ensure correct initialization
  517. bob = MockBob()
  518. self.check_preconditions(bob)
  519. bob.start_all_processes()
  520. bob._BoB_started = True
  521. bob.runnable = True
  522. bob.config_handler(self.construct_config(False, False))
  523. self.check_started_dhcp(bob, False, False)
  524. def test_start_dhcp_v6only(self):
  525. # Create BoB and ensure correct initialization
  526. bob = MockBob()
  527. self.check_preconditions(bob)
  528. # v6 only enabled
  529. bob.start_all_processes()
  530. bob.runnable = True
  531. bob._BoB_started = True
  532. config = self.construct_config(False, False)
  533. config['components']['b10-dhcp6'] = { 'kind': 'needed',
  534. 'address': 'Dhcp6' }
  535. bob.config_handler(config)
  536. self.check_started_dhcp(bob, False, True)
  537. # uncomment when dhcpv4 becomes implemented
  538. # v4 only enabled
  539. #bob.cfg_start_dhcp6 = False
  540. #bob.cfg_start_dhcp4 = True
  541. #self.check_started_dhcp(bob, True, False)
  542. # both v4 and v6 enabled
  543. #bob.cfg_start_dhcp6 = True
  544. #bob.cfg_start_dhcp4 = True
  545. #self.check_started_dhcp(bob, True, True)
  546. class MockComponent:
  547. def __init__(self, name, pid):
  548. self.name = lambda: name
  549. self.pid = lambda: pid
  550. class TestBossCmd(unittest.TestCase):
  551. def test_ping(self):
  552. """
  553. Confirm simple ping command works.
  554. """
  555. bob = MockBob()
  556. answer = bob.command_handler("ping", None)
  557. self.assertEqual(answer, {'result': [0, 'pong']})
  558. def test_show_processes(self):
  559. """
  560. Confirm getting a list of processes works.
  561. """
  562. bob = MockBob()
  563. answer = bob.command_handler("show_processes", None)
  564. self.assertEqual(answer, {'result': [0, []]})
  565. def test_show_processes_started(self):
  566. """
  567. Confirm getting a list of processes works.
  568. """
  569. bob = MockBob()
  570. bob.register_process(1, MockComponent('first', 1))
  571. bob.register_process(2, MockComponent('second', 2))
  572. answer = bob.command_handler("show_processes", None)
  573. processes = [[1, 'first'],
  574. [2, 'second']]
  575. self.assertEqual(answer, {'result': [0, processes]})
  576. class TestParseArgs(unittest.TestCase):
  577. """
  578. This tests parsing of arguments of the bind10 master process.
  579. """
  580. #TODO: Write tests for the original parsing, bad options, etc.
  581. def test_no_opts(self):
  582. """
  583. Test correct default values when no options are passed.
  584. """
  585. options = parse_args([], TestOptParser)
  586. self.assertEqual(None, options.data_path)
  587. self.assertEqual(None, options.config_file)
  588. self.assertEqual(None, options.cmdctl_port)
  589. def test_data_path(self):
  590. """
  591. Test it can parse the data path.
  592. """
  593. self.assertRaises(OptsError, parse_args, ['-p'], TestOptParser)
  594. self.assertRaises(OptsError, parse_args, ['--data-path'],
  595. TestOptParser)
  596. options = parse_args(['-p', '/data/path'], TestOptParser)
  597. self.assertEqual('/data/path', options.data_path)
  598. options = parse_args(['--data-path=/data/path'], TestOptParser)
  599. self.assertEqual('/data/path', options.data_path)
  600. def test_config_filename(self):
  601. """
  602. Test it can parse the config switch.
  603. """
  604. self.assertRaises(OptsError, parse_args, ['-c'], TestOptParser)
  605. self.assertRaises(OptsError, parse_args, ['--config-file'],
  606. TestOptParser)
  607. options = parse_args(['-c', 'config-file'], TestOptParser)
  608. self.assertEqual('config-file', options.config_file)
  609. options = parse_args(['--config-file=config-file'], TestOptParser)
  610. self.assertEqual('config-file', options.config_file)
  611. def test_cmdctl_port(self):
  612. """
  613. Test it can parse the command control port.
  614. """
  615. self.assertRaises(OptsError, parse_args, ['--cmdctl-port=abc'],
  616. TestOptParser)
  617. self.assertRaises(OptsError, parse_args, ['--cmdctl-port=100000000'],
  618. TestOptParser)
  619. self.assertRaises(OptsError, parse_args, ['--cmdctl-port'],
  620. TestOptParser)
  621. options = parse_args(['--cmdctl-port=1234'], TestOptParser)
  622. self.assertEqual(1234, options.cmdctl_port)
  623. def test_brittle(self):
  624. """
  625. Test we can use the "brittle" flag.
  626. """
  627. options = parse_args([], TestOptParser)
  628. self.assertFalse(options.brittle)
  629. options = parse_args(['--brittle'], TestOptParser)
  630. self.assertTrue(options.brittle)
  631. class TestPIDFile(unittest.TestCase):
  632. def setUp(self):
  633. self.pid_file = '@builddir@' + os.sep + 'bind10.pid'
  634. if os.path.exists(self.pid_file):
  635. os.unlink(self.pid_file)
  636. def tearDown(self):
  637. if os.path.exists(self.pid_file):
  638. os.unlink(self.pid_file)
  639. def check_pid_file(self):
  640. # dump PID to the file, and confirm the content is correct
  641. dump_pid(self.pid_file)
  642. my_pid = os.getpid()
  643. self.assertEqual(my_pid, int(open(self.pid_file, "r").read()))
  644. def test_dump_pid(self):
  645. self.check_pid_file()
  646. # make sure any existing content will be removed
  647. open(self.pid_file, "w").write('dummy data\n')
  648. self.check_pid_file()
  649. def test_unlink_pid_file_notexist(self):
  650. dummy_data = 'dummy_data\n'
  651. open(self.pid_file, "w").write(dummy_data)
  652. unlink_pid_file("no_such_pid_file")
  653. # the file specified for unlink_pid_file doesn't exist,
  654. # and the original content of the file should be intact.
  655. self.assertEqual(dummy_data, open(self.pid_file, "r").read())
  656. def test_dump_pid_with_none(self):
  657. # Check the behavior of dump_pid() and unlink_pid_file() with None.
  658. # This should be no-op.
  659. dump_pid(None)
  660. self.assertFalse(os.path.exists(self.pid_file))
  661. dummy_data = 'dummy_data\n'
  662. open(self.pid_file, "w").write(dummy_data)
  663. unlink_pid_file(None)
  664. self.assertEqual(dummy_data, open(self.pid_file, "r").read())
  665. def test_dump_pid_failure(self):
  666. # the attempt to open file will fail, which should result in exception.
  667. self.assertRaises(IOError, dump_pid,
  668. 'nonexistent_dir' + os.sep + 'bind10.pid')
  669. # TODO: Do we want brittle mode? Probably yes. So we need to re-enable to after that.
  670. @unittest.skip("Brittle mode temporarily broken")
  671. class TestBrittle(unittest.TestCase):
  672. def test_brittle_disabled(self):
  673. bob = MockBob()
  674. bob.start_all_processes()
  675. bob.runnable = True
  676. bob.reap_children()
  677. self.assertTrue(bob.runnable)
  678. def simulated_exit(self):
  679. ret_val = self.exit_info
  680. self.exit_info = (0, 0)
  681. return ret_val
  682. def test_brittle_enabled(self):
  683. bob = MockBob()
  684. bob.start_all_processes()
  685. bob.runnable = True
  686. bob.brittle = True
  687. self.exit_info = (5, 0)
  688. bob._get_process_exit_status = self.simulated_exit
  689. old_stdout = sys.stdout
  690. sys.stdout = open("/dev/null", "w")
  691. bob.reap_children()
  692. sys.stdout = old_stdout
  693. self.assertFalse(bob.runnable)
  694. class TestBossComponents(unittest.TestCase):
  695. """
  696. Test the boss propagates component configuration properly to the
  697. component configurator and acts sane.
  698. """
  699. def setUp(self):
  700. self.__param = None
  701. self.__called = False
  702. self.__compconfig = {
  703. 'comp': {
  704. 'kind': 'needed',
  705. 'process': 'cat'
  706. }
  707. }
  708. def __unary_hook(self, param):
  709. """
  710. A hook function that stores the parameter for later examination.
  711. """
  712. self.__param = param
  713. def __nullary_hook(self):
  714. """
  715. A hook function that notes down it was called.
  716. """
  717. self.__called = True
  718. def __check_core(self, config):
  719. """
  720. A function checking that the config contains parts for the valid
  721. core component configuration.
  722. """
  723. self.assertIsNotNone(config)
  724. for component in ['sockcreator', 'msgq', 'cfgmgr']:
  725. self.assertTrue(component in config)
  726. self.assertEqual(component, config[component]['special'])
  727. self.assertEqual('core', config[component]['kind'])
  728. def __check_extended(self, config):
  729. """
  730. This checks that the config contains the core and one more component.
  731. """
  732. self.__check_core(config)
  733. self.assertTrue('comp' in config)
  734. self.assertEqual('cat', config['comp']['process'])
  735. self.assertEqual('needed', config['comp']['kind'])
  736. self.assertEqual(4, len(config))
  737. def test_correct_run(self):
  738. """
  739. Test the situation when we run in usual scenario, nothing fails,
  740. we just start, reconfigure and then stop peacefully.
  741. """
  742. bob = MockBob()
  743. # Start it
  744. orig = bob._component_configurator.startup
  745. bob._component_configurator.startup = self.__unary_hook
  746. bob.start_all_processes()
  747. bob._component_configurator.startup = orig
  748. self.__check_core(self.__param)
  749. self.assertEqual(3, len(self.__param))
  750. # Reconfigure it
  751. self.__param = None
  752. orig = bob._component_configurator.reconfigure
  753. bob._component_configurator.reconfigure = self.__unary_hook
  754. # Otherwise it does not work
  755. bob.runnable = True
  756. bob.config_handler({'components': self.__compconfig})
  757. self.__check_extended(self.__param)
  758. currconfig = self.__param
  759. # If we reconfigure it, but it does not contain the components part,
  760. # nothing is called
  761. bob.config_handler({})
  762. self.assertEqual(self.__param, currconfig)
  763. self.__param = None
  764. bob._component_configurator.reconfigure = orig
  765. # Check a configuration that messes up the core components is rejected.
  766. compconf = dict(self.__compconfig)
  767. compconf['msgq'] = { 'process': 'echo' }
  768. result = bob.config_handler({'components': compconf})
  769. # Check it rejected it
  770. self.assertEqual(1, result['result'][0])
  771. # We can't call shutdown, that one relies on the stuff in main
  772. # We check somewhere else that the shutdown is actually called
  773. # from there (the test_kills).
  774. def test_kills(self):
  775. """
  776. Test that the boss kills processes which don't want to stop.
  777. """
  778. bob = MockBob()
  779. killed = []
  780. class ImmortalComponent:
  781. """
  782. An immortal component. It does not stop when it is told so
  783. (anyway it is not told so). It does not die if it is killed
  784. the first time. It dies only when killed forcefully.
  785. """
  786. def kill(self, forcefull=False):
  787. killed.append(forcefull)
  788. if forcefull:
  789. bob.processes = {}
  790. def pid(self):
  791. return 1
  792. def name(self):
  793. return "Immortal"
  794. bob.processes = {}
  795. bob.register_process(1, ImmortalComponent())
  796. # While at it, we check the configurator shutdown is actually called
  797. orig = bob._component_configurator.shutdown
  798. bob._component_configurator.shutdown = self.__nullary_hook
  799. self.__called = False
  800. bob.shutdown()
  801. self.assertEqual([False, True], killed)
  802. self.assertTrue(self.__called)
  803. bob._component_configurator.shutdown = orig
  804. def test_component_shutdown(self):
  805. """
  806. Test the component_shutdown sets all variables accordingly.
  807. """
  808. bob = MockBob()
  809. self.assertRaises(Exception, bob.component_shutdown, 1)
  810. self.assertEqual(1, bob.exitcode)
  811. bob._BoB__started = True
  812. bob.runnable = True
  813. bob.component_shutdown(2)
  814. self.assertEqual(2, bob.exitcode)
  815. self.assertFalse(bob.runnable)
  816. def test_init_config(self):
  817. """
  818. Test initial configuration is loaded.
  819. """
  820. bob = MockBob()
  821. # Start it
  822. bob._component_configurator.reconfigure = self.__unary_hook
  823. # We need to return the original read_bind10_config
  824. bob.read_bind10_config = lambda: BoB.read_bind10_config(bob)
  825. # And provide a session to read the data from
  826. class CC:
  827. pass
  828. bob.ccs = CC()
  829. bob.ccs.get_full_config = lambda: {'components': self.__compconfig}
  830. bob.start_all_processes()
  831. self.__check_extended(self.__param)
  832. if __name__ == '__main__':
  833. # store os.environ for test_unchanged_environment
  834. original_os_environ = copy.deepcopy(os.environ)
  835. isc.log.resetUnitTestRootLogger()
  836. unittest.main()