bind10_test.py.in 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184
  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. import bind10_src
  17. # XXX: environment tests are currently disabled, due to the preprocessor
  18. # setup that we have now complicating the environment
  19. import unittest
  20. import sys
  21. import os
  22. import copy
  23. import signal
  24. import socket
  25. from isc.net.addr import IPAddr
  26. import time
  27. import isc
  28. import isc.log
  29. import isc.bind10.socket_cache
  30. from isc.testutils.parse_args import TestOptParser, OptsError
  31. class TestProcessInfo(unittest.TestCase):
  32. def setUp(self):
  33. # redirect stdout to a pipe so we can check that our
  34. # process spawning is doing the right thing with stdout
  35. self.old_stdout = os.dup(sys.stdout.fileno())
  36. self.pipes = os.pipe()
  37. os.dup2(self.pipes[1], sys.stdout.fileno())
  38. os.close(self.pipes[1])
  39. # note that we use dup2() to restore the original stdout
  40. # to the main program ASAP in each test... this prevents
  41. # hangs reading from the child process (as the pipe is only
  42. # open in the child), and also insures nice pretty output
  43. def tearDown(self):
  44. # clean up our stdout munging
  45. os.dup2(self.old_stdout, sys.stdout.fileno())
  46. os.close(self.pipes[0])
  47. def test_init(self):
  48. pi = ProcessInfo('Test Process', [ '/bin/echo', 'foo' ])
  49. pi.spawn()
  50. os.dup2(self.old_stdout, sys.stdout.fileno())
  51. self.assertEqual(pi.name, 'Test Process')
  52. self.assertEqual(pi.args, [ '/bin/echo', 'foo' ])
  53. # self.assertEqual(pi.env, { 'PATH': os.environ['PATH'],
  54. # 'PYTHON_EXEC': os.environ['PYTHON_EXEC'] })
  55. self.assertEqual(pi.dev_null_stdout, False)
  56. self.assertEqual(os.read(self.pipes[0], 100), b"foo\n")
  57. self.assertNotEqual(pi.process, None)
  58. self.assertTrue(type(pi.pid) is int)
  59. # def test_setting_env(self):
  60. # pi = ProcessInfo('Test Process', [ '/bin/true' ], env={'FOO': 'BAR'})
  61. # os.dup2(self.old_stdout, sys.stdout.fileno())
  62. # self.assertEqual(pi.env, { 'PATH': os.environ['PATH'],
  63. # 'PYTHON_EXEC': os.environ['PYTHON_EXEC'],
  64. # 'FOO': 'BAR' })
  65. def test_setting_null_stdout(self):
  66. pi = ProcessInfo('Test Process', [ '/bin/echo', 'foo' ],
  67. dev_null_stdout=True)
  68. pi.spawn()
  69. os.dup2(self.old_stdout, sys.stdout.fileno())
  70. self.assertEqual(pi.dev_null_stdout, True)
  71. self.assertEqual(os.read(self.pipes[0], 100), b"")
  72. def test_respawn(self):
  73. pi = ProcessInfo('Test Process', [ '/bin/echo', 'foo' ])
  74. pi.spawn()
  75. # wait for old process to work...
  76. self.assertEqual(os.read(self.pipes[0], 100), b"foo\n")
  77. # respawn it
  78. old_pid = pi.pid
  79. pi.respawn()
  80. os.dup2(self.old_stdout, sys.stdout.fileno())
  81. # make sure the new one started properly
  82. self.assertEqual(pi.name, 'Test Process')
  83. self.assertEqual(pi.args, [ '/bin/echo', 'foo' ])
  84. # self.assertEqual(pi.env, { 'PATH': os.environ['PATH'],
  85. # 'PYTHON_EXEC': os.environ['PYTHON_EXEC'] })
  86. self.assertEqual(pi.dev_null_stdout, False)
  87. self.assertEqual(os.read(self.pipes[0], 100), b"foo\n")
  88. self.assertNotEqual(pi.process, None)
  89. self.assertTrue(type(pi.pid) is int)
  90. self.assertNotEqual(pi.pid, old_pid)
  91. class TestCacheCommands(unittest.TestCase):
  92. """
  93. Test methods of boss related to the socket cache and socket handling.
  94. """
  95. def setUp(self):
  96. """
  97. Prepare the boss for some tests.
  98. Also prepare some variables we need.
  99. """
  100. self.__boss = BoB()
  101. # Fake the cache here so we can pretend it is us and hijack the
  102. # calls to its methods.
  103. self.__boss._socket_cache = self
  104. self.__boss._socket_path = '/socket/path'
  105. self.__raise_exception = None
  106. self.__socket_args = {
  107. "port": 53,
  108. "address": "0.0.0.0",
  109. "protocol": "UDP",
  110. "share_mode": "ANY",
  111. "share_name": "app"
  112. }
  113. # What was and wasn't called.
  114. self.__drop_app_called = None
  115. self.__get_socket_called = None
  116. self.__send_fd_called = None
  117. self.__get_token_called = None
  118. self.__drop_socket_called = None
  119. bind10_src.libutil_io_python.send_fd = self.__send_fd
  120. def __send_fd(self, to, socket):
  121. """
  122. A function to hook the send_fd in the bind10_src.
  123. """
  124. self.__send_fd_called = (to, socket)
  125. class FalseSocket:
  126. """
  127. A socket where we can fake methods we need instead of having a real
  128. socket.
  129. """
  130. def __init__(self):
  131. self.send = ""
  132. def fileno(self):
  133. """
  134. The file number. Used for identifying the remote application.
  135. """
  136. return 42
  137. def sendall(self, data):
  138. """
  139. Adds data to the self.send.
  140. """
  141. self.send += data
  142. def drop_application(self, application):
  143. """
  144. Part of pretending to be the cache. Logs the parameter to
  145. self.__drop_app_called.
  146. """
  147. self.__drop_app_called = application
  148. def test_consumer_dead(self):
  149. """
  150. Test that it calls the drop_application method of the cache.
  151. """
  152. self.__boss.socket_consumer_dead(self.FalseSocket())
  153. self.assertEqual(42, self.__drop_app_called)
  154. def get_socket(self, token, application):
  155. """
  156. Part of pretending to be the cache. If there's anything in
  157. __raise_exception, it is raised. Otherwise, the call is logged
  158. into __get_socket_called and a number is returned.
  159. """
  160. if self.__raise_exception is not None:
  161. raise self.__raise_exception
  162. self.__get_socket_called = (token, application)
  163. return 13
  164. def test_request_handler(self):
  165. """
  166. Test that a request for socket is forwarded and the socket is sent
  167. back, if it returns a socket.
  168. """
  169. socket = self.FalseSocket()
  170. # An exception from the cache
  171. self.__raise_exception = ValueError("Test value error")
  172. self.__boss.socket_request_handler("token", socket)
  173. # It was called, but it threw, so it is not noted here
  174. self.assertIsNone(self.__get_socket_called)
  175. self.assertEqual("0\n", socket.send)
  176. # It should not have sent any socket.
  177. self.assertIsNone(self.__send_fd_called)
  178. # Now prepare a valid scenario
  179. self.__raise_exception = None
  180. socket.send = ""
  181. self.__boss.socket_request_handler("token", socket)
  182. self.assertEqual("1\n", socket.send)
  183. self.assertEqual((42, 13), self.__send_fd_called)
  184. self.assertEqual(("token", 42), self.__get_socket_called)
  185. def get_token(self, protocol, address, port, share_mode, share_name):
  186. """
  187. Part of pretending to be the cache. If there's anything in
  188. __raise_exception, it is raised. Otherwise, the parameters are
  189. logged into __get_token_called and a token is returned.
  190. """
  191. if self.__raise_exception is not None:
  192. raise self.__raise_exception
  193. self.__get_token_called = (protocol, address, port, share_mode,
  194. share_name)
  195. return "token"
  196. def test_get_socket_ok(self):
  197. """
  198. Test the successful scenario of getting a socket.
  199. """
  200. result = self.__boss._get_socket(self.__socket_args)
  201. [code, answer] = result['result']
  202. self.assertEqual(0, code)
  203. self.assertEqual({
  204. 'token': 'token',
  205. 'path': '/socket/path'
  206. }, answer)
  207. addr = self.__get_token_called[1]
  208. self.assertIsInstance(addr, IPAddr)
  209. self.assertEqual("0.0.0.0", str(addr))
  210. self.assertEqual(("UDP", addr, 53, "ANY", "app"),
  211. self.__get_token_called)
  212. def test_get_socket_error(self):
  213. """
  214. Test that bad inputs are handled correctly, etc.
  215. """
  216. def check_code(code, args):
  217. """
  218. Pass the args there and check if it returs success or not.
  219. The rest is not tested, as it is already checked in the
  220. test_get_socket_ok.
  221. """
  222. [rcode, ranswer] = self.__boss._get_socket(args)['result']
  223. self.assertEqual(code, rcode)
  224. if code == 1:
  225. # This should be an error message. The exact formatting
  226. # is unknown, but we check it is string at last
  227. self.assertIsInstance(ranswer, str)
  228. def mod_args(name, value):
  229. """
  230. Override a parameter in the args.
  231. """
  232. result = dict(self.__socket_args)
  233. result[name] = value
  234. return result
  235. # Port too large
  236. check_code(1, mod_args('port', 65536))
  237. # Not numeric address
  238. check_code(1, mod_args('address', 'example.org.'))
  239. # Some bad values of enum-like params
  240. check_code(1, mod_args('protocol', 'BAD PROTO'))
  241. check_code(1, mod_args('share_mode', 'BAD SHARE'))
  242. # Check missing parameters
  243. for param in self.__socket_args.keys():
  244. args = dict(self.__socket_args)
  245. del args[param]
  246. check_code(1, args)
  247. # These are OK values for the enum-like parameters
  248. # The ones from test_get_socket_ok are not tested here
  249. check_code(0, mod_args('protocol', 'TCP'))
  250. check_code(0, mod_args('share_mode', 'SAMEAPP'))
  251. check_code(0, mod_args('share_mode', 'NO'))
  252. # If an exception is raised from within the cache, it is converted
  253. # to an error, not propagated
  254. self.__raise_exception = Exception("Test exception")
  255. check_code(1, self.__socket_args)
  256. def drop_socket(self, token):
  257. """
  258. Part of pretending to be the cache. If there's anything in
  259. __raise_exception, it is raised. Otherwise, the parameter is stored
  260. in __drop_socket_called.
  261. """
  262. if self.__raise_exception is not None:
  263. raise self.__raise_exception
  264. self.__drop_socket_called = token
  265. def test_drop_socket(self):
  266. """
  267. Check the drop_socket command. It should directly call the method
  268. on the cache. Exceptions should be translated to error messages.
  269. """
  270. # This should be OK and just propagated to the call.
  271. self.assertEqual({"result": [0]},
  272. self.__boss.command_handler("drop_socket",
  273. {"token": "token"}))
  274. self.assertEqual("token", self.__drop_socket_called)
  275. self.__drop_socket_called = None
  276. # Missing parameter
  277. self.assertEqual({"result": [1, "Missing token parameter"]},
  278. self.__boss.command_handler("drop_socket", {}))
  279. self.assertIsNone(self.__drop_socket_called)
  280. # An exception is raised from within the cache
  281. self.__raise_exception = ValueError("Test error")
  282. self.assertEqual({"result": [1, "Test error"]},
  283. self.__boss.command_handler("drop_socket",
  284. {"token": "token"}))
  285. class TestBoB(unittest.TestCase):
  286. def test_init(self):
  287. bob = BoB()
  288. self.assertEqual(bob.verbose, False)
  289. self.assertEqual(bob.msgq_socket_file, None)
  290. self.assertEqual(bob.cc_session, None)
  291. self.assertEqual(bob.ccs, None)
  292. self.assertEqual(bob.components, {})
  293. self.assertEqual(bob.runnable, False)
  294. self.assertEqual(bob.uid, None)
  295. self.assertEqual(bob.username, None)
  296. self.assertEqual(bob.nocache, False)
  297. self.assertIsNone(bob._socket_cache)
  298. def test_insert_creator(self):
  299. """
  300. Test the call to insert_creator. First time, the cache is created
  301. with the passed creator. The next time, it throws an exception.
  302. """
  303. bob = BoB()
  304. # The cache doesn't use it at start, so just create an empty class
  305. class Creator: pass
  306. creator = Creator()
  307. bob.insert_creator(creator)
  308. self.assertIsInstance(bob._socket_cache, isc.bind10.socket_cache.Cache)
  309. self.assertEqual(creator, bob._socket_cache._creator)
  310. self.assertRaises(ValueError, bob.insert_creator, creator)
  311. def test_init_alternate_socket(self):
  312. bob = BoB("alt_socket_file")
  313. self.assertEqual(bob.verbose, False)
  314. self.assertEqual(bob.msgq_socket_file, "alt_socket_file")
  315. self.assertEqual(bob.cc_session, None)
  316. self.assertEqual(bob.ccs, None)
  317. self.assertEqual(bob.components, {})
  318. self.assertEqual(bob.runnable, False)
  319. self.assertEqual(bob.uid, None)
  320. self.assertEqual(bob.username, None)
  321. self.assertEqual(bob.nocache, False)
  322. def test_command_handler(self):
  323. class DummySession():
  324. def group_sendmsg(self, msg, group):
  325. (self.msg, self.group) = (msg, group)
  326. def group_recvmsg(self, nonblock, seq): pass
  327. class DummyModuleCCSession():
  328. module_spec = isc.config.module_spec.ModuleSpec({
  329. "module_name": "Boss",
  330. "statistics": [
  331. {
  332. "item_name": "boot_time",
  333. "item_type": "string",
  334. "item_optional": False,
  335. "item_default": "1970-01-01T00:00:00Z",
  336. "item_title": "Boot time",
  337. "item_description": "A date time when bind10 process starts initially",
  338. "item_format": "date-time"
  339. }
  340. ]
  341. })
  342. def get_module_spec(self):
  343. return self.module_spec
  344. bob = BoB()
  345. bob.verbose = True
  346. bob.cc_session = DummySession()
  347. bob.ccs = DummyModuleCCSession()
  348. # a bad command
  349. self.assertEqual(bob.command_handler(-1, None),
  350. isc.config.ccsession.create_answer(1, "bad command"))
  351. # "shutdown" command
  352. self.assertEqual(bob.command_handler("shutdown", None),
  353. isc.config.ccsession.create_answer(0))
  354. self.assertFalse(bob.runnable)
  355. # "getstats" command
  356. self.assertEqual(bob.command_handler("getstats", None),
  357. isc.config.ccsession.create_answer(0,
  358. { "owner": "Boss",
  359. "data": {
  360. 'boot_time': time.strftime('%Y-%m-%dT%H:%M:%SZ', _BASETIME)
  361. }}))
  362. # "sendstats" command
  363. self.assertEqual(bob.command_handler("sendstats", None),
  364. isc.config.ccsession.create_answer(0))
  365. self.assertEqual(bob.cc_session.group, "Stats")
  366. self.assertEqual(bob.cc_session.msg,
  367. isc.config.ccsession.create_command(
  368. "set", { "owner": "Boss",
  369. "data": {
  370. "boot_time": time.strftime("%Y-%m-%dT%H:%M:%SZ", _BASETIME)
  371. }}))
  372. # "ping" command
  373. self.assertEqual(bob.command_handler("ping", None),
  374. isc.config.ccsession.create_answer(0, "pong"))
  375. # "show_processes" command
  376. self.assertEqual(bob.command_handler("show_processes", None),
  377. isc.config.ccsession.create_answer(0,
  378. bob.get_processes()))
  379. # an unknown command
  380. self.assertEqual(bob.command_handler("__UNKNOWN__", None),
  381. isc.config.ccsession.create_answer(1, "Unknown command"))
  382. # Fake the _get_socket, which is complicated and tested elsewhere
  383. # We just want to pass the parameters in and let it create a response
  384. def get_socket(args):
  385. return isc.config.ccsession.create_answer(0, args)
  386. bob._get_socket = get_socket
  387. args = {
  388. "port": 53,
  389. "address": "0.0.0.0",
  390. "protocol": "UDP",
  391. "share_mode": "ANY",
  392. "share_name": "app"
  393. }
  394. # Test it just returns whatever it got. The real function doesn't
  395. # work like this, but we don't want the command_handler to touch it
  396. # at all and this is the easiest way to check.
  397. self.assertEqual({'result': [0, args]},
  398. bob.command_handler("get_socket", args))
  399. # The drop_socket is not tested here, but in TestCacheCommands.
  400. # It needs the cache mocks to be in place and they are there.
  401. # Class for testing the BoB without actually starting processes.
  402. # This is used for testing the start/stop components routines and
  403. # the BoB commands.
  404. #
  405. # Testing that external processes start is outside the scope
  406. # of the unit test, by overriding the process start methods we can check
  407. # that the right processes are started depending on the configuration
  408. # options.
  409. class MockBob(BoB):
  410. def __init__(self):
  411. BoB.__init__(self)
  412. # Set flags as to which of the overridden methods has been run.
  413. self.msgq = False
  414. self.cfgmgr = False
  415. self.ccsession = False
  416. self.auth = False
  417. self.resolver = False
  418. self.xfrout = False
  419. self.xfrin = False
  420. self.zonemgr = False
  421. self.stats = False
  422. self.stats_httpd = False
  423. self.cmdctl = False
  424. self.dhcp6 = False
  425. self.dhcp4 = False
  426. self.c_channel_env = {}
  427. self.components = { }
  428. self.creator = False
  429. class MockSockCreator(isc.bind10.component.Component):
  430. def __init__(self, process, boss, kind, address=None, params=None):
  431. isc.bind10.component.Component.__init__(self, process, boss,
  432. kind, 'SockCreator')
  433. self._start_func = boss.start_creator
  434. specials = isc.bind10.special_component.get_specials()
  435. specials['sockcreator'] = MockSockCreator
  436. self._component_configurator = \
  437. isc.bind10.component.Configurator(self, specials)
  438. def start_creator(self):
  439. self.creator = True
  440. procinfo = ProcessInfo('b10-sockcreator', ['/bin/false'])
  441. procinfo.pid = 1
  442. return procinfo
  443. def _read_bind10_config(self):
  444. # Configuration options are set directly
  445. pass
  446. def start_msgq(self):
  447. self.msgq = True
  448. procinfo = ProcessInfo('b10-msgq', ['/bin/false'])
  449. procinfo.pid = 2
  450. return procinfo
  451. def start_ccsession(self, c_channel_env):
  452. # this is not a process, don't have to do anything with procinfo
  453. self.ccsession = True
  454. def start_cfgmgr(self):
  455. self.cfgmgr = True
  456. procinfo = ProcessInfo('b10-cfgmgr', ['/bin/false'])
  457. procinfo.pid = 3
  458. return procinfo
  459. def start_auth(self):
  460. self.auth = True
  461. procinfo = ProcessInfo('b10-auth', ['/bin/false'])
  462. procinfo.pid = 5
  463. return procinfo
  464. def start_resolver(self):
  465. self.resolver = True
  466. procinfo = ProcessInfo('b10-resolver', ['/bin/false'])
  467. procinfo.pid = 6
  468. return procinfo
  469. def start_simple(self, name):
  470. procmap = { 'b10-zonemgr': self.start_zonemgr,
  471. 'b10-stats': self.start_stats,
  472. 'b10-stats-httpd': self.start_stats_httpd,
  473. 'b10-cmdctl': self.start_cmdctl,
  474. 'b10-dhcp6': self.start_dhcp6,
  475. 'b10-dhcp4': self.start_dhcp4 }
  476. return procmap[name]()
  477. def start_xfrout(self):
  478. self.xfrout = True
  479. procinfo = ProcessInfo('b10-xfrout', ['/bin/false'])
  480. procinfo.pid = 7
  481. return procinfo
  482. def start_xfrin(self):
  483. self.xfrin = True
  484. procinfo = ProcessInfo('b10-xfrin', ['/bin/false'])
  485. procinfo.pid = 8
  486. return procinfo
  487. def start_zonemgr(self):
  488. self.zonemgr = True
  489. procinfo = ProcessInfo('b10-zonemgr', ['/bin/false'])
  490. procinfo.pid = 9
  491. return procinfo
  492. def start_stats(self):
  493. self.stats = True
  494. procinfo = ProcessInfo('b10-stats', ['/bin/false'])
  495. procinfo.pid = 10
  496. return procinfo
  497. def start_stats_httpd(self):
  498. self.stats_httpd = True
  499. procinfo = ProcessInfo('b10-stats-httpd', ['/bin/false'])
  500. procinfo.pid = 11
  501. return procinfo
  502. def start_cmdctl(self):
  503. self.cmdctl = True
  504. procinfo = ProcessInfo('b10-cmdctl', ['/bin/false'])
  505. procinfo.pid = 12
  506. return procinfo
  507. def start_dhcp6(self):
  508. self.dhcp6 = True
  509. procinfo = ProcessInfo('b10-dhcp6', ['/bin/false'])
  510. procinfo.pid = 13
  511. return procinfo
  512. def start_dhcp4(self):
  513. self.dhcp4 = True
  514. procinfo = ProcessInfo('b10-dhcp4', ['/bin/false'])
  515. procinfo.pid = 14
  516. return procinfo
  517. def stop_process(self, process, recipient):
  518. procmap = { 'b10-auth': self.stop_auth,
  519. 'b10-resolver': self.stop_resolver,
  520. 'b10-xfrout': self.stop_xfrout,
  521. 'b10-xfrin': self.stop_xfrin,
  522. 'b10-zonemgr': self.stop_zonemgr,
  523. 'b10-stats': self.stop_stats,
  524. 'b10-stats-httpd': self.stop_stats_httpd,
  525. 'b10-cmdctl': self.stop_cmdctl }
  526. procmap[process]()
  527. # Some functions to pretend we stop processes, use by stop_process
  528. def stop_msgq(self):
  529. if self.msgq:
  530. del self.components[2]
  531. self.msgq = False
  532. def stop_cfgmgr(self):
  533. if self.cfgmgr:
  534. del self.components[3]
  535. self.cfgmgr = False
  536. def stop_auth(self):
  537. if self.auth:
  538. del self.components[5]
  539. self.auth = False
  540. def stop_resolver(self):
  541. if self.resolver:
  542. del self.components[6]
  543. self.resolver = False
  544. def stop_xfrout(self):
  545. if self.xfrout:
  546. del self.components[7]
  547. self.xfrout = False
  548. def stop_xfrin(self):
  549. if self.xfrin:
  550. del self.components[8]
  551. self.xfrin = False
  552. def stop_zonemgr(self):
  553. if self.zonemgr:
  554. del self.components[9]
  555. self.zonemgr = False
  556. def stop_stats(self):
  557. if self.stats:
  558. del self.components[10]
  559. self.stats = False
  560. def stop_stats_httpd(self):
  561. if self.stats_httpd:
  562. del self.components[11]
  563. self.stats_httpd = False
  564. def stop_cmdctl(self):
  565. if self.cmdctl:
  566. del self.components[12]
  567. self.cmdctl = False
  568. class TestStartStopProcessesBob(unittest.TestCase):
  569. """
  570. Check that the start_all_components method starts the right combination
  571. of components and that the right components are started and stopped
  572. according to changes in configuration.
  573. """
  574. def check_environment_unchanged(self):
  575. # Check whether the environment has not been changed
  576. self.assertEqual(original_os_environ, os.environ)
  577. def check_started(self, bob, core, auth, resolver):
  578. """
  579. Check that the right sets of services are started. The ones that
  580. should be running are specified by the core, auth and resolver parameters
  581. (they are groups of processes, eg. auth means b10-auth, -xfrout, -xfrin
  582. and -zonemgr).
  583. """
  584. self.assertEqual(bob.msgq, core)
  585. self.assertEqual(bob.cfgmgr, core)
  586. self.assertEqual(bob.ccsession, core)
  587. self.assertEqual(bob.creator, core)
  588. self.assertEqual(bob.auth, auth)
  589. self.assertEqual(bob.resolver, resolver)
  590. self.assertEqual(bob.xfrout, auth)
  591. self.assertEqual(bob.xfrin, auth)
  592. self.assertEqual(bob.zonemgr, auth)
  593. self.assertEqual(bob.stats, core)
  594. self.assertEqual(bob.stats_httpd, core)
  595. self.assertEqual(bob.cmdctl, core)
  596. self.check_environment_unchanged()
  597. def check_preconditions(self, bob):
  598. self.check_started(bob, False, False, False)
  599. def check_started_none(self, bob):
  600. """
  601. Check that the situation is according to configuration where no servers
  602. should be started. Some components still need to be running.
  603. """
  604. self.check_started(bob, True, False, False)
  605. self.check_environment_unchanged()
  606. def check_started_both(self, bob):
  607. """
  608. Check the situation is according to configuration where both servers
  609. (auth and resolver) are enabled.
  610. """
  611. self.check_started(bob, True, True, True)
  612. self.check_environment_unchanged()
  613. def check_started_auth(self, bob):
  614. """
  615. Check the set of components needed to run auth only is started.
  616. """
  617. self.check_started(bob, True, True, False)
  618. self.check_environment_unchanged()
  619. def check_started_resolver(self, bob):
  620. """
  621. Check the set of components needed to run resolver only is started.
  622. """
  623. self.check_started(bob, True, False, True)
  624. self.check_environment_unchanged()
  625. def check_started_dhcp(self, bob, v4, v6):
  626. """
  627. Check if proper combinations of DHCPv4 and DHCpv6 can be started
  628. """
  629. self.assertEqual(v4, bob.dhcp4)
  630. self.assertEqual(v6, bob.dhcp6)
  631. self.check_environment_unchanged()
  632. def construct_config(self, start_auth, start_resolver):
  633. # The things that are common, not turned on an off
  634. config = {}
  635. config['b10-stats'] = { 'kind': 'dispensable', 'address': 'Stats' }
  636. config['b10-stats-httpd'] = { 'kind': 'dispensable',
  637. 'address': 'StatsHttpd' }
  638. config['b10-cmdctl'] = { 'kind': 'needed', 'special': 'cmdctl' }
  639. if start_auth:
  640. config['b10-auth'] = { 'kind': 'needed', 'special': 'auth' }
  641. config['b10-xfrout'] = { 'kind': 'dispensable',
  642. 'special': 'xfrout' }
  643. config['b10-xfrin'] = { 'kind': 'dispensable', 'special': 'xfrin' }
  644. config['b10-zonemgr'] = { 'kind': 'dispensable',
  645. 'address': 'Zonemgr' }
  646. if start_resolver:
  647. config['b10-resolver'] = { 'kind': 'needed',
  648. 'special': 'resolver' }
  649. return {'components': config}
  650. def config_start_init(self, start_auth, start_resolver):
  651. """
  652. Test the configuration is loaded at the startup.
  653. """
  654. bob = MockBob()
  655. config = self.construct_config(start_auth, start_resolver)
  656. class CC:
  657. def get_full_config(self):
  658. return config
  659. # Provide the fake CC with data
  660. bob.ccs = CC()
  661. # And make sure it's not overwritten
  662. def start_ccsession():
  663. bob.ccsession = True
  664. bob.start_ccsession = lambda _: start_ccsession()
  665. # We need to return the original _read_bind10_config
  666. bob._read_bind10_config = lambda: BoB._read_bind10_config(bob)
  667. bob.start_all_components()
  668. self.check_started(bob, True, start_auth, start_resolver)
  669. self.check_environment_unchanged()
  670. def test_start_none(self):
  671. self.config_start_init(False, False)
  672. def test_start_resolver(self):
  673. self.config_start_init(False, True)
  674. def test_start_auth(self):
  675. self.config_start_init(True, False)
  676. def test_start_both(self):
  677. self.config_start_init(True, True)
  678. def test_config_start(self):
  679. """
  680. Test that the configuration starts and stops components according
  681. to configuration changes.
  682. """
  683. # Create BoB and ensure correct initialization
  684. bob = MockBob()
  685. self.check_preconditions(bob)
  686. bob.start_all_components()
  687. bob.runnable = True
  688. bob.config_handler(self.construct_config(False, False))
  689. self.check_started_none(bob)
  690. # Enable both at once
  691. bob.config_handler(self.construct_config(True, True))
  692. self.check_started_both(bob)
  693. # Not touched by empty change
  694. bob.config_handler({})
  695. self.check_started_both(bob)
  696. # Not touched by change to the same configuration
  697. bob.config_handler(self.construct_config(True, True))
  698. self.check_started_both(bob)
  699. # Turn them both off again
  700. bob.config_handler(self.construct_config(False, False))
  701. self.check_started_none(bob)
  702. # Not touched by empty change
  703. bob.config_handler({})
  704. self.check_started_none(bob)
  705. # Not touched by change to the same configuration
  706. bob.config_handler(self.construct_config(False, False))
  707. self.check_started_none(bob)
  708. # Start and stop auth separately
  709. bob.config_handler(self.construct_config(True, False))
  710. self.check_started_auth(bob)
  711. bob.config_handler(self.construct_config(False, False))
  712. self.check_started_none(bob)
  713. # Start and stop resolver separately
  714. bob.config_handler(self.construct_config(False, True))
  715. self.check_started_resolver(bob)
  716. bob.config_handler(self.construct_config(False, False))
  717. self.check_started_none(bob)
  718. # Alternate
  719. bob.config_handler(self.construct_config(True, False))
  720. self.check_started_auth(bob)
  721. bob.config_handler(self.construct_config(False, True))
  722. self.check_started_resolver(bob)
  723. bob.config_handler(self.construct_config(True, False))
  724. self.check_started_auth(bob)
  725. def test_config_start_once(self):
  726. """
  727. Tests that a component is started only once.
  728. """
  729. # Create BoB and ensure correct initialization
  730. bob = MockBob()
  731. self.check_preconditions(bob)
  732. bob.start_all_components()
  733. bob.runnable = True
  734. bob.config_handler(self.construct_config(True, True))
  735. self.check_started_both(bob)
  736. bob.start_auth = lambda: self.fail("Started auth again")
  737. bob.start_xfrout = lambda: self.fail("Started xfrout again")
  738. bob.start_xfrin = lambda: self.fail("Started xfrin again")
  739. bob.start_zonemgr = lambda: self.fail("Started zonemgr again")
  740. bob.start_resolver = lambda: self.fail("Started resolver again")
  741. # Send again we want to start them. Should not do it, as they are.
  742. bob.config_handler(self.construct_config(True, True))
  743. def test_config_not_started_early(self):
  744. """
  745. Test that components are not started by the config handler before
  746. startup.
  747. """
  748. bob = MockBob()
  749. self.check_preconditions(bob)
  750. bob.start_auth = lambda: self.fail("Started auth again")
  751. bob.start_xfrout = lambda: self.fail("Started xfrout again")
  752. bob.start_xfrin = lambda: self.fail("Started xfrin again")
  753. bob.start_zonemgr = lambda: self.fail("Started zonemgr again")
  754. bob.start_resolver = lambda: self.fail("Started resolver again")
  755. bob.config_handler({'start_auth': True, 'start_resolver': True})
  756. # Checks that DHCP (v4 and v6) components are started when expected
  757. def test_start_dhcp(self):
  758. # Create BoB and ensure correct initialization
  759. bob = MockBob()
  760. self.check_preconditions(bob)
  761. bob.start_all_components()
  762. bob.config_handler(self.construct_config(False, False))
  763. self.check_started_dhcp(bob, False, False)
  764. def test_start_dhcp_v6only(self):
  765. # Create BoB and ensure correct initialization
  766. bob = MockBob()
  767. self.check_preconditions(bob)
  768. # v6 only enabled
  769. bob.start_all_components()
  770. bob.runnable = True
  771. bob._BoB_started = True
  772. config = self.construct_config(False, False)
  773. config['components']['b10-dhcp6'] = { 'kind': 'needed',
  774. 'address': 'Dhcp6' }
  775. bob.config_handler(config)
  776. self.check_started_dhcp(bob, False, True)
  777. # uncomment when dhcpv4 becomes implemented
  778. # v4 only enabled
  779. #bob.cfg_start_dhcp6 = False
  780. #bob.cfg_start_dhcp4 = True
  781. #self.check_started_dhcp(bob, True, False)
  782. # both v4 and v6 enabled
  783. #bob.cfg_start_dhcp6 = True
  784. #bob.cfg_start_dhcp4 = True
  785. #self.check_started_dhcp(bob, True, True)
  786. class MockComponent:
  787. def __init__(self, name, pid):
  788. self.name = lambda: name
  789. self.pid = lambda: pid
  790. class TestBossCmd(unittest.TestCase):
  791. def test_ping(self):
  792. """
  793. Confirm simple ping command works.
  794. """
  795. bob = MockBob()
  796. answer = bob.command_handler("ping", None)
  797. self.assertEqual(answer, {'result': [0, 'pong']})
  798. def test_show_processes_empty(self):
  799. """
  800. Confirm getting a list of processes works.
  801. """
  802. bob = MockBob()
  803. answer = bob.command_handler("show_processes", None)
  804. self.assertEqual(answer, {'result': [0, []]})
  805. def test_show_processes(self):
  806. """
  807. Confirm getting a list of processes works.
  808. """
  809. bob = MockBob()
  810. bob.register_process(1, MockComponent('first', 1))
  811. bob.register_process(2, MockComponent('second', 2))
  812. answer = bob.command_handler("show_processes", None)
  813. processes = [[1, 'first'],
  814. [2, 'second']]
  815. self.assertEqual(answer, {'result': [0, processes]})
  816. class TestParseArgs(unittest.TestCase):
  817. """
  818. This tests parsing of arguments of the bind10 master process.
  819. """
  820. #TODO: Write tests for the original parsing, bad options, etc.
  821. def test_no_opts(self):
  822. """
  823. Test correct default values when no options are passed.
  824. """
  825. options = parse_args([], TestOptParser)
  826. self.assertEqual(None, options.data_path)
  827. self.assertEqual(None, options.config_file)
  828. self.assertEqual(None, options.cmdctl_port)
  829. def test_data_path(self):
  830. """
  831. Test it can parse the data path.
  832. """
  833. self.assertRaises(OptsError, parse_args, ['-p'], TestOptParser)
  834. self.assertRaises(OptsError, parse_args, ['--data-path'],
  835. TestOptParser)
  836. options = parse_args(['-p', '/data/path'], TestOptParser)
  837. self.assertEqual('/data/path', options.data_path)
  838. options = parse_args(['--data-path=/data/path'], TestOptParser)
  839. self.assertEqual('/data/path', options.data_path)
  840. def test_config_filename(self):
  841. """
  842. Test it can parse the config switch.
  843. """
  844. self.assertRaises(OptsError, parse_args, ['-c'], TestOptParser)
  845. self.assertRaises(OptsError, parse_args, ['--config-file'],
  846. TestOptParser)
  847. options = parse_args(['-c', 'config-file'], TestOptParser)
  848. self.assertEqual('config-file', options.config_file)
  849. options = parse_args(['--config-file=config-file'], TestOptParser)
  850. self.assertEqual('config-file', options.config_file)
  851. def test_cmdctl_port(self):
  852. """
  853. Test it can parse the command control port.
  854. """
  855. self.assertRaises(OptsError, parse_args, ['--cmdctl-port=abc'],
  856. TestOptParser)
  857. self.assertRaises(OptsError, parse_args, ['--cmdctl-port=100000000'],
  858. TestOptParser)
  859. self.assertRaises(OptsError, parse_args, ['--cmdctl-port'],
  860. TestOptParser)
  861. options = parse_args(['--cmdctl-port=1234'], TestOptParser)
  862. self.assertEqual(1234, options.cmdctl_port)
  863. class TestPIDFile(unittest.TestCase):
  864. def setUp(self):
  865. self.pid_file = '@builddir@' + os.sep + 'bind10.pid'
  866. if os.path.exists(self.pid_file):
  867. os.unlink(self.pid_file)
  868. def tearDown(self):
  869. if os.path.exists(self.pid_file):
  870. os.unlink(self.pid_file)
  871. def check_pid_file(self):
  872. # dump PID to the file, and confirm the content is correct
  873. dump_pid(self.pid_file)
  874. my_pid = os.getpid()
  875. self.assertEqual(my_pid, int(open(self.pid_file, "r").read()))
  876. def test_dump_pid(self):
  877. self.check_pid_file()
  878. # make sure any existing content will be removed
  879. open(self.pid_file, "w").write('dummy data\n')
  880. self.check_pid_file()
  881. def test_unlink_pid_file_notexist(self):
  882. dummy_data = 'dummy_data\n'
  883. open(self.pid_file, "w").write(dummy_data)
  884. unlink_pid_file("no_such_pid_file")
  885. # the file specified for unlink_pid_file doesn't exist,
  886. # and the original content of the file should be intact.
  887. self.assertEqual(dummy_data, open(self.pid_file, "r").read())
  888. def test_dump_pid_with_none(self):
  889. # Check the behavior of dump_pid() and unlink_pid_file() with None.
  890. # This should be no-op.
  891. dump_pid(None)
  892. self.assertFalse(os.path.exists(self.pid_file))
  893. dummy_data = 'dummy_data\n'
  894. open(self.pid_file, "w").write(dummy_data)
  895. unlink_pid_file(None)
  896. self.assertEqual(dummy_data, open(self.pid_file, "r").read())
  897. def test_dump_pid_failure(self):
  898. # the attempt to open file will fail, which should result in exception.
  899. self.assertRaises(IOError, dump_pid,
  900. 'nonexistent_dir' + os.sep + 'bind10.pid')
  901. class TestBossComponents(unittest.TestCase):
  902. """
  903. Test the boss propagates component configuration properly to the
  904. component configurator and acts sane.
  905. """
  906. def setUp(self):
  907. self.__param = None
  908. self.__called = False
  909. self.__compconfig = {
  910. 'comp': {
  911. 'kind': 'needed',
  912. 'process': 'cat'
  913. }
  914. }
  915. def __unary_hook(self, param):
  916. """
  917. A hook function that stores the parameter for later examination.
  918. """
  919. self.__param = param
  920. def __nullary_hook(self):
  921. """
  922. A hook function that notes down it was called.
  923. """
  924. self.__called = True
  925. def __check_core(self, config):
  926. """
  927. A function checking that the config contains parts for the valid
  928. core component configuration.
  929. """
  930. self.assertIsNotNone(config)
  931. for component in ['sockcreator', 'msgq', 'cfgmgr']:
  932. self.assertTrue(component in config)
  933. self.assertEqual(component, config[component]['special'])
  934. self.assertEqual('core', config[component]['kind'])
  935. def __check_extended(self, config):
  936. """
  937. This checks that the config contains the core and one more component.
  938. """
  939. self.__check_core(config)
  940. self.assertTrue('comp' in config)
  941. self.assertEqual('cat', config['comp']['process'])
  942. self.assertEqual('needed', config['comp']['kind'])
  943. self.assertEqual(4, len(config))
  944. def test_correct_run(self):
  945. """
  946. Test the situation when we run in usual scenario, nothing fails,
  947. we just start, reconfigure and then stop peacefully.
  948. """
  949. bob = MockBob()
  950. # Start it
  951. orig = bob._component_configurator.startup
  952. bob._component_configurator.startup = self.__unary_hook
  953. bob.start_all_components()
  954. bob._component_configurator.startup = orig
  955. self.__check_core(self.__param)
  956. self.assertEqual(3, len(self.__param))
  957. # Reconfigure it
  958. self.__param = None
  959. orig = bob._component_configurator.reconfigure
  960. bob._component_configurator.reconfigure = self.__unary_hook
  961. # Otherwise it does not work
  962. bob.runnable = True
  963. bob.config_handler({'components': self.__compconfig})
  964. self.__check_extended(self.__param)
  965. currconfig = self.__param
  966. # If we reconfigure it, but it does not contain the components part,
  967. # nothing is called
  968. bob.config_handler({})
  969. self.assertEqual(self.__param, currconfig)
  970. self.__param = None
  971. bob._component_configurator.reconfigure = orig
  972. # Check a configuration that messes up the core components is rejected.
  973. compconf = dict(self.__compconfig)
  974. compconf['msgq'] = { 'process': 'echo' }
  975. result = bob.config_handler({'components': compconf})
  976. # Check it rejected it
  977. self.assertEqual(1, result['result'][0])
  978. # We can't call shutdown, that one relies on the stuff in main
  979. # We check somewhere else that the shutdown is actually called
  980. # from there (the test_kills).
  981. def test_kills(self):
  982. """
  983. Test that the boss kills components which don't want to stop.
  984. """
  985. bob = MockBob()
  986. killed = []
  987. class ImmortalComponent:
  988. """
  989. An immortal component. It does not stop when it is told so
  990. (anyway it is not told so). It does not die if it is killed
  991. the first time. It dies only when killed forcefully.
  992. """
  993. def kill(self, forcefull=False):
  994. killed.append(forcefull)
  995. if forcefull:
  996. bob.components = {}
  997. def pid(self):
  998. return 1
  999. def name(self):
  1000. return "Immortal"
  1001. bob.components = {}
  1002. bob.register_process(1, ImmortalComponent())
  1003. # While at it, we check the configurator shutdown is actually called
  1004. orig = bob._component_configurator.shutdown
  1005. bob._component_configurator.shutdown = self.__nullary_hook
  1006. self.__called = False
  1007. bob.shutdown()
  1008. self.assertEqual([False, True], killed)
  1009. self.assertTrue(self.__called)
  1010. bob._component_configurator.shutdown = orig
  1011. def test_component_shutdown(self):
  1012. """
  1013. Test the component_shutdown sets all variables accordingly.
  1014. """
  1015. bob = MockBob()
  1016. self.assertRaises(Exception, bob.component_shutdown, 1)
  1017. self.assertEqual(1, bob.exitcode)
  1018. bob._BoB__started = True
  1019. bob.component_shutdown(2)
  1020. self.assertEqual(2, bob.exitcode)
  1021. self.assertFalse(bob.runnable)
  1022. def test_init_config(self):
  1023. """
  1024. Test initial configuration is loaded.
  1025. """
  1026. bob = MockBob()
  1027. # Start it
  1028. bob._component_configurator.reconfigure = self.__unary_hook
  1029. # We need to return the original read_bind10_config
  1030. bob._read_bind10_config = lambda: BoB._read_bind10_config(bob)
  1031. # And provide a session to read the data from
  1032. class CC:
  1033. pass
  1034. bob.ccs = CC()
  1035. bob.ccs.get_full_config = lambda: {'components': self.__compconfig}
  1036. bob.start_all_components()
  1037. self.__check_extended(self.__param)
  1038. if __name__ == '__main__':
  1039. # store os.environ for test_unchanged_environment
  1040. original_os_environ = copy.deepcopy(os.environ)
  1041. isc.log.resetUnitTestRootLogger()
  1042. unittest.main()