component_test.py 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097
  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 isc.bind10.component module and the
  17. isc.bind10.special_component module.
  18. """
  19. import unittest
  20. import isc.log
  21. import time
  22. import copy
  23. from isc.bind10.component import Component, Configurator, BaseComponent
  24. import isc.bind10.special_component
  25. class TestError(Exception):
  26. """
  27. Just a private exception not known to anybody we use for our tests.
  28. """
  29. pass
  30. class BossUtils:
  31. """
  32. A class that brings some utilities for pretending we're Boss.
  33. This is expected to be inherited by the testcases themselves.
  34. """
  35. def setUp(self):
  36. """
  37. Part of setup. Should be called by descendant's setUp.
  38. """
  39. self._shutdown = False
  40. self._exitcode = None
  41. # Back up the time function, we may want to replace it with something
  42. self.__orig_time = isc.bind10.component.time.time
  43. def tearDown(self):
  44. """
  45. Clean up after tests. If the descendant implements a tearDown, it
  46. should call this method internally.
  47. """
  48. # Return the original time function
  49. isc.bind10.component.time.time = self.__orig_time
  50. def component_shutdown(self, exitcode=0):
  51. """
  52. Mock function to shut down. We just note we were asked to do so.
  53. """
  54. self._shutdown = True
  55. self._exitcode = exitcode
  56. def _timeskip(self):
  57. """
  58. Skip in time to future some 30s. Implemented by replacing the
  59. time.time function in the tested module with function that returns
  60. current time increased by 30.
  61. """
  62. tm = time.time()
  63. isc.bind10.component.time.time = lambda: tm + 30
  64. # Few functions that pretend to start something. Part of pretending of
  65. # being boss.
  66. def start_msgq(self):
  67. pass
  68. def start_cfgmgr(self):
  69. pass
  70. def start_auth(self):
  71. pass
  72. def start_resolver(self):
  73. pass
  74. def start_cmdctl(self):
  75. pass
  76. class ComponentTests(BossUtils, unittest.TestCase):
  77. """
  78. Tests for the bind10.component.Component class
  79. """
  80. def setUp(self):
  81. """
  82. Pretend a newly started system.
  83. """
  84. BossUtils.setUp(self)
  85. self._shutdown = False
  86. self._exitcode = None
  87. self.__start_called = False
  88. self.__stop_called = False
  89. self.__failed_called = False
  90. self.__registered_processes = {}
  91. self.__stop_process_params = None
  92. self.__start_simple_params = None
  93. # Pretending to be boss
  94. self.gid = None
  95. self.__gid_set = None
  96. self.uid = None
  97. self.__uid_set = None
  98. def __start(self):
  99. """
  100. Mock function, installed into the component into _start_internal.
  101. This only notes the component was "started".
  102. """
  103. self.__start_called = True
  104. def __stop(self):
  105. """
  106. Mock function, installed into the component into _stop_internal.
  107. This only notes the component was "stopped".
  108. """
  109. self.__stop_called = True
  110. def __fail(self):
  111. """
  112. Mock function, installed into the component into _failed_internal.
  113. This only notes the component called the method.
  114. """
  115. self.__failed_called = True
  116. def __fail_to_start(self):
  117. """
  118. Mock function. It can be installed into the component's _start_internal
  119. to simulate a component that fails to start by raising an exception.
  120. """
  121. orig_started = self.__start_called
  122. self.__start_called = True
  123. if not orig_started:
  124. # This one is from restart. Avoid infinite recursion for now.
  125. # FIXME: We should use the restart scheduler to avoid it, not this.
  126. raise TestError("Test error")
  127. def __create_component(self, kind):
  128. """
  129. Convenience function that creates a component of given kind
  130. and installs the mock functions into it so we can hook up into
  131. its behaviour.
  132. The process used is some nonsense, as this isn't used in this
  133. kind of tests and we pretend to be the boss.
  134. """
  135. component = Component('No process', self, kind, 'homeless', [])
  136. component._start_internal = self.__start
  137. component._stop_internal = self.__stop
  138. component._failed_internal = self.__fail
  139. return component
  140. def test_name(self):
  141. """
  142. Test the name provides whatever we passed to the constructor as process.
  143. """
  144. component = self.__create_component('core')
  145. self.assertEqual('No process', component.name())
  146. def test_address(self):
  147. """
  148. Test the address provides whatever we passed to the constructor as process.
  149. """
  150. component = self.__create_component('core')
  151. self.assertEqual("homeless", component.address())
  152. def test_guts(self):
  153. """
  154. Test the correct data are stored inside the component.
  155. """
  156. component = self.__create_component('core')
  157. self.assertEqual(self, component._boss)
  158. self.assertEqual("No process", component._process)
  159. self.assertEqual(None, component._start_func)
  160. self.assertEqual("homeless", component._address)
  161. self.assertEqual([], component._params)
  162. def __check_startup(self, component):
  163. """
  164. Check that nothing was called yet. A newly created component should
  165. not get started right away, so this should pass after the creation.
  166. """
  167. self.assertFalse(self._shutdown)
  168. self.assertFalse(self.__start_called)
  169. self.assertFalse(self.__stop_called)
  170. self.assertFalse(self.__failed_called)
  171. self.assertFalse(component.running())
  172. self.assertFalse(component.is_failed())
  173. # We can't stop or fail the component yet
  174. self.assertRaises(ValueError, component.stop)
  175. self.assertRaises(ValueError, component.failed, 1)
  176. def __check_started(self, component):
  177. """
  178. Check the component was started, but not stopped anyhow yet.
  179. """
  180. self.assertFalse(self._shutdown)
  181. self.assertTrue(self.__start_called)
  182. self.assertFalse(self.__stop_called)
  183. self.assertFalse(self.__failed_called)
  184. self.assertTrue(component.running())
  185. self.assertFalse(component.is_failed())
  186. def __check_dead(self, component):
  187. """
  188. Check the component is completely dead, and the server too.
  189. """
  190. self.assertTrue(self._shutdown)
  191. self.assertTrue(self.__start_called)
  192. self.assertFalse(self.__stop_called)
  193. self.assertTrue(self.__failed_called)
  194. self.assertEqual(1, self._exitcode)
  195. self.assertFalse(component.running())
  196. self.assertFalse(component.is_failed())
  197. # Surely it can't be stopped when already dead
  198. self.assertRaises(ValueError, component.stop)
  199. # Nor started
  200. self.assertRaises(ValueError, component.start)
  201. # Nor it can fail again
  202. self.assertRaises(ValueError, component.failed, 1)
  203. def __check_restarted(self, component):
  204. """
  205. Check the component restarted successfully.
  206. Reset the self.__start_called to False before calling the function when
  207. the component should fail.
  208. """
  209. self.assertFalse(self._shutdown)
  210. self.assertTrue(self.__start_called)
  211. self.assertFalse(self.__stop_called)
  212. self.assertTrue(self.__failed_called)
  213. self.assertTrue(component.running())
  214. self.assertFalse(component.is_failed())
  215. # Check it can't be started again
  216. self.assertRaises(ValueError, component.start)
  217. def __check_not_restarted(self, component):
  218. """
  219. Check the component has not (yet) restarted successfully.
  220. """
  221. self.assertFalse(self._shutdown)
  222. self.assertTrue(self.__start_called)
  223. self.assertFalse(self.__stop_called)
  224. self.assertTrue(self.__failed_called)
  225. self.assertFalse(component.running())
  226. self.assertTrue(component.is_failed())
  227. def __do_start_stop(self, kind):
  228. """
  229. This is a body of a test. It creates a component of given kind,
  230. then starts it and stops it. It checks correct functions are called
  231. and the component's status is correct.
  232. It also checks the component can't be started/stopped twice.
  233. """
  234. # Create it and check it did not do any funny stuff yet
  235. component = self.__create_component(kind)
  236. self.__check_startup(component)
  237. # Start it and check it called the correct starting functions
  238. component.start()
  239. self.__check_started(component)
  240. # Check it can't be started twice
  241. self.assertRaises(ValueError, component.start)
  242. # Stop it again and check
  243. component.stop()
  244. self.assertFalse(self._shutdown)
  245. self.assertTrue(self.__start_called)
  246. self.assertTrue(self.__stop_called)
  247. self.assertFalse(self.__failed_called)
  248. self.assertFalse(component.running())
  249. self.assertFalse(component.is_failed())
  250. # Check it can't be stopped twice
  251. self.assertRaises(ValueError, component.stop)
  252. # Or failed
  253. self.assertRaises(ValueError, component.failed, 1)
  254. # But it can be started again if it is stopped
  255. # (no more checking here, just it doesn't crash)
  256. component.start()
  257. def test_start_stop_core(self):
  258. """
  259. A start-stop test for core component. See do_start_stop.
  260. """
  261. self.__do_start_stop('core')
  262. def test_start_stop_needed(self):
  263. """
  264. A start-stop test for needed component. See do_start_stop.
  265. """
  266. self.__do_start_stop('needed')
  267. def test_start_stop_dispensable(self):
  268. """
  269. A start-stop test for dispensable component. See do_start_stop.
  270. """
  271. self.__do_start_stop('dispensable')
  272. def test_start_fail_core(self):
  273. """
  274. Start and then fail a core component. It should stop the whole server.
  275. """
  276. # Just ordinary startup
  277. component = self.__create_component('core')
  278. self.__check_startup(component)
  279. component.start()
  280. self.__check_started(component)
  281. # Pretend the component died
  282. restarted = component.failed(1)
  283. # Since it is a core component, it should not be restarted
  284. self.assertFalse(restarted)
  285. # It should bring down the whole server
  286. self.__check_dead(component)
  287. def test_start_fail_core_later(self):
  288. """
  289. Start and then fail a core component, but let it be running for longer time.
  290. It should still stop the whole server.
  291. """
  292. # Just ordinary startup
  293. component = self.__create_component('core')
  294. self.__check_startup(component)
  295. component.start()
  296. self.__check_started(component)
  297. self._timeskip()
  298. # Pretend the component died some time later
  299. restarted = component.failed(1)
  300. # Should not be restarted
  301. self.assertFalse(restarted)
  302. # Check the component is still dead
  303. self.__check_dead(component)
  304. def test_start_fail_needed(self):
  305. """
  306. Start and then fail a needed component. As this happens really soon after
  307. being started, it is considered failure to start and should bring down the
  308. whole server.
  309. """
  310. # Just ordinary startup
  311. component = self.__create_component('needed')
  312. self.__check_startup(component)
  313. component.start()
  314. self.__check_started(component)
  315. # Make it fail right away.
  316. restarted = component.failed(1)
  317. # Should not have restarted
  318. self.assertFalse(restarted)
  319. self.__check_dead(component)
  320. def test_start_fail_needed_later(self):
  321. """
  322. Start and then fail a needed component. But the failure is later on, so
  323. we just restart it and will be happy.
  324. """
  325. # Just ordinary startup
  326. component = self.__create_component('needed')
  327. self.__check_startup(component)
  328. component.start()
  329. self.__check_started(component)
  330. # Make it fail later on
  331. self.__start_called = False
  332. self._timeskip()
  333. restarted = component.failed(1)
  334. # Should have restarted
  335. self.assertTrue(restarted)
  336. self.__check_restarted(component)
  337. def test_start_fail_dispensable(self):
  338. """
  339. Start and then fail a dispensable component. Should not get restarted.
  340. """
  341. # Just ordinary startup
  342. component = self.__create_component('dispensable')
  343. self.__check_startup(component)
  344. component.start()
  345. self.__check_started(component)
  346. # Make it fail right away
  347. restarted = component.failed(1)
  348. # Should signal that it did not restart
  349. self.assertFalse(restarted)
  350. self.__check_not_restarted(component)
  351. def test_start_fail_dispensable_later(self):
  352. """
  353. Start and then later on fail a dispensable component. Should just get
  354. restarted.
  355. """
  356. # Just ordinary startup
  357. component = self.__create_component('dispensable')
  358. self.__check_startup(component)
  359. component.start()
  360. self.__check_started(component)
  361. # Make it fail later on
  362. self._timeskip()
  363. restarted = component.failed(1)
  364. # should signal that it restarted
  365. self.assertTrue(restarted)
  366. # and check if it really did
  367. self.__check_restarted(component)
  368. def test_start_fail_dispensable_restart_later(self):
  369. """
  370. Start and then fail a dispensable component, wait a bit and try to
  371. restart. Should get restarted after the wait.
  372. """
  373. # Just ordinary startup
  374. component = self.__create_component('dispensable')
  375. self.__check_startup(component)
  376. component.start()
  377. self.__check_started(component)
  378. # Make it fail immediately
  379. restarted = component.failed(1)
  380. # should signal that it did not restart
  381. self.assertFalse(restarted)
  382. self.__check_not_restarted(component)
  383. self._timeskip()
  384. # try to restart again
  385. restarted = component.restart()
  386. # should signal that it restarted
  387. self.assertTrue(restarted)
  388. # and check if it really did
  389. self.__check_restarted(component)
  390. def test_fail_core(self):
  391. """
  392. Failure to start a core component. Should bring the system down
  393. and the exception should get through.
  394. """
  395. component = self.__create_component('core')
  396. self.__check_startup(component)
  397. component._start_internal = self.__fail_to_start
  398. self.assertRaises(TestError, component.start)
  399. self.__check_dead(component)
  400. def test_fail_needed(self):
  401. """
  402. Failure to start a needed component. Should bring the system down
  403. and the exception should get through.
  404. """
  405. component = self.__create_component('needed')
  406. self.__check_startup(component)
  407. component._start_internal = self.__fail_to_start
  408. self.assertRaises(TestError, component.start)
  409. self.__check_dead(component)
  410. def test_fail_dispensable(self):
  411. """
  412. Failure to start a dispensable component. The exception should get
  413. through, but it should be restarted after a time skip.
  414. """
  415. component = self.__create_component('dispensable')
  416. self.__check_startup(component)
  417. component._start_internal = self.__fail_to_start
  418. self.assertRaises(TestError, component.start)
  419. # tell it to see if it must restart
  420. restarted = component.restart()
  421. # should not have restarted yet
  422. self.assertFalse(restarted)
  423. self.__check_not_restarted(component)
  424. self._timeskip()
  425. # tell it to see if it must restart and do so, with our vision of time
  426. restarted = component.restart()
  427. # should have restarted now
  428. self.assertTrue(restarted)
  429. self.__check_restarted(component)
  430. def test_component_start_time(self):
  431. """
  432. Check that original start time is set initially, and remains the same
  433. after a restart, while the internal __start_time does change
  434. """
  435. # Just ordinary startup
  436. component = self.__create_component('dispensable')
  437. self.__check_startup(component)
  438. self.assertIsNone(component._original_start_time)
  439. component.start()
  440. self.__check_started(component)
  441. self.assertIsNotNone(component._original_start_time)
  442. self.assertIsNotNone(component._BaseComponent__start_time)
  443. original_start_time = component._original_start_time
  444. start_time = component._BaseComponent__start_time
  445. # Not restarted yet, so they should be the same
  446. self.assertEqual(original_start_time, start_time)
  447. self._timeskip()
  448. # Make it fail
  449. restarted = component.failed(1)
  450. # should signal that it restarted
  451. self.assertTrue(restarted)
  452. # and check if it really did
  453. self.__check_restarted(component)
  454. # original start time should not have changed
  455. self.assertEqual(original_start_time, component._original_start_time)
  456. # but actual start time should
  457. self.assertNotEqual(start_time, component._BaseComponent__start_time)
  458. def test_bad_kind(self):
  459. """
  460. Test the component rejects nonsensical kinds. This includes bad
  461. capitalization.
  462. """
  463. for kind in ['Core', 'CORE', 'nonsense', 'need ed', 'required']:
  464. self.assertRaises(ValueError, Component, 'No process', self, kind)
  465. def test_pid_not_running(self):
  466. """
  467. Test that a componet that is not yet started doesn't have a PID.
  468. But it won't fail if asked for and return None.
  469. """
  470. for component_type in [Component,
  471. isc.bind10.special_component.SockCreator,
  472. isc.bind10.special_component.Msgq,
  473. isc.bind10.special_component.CfgMgr,
  474. isc.bind10.special_component.Auth,
  475. isc.bind10.special_component.Resolver,
  476. isc.bind10.special_component.CmdCtl]:
  477. component = component_type('none', self, 'needed')
  478. self.assertIsNone(component.pid())
  479. def test_kill_unstarted(self):
  480. """
  481. Try to kill the component if it's not started. Should not fail.
  482. We do not try to kill a running component, as we should not start
  483. it during unit tests.
  484. """
  485. component = Component('component', self, 'needed')
  486. component.kill()
  487. component.kill(True)
  488. def register_process(self, pid, process):
  489. """
  490. Part of pretending to be a boss
  491. """
  492. self.__registered_processes[pid] = process
  493. def test_component_attributes(self):
  494. """
  495. Test the default attributes of Component (not BaseComponent) and
  496. some of the methods we might be allowed to call.
  497. """
  498. class TestProcInfo:
  499. def __init__(self):
  500. self.pid = 42
  501. component = Component('component', self, 'needed', 'Address',
  502. ['hello'], TestProcInfo)
  503. self.assertEqual('component', component._process)
  504. self.assertEqual('component', component.name())
  505. self.assertIsNone(component._procinfo)
  506. self.assertIsNone(component.pid())
  507. self.assertEqual(['hello'], component._params)
  508. self.assertEqual('Address', component._address)
  509. self.assertFalse(component.running())
  510. self.assertEqual({}, self.__registered_processes)
  511. component.start()
  512. self.assertTrue(component.running())
  513. # Some versions of unittest miss assertIsInstance
  514. self.assertTrue(isinstance(component._procinfo, TestProcInfo))
  515. self.assertEqual(42, component.pid())
  516. self.assertEqual(component, self.__registered_processes.get(42))
  517. def stop_process(self, process, address, pid):
  518. """
  519. Part of pretending to be boss.
  520. """
  521. self.__stop_process_params = (process, address, pid)
  522. def start_simple(self, process):
  523. """
  524. Part of pretending to be boss.
  525. """
  526. self.__start_simple_params = process
  527. def test_component_start_stop_internal(self):
  528. """
  529. Test the behavior of _stop_internal and _start_internal.
  530. """
  531. component = Component('component', self, 'needed', 'Address')
  532. component.start()
  533. self.assertTrue(component.running())
  534. self.assertEqual('component', self.__start_simple_params)
  535. component.pid = lambda: 42
  536. component.stop()
  537. self.assertFalse(component.running())
  538. self.assertEqual(('component', 'Address', 42),
  539. self.__stop_process_params)
  540. def test_component_kill(self):
  541. """
  542. Check the kill is propagated. The case when component wasn't started
  543. yet is already tested elsewhere.
  544. """
  545. class Process:
  546. def __init__(self):
  547. self.killed = False
  548. self.terminated = False
  549. def kill(self):
  550. self.killed = True
  551. def terminate(self):
  552. self.terminated = True
  553. process = Process()
  554. class ProcInfo:
  555. def __init__(self):
  556. self.process = process
  557. self.pid = 42
  558. component = Component('component', self, 'needed', 'Address',
  559. [], ProcInfo)
  560. component.start()
  561. self.assertTrue(component.running())
  562. component.kill()
  563. self.assertTrue(process.terminated)
  564. self.assertFalse(process.killed)
  565. process.terminated = False
  566. component.kill(True)
  567. self.assertTrue(process.killed)
  568. self.assertFalse(process.terminated)
  569. def setgid(self, gid):
  570. self.__gid_set = gid
  571. def setuid(self, uid):
  572. self.__uid_set = uid
  573. class FakeCreator:
  574. def pid(self):
  575. return 42
  576. def terminate(self): pass
  577. def kill(self): pass
  578. def set_creator(self, creator):
  579. """
  580. Part of faking being the boss. Check the creator (faked as well)
  581. is passed here.
  582. """
  583. self.assertTrue(isinstance(creator, self.FakeCreator))
  584. def log_started(self, pid):
  585. """
  586. Part of faking the boss. Check the pid is the one of the fake creator.
  587. """
  588. self.assertEqual(42, pid)
  589. def test_creator(self):
  590. """
  591. Some tests around the SockCreator component.
  592. """
  593. component = isc.bind10.special_component.SockCreator(None, self,
  594. 'needed', None)
  595. orig_setgid = isc.bind10.special_component.posix.setgid
  596. orig_setuid = isc.bind10.special_component.posix.setuid
  597. isc.bind10.special_component.posix.setgid = self.setgid
  598. isc.bind10.special_component.posix.setuid = self.setuid
  599. orig_creator = \
  600. isc.bind10.special_component.isc.bind10.sockcreator.Creator
  601. # Just ignore the creator call
  602. isc.bind10.special_component.isc.bind10.sockcreator.Creator = \
  603. lambda path: self.FakeCreator()
  604. component.start()
  605. # No gid/uid set in boss, nothing called.
  606. self.assertIsNone(self.__gid_set)
  607. self.assertIsNone(self.__uid_set)
  608. # Doesn't do anything, but doesn't crash
  609. component.stop()
  610. component.kill()
  611. component.kill(True)
  612. self.gid = 4200
  613. self.uid = 42
  614. component = isc.bind10.special_component.SockCreator(None, self,
  615. 'needed', None)
  616. component.start()
  617. # This time, it get's called
  618. self.assertEqual(4200, self.__gid_set)
  619. self.assertEqual(42, self.__uid_set)
  620. isc.bind10.special_component.posix.setgid = orig_setgid
  621. isc.bind10.special_component.posix.setuid = orig_setuid
  622. isc.bind10.special_component.isc.bind10.sockcreator.Creator = \
  623. orig_creator
  624. class TestComponent(BaseComponent):
  625. """
  626. A test component. It does not start any processes or so, it just logs
  627. information about what happens.
  628. """
  629. def __init__(self, owner, name, kind, address=None, params=None):
  630. """
  631. Initializes the component. The owner is the test that started the
  632. component. The logging will happen into it.
  633. The process is used as a name for the logging.
  634. """
  635. BaseComponent.__init__(self, owner, kind)
  636. self.__owner = owner
  637. self.__name = name
  638. self.log('init')
  639. self.log(kind)
  640. self._address = address
  641. self._params = params
  642. def log(self, event):
  643. """
  644. Log an event into the owner. The owner can then check the correct
  645. order of events that happened.
  646. """
  647. self.__owner.log.append((self.__name, event))
  648. def _start_internal(self):
  649. self.log('start')
  650. def _stop_internal(self):
  651. self.log('stop')
  652. def _failed_internal(self):
  653. self.log('failed')
  654. def kill(self, forceful=False):
  655. self.log('killed')
  656. class FailComponent(BaseComponent):
  657. """
  658. A mock component that fails whenever it is started.
  659. """
  660. def __init__(self, name, boss, kind, address=None, params=None):
  661. BaseComponent.__init__(self, boss, kind)
  662. def _start_internal(self):
  663. raise TestError("test error")
  664. class ConfiguratorTest(BossUtils, unittest.TestCase):
  665. """
  666. Tests for the configurator.
  667. """
  668. def setUp(self):
  669. """
  670. Prepare some test data for the tests.
  671. """
  672. BossUtils.setUp(self)
  673. self.log = []
  674. # The core "hardcoded" configuration
  675. self.__core = {
  676. 'core1': {
  677. 'priority': 5,
  678. 'process': 'core1',
  679. 'special': 'test',
  680. 'kind': 'core'
  681. },
  682. 'core2': {
  683. 'process': 'core2',
  684. 'special': 'test',
  685. 'kind': 'core'
  686. },
  687. 'core3': {
  688. 'process': 'core3',
  689. 'priority': 3,
  690. 'special': 'test',
  691. 'kind': 'core'
  692. }
  693. }
  694. # How they should be started. They are created in the order they are
  695. # found in the dict, but then they should be started by priority.
  696. # This expects that the same dict returns its keys in the same order
  697. # every time
  698. self.__core_log_create = []
  699. for core in self.__core.keys():
  700. self.__core_log_create.append((core, 'init'))
  701. self.__core_log_create.append((core, 'core'))
  702. self.__core_log_start = [('core1', 'start'), ('core3', 'start'),
  703. ('core2', 'start')]
  704. self.__core_log = self.__core_log_create + self.__core_log_start
  705. self.__specials = { 'test': self.__component_test }
  706. def __component_test(self, process, boss, kind, address=None, params=None):
  707. """
  708. Create a test component. It will log events to us.
  709. """
  710. self.assertEqual(self, boss)
  711. return TestComponent(self, process, kind, address, params)
  712. def test_init(self):
  713. """
  714. Tests the configurator can be created and it does not create
  715. any components yet, nor does it remember anything.
  716. """
  717. configurator = Configurator(self, self.__specials)
  718. self.assertEqual([], self.log)
  719. self.assertEqual({}, configurator._components)
  720. self.assertFalse(configurator.running())
  721. def test_run_plan(self):
  722. """
  723. Test the internal function of running plans. Just see it can handle
  724. the commands in the given order. We see that by the log.
  725. Also includes one that raises, so we see it just stops there.
  726. """
  727. # Prepare the configurator and the plan
  728. configurator = Configurator(self, self.__specials)
  729. started = self.__component_test('second', self, 'dispensable')
  730. started.start()
  731. stopped = self.__component_test('first', self, 'core')
  732. configurator._components = {'second': started}
  733. plan = [
  734. {
  735. 'component': stopped,
  736. 'command': 'start',
  737. 'name': 'first',
  738. 'config': {'a': 1}
  739. },
  740. {
  741. 'component': started,
  742. 'command': 'stop',
  743. 'name': 'second',
  744. 'config': {}
  745. },
  746. {
  747. 'component': FailComponent('third', self, 'needed'),
  748. 'command': 'start',
  749. 'name': 'third',
  750. 'config': {}
  751. },
  752. {
  753. 'component': self.__component_test('fourth', self, 'core'),
  754. 'command': 'start',
  755. 'name': 'fourth',
  756. 'config': {}
  757. }
  758. ]
  759. # Don't include the preparation into the log
  760. self.log = []
  761. # The error from the third component is propagated
  762. self.assertRaises(TestError, configurator._run_plan, plan)
  763. # The first two were handled, the rest not, due to the exception
  764. self.assertEqual([('first', 'start'), ('second', 'stop')], self.log)
  765. self.assertEqual({'first': ({'a': 1}, stopped)},
  766. configurator._components)
  767. def __build_components(self, config):
  768. """
  769. Insert the components into the configuration to specify possible
  770. Configurator._components.
  771. Actually, the components are None, but we need something to be there.
  772. """
  773. result = {}
  774. for name in config.keys():
  775. result[name] = (config[name], None)
  776. return result
  777. def test_build_plan(self):
  778. """
  779. Test building the plan correctly. Not complete yet, this grows as we
  780. add more ways of changing the plan.
  781. """
  782. configurator = Configurator(self, self.__specials)
  783. plan = configurator._build_plan({}, self.__core)
  784. # This should have created the components
  785. self.assertEqual(self.__core_log_create, self.log)
  786. self.assertEqual(3, len(plan))
  787. for (task, name) in zip(plan, ['core1', 'core3', 'core2']):
  788. self.assertTrue('component' in task)
  789. self.assertEqual('start', task['command'])
  790. self.assertEqual(name, task['name'])
  791. component = task['component']
  792. self.assertIsNone(component._address)
  793. self.assertIsNone(component._params)
  794. # A plan to go from older state to newer one containing more components
  795. bigger = copy.copy(self.__core)
  796. bigger['additional'] = {
  797. 'priority': 6,
  798. 'special': 'test',
  799. 'process': 'additional',
  800. 'kind': 'dispensable' # need to be dispensable so it could restart
  801. }
  802. self.log = []
  803. plan = configurator._build_plan(self.__build_components(self.__core),
  804. bigger)
  805. self.assertEqual([('additional', 'init'),
  806. ('additional', 'dispensable')],
  807. self.log)
  808. self.assertEqual(1, len(plan))
  809. self.assertTrue('component' in plan[0])
  810. component = plan[0]['component']
  811. self.assertEqual('start', plan[0]['command'])
  812. self.assertEqual('additional', plan[0]['name'])
  813. # Now remove the one component again
  814. # We run the plan so the component is wired into internal structures
  815. configurator._run_plan(plan)
  816. # We should have the 'additional' component in the configurator.
  817. self.assertTrue('additional' in configurator._components)
  818. for count in [0, 1]: # repeat two times, see below
  819. self.log = []
  820. plan = configurator._build_plan(self.__build_components(bigger),
  821. self.__core)
  822. self.assertEqual([], self.log)
  823. self.assertEqual([{
  824. 'command': 'stop',
  825. 'name': 'additional',
  826. 'component': component
  827. }], plan)
  828. if count is 0:
  829. # We then emulate unexpected failure of the component (but
  830. # before it restarts). It shouldn't confuse the
  831. # configurator in the second phase of the test
  832. component.failed(0)
  833. # Run the plan, confirm the specified component is gone.
  834. configurator._run_plan(plan)
  835. self.assertFalse('additional' in configurator._components)
  836. # We want to switch a component. So, prepare the configurator so it
  837. # holds one
  838. configurator._run_plan(configurator._build_plan(
  839. self.__build_components(self.__core), bigger))
  840. # Get a different configuration with a different component
  841. different = copy.copy(self.__core)
  842. different['another'] = {
  843. 'special': 'test',
  844. 'process': 'another',
  845. 'kind': 'dispensable'
  846. }
  847. self.log = []
  848. plan = configurator._build_plan(self.__build_components(bigger),
  849. different)
  850. self.assertEqual([('another', 'init'), ('another', 'dispensable')],
  851. self.log)
  852. self.assertEqual(2, len(plan))
  853. self.assertEqual('stop', plan[0]['command'])
  854. self.assertEqual('additional', plan[0]['name'])
  855. self.assertTrue('component' in plan[0])
  856. self.assertEqual('start', plan[1]['command'])
  857. self.assertEqual('another', plan[1]['name'])
  858. self.assertTrue('component' in plan[1])
  859. # Some slightly insane plans, like missing process, having parameters,
  860. # no special, etc
  861. plan = configurator._build_plan({}, {
  862. 'component': {
  863. 'kind': 'needed',
  864. 'params': ["1", "2"],
  865. 'address': 'address'
  866. }
  867. })
  868. self.assertEqual(1, len(plan))
  869. self.assertEqual('start', plan[0]['command'])
  870. self.assertEqual('component', plan[0]['name'])
  871. component = plan[0]['component']
  872. self.assertEqual('component', component.name())
  873. self.assertEqual(["1", "2"], component._params)
  874. self.assertEqual('address', component._address)
  875. self.assertEqual('needed', component._kind)
  876. # We don't use isinstance on purpose, it would allow a descendant
  877. self.assertTrue(type(component) is Component)
  878. plan = configurator._build_plan({}, {
  879. 'component': { 'kind': 'dispensable' }
  880. })
  881. self.assertEqual(1, len(plan))
  882. self.assertEqual('start', plan[0]['command'])
  883. self.assertEqual('component', plan[0]['name'])
  884. component = plan[0]['component']
  885. self.assertEqual('component', component.name())
  886. self.assertIsNone(component._params)
  887. self.assertIsNone(component._address)
  888. self.assertEqual('dispensable', component._kind)
  889. def __do_switch(self, option, value):
  890. """
  891. Start it with some component and then switch the configuration of the
  892. component. This will probably raise, as it is not yet supported.
  893. """
  894. configurator = Configurator(self, self.__specials)
  895. compconfig = {
  896. 'special': 'test',
  897. 'process': 'process',
  898. 'priority': 13,
  899. 'kind': 'core'
  900. }
  901. modifiedconfig = copy.copy(compconfig)
  902. modifiedconfig[option] = value
  903. return configurator._build_plan({'comp': (compconfig, None)},
  904. {'comp': modifiedconfig})
  905. def test_change_config_plan(self):
  906. """
  907. Test changing a configuration of one component. This is not yet
  908. implemented and should therefore throw.
  909. """
  910. self.assertRaises(NotImplementedError, self.__do_switch, 'kind',
  911. 'dispensable')
  912. self.assertRaises(NotImplementedError, self.__do_switch, 'special',
  913. 'not_a_test')
  914. self.assertRaises(NotImplementedError, self.__do_switch, 'process',
  915. 'different')
  916. self.assertRaises(NotImplementedError, self.__do_switch, 'address',
  917. 'different')
  918. self.assertRaises(NotImplementedError, self.__do_switch, 'params',
  919. ['different'])
  920. # This does not change anything on running component, so no need to
  921. # raise
  922. self.assertEqual([], self.__do_switch('priority', 5))
  923. # Check against false positive, if the data are the same, but different
  924. # instance
  925. self.assertEqual([], self.__do_switch('special', 'test'))
  926. def __check_shutdown_log(self):
  927. """
  928. Checks the log for shutting down from the core configuration.
  929. """
  930. # We know everything must be stopped, we know what it is.
  931. # But we don't know the order, so we check everything is exactly
  932. # once in the log
  933. components = set(self.__core.keys())
  934. for (name, command) in self.log:
  935. self.assertEqual('stop', command)
  936. self.assertTrue(name in components)
  937. components.remove(name)
  938. self.assertEqual(set([]), components, "Some component wasn't stopped")
  939. def test_run(self):
  940. """
  941. Passes some configuration to the startup method and sees if
  942. the components are started up. Then it reconfigures it with
  943. empty configuration, the original configuration again and shuts
  944. down.
  945. It also checks the components are kept inside the configurator.
  946. """
  947. configurator = Configurator(self, self.__specials)
  948. # Can't reconfigure nor stop yet
  949. self.assertRaises(ValueError, configurator.reconfigure, self.__core)
  950. self.assertRaises(ValueError, configurator.shutdown)
  951. self.assertFalse(configurator.running())
  952. # Start it
  953. configurator.startup(self.__core)
  954. self.assertEqual(self.__core_log, self.log)
  955. for core in self.__core.keys():
  956. self.assertTrue(core in configurator._components)
  957. self.assertEqual(self.__core[core],
  958. configurator._components[core][0])
  959. self.assertEqual(set(self.__core), set(configurator._components))
  960. self.assertTrue(configurator.running())
  961. # It can't be started twice
  962. self.assertRaises(ValueError, configurator.startup, self.__core)
  963. self.log = []
  964. # Reconfigure - stop everything
  965. configurator.reconfigure({})
  966. self.assertEqual({}, configurator._components)
  967. self.assertTrue(configurator.running())
  968. self.__check_shutdown_log()
  969. # Start it again
  970. self.log = []
  971. configurator.reconfigure(self.__core)
  972. self.assertEqual(self.__core_log, self.log)
  973. for core in self.__core.keys():
  974. self.assertTrue(core in configurator._components)
  975. self.assertEqual(self.__core[core],
  976. configurator._components[core][0])
  977. self.assertEqual(set(self.__core), set(configurator._components))
  978. self.assertTrue(configurator.running())
  979. # Do a shutdown
  980. self.log = []
  981. configurator.shutdown()
  982. self.assertEqual({}, configurator._components)
  983. self.assertFalse(configurator.running())
  984. self.__check_shutdown_log()
  985. # It can't be stopped twice
  986. self.assertRaises(ValueError, configurator.shutdown)
  987. def test_sort_no_prio(self):
  988. """
  989. There was a bug if there were two things with the same priority
  990. (or without priority), it failed as it couldn't compare the dicts
  991. there. This tests it doesn't crash.
  992. """
  993. configurator = Configurator(self, self.__specials)
  994. configurator._build_plan({}, {
  995. "c1": { 'kind': 'dispensable'},
  996. "c2": { 'kind': 'dispensable'}
  997. })
  998. if __name__ == '__main__':
  999. isc.log.init("bind10") # FIXME Should this be needed?
  1000. isc.log.resetUnitTestRootLogger()
  1001. unittest.main()