component_test.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. # Copyright (C) 2011 Internet Systems Consortium, Inc. ("ISC")
  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. Tests for the bind10.component module
  17. """
  18. import unittest
  19. import isc.log
  20. import time
  21. import copy
  22. from isc.bind10.component import Component, Configurator, specials
  23. class TestError(Exception):
  24. """
  25. Just a private exception not known to anybody we use for our tests.
  26. """
  27. pass
  28. class BossUtils:
  29. """
  30. A class that brings some utilities for pretending we're Boss.
  31. This is expected to be inherited by the testcases themself.
  32. """
  33. def setUp(self):
  34. """
  35. Part of setup. Should be called by descendand's setUp.
  36. """
  37. self._shutdown = False
  38. self._exitcode = None
  39. # Back up the time function, we may want to replace it with something
  40. self.__orig_time = isc.bind10.component.time.time
  41. def tearDown(self):
  42. """
  43. Clean up after tests. If the descendand implements a tearDown, it
  44. should call this method internally.
  45. """
  46. # Return the original time function
  47. isc.bind10.component.time.time = self.__orig_time
  48. def shutdown(self, exitcode=0):
  49. """
  50. Mock function to shut down. We just note we were asked to do so.
  51. """
  52. self._shutdown = True
  53. self._exitcode = None
  54. def _timeskip(self):
  55. """
  56. Skip in time to future some 30s. Implemented by replacing the
  57. time.time function in the tested module with function that returns
  58. current time increased by 30.
  59. """
  60. tm = time.time()
  61. isc.bind10.component.time.time = lambda: tm + 30
  62. class ComponentTests(BossUtils, unittest.TestCase):
  63. """
  64. Tests for the bind10.component.Component class
  65. """
  66. def setUp(self):
  67. """
  68. Pretend a newly started system.
  69. """
  70. BossUtils.setUp(self)
  71. self._shutdown = False
  72. self._exitcode = None
  73. self.__start_called = False
  74. self.__stop_called = False
  75. self.__failed_called = False
  76. def __start(self):
  77. """
  78. Mock function, installed into the component into start_internal.
  79. This only notes the component was "started".
  80. """
  81. self.__start_called = True
  82. def __stop(self):
  83. """
  84. Mock function, installed into the component into stop_internal.
  85. This only notes the component was "stopped".
  86. """
  87. self.__stop_called = True
  88. def __fail(self):
  89. """
  90. Mock function, installed into the component into failed_internal.
  91. This only notes the component called the method.
  92. """
  93. self.__failed_called = True
  94. def __fail_to_start(self):
  95. """
  96. Mock function. It can be installed into the component's start_internal
  97. to simulate a component that fails to start by raising an exception.
  98. """
  99. orig_started = self.__start_called
  100. self.__start_called = True
  101. if not orig_started:
  102. # This one is from restart. Avoid infinite recursion for now.
  103. # FIXME: We should use the restart scheduler to avoid it, not this.
  104. raise TestError("Test error")
  105. def __create_component(self, kind):
  106. """
  107. Convenience function that creates a component of given kind
  108. and installs the mock functions into it so we can hook up into
  109. its behaviour.
  110. The process used is some nonsense, as this isn't used in this
  111. kind of tests and we pretend to be the boss.
  112. """
  113. component = Component('No process', self, kind)
  114. component.start_internal = self.__start
  115. component.stop_internal = self.__stop
  116. component.failed_internal = self.__fail
  117. return component
  118. def __check_startup(self, component):
  119. """
  120. Check that nothing was called yet. A newly created component should
  121. not get started right away, so this should pass after the creation.
  122. """
  123. self.assertFalse(self._shutdown)
  124. self.assertFalse(self.__start_called)
  125. self.assertFalse(self.__stop_called)
  126. self.assertFalse(self.__failed_called)
  127. self.assertFalse(component.running())
  128. # We can't stop or fail the component yet
  129. self.assertRaises(ValueError, component.stop)
  130. self.assertRaises(ValueError, component.failed)
  131. def __check_started(self, component):
  132. """
  133. Check the component was started, but not stopped anyhow yet.
  134. """
  135. self.assertFalse(self._shutdown)
  136. self.assertTrue(self.__start_called)
  137. self.assertFalse(self.__stop_called)
  138. self.assertFalse(self.__failed_called)
  139. self.assertTrue(component.running())
  140. def __check_dead(self, component):
  141. """
  142. Check the component is completely dead, and the server too.
  143. """
  144. self.assertTrue(self._shutdown)
  145. self.assertTrue(self.__start_called)
  146. self.assertFalse(self.__stop_called)
  147. self.assertTrue(self.__failed_called)
  148. self.assertNotEqual(0, self._exitcode)
  149. self.assertFalse(component.running())
  150. # Surely it can't be stopped again
  151. self.assertRaises(ValueError, component.stop)
  152. # Nor started
  153. self.assertRaises(ValueError, component.start)
  154. def __check_restarted(self, component):
  155. """
  156. Check the component restarted successfully.
  157. Currently, it is implemented as starting it again right away. This will
  158. change, it will register itself into the restart schedule in boss. But
  159. as the integration with boss is not clear yet, we don't know how
  160. exactly that will happen.
  161. Reset the self.__start_called to False before calling the function when
  162. the component should fail.
  163. """
  164. self.assertFalse(self._shutdown)
  165. self.assertTrue(self.__start_called)
  166. self.assertFalse(self.__stop_called)
  167. self.assertTrue(self.__failed_called)
  168. self.assertTrue(component.running())
  169. # Check it can't be started again
  170. self.assertRaises(ValueError, component.start)
  171. def __do_start_stop(self, kind):
  172. """
  173. This is a body of a test. It creates a componend of given kind,
  174. then starts it and stops it. It checks correct functions are called
  175. and the component's status is correct.
  176. It also checks the component can't be started/stopped twice.
  177. """
  178. # Create it and check it did not do any funny stuff yet
  179. component = self.__create_component(kind)
  180. self.__check_startup(component)
  181. # Start it and check it called the correct starting functions
  182. component.start()
  183. self.__check_started(component)
  184. # Check it can't be started twice
  185. self.assertRaises(ValueError, component.start)
  186. # Stop it again and check
  187. component.stop()
  188. self.assertFalse(self._shutdown)
  189. self.assertTrue(self.__start_called)
  190. self.assertTrue(self.__stop_called)
  191. self.assertFalse(self.__failed_called)
  192. self.assertFalse(component.running())
  193. # Check it can't be stopped twice
  194. self.assertRaises(ValueError, component.stop)
  195. # Or failed
  196. self.assertRaises(ValueError, component.failed)
  197. # But it can be started again if it is stopped
  198. # (no more checking here, just it doesn't crash)
  199. component.start()
  200. def test_start_stop_core(self):
  201. """
  202. A start-stop test for core component. See do_start_stop.
  203. """
  204. self.__do_start_stop('core')
  205. def test_start_stop_needed(self):
  206. """
  207. A start-stop test for needed component. See do_start_stop.
  208. """
  209. self.__do_start_stop('needed')
  210. def test_start_stop_dispensable(self):
  211. """
  212. A start-stop test for dispensable component. See do_start_stop.
  213. """
  214. self.__do_start_stop('dispensable')
  215. def test_start_fail_core(self):
  216. """
  217. Start and then fail a core component. It should stop the whole server.
  218. """
  219. # Just ordinary startup
  220. component = self.__create_component('core')
  221. self.__check_startup(component)
  222. component.start()
  223. self.__check_started(component)
  224. # Pretend the component died
  225. component.failed()
  226. # It should bring down the whole server
  227. self.__check_dead(component)
  228. def test_start_fail_core_later(self):
  229. """
  230. Start and then fail a core component, but let it be running for longer time.
  231. It should still stop the whole server.
  232. """
  233. # Just ordinary startup
  234. component = self.__create_component('core')
  235. self.__check_startup(component)
  236. component.start()
  237. self.__check_started(component)
  238. self._timeskip()
  239. # Pretend the componend died some time later
  240. component.failed()
  241. # Check the component is still dead
  242. self.__check_dead(component)
  243. def test_start_fail_needed(self):
  244. """
  245. Start and then fail a needed component. As this happens really soon after
  246. being started, it is considered failure to start and should bring down the
  247. whole server.
  248. """
  249. # Just ordinary startup
  250. component = self.__create_component('needed')
  251. self.__check_startup(component)
  252. component.start()
  253. self.__check_started(component)
  254. # Make it fail right away.
  255. component.failed()
  256. self.__check_dead(component)
  257. def test_start_fail_needed_later(self):
  258. """
  259. Start and then fail a needed component. But the failure is later on, so
  260. we just restart it and will be happy.
  261. """
  262. # Just ordinary startup
  263. component = self.__create_component('needed')
  264. self.__check_startup(component)
  265. component.start()
  266. self.__check_started(component)
  267. # Make it fail later on
  268. self.__start_called = False
  269. self._timeskip()
  270. component.failed()
  271. self.__check_restarted(component)
  272. def test_start_fail_dispensable(self):
  273. """
  274. Start and then fail a dispensable component. Should just get restarted.
  275. """
  276. # Just ordinary startup
  277. component = self.__create_component('needed')
  278. self.__check_startup(component)
  279. component.start()
  280. self.__check_started(component)
  281. # Make it fail right away
  282. self.__start_called = False
  283. component.failed()
  284. self.__check_restarted(component)
  285. def test_start_fail_dispensable(self):
  286. """
  287. Start and then later on fail a dispensable component. Should just get
  288. restarted.
  289. """
  290. # Just ordinary startup
  291. component = self.__create_component('needed')
  292. self.__check_startup(component)
  293. component.start()
  294. self.__check_started(component)
  295. # Make it fail later on
  296. self.__start_called = False
  297. self._timeskip()
  298. component.failed()
  299. self.__check_restarted(component)
  300. def test_fail_core(self):
  301. """
  302. Failure to start a core component. Should bring the system down
  303. and the exception should get through.
  304. """
  305. component = self.__create_component('core')
  306. self.__check_startup(component)
  307. component.start_internal = self.__fail_to_start
  308. self.assertRaises(TestError, component.start)
  309. self.__check_dead(component)
  310. def test_fail_needed(self):
  311. """
  312. Failure to start a needed component. Should bring the system down
  313. and the exception should get through.
  314. """
  315. component = self.__create_component('needed')
  316. self.__check_startup(component)
  317. component.start_internal = self.__fail_to_start
  318. self.assertRaises(TestError, component.start)
  319. self.__check_dead(component)
  320. def test_fail_dispensable(self):
  321. """
  322. Failure to start a dispensable component. The exception should get
  323. through, but it should be restarted.
  324. """
  325. component = self.__create_component('dispensable')
  326. self.__check_startup(component)
  327. component.start_internal = self.__fail_to_start
  328. self.assertRaises(TestError, component.start)
  329. self.__check_restarted(component)
  330. def test_bad_kind(self):
  331. """
  332. Test the component rejects nonsensual kinds. This includes bad
  333. capitalization.
  334. """
  335. for kind in ['Core', 'CORE', 'nonsense', 'need ed', 'required']:
  336. self.assertRaises(ValueError, Component, 'No process', self, kind)
  337. class TestComponent(Component):
  338. """
  339. A test component. It does not start any processes or so, it just logs
  340. information about what happens.
  341. """
  342. def __init__(self, owner, name, kind):
  343. """
  344. Initializes the component. The owner is the test that started the
  345. component. The logging will happen into it.
  346. The process is used as a name for the logging.
  347. """
  348. Component.__init__(self, name, owner, kind)
  349. self.__owner = owner
  350. self.__name = name
  351. self.log('init')
  352. self.log(kind)
  353. def log(self, event):
  354. """
  355. Log an event into the owner. The owner can then check the correct
  356. order of events that happened.
  357. """
  358. self.__owner.log.append((self.__name, event))
  359. def start_internal(self):
  360. self.log('start')
  361. def stop_internal(self):
  362. self.log('stop')
  363. def failed_internal(self):
  364. self.log('failed')
  365. class FailComponent(Component):
  366. """
  367. A mock component that fails whenever it is started.
  368. """
  369. def start_internal(self):
  370. raise TestError("test error")
  371. class ConfiguratorTest(BossUtils, unittest.TestCase):
  372. """
  373. Tests for the configurator.
  374. """
  375. def setUp(self):
  376. """
  377. Insert the special evaluated test components we use and prepare the
  378. log. Also provide some data for the tests and prepare us to pretend
  379. we're boss.
  380. """
  381. BossUtils.setUp(self)
  382. # We put our functions inside instead of class constructors,
  383. # so we can look into what is happening more easily
  384. self.__orig_specials = copy.copy(specials)
  385. specials['test'] = self.__component_test
  386. self.log = []
  387. # The core "hardcoded" configuration
  388. self.__core = {
  389. 'core1': {
  390. 'priority': 5,
  391. 'process': 'core1',
  392. 'special': 'test',
  393. 'kind': 'core'
  394. },
  395. 'core2': {
  396. 'process': 'core2',
  397. 'special': 'test',
  398. 'kind': 'core'
  399. },
  400. 'core3': {
  401. 'process': 'core3',
  402. 'priority': 3,
  403. 'special': 'test',
  404. 'kind': 'core'
  405. }
  406. }
  407. # How they should be started. They are created in the order they are
  408. # found in the dict, but then they should be started by priority.
  409. # This expects that the same dict returns its keys in the same order
  410. # every time
  411. self.__core_log_create = []
  412. for core in self.__core.keys():
  413. self.__core_log_create.append((core, 'init'))
  414. self.__core_log_create.append((core, 'core'))
  415. self.__core_log_start = [('core1', 'start'), ('core3', 'start'),
  416. ('core2', 'start')]
  417. self.__core_log = self.__core_log_create + self.__core_log_start
  418. def tearDown(self):
  419. """
  420. Clean up the special evaluated test components and other stuff.
  421. """
  422. BossUtils.tearDown(self)
  423. specials = self.__orig_specials
  424. def __component_test(self, process, boss, kind):
  425. """
  426. Create a test component. It will log events to us.
  427. """
  428. self.assertEqual(self, boss)
  429. return TestComponent(self, process, kind)
  430. def test_init(self):
  431. """
  432. Tests the configurator can be created and it does not create
  433. any components yet, nor does it remember anything.
  434. """
  435. configurator = Configurator(self)
  436. self.assertEqual([], self.log)
  437. self.assertEqual({}, configurator._components)
  438. self.assertEqual({}, configurator._old_config)
  439. self.assertFalse(configurator._running)
  440. def test_run_plan(self):
  441. """
  442. Test the internal function of running plans. Just see it can handle
  443. the commands in the given order. We see that by the log.
  444. Also includes one that raises, so we see it just stops there.
  445. """
  446. # Prepare the configurator and the plan
  447. configurator = Configurator(self)
  448. started = self.__component_test('second', self, 'dispensable')
  449. started.start()
  450. stopped = self.__component_test('first', self, 'core')
  451. configurator._components = {'second': started}
  452. plan = [
  453. {
  454. 'component': stopped,
  455. 'command': 'start',
  456. 'name': 'first'
  457. },
  458. {
  459. 'component': started,
  460. 'command': 'stop',
  461. 'name': 'second'
  462. },
  463. {
  464. 'component': FailComponent('third', self, 'needed'),
  465. 'command': 'start',
  466. 'name': 'third'
  467. },
  468. {
  469. 'component': self.__component_test('fourth', self, 'core'),
  470. 'command': 'start',
  471. 'name': 'fourth'
  472. }
  473. ]
  474. # Don't include the preparation into the log
  475. self.log = []
  476. # The error from the third component is propagated
  477. self.assertRaises(TestError, configurator._run_plan, plan)
  478. # The first two were handled, the rest not, due to the exception
  479. self.assertEqual([('first', 'start'), ('second', 'stop')], self.log)
  480. self.assertEqual({'first': stopped}, configurator._components)
  481. def test_build_plan(self):
  482. """
  483. Test building the plan correctly. Not complete yet, this grows as we
  484. add more ways of changing the plan.
  485. """
  486. configurator = Configurator(self)
  487. plan = configurator._build_plan({}, self.__core)
  488. # This should have created the components
  489. self.assertEqual(self.__core_log_create, self.log)
  490. self.assertEqual(3, len(plan))
  491. for (task, name) in zip(plan, ['core1', 'core3', 'core2']):
  492. self.assertTrue('component' in task)
  493. self.assertEqual('start', task['command'])
  494. self.assertEqual(name, task['name'])
  495. # A plan to go from older state to newer one containing more components
  496. bigger = copy.copy(self.__core)
  497. bigger['additional'] = {
  498. 'priority': 6,
  499. 'special': 'test',
  500. 'process': 'additional',
  501. 'kind': 'needed'
  502. }
  503. self.log = []
  504. plan = configurator._build_plan(self.__core, bigger)
  505. self.assertEqual([('additional', 'init'), ('additional', 'needed')],
  506. self.log)
  507. self.assertEqual(1, len(plan))
  508. self.assertTrue('component' in plan[0])
  509. component = plan[0]['component']
  510. self.assertEqual('start', plan[0]['command'])
  511. self.assertEqual('additional', plan[0]['name'])
  512. # Now remove the one component again
  513. # We run the plan so the component is wired into internal structures
  514. configurator._run_plan(plan)
  515. self.log = []
  516. plan = configurator._build_plan(bigger, self.__core)
  517. self.assertEqual([], self.log)
  518. self.assertEqual([{
  519. 'command': 'stop',
  520. 'component': component
  521. }], plan)
  522. # TODO: More scenarios for changes between configurations are needed
  523. def test_startup(self):
  524. """
  525. Passes some configuration to the startup method and sees if
  526. the components are started up.
  527. It also checks the components are kept inside the configurator.
  528. """
  529. configurator = Configurator(self)
  530. configurator.startup(self.__core)
  531. self.assertEqual(self.__core_log, self.log)
  532. for core in self.__core.keys():
  533. self.assertTrue(core in configurator._components)
  534. self.assertEqual(self.__core, configurator._old_config)
  535. self.assertTrue(configurator._running)
  536. # It can't be started twice
  537. self.assertRaises(ValueError, configurator.startup, self.__core)
  538. if __name__ == '__main__':
  539. isc.log.init("bind10") # FIXME Should this be needed?
  540. isc.log.resetUnitTestRootLogger()
  541. unittest.main()