bind10_test.py.in 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607
  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. # Most of the time, we omit the "bind10_src" for brevity. Sometimes,
  16. # we want to be explicit about what we do, like when hijacking a library
  17. # call used by the bind10_src.
  18. from bind10_src import ProcessInfo, BoB, parse_args, dump_pid, unlink_pid_file, _BASETIME
  19. import bind10_src
  20. # XXX: environment tests are currently disabled, due to the preprocessor
  21. # setup that we have now complicating the environment
  22. import unittest
  23. import sys
  24. import os
  25. import copy
  26. import signal
  27. import socket
  28. from isc.net.addr import IPAddr
  29. import time
  30. import isc
  31. import isc.log
  32. import isc.bind10.socket_cache
  33. import errno
  34. from isc.testutils.parse_args import TestOptParser, OptsError
  35. from isc.testutils.ccsession_mock import MockModuleCCSession
  36. class TestProcessInfo(unittest.TestCase):
  37. def setUp(self):
  38. # redirect stdout to a pipe so we can check that our
  39. # process spawning is doing the right thing with stdout
  40. self.old_stdout = os.dup(sys.stdout.fileno())
  41. self.pipes = os.pipe()
  42. os.dup2(self.pipes[1], sys.stdout.fileno())
  43. os.close(self.pipes[1])
  44. # note that we use dup2() to restore the original stdout
  45. # to the main program ASAP in each test... this prevents
  46. # hangs reading from the child process (as the pipe is only
  47. # open in the child), and also insures nice pretty output
  48. def tearDown(self):
  49. # clean up our stdout munging
  50. os.dup2(self.old_stdout, sys.stdout.fileno())
  51. os.close(self.pipes[0])
  52. def test_init(self):
  53. pi = ProcessInfo('Test Process', [ '/bin/echo', 'foo' ])
  54. pi.spawn()
  55. os.dup2(self.old_stdout, sys.stdout.fileno())
  56. self.assertEqual(pi.name, 'Test Process')
  57. self.assertEqual(pi.args, [ '/bin/echo', 'foo' ])
  58. # self.assertEqual(pi.env, { 'PATH': os.environ['PATH'],
  59. # 'PYTHON_EXEC': os.environ['PYTHON_EXEC'] })
  60. self.assertEqual(pi.dev_null_stdout, False)
  61. self.assertEqual(os.read(self.pipes[0], 100), b"foo\n")
  62. self.assertNotEqual(pi.process, None)
  63. self.assertTrue(type(pi.pid) is int)
  64. # def test_setting_env(self):
  65. # pi = ProcessInfo('Test Process', [ '/bin/true' ], env={'FOO': 'BAR'})
  66. # os.dup2(self.old_stdout, sys.stdout.fileno())
  67. # self.assertEqual(pi.env, { 'PATH': os.environ['PATH'],
  68. # 'PYTHON_EXEC': os.environ['PYTHON_EXEC'],
  69. # 'FOO': 'BAR' })
  70. def test_setting_null_stdout(self):
  71. pi = ProcessInfo('Test Process', [ '/bin/echo', 'foo' ],
  72. dev_null_stdout=True)
  73. pi.spawn()
  74. os.dup2(self.old_stdout, sys.stdout.fileno())
  75. self.assertEqual(pi.dev_null_stdout, True)
  76. self.assertEqual(os.read(self.pipes[0], 100), b"")
  77. def test_respawn(self):
  78. pi = ProcessInfo('Test Process', [ '/bin/echo', 'foo' ])
  79. pi.spawn()
  80. # wait for old process to work...
  81. self.assertEqual(os.read(self.pipes[0], 100), b"foo\n")
  82. # respawn it
  83. old_pid = pi.pid
  84. pi.respawn()
  85. os.dup2(self.old_stdout, sys.stdout.fileno())
  86. # make sure the new one started properly
  87. self.assertEqual(pi.name, 'Test Process')
  88. self.assertEqual(pi.args, [ '/bin/echo', 'foo' ])
  89. # self.assertEqual(pi.env, { 'PATH': os.environ['PATH'],
  90. # 'PYTHON_EXEC': os.environ['PYTHON_EXEC'] })
  91. self.assertEqual(pi.dev_null_stdout, False)
  92. self.assertEqual(os.read(self.pipes[0], 100), b"foo\n")
  93. self.assertNotEqual(pi.process, None)
  94. self.assertTrue(type(pi.pid) is int)
  95. self.assertNotEqual(pi.pid, old_pid)
  96. class TestCacheCommands(unittest.TestCase):
  97. """
  98. Test methods of boss related to the socket cache and socket handling.
  99. """
  100. def setUp(self):
  101. """
  102. Prepare the boss for some tests.
  103. Also prepare some variables we need.
  104. """
  105. self.__boss = BoB()
  106. # Fake the cache here so we can pretend it is us and hijack the
  107. # calls to its methods.
  108. self.__boss._socket_cache = self
  109. self.__boss._socket_path = '/socket/path'
  110. self.__raise_exception = None
  111. self.__socket_args = {
  112. "port": 53,
  113. "address": "::",
  114. "protocol": "UDP",
  115. "share_mode": "ANY",
  116. "share_name": "app"
  117. }
  118. # What was and wasn't called.
  119. self.__drop_app_called = None
  120. self.__get_socket_called = None
  121. self.__send_fd_called = None
  122. self.__get_token_called = None
  123. self.__drop_socket_called = None
  124. bind10_src.libutil_io_python.send_fd = self.__send_fd
  125. def __send_fd(self, to, socket):
  126. """
  127. A function to hook the send_fd in the bind10_src.
  128. """
  129. self.__send_fd_called = (to, socket)
  130. class FalseSocket:
  131. """
  132. A socket where we can fake methods we need instead of having a real
  133. socket.
  134. """
  135. def __init__(self):
  136. self.send = b""
  137. def fileno(self):
  138. """
  139. The file number. Used for identifying the remote application.
  140. """
  141. return 42
  142. def sendall(self, data):
  143. """
  144. Adds data to the self.send.
  145. """
  146. self.send += data
  147. def drop_application(self, application):
  148. """
  149. Part of pretending to be the cache. Logs the parameter to
  150. self.__drop_app_called.
  151. In the case self.__raise_exception is set, the exception there
  152. is raised instead.
  153. """
  154. if self.__raise_exception is not None:
  155. raise self.__raise_exception
  156. self.__drop_app_called = application
  157. def test_consumer_dead(self):
  158. """
  159. Test that it calls the drop_application method of the cache.
  160. """
  161. self.__boss.socket_consumer_dead(self.FalseSocket())
  162. self.assertEqual(42, self.__drop_app_called)
  163. def test_consumer_dead_invalid(self):
  164. """
  165. Test that it doesn't crash in case the application is not known to
  166. the cache, the boss doesn't crash, as this actually can happen in
  167. practice.
  168. """
  169. self.__raise_exception = ValueError("This application is unknown")
  170. # This doesn't crash
  171. self.__boss.socket_consumer_dead(self.FalseSocket())
  172. def get_socket(self, token, application):
  173. """
  174. Part of pretending to be the cache. If there's anything in
  175. __raise_exception, it is raised. Otherwise, the call is logged
  176. into __get_socket_called and a number is returned.
  177. """
  178. if self.__raise_exception is not None:
  179. raise self.__raise_exception
  180. self.__get_socket_called = (token, application)
  181. return 13
  182. def test_request_handler(self):
  183. """
  184. Test that a request for socket is forwarded and the socket is sent
  185. back, if it returns a socket.
  186. """
  187. socket = self.FalseSocket()
  188. # An exception from the cache
  189. self.__raise_exception = ValueError("Test value error")
  190. self.__boss.socket_request_handler(b"token", socket)
  191. # It was called, but it threw, so it is not noted here
  192. self.assertIsNone(self.__get_socket_called)
  193. self.assertEqual(b"0\n", socket.send)
  194. # It should not have sent any socket.
  195. self.assertIsNone(self.__send_fd_called)
  196. # Now prepare a valid scenario
  197. self.__raise_exception = None
  198. socket.send = b""
  199. self.__boss.socket_request_handler(b"token", socket)
  200. self.assertEqual(b"1\n", socket.send)
  201. self.assertEqual((42, 13), self.__send_fd_called)
  202. self.assertEqual(("token", 42), self.__get_socket_called)
  203. def get_token(self, protocol, address, port, share_mode, share_name):
  204. """
  205. Part of pretending to be the cache. If there's anything in
  206. __raise_exception, it is raised. Otherwise, the parameters are
  207. logged into __get_token_called and a token is returned.
  208. """
  209. if self.__raise_exception is not None:
  210. raise self.__raise_exception
  211. self.__get_token_called = (protocol, address, port, share_mode,
  212. share_name)
  213. return "token"
  214. def test_get_socket_ok(self):
  215. """
  216. Test the successful scenario of getting a socket.
  217. """
  218. result = self.__boss._get_socket(self.__socket_args)
  219. [code, answer] = result['result']
  220. self.assertEqual(0, code)
  221. self.assertEqual({
  222. 'token': 'token',
  223. 'path': '/socket/path'
  224. }, answer)
  225. addr = self.__get_token_called[1]
  226. self.assertTrue(isinstance(addr, IPAddr))
  227. self.assertEqual("::", str(addr))
  228. self.assertEqual(("UDP", addr, 53, "ANY", "app"),
  229. self.__get_token_called)
  230. def test_get_socket_error(self):
  231. """
  232. Test that bad inputs are handled correctly, etc.
  233. """
  234. def check_code(code, args):
  235. """
  236. Pass the args there and check if it returns success or not.
  237. The rest is not tested, as it is already checked in the
  238. test_get_socket_ok.
  239. """
  240. [rcode, ranswer] = self.__boss._get_socket(args)['result']
  241. self.assertEqual(code, rcode)
  242. if code != 0:
  243. # This should be an error message. The exact formatting
  244. # is unknown, but we check it is string at least
  245. self.assertTrue(isinstance(ranswer, str))
  246. def mod_args(name, value):
  247. """
  248. Override a parameter in the args.
  249. """
  250. result = dict(self.__socket_args)
  251. result[name] = value
  252. return result
  253. # Port too large
  254. check_code(1, mod_args('port', 65536))
  255. # Not numeric address
  256. check_code(1, mod_args('address', 'example.org.'))
  257. # Some bad values of enum-like params
  258. check_code(1, mod_args('protocol', 'BAD PROTO'))
  259. check_code(1, mod_args('share_mode', 'BAD SHARE'))
  260. # Check missing parameters
  261. for param in self.__socket_args.keys():
  262. args = dict(self.__socket_args)
  263. del args[param]
  264. check_code(1, args)
  265. # These are OK values for the enum-like parameters
  266. # The ones from test_get_socket_ok are not tested here
  267. check_code(0, mod_args('protocol', 'TCP'))
  268. check_code(0, mod_args('share_mode', 'SAMEAPP'))
  269. check_code(0, mod_args('share_mode', 'NO'))
  270. # If an exception is raised from within the cache, it is converted
  271. # to an error, not propagated
  272. self.__raise_exception = Exception("Test exception")
  273. check_code(1, self.__socket_args)
  274. # The special "expected" exceptions
  275. self.__raise_exception = \
  276. isc.bind10.socket_cache.ShareError("Not shared")
  277. check_code(3, self.__socket_args)
  278. self.__raise_exception = \
  279. isc.bind10.socket_cache.SocketError("Not shared", 13)
  280. check_code(2, self.__socket_args)
  281. def drop_socket(self, token):
  282. """
  283. Part of pretending to be the cache. If there's anything in
  284. __raise_exception, it is raised. Otherwise, the parameter is stored
  285. in __drop_socket_called.
  286. """
  287. if self.__raise_exception is not None:
  288. raise self.__raise_exception
  289. self.__drop_socket_called = token
  290. def test_drop_socket(self):
  291. """
  292. Check the drop_socket command. It should directly call the method
  293. on the cache. Exceptions should be translated to error messages.
  294. """
  295. # This should be OK and just propagated to the call.
  296. self.assertEqual({"result": [0]},
  297. self.__boss.command_handler("drop_socket",
  298. {"token": "token"}))
  299. self.assertEqual("token", self.__drop_socket_called)
  300. self.__drop_socket_called = None
  301. # Missing parameter
  302. self.assertEqual({"result": [1, "Missing token parameter"]},
  303. self.__boss.command_handler("drop_socket", {}))
  304. self.assertIsNone(self.__drop_socket_called)
  305. # An exception is raised from within the cache
  306. self.__raise_exception = ValueError("Test error")
  307. self.assertEqual({"result": [1, "Test error"]},
  308. self.__boss.command_handler("drop_socket",
  309. {"token": "token"}))
  310. class TestBoB(unittest.TestCase):
  311. def test_init(self):
  312. bob = BoB()
  313. self.assertEqual(bob.verbose, False)
  314. self.assertEqual(bob.msgq_socket_file, None)
  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.assertIsNone(bob._socket_cache)
  322. def test_set_creator(self):
  323. """
  324. Test the call to set_creator. First time, the cache is created
  325. with the passed creator. The next time, it throws an exception.
  326. """
  327. bob = BoB()
  328. # The cache doesn't use it at start, so just create an empty class
  329. class Creator: pass
  330. creator = Creator()
  331. bob.set_creator(creator)
  332. self.assertTrue(isinstance(bob._socket_cache,
  333. isc.bind10.socket_cache.Cache))
  334. self.assertEqual(creator, bob._socket_cache._creator)
  335. self.assertRaises(ValueError, bob.set_creator, creator)
  336. def test_init_alternate_socket(self):
  337. bob = BoB("alt_socket_file")
  338. self.assertEqual(bob.verbose, False)
  339. self.assertEqual(bob.msgq_socket_file, "alt_socket_file")
  340. self.assertEqual(bob.cc_session, None)
  341. self.assertEqual(bob.ccs, None)
  342. self.assertEqual(bob.components, {})
  343. self.assertEqual(bob.runnable, False)
  344. self.assertEqual(bob.uid, None)
  345. self.assertEqual(bob.username, None)
  346. def test_command_handler(self):
  347. class DummySession():
  348. def group_sendmsg(self, msg, group):
  349. (self.msg, self.group) = (msg, group)
  350. def group_recvmsg(self, nonblock, seq): pass
  351. class DummyModuleCCSession():
  352. module_spec = isc.config.module_spec.ModuleSpec({
  353. "module_name": "Boss",
  354. "statistics": [
  355. {
  356. "item_name": "boot_time",
  357. "item_type": "string",
  358. "item_optional": False,
  359. "item_default": "1970-01-01T00:00:00Z",
  360. "item_title": "Boot time",
  361. "item_description": "A date time when bind10 process starts initially",
  362. "item_format": "date-time"
  363. }
  364. ]
  365. })
  366. def get_module_spec(self):
  367. return self.module_spec
  368. bob = BoB()
  369. bob.verbose = True
  370. bob.cc_session = DummySession()
  371. bob.ccs = DummyModuleCCSession()
  372. # a bad command
  373. self.assertEqual(bob.command_handler(-1, None),
  374. isc.config.ccsession.create_answer(1, "bad command"))
  375. # "shutdown" command
  376. self.assertEqual(bob.command_handler("shutdown", None),
  377. isc.config.ccsession.create_answer(0))
  378. self.assertFalse(bob.runnable)
  379. # "getstats" command
  380. self.assertEqual(bob.command_handler("getstats", None),
  381. isc.config.ccsession.create_answer(0,
  382. { 'boot_time': time.strftime('%Y-%m-%dT%H:%M:%SZ', _BASETIME) }))
  383. # "ping" command
  384. self.assertEqual(bob.command_handler("ping", None),
  385. isc.config.ccsession.create_answer(0, "pong"))
  386. # "show_processes" command
  387. self.assertEqual(bob.command_handler("show_processes", None),
  388. isc.config.ccsession.create_answer(0,
  389. bob.get_processes()))
  390. # an unknown command
  391. self.assertEqual(bob.command_handler("__UNKNOWN__", None),
  392. isc.config.ccsession.create_answer(1, "Unknown command"))
  393. # Fake the get_token of cache and test the command works
  394. bob._socket_path = '/socket/path'
  395. class cache:
  396. def get_token(self, protocol, addr, port, share_mode, share_name):
  397. return str(addr) + ':' + str(port)
  398. bob._socket_cache = cache()
  399. args = {
  400. "port": 53,
  401. "address": "0.0.0.0",
  402. "protocol": "UDP",
  403. "share_mode": "ANY",
  404. "share_name": "app"
  405. }
  406. # at all and this is the easiest way to check.
  407. self.assertEqual({'result': [0, {'token': '0.0.0.0:53',
  408. 'path': '/socket/path'}]},
  409. bob.command_handler("get_socket", args))
  410. # The drop_socket is not tested here, but in TestCacheCommands.
  411. # It needs the cache mocks to be in place and they are there.
  412. def test_stop_process(self):
  413. """
  414. Test checking the stop_process method sends the right message over
  415. the message bus.
  416. """
  417. class DummySession():
  418. def group_sendmsg(self, msg, group, instance="*"):
  419. (self.msg, self.group, self.instance) = (msg, group, instance)
  420. bob = BoB()
  421. bob.cc_session = DummySession()
  422. bob.stop_process('process', 'address', 42)
  423. self.assertEqual('address', bob.cc_session.group)
  424. self.assertEqual('address', bob.cc_session.instance)
  425. self.assertEqual({'command': ['shutdown', {'pid': 42}]},
  426. bob.cc_session.msg)
  427. # Class for testing the BoB without actually starting processes.
  428. # This is used for testing the start/stop components routines and
  429. # the BoB commands.
  430. #
  431. # Testing that external processes start is outside the scope
  432. # of the unit test, by overriding the process start methods we can check
  433. # that the right processes are started depending on the configuration
  434. # options.
  435. class MockBob(BoB):
  436. def __init__(self):
  437. BoB.__init__(self)
  438. # Set flags as to which of the overridden methods has been run.
  439. self.msgq = False
  440. self.cfgmgr = False
  441. self.ccsession = False
  442. self.auth = False
  443. self.resolver = False
  444. self.xfrout = False
  445. self.xfrin = False
  446. self.zonemgr = False
  447. self.stats = False
  448. self.stats_httpd = False
  449. self.cmdctl = False
  450. self.dhcp6 = False
  451. self.dhcp4 = False
  452. self.c_channel_env = {}
  453. self.components = { }
  454. self.creator = False
  455. self.get_process_exit_status_called = False
  456. class MockSockCreator(isc.bind10.component.Component):
  457. def __init__(self, process, boss, kind, address=None, params=None):
  458. isc.bind10.component.Component.__init__(self, process, boss,
  459. kind, 'SockCreator')
  460. self._start_func = boss.start_creator
  461. specials = isc.bind10.special_component.get_specials()
  462. specials['sockcreator'] = MockSockCreator
  463. self._component_configurator = \
  464. isc.bind10.component.Configurator(self, specials)
  465. def start_creator(self):
  466. self.creator = True
  467. procinfo = ProcessInfo('b10-sockcreator', ['/bin/false'])
  468. procinfo.pid = 1
  469. return procinfo
  470. def _read_bind10_config(self):
  471. # Configuration options are set directly
  472. pass
  473. def start_msgq(self):
  474. self.msgq = True
  475. procinfo = ProcessInfo('b10-msgq', ['/bin/false'])
  476. procinfo.pid = 2
  477. return procinfo
  478. def start_ccsession(self, c_channel_env):
  479. # this is not a process, don't have to do anything with procinfo
  480. self.ccsession = True
  481. def start_cfgmgr(self):
  482. self.cfgmgr = True
  483. procinfo = ProcessInfo('b10-cfgmgr', ['/bin/false'])
  484. procinfo.pid = 3
  485. return procinfo
  486. def start_auth(self):
  487. self.auth = True
  488. procinfo = ProcessInfo('b10-auth', ['/bin/false'])
  489. procinfo.pid = 5
  490. return procinfo
  491. def start_resolver(self):
  492. self.resolver = True
  493. procinfo = ProcessInfo('b10-resolver', ['/bin/false'])
  494. procinfo.pid = 6
  495. return procinfo
  496. def start_simple(self, name):
  497. procmap = { 'b10-zonemgr': self.start_zonemgr,
  498. 'b10-stats': self.start_stats,
  499. 'b10-stats-httpd': self.start_stats_httpd,
  500. 'b10-cmdctl': self.start_cmdctl,
  501. 'b10-dhcp6': self.start_dhcp6,
  502. 'b10-dhcp4': self.start_dhcp4,
  503. 'b10-xfrin': self.start_xfrin,
  504. 'b10-xfrout': self.start_xfrout }
  505. return procmap[name]()
  506. def start_xfrout(self):
  507. self.xfrout = True
  508. procinfo = ProcessInfo('b10-xfrout', ['/bin/false'])
  509. procinfo.pid = 7
  510. return procinfo
  511. def start_xfrin(self):
  512. self.xfrin = True
  513. procinfo = ProcessInfo('b10-xfrin', ['/bin/false'])
  514. procinfo.pid = 8
  515. return procinfo
  516. def start_zonemgr(self):
  517. self.zonemgr = True
  518. procinfo = ProcessInfo('b10-zonemgr', ['/bin/false'])
  519. procinfo.pid = 9
  520. return procinfo
  521. def start_stats(self):
  522. self.stats = True
  523. procinfo = ProcessInfo('b10-stats', ['/bin/false'])
  524. procinfo.pid = 10
  525. return procinfo
  526. def start_stats_httpd(self):
  527. self.stats_httpd = True
  528. procinfo = ProcessInfo('b10-stats-httpd', ['/bin/false'])
  529. procinfo.pid = 11
  530. return procinfo
  531. def start_cmdctl(self):
  532. self.cmdctl = True
  533. procinfo = ProcessInfo('b10-cmdctl', ['/bin/false'])
  534. procinfo.pid = 12
  535. return procinfo
  536. def start_dhcp6(self):
  537. self.dhcp6 = True
  538. procinfo = ProcessInfo('b10-dhcp6', ['/bin/false'])
  539. procinfo.pid = 13
  540. return procinfo
  541. def start_dhcp4(self):
  542. self.dhcp4 = True
  543. procinfo = ProcessInfo('b10-dhcp4', ['/bin/false'])
  544. procinfo.pid = 14
  545. return procinfo
  546. def stop_process(self, process, recipient, pid):
  547. procmap = { 'b10-auth': self.stop_auth,
  548. 'b10-resolver': self.stop_resolver,
  549. 'b10-xfrout': self.stop_xfrout,
  550. 'b10-xfrin': self.stop_xfrin,
  551. 'b10-zonemgr': self.stop_zonemgr,
  552. 'b10-stats': self.stop_stats,
  553. 'b10-stats-httpd': self.stop_stats_httpd,
  554. 'b10-cmdctl': self.stop_cmdctl }
  555. procmap[process]()
  556. # Some functions to pretend we stop processes, use by stop_process
  557. def stop_msgq(self):
  558. if self.msgq:
  559. del self.components[2]
  560. self.msgq = False
  561. def stop_cfgmgr(self):
  562. if self.cfgmgr:
  563. del self.components[3]
  564. self.cfgmgr = False
  565. def stop_auth(self):
  566. if self.auth:
  567. del self.components[5]
  568. self.auth = False
  569. def stop_resolver(self):
  570. if self.resolver:
  571. del self.components[6]
  572. self.resolver = False
  573. def stop_xfrout(self):
  574. if self.xfrout:
  575. del self.components[7]
  576. self.xfrout = False
  577. def stop_xfrin(self):
  578. if self.xfrin:
  579. del self.components[8]
  580. self.xfrin = False
  581. def stop_zonemgr(self):
  582. if self.zonemgr:
  583. del self.components[9]
  584. self.zonemgr = False
  585. def stop_stats(self):
  586. if self.stats:
  587. del self.components[10]
  588. self.stats = False
  589. def stop_stats_httpd(self):
  590. if self.stats_httpd:
  591. del self.components[11]
  592. self.stats_httpd = False
  593. def stop_cmdctl(self):
  594. if self.cmdctl:
  595. del self.components[12]
  596. self.cmdctl = False
  597. def _get_process_exit_status(self):
  598. if self.get_process_exit_status_called:
  599. return (0, 0)
  600. self.get_process_exit_status_called = True
  601. return (53, 0)
  602. class TestStartStopProcessesBob(unittest.TestCase):
  603. """
  604. Check that the start_all_components method starts the right combination
  605. of components and that the right components are started and stopped
  606. according to changes in configuration.
  607. """
  608. def check_environment_unchanged(self):
  609. # Check whether the environment has not been changed
  610. self.assertEqual(original_os_environ, os.environ)
  611. def check_started(self, bob, core, auth, resolver):
  612. """
  613. Check that the right sets of services are started. The ones that
  614. should be running are specified by the core, auth and resolver parameters
  615. (they are groups of processes, eg. auth means b10-auth, -xfrout, -xfrin
  616. and -zonemgr).
  617. """
  618. self.assertEqual(bob.msgq, core)
  619. self.assertEqual(bob.cfgmgr, core)
  620. self.assertEqual(bob.ccsession, core)
  621. self.assertEqual(bob.creator, core)
  622. self.assertEqual(bob.auth, auth)
  623. self.assertEqual(bob.resolver, resolver)
  624. self.assertEqual(bob.xfrout, auth)
  625. self.assertEqual(bob.xfrin, auth)
  626. self.assertEqual(bob.zonemgr, auth)
  627. self.assertEqual(bob.stats, core)
  628. self.assertEqual(bob.stats_httpd, core)
  629. self.assertEqual(bob.cmdctl, core)
  630. self.check_environment_unchanged()
  631. def check_preconditions(self, bob):
  632. self.check_started(bob, False, False, False)
  633. def check_started_none(self, bob):
  634. """
  635. Check that the situation is according to configuration where no servers
  636. should be started. Some components still need to be running.
  637. """
  638. self.check_started(bob, True, False, False)
  639. self.check_environment_unchanged()
  640. def check_started_both(self, bob):
  641. """
  642. Check the situation is according to configuration where both servers
  643. (auth and resolver) are enabled.
  644. """
  645. self.check_started(bob, True, True, True)
  646. self.check_environment_unchanged()
  647. def check_started_auth(self, bob):
  648. """
  649. Check the set of components needed to run auth only is started.
  650. """
  651. self.check_started(bob, True, True, False)
  652. self.check_environment_unchanged()
  653. def check_started_resolver(self, bob):
  654. """
  655. Check the set of components needed to run resolver only is started.
  656. """
  657. self.check_started(bob, True, False, True)
  658. self.check_environment_unchanged()
  659. def check_started_dhcp(self, bob, v4, v6):
  660. """
  661. Check if proper combinations of DHCPv4 and DHCpv6 can be started
  662. """
  663. self.assertEqual(v4, bob.dhcp4)
  664. self.assertEqual(v6, bob.dhcp6)
  665. self.check_environment_unchanged()
  666. def construct_config(self, start_auth, start_resolver):
  667. # The things that are common, not turned on an off
  668. config = {}
  669. config['b10-stats'] = { 'kind': 'dispensable', 'address': 'Stats' }
  670. config['b10-stats-httpd'] = { 'kind': 'dispensable',
  671. 'address': 'StatsHttpd' }
  672. config['b10-cmdctl'] = { 'kind': 'needed', 'special': 'cmdctl' }
  673. if start_auth:
  674. config['b10-auth'] = { 'kind': 'needed', 'special': 'auth' }
  675. config['b10-xfrout'] = { 'kind': 'dispensable',
  676. 'address': 'Xfrout' }
  677. config['b10-xfrin'] = { 'kind': 'dispensable',
  678. 'address': 'Xfrin' }
  679. config['b10-zonemgr'] = { 'kind': 'dispensable',
  680. 'address': 'Zonemgr' }
  681. if start_resolver:
  682. config['b10-resolver'] = { 'kind': 'needed',
  683. 'special': 'resolver' }
  684. return {'components': config}
  685. def config_start_init(self, start_auth, start_resolver):
  686. """
  687. Test the configuration is loaded at the startup.
  688. """
  689. bob = MockBob()
  690. config = self.construct_config(start_auth, start_resolver)
  691. class CC:
  692. def get_full_config(self):
  693. return config
  694. # Provide the fake CC with data
  695. bob.ccs = CC()
  696. # And make sure it's not overwritten
  697. def start_ccsession():
  698. bob.ccsession = True
  699. bob.start_ccsession = lambda _: start_ccsession()
  700. # We need to return the original _read_bind10_config
  701. bob._read_bind10_config = lambda: BoB._read_bind10_config(bob)
  702. bob.start_all_components()
  703. self.check_started(bob, True, start_auth, start_resolver)
  704. self.check_environment_unchanged()
  705. def test_start_none(self):
  706. self.config_start_init(False, False)
  707. def test_start_resolver(self):
  708. self.config_start_init(False, True)
  709. def test_start_auth(self):
  710. self.config_start_init(True, False)
  711. def test_start_both(self):
  712. self.config_start_init(True, True)
  713. def test_config_start(self):
  714. """
  715. Test that the configuration starts and stops components according
  716. to configuration changes.
  717. """
  718. # Create BoB and ensure correct initialization
  719. bob = MockBob()
  720. self.check_preconditions(bob)
  721. bob.start_all_components()
  722. bob.runnable = True
  723. bob.config_handler(self.construct_config(False, False))
  724. self.check_started_none(bob)
  725. # Enable both at once
  726. bob.config_handler(self.construct_config(True, True))
  727. self.check_started_both(bob)
  728. # Not touched by empty change
  729. bob.config_handler({})
  730. self.check_started_both(bob)
  731. # Not touched by change to the same configuration
  732. bob.config_handler(self.construct_config(True, True))
  733. self.check_started_both(bob)
  734. # Turn them both off again
  735. bob.config_handler(self.construct_config(False, False))
  736. self.check_started_none(bob)
  737. # Not touched by empty change
  738. bob.config_handler({})
  739. self.check_started_none(bob)
  740. # Not touched by change to the same configuration
  741. bob.config_handler(self.construct_config(False, False))
  742. self.check_started_none(bob)
  743. # Start and stop auth separately
  744. bob.config_handler(self.construct_config(True, False))
  745. self.check_started_auth(bob)
  746. bob.config_handler(self.construct_config(False, False))
  747. self.check_started_none(bob)
  748. # Start and stop resolver separately
  749. bob.config_handler(self.construct_config(False, True))
  750. self.check_started_resolver(bob)
  751. bob.config_handler(self.construct_config(False, False))
  752. self.check_started_none(bob)
  753. # Alternate
  754. bob.config_handler(self.construct_config(True, False))
  755. self.check_started_auth(bob)
  756. bob.config_handler(self.construct_config(False, True))
  757. self.check_started_resolver(bob)
  758. bob.config_handler(self.construct_config(True, False))
  759. self.check_started_auth(bob)
  760. def test_config_start_once(self):
  761. """
  762. Tests that a component is started only once.
  763. """
  764. # Create BoB and ensure correct initialization
  765. bob = MockBob()
  766. self.check_preconditions(bob)
  767. bob.start_all_components()
  768. bob.runnable = True
  769. bob.config_handler(self.construct_config(True, True))
  770. self.check_started_both(bob)
  771. bob.start_auth = lambda: self.fail("Started auth again")
  772. bob.start_xfrout = lambda: self.fail("Started xfrout again")
  773. bob.start_xfrin = lambda: self.fail("Started xfrin again")
  774. bob.start_zonemgr = lambda: self.fail("Started zonemgr again")
  775. bob.start_resolver = lambda: self.fail("Started resolver again")
  776. # Send again we want to start them. Should not do it, as they are.
  777. bob.config_handler(self.construct_config(True, True))
  778. def test_config_not_started_early(self):
  779. """
  780. Test that components are not started by the config handler before
  781. startup.
  782. """
  783. bob = MockBob()
  784. self.check_preconditions(bob)
  785. bob.start_auth = lambda: self.fail("Started auth again")
  786. bob.start_xfrout = lambda: self.fail("Started xfrout again")
  787. bob.start_xfrin = lambda: self.fail("Started xfrin again")
  788. bob.start_zonemgr = lambda: self.fail("Started zonemgr again")
  789. bob.start_resolver = lambda: self.fail("Started resolver again")
  790. bob.config_handler({'start_auth': True, 'start_resolver': True})
  791. # Checks that DHCP (v4 and v6) components are started when expected
  792. def test_start_dhcp(self):
  793. # Create BoB and ensure correct initialization
  794. bob = MockBob()
  795. self.check_preconditions(bob)
  796. bob.start_all_components()
  797. bob.config_handler(self.construct_config(False, False))
  798. self.check_started_dhcp(bob, False, False)
  799. def test_start_dhcp_v6only(self):
  800. # Create BoB and ensure correct initialization
  801. bob = MockBob()
  802. self.check_preconditions(bob)
  803. # v6 only enabled
  804. bob.start_all_components()
  805. bob.runnable = True
  806. bob._BoB_started = True
  807. config = self.construct_config(False, False)
  808. config['components']['b10-dhcp6'] = { 'kind': 'needed',
  809. 'address': 'Dhcp6' }
  810. bob.config_handler(config)
  811. self.check_started_dhcp(bob, False, True)
  812. # uncomment when dhcpv4 becomes implemented
  813. # v4 only enabled
  814. #bob.cfg_start_dhcp6 = False
  815. #bob.cfg_start_dhcp4 = True
  816. #self.check_started_dhcp(bob, True, False)
  817. # both v4 and v6 enabled
  818. #bob.cfg_start_dhcp6 = True
  819. #bob.cfg_start_dhcp4 = True
  820. #self.check_started_dhcp(bob, True, True)
  821. class MockComponent:
  822. def __init__(self, name, pid, address=None):
  823. self.name = lambda: name
  824. self.pid = lambda: pid
  825. self.address = lambda: address
  826. self.restarted = False
  827. def get_restart_time(self):
  828. return 0 # arbitrary dummy value
  829. def restart(self, now):
  830. self.restarted = True
  831. return True
  832. def is_running(self):
  833. return True
  834. def failed(self, status):
  835. return False
  836. class TestBossCmd(unittest.TestCase):
  837. def test_ping(self):
  838. """
  839. Confirm simple ping command works.
  840. """
  841. bob = MockBob()
  842. answer = bob.command_handler("ping", None)
  843. self.assertEqual(answer, {'result': [0, 'pong']})
  844. def test_show_processes_empty(self):
  845. """
  846. Confirm getting a list of processes works.
  847. """
  848. bob = MockBob()
  849. answer = bob.command_handler("show_processes", None)
  850. self.assertEqual(answer, {'result': [0, []]})
  851. def test_show_processes(self):
  852. """
  853. Confirm getting a list of processes works.
  854. """
  855. bob = MockBob()
  856. bob.register_process(1, MockComponent('first', 1))
  857. bob.register_process(2, MockComponent('second', 2, 'Second'))
  858. answer = bob.command_handler("show_processes", None)
  859. processes = [[1, 'first', None],
  860. [2, 'second', 'Second']]
  861. self.assertEqual(answer, {'result': [0, processes]})
  862. class TestParseArgs(unittest.TestCase):
  863. """
  864. This tests parsing of arguments of the bind10 master process.
  865. """
  866. #TODO: Write tests for the original parsing, bad options, etc.
  867. def test_no_opts(self):
  868. """
  869. Test correct default values when no options are passed.
  870. """
  871. options = parse_args([], TestOptParser)
  872. self.assertEqual(None, options.data_path)
  873. self.assertEqual(None, options.config_file)
  874. self.assertEqual(None, options.cmdctl_port)
  875. def test_data_path(self):
  876. """
  877. Test it can parse the data path.
  878. """
  879. self.assertRaises(OptsError, parse_args, ['-p'], TestOptParser)
  880. self.assertRaises(OptsError, parse_args, ['--data-path'],
  881. TestOptParser)
  882. options = parse_args(['-p', '/data/path'], TestOptParser)
  883. self.assertEqual('/data/path', options.data_path)
  884. options = parse_args(['--data-path=/data/path'], TestOptParser)
  885. self.assertEqual('/data/path', options.data_path)
  886. def test_config_filename(self):
  887. """
  888. Test it can parse the config switch.
  889. """
  890. self.assertRaises(OptsError, parse_args, ['-c'], TestOptParser)
  891. self.assertRaises(OptsError, parse_args, ['--config-file'],
  892. TestOptParser)
  893. options = parse_args(['-c', 'config-file'], TestOptParser)
  894. self.assertEqual('config-file', options.config_file)
  895. options = parse_args(['--config-file=config-file'], TestOptParser)
  896. self.assertEqual('config-file', options.config_file)
  897. def test_clear_config(self):
  898. options = parse_args([], TestOptParser)
  899. self.assertEqual(False, options.clear_config)
  900. options = parse_args(['--clear-config'], TestOptParser)
  901. self.assertEqual(True, options.clear_config)
  902. def test_nokill(self):
  903. options = parse_args([], TestOptParser)
  904. self.assertEqual(False, options.nokill)
  905. options = parse_args(['--no-kill'], TestOptParser)
  906. self.assertEqual(True, options.nokill)
  907. options = parse_args([], TestOptParser)
  908. self.assertEqual(False, options.nokill)
  909. options = parse_args(['-i'], TestOptParser)
  910. self.assertEqual(True, options.nokill)
  911. def test_cmdctl_port(self):
  912. """
  913. Test it can parse the command control port.
  914. """
  915. self.assertRaises(OptsError, parse_args, ['--cmdctl-port=abc'],
  916. TestOptParser)
  917. self.assertRaises(OptsError, parse_args, ['--cmdctl-port=100000000'],
  918. TestOptParser)
  919. self.assertRaises(OptsError, parse_args, ['--cmdctl-port'],
  920. TestOptParser)
  921. options = parse_args(['--cmdctl-port=1234'], TestOptParser)
  922. self.assertEqual(1234, options.cmdctl_port)
  923. class TestPIDFile(unittest.TestCase):
  924. def setUp(self):
  925. self.pid_file = '@builddir@' + os.sep + 'bind10.pid'
  926. if os.path.exists(self.pid_file):
  927. os.unlink(self.pid_file)
  928. def tearDown(self):
  929. if os.path.exists(self.pid_file):
  930. os.unlink(self.pid_file)
  931. def check_pid_file(self):
  932. # dump PID to the file, and confirm the content is correct
  933. dump_pid(self.pid_file)
  934. my_pid = os.getpid()
  935. with open(self.pid_file, "r") as f:
  936. self.assertEqual(my_pid, int(f.read()))
  937. def test_dump_pid(self):
  938. self.check_pid_file()
  939. # make sure any existing content will be removed
  940. with open(self.pid_file, "w") as f:
  941. f.write('dummy data\n')
  942. self.check_pid_file()
  943. def test_unlink_pid_file_notexist(self):
  944. dummy_data = 'dummy_data\n'
  945. with open(self.pid_file, "w") as f:
  946. f.write(dummy_data)
  947. unlink_pid_file("no_such_pid_file")
  948. # the file specified for unlink_pid_file doesn't exist,
  949. # and the original content of the file should be intact.
  950. with open(self.pid_file, "r") as f:
  951. self.assertEqual(dummy_data, f.read())
  952. def test_dump_pid_with_none(self):
  953. # Check the behavior of dump_pid() and unlink_pid_file() with None.
  954. # This should be no-op.
  955. dump_pid(None)
  956. self.assertFalse(os.path.exists(self.pid_file))
  957. dummy_data = 'dummy_data\n'
  958. with open(self.pid_file, "w") as f:
  959. f.write(dummy_data)
  960. unlink_pid_file(None)
  961. with open(self.pid_file, "r") as f:
  962. self.assertEqual(dummy_data, f.read())
  963. def test_dump_pid_failure(self):
  964. # the attempt to open file will fail, which should result in exception.
  965. self.assertRaises(IOError, dump_pid,
  966. 'nonexistent_dir' + os.sep + 'bind10.pid')
  967. class TestBossComponents(unittest.TestCase):
  968. """
  969. Test the boss propagates component configuration properly to the
  970. component configurator and acts sane.
  971. """
  972. def setUp(self):
  973. self.__param = None
  974. self.__called = False
  975. self.__compconfig = {
  976. 'comp': {
  977. 'kind': 'needed',
  978. 'process': 'cat'
  979. }
  980. }
  981. def __unary_hook(self, param):
  982. """
  983. A hook function that stores the parameter for later examination.
  984. """
  985. self.__param = param
  986. def __nullary_hook(self):
  987. """
  988. A hook function that notes down it was called.
  989. """
  990. self.__called = True
  991. def __check_core(self, config):
  992. """
  993. A function checking that the config contains parts for the valid
  994. core component configuration.
  995. """
  996. self.assertIsNotNone(config)
  997. for component in ['sockcreator', 'msgq', 'cfgmgr']:
  998. self.assertTrue(component in config)
  999. self.assertEqual(component, config[component]['special'])
  1000. self.assertEqual('core', config[component]['kind'])
  1001. def __check_extended(self, config):
  1002. """
  1003. This checks that the config contains the core and one more component.
  1004. """
  1005. self.__check_core(config)
  1006. self.assertTrue('comp' in config)
  1007. self.assertEqual('cat', config['comp']['process'])
  1008. self.assertEqual('needed', config['comp']['kind'])
  1009. self.assertEqual(4, len(config))
  1010. def test_correct_run(self):
  1011. """
  1012. Test the situation when we run in usual scenario, nothing fails,
  1013. we just start, reconfigure and then stop peacefully.
  1014. """
  1015. bob = MockBob()
  1016. # Start it
  1017. orig = bob._component_configurator.startup
  1018. bob._component_configurator.startup = self.__unary_hook
  1019. bob.start_all_components()
  1020. bob._component_configurator.startup = orig
  1021. self.__check_core(self.__param)
  1022. self.assertEqual(3, len(self.__param))
  1023. # Reconfigure it
  1024. self.__param = None
  1025. orig = bob._component_configurator.reconfigure
  1026. bob._component_configurator.reconfigure = self.__unary_hook
  1027. # Otherwise it does not work
  1028. bob.runnable = True
  1029. bob.config_handler({'components': self.__compconfig})
  1030. self.__check_extended(self.__param)
  1031. currconfig = self.__param
  1032. # If we reconfigure it, but it does not contain the components part,
  1033. # nothing is called
  1034. bob.config_handler({})
  1035. self.assertEqual(self.__param, currconfig)
  1036. self.__param = None
  1037. bob._component_configurator.reconfigure = orig
  1038. # Check a configuration that messes up the core components is rejected.
  1039. compconf = dict(self.__compconfig)
  1040. compconf['msgq'] = { 'process': 'echo' }
  1041. result = bob.config_handler({'components': compconf})
  1042. # Check it rejected it
  1043. self.assertEqual(1, result['result'][0])
  1044. # We can't call shutdown, that one relies on the stuff in main
  1045. # We check somewhere else that the shutdown is actually called
  1046. # from there (the test_kills).
  1047. def __real_test_kill(self, nokill=False, ex_on_kill=None):
  1048. """
  1049. Helper function that does the actual kill functionality testing.
  1050. """
  1051. bob = MockBob()
  1052. bob.nokill = nokill
  1053. killed = []
  1054. class ImmortalComponent:
  1055. """
  1056. An immortal component. It does not stop when it is told so
  1057. (anyway it is not told so). It does not die if it is killed
  1058. the first time. It dies only when killed forcefully.
  1059. """
  1060. def __init__(self):
  1061. # number of kill() calls, preventing infinite loop.
  1062. self.__call_count = 0
  1063. def kill(self, forceful=False):
  1064. self.__call_count += 1
  1065. if self.__call_count > 2:
  1066. raise Exception('Too many calls to ImmortalComponent.kill')
  1067. killed.append(forceful)
  1068. if ex_on_kill is not None:
  1069. # If exception is given by the test, raise it here.
  1070. # In the case of ESRCH, the process should have gone
  1071. # somehow, so we clear the components.
  1072. if ex_on_kill.errno == errno.ESRCH:
  1073. bob.components = {}
  1074. raise ex_on_kill
  1075. if forceful:
  1076. bob.components = {}
  1077. def pid(self):
  1078. return 1
  1079. def name(self):
  1080. return "Immortal"
  1081. bob.components = {}
  1082. bob.register_process(1, ImmortalComponent())
  1083. # While at it, we check the configurator shutdown is actually called
  1084. orig = bob._component_configurator.shutdown
  1085. bob._component_configurator.shutdown = self.__nullary_hook
  1086. self.__called = False
  1087. bob.ccs = MockModuleCCSession()
  1088. self.assertFalse(bob.ccs.stopped)
  1089. bob.shutdown()
  1090. self.assertTrue(bob.ccs.stopped)
  1091. # Here, killed is an array where False is added if SIGTERM
  1092. # should be sent, or True if SIGKILL should be sent, in order in
  1093. # which they're sent.
  1094. if nokill:
  1095. self.assertEqual([], killed)
  1096. else:
  1097. if ex_on_kill is not None:
  1098. self.assertEqual([False], killed)
  1099. else:
  1100. self.assertEqual([False, True], killed)
  1101. self.assertTrue(self.__called)
  1102. bob._component_configurator.shutdown = orig
  1103. def test_kills(self):
  1104. """
  1105. Test that the boss kills components which don't want to stop.
  1106. """
  1107. self.__real_test_kill()
  1108. def test_kill_fail(self):
  1109. """Test cases where kill() results in an exception due to OS error.
  1110. The behavior should be different for EPERM, so we test two cases.
  1111. """
  1112. ex = OSError()
  1113. ex.errno, ex.strerror = errno.ESRCH, 'No such process'
  1114. self.__real_test_kill(ex_on_kill=ex)
  1115. ex.errno, ex.strerror = errno.EPERM, 'Operation not permitted'
  1116. self.__real_test_kill(ex_on_kill=ex)
  1117. def test_nokill(self):
  1118. """
  1119. Test that the boss *doesn't* kill components which don't want to
  1120. stop, when asked not to (by passing the --no-kill option which
  1121. sets bob.nokill to True).
  1122. """
  1123. self.__real_test_kill(True)
  1124. def test_component_shutdown(self):
  1125. """
  1126. Test the component_shutdown sets all variables accordingly.
  1127. """
  1128. bob = MockBob()
  1129. self.assertRaises(Exception, bob.component_shutdown, 1)
  1130. self.assertEqual(1, bob.exitcode)
  1131. bob._BoB__started = True
  1132. bob.component_shutdown(2)
  1133. self.assertEqual(2, bob.exitcode)
  1134. self.assertFalse(bob.runnable)
  1135. def test_init_config(self):
  1136. """
  1137. Test initial configuration is loaded.
  1138. """
  1139. bob = MockBob()
  1140. # Start it
  1141. bob._component_configurator.reconfigure = self.__unary_hook
  1142. # We need to return the original read_bind10_config
  1143. bob._read_bind10_config = lambda: BoB._read_bind10_config(bob)
  1144. # And provide a session to read the data from
  1145. class CC:
  1146. pass
  1147. bob.ccs = CC()
  1148. bob.ccs.get_full_config = lambda: {'components': self.__compconfig}
  1149. bob.start_all_components()
  1150. self.__check_extended(self.__param)
  1151. def __setup_restart(self, bob, component):
  1152. '''Common procedure for restarting a component used below.'''
  1153. bob.components_to_restart = { component }
  1154. component.restarted = False
  1155. bob.restart_processes()
  1156. def test_restart_processes(self):
  1157. '''Check some behavior on restarting processes.'''
  1158. bob = MockBob()
  1159. bob.runnable = True
  1160. component = MockComponent('test', 53)
  1161. # A component to be restarted will actually be restarted iff it's
  1162. # in the configurator's configuration.
  1163. # We bruteforce the configurator internal below; ugly, but the easiest
  1164. # way for the test.
  1165. bob._component_configurator._components['test'] = (None, component)
  1166. self.__setup_restart(bob, component)
  1167. self.assertTrue(component.restarted)
  1168. self.assertFalse(component in bob.components_to_restart)
  1169. # Remove the component from the configuration. It won't be restarted
  1170. # even if scheduled, nor will remain in the to-be-restarted list.
  1171. del bob._component_configurator._components['test']
  1172. self.__setup_restart(bob, component)
  1173. self.assertFalse(component.restarted)
  1174. self.assertFalse(component in bob.components_to_restart)
  1175. def test_get_processes(self):
  1176. '''Test that procsses are returned correctly.'''
  1177. bob = MockBob()
  1178. bob.runnable = True
  1179. component = MockComponent('test', 53, 'Test')
  1180. bob.components[53] = component
  1181. process_list = bob.get_processes()
  1182. self.assertEqual([[53, 'test', 'Test']], process_list)
  1183. def test_reap_children(self):
  1184. '''Test that children are queued to be restarted when they ask for it.'''
  1185. bob = MockBob()
  1186. bob.runnable = True
  1187. component = MockComponent('test', 53)
  1188. bob.components[53] = component
  1189. # at first, we don't have the component with pid 53 that
  1190. # terminated in our restart queue.
  1191. self.assertFalse(component in bob.components_to_restart)
  1192. bob.reap_children()
  1193. # now, we should as the mock component.failed() returns False
  1194. self.assertTrue(component in bob.components_to_restart)
  1195. class SocketSrvTest(unittest.TestCase):
  1196. """
  1197. This tests some methods of boss related to the unix domain sockets used
  1198. to transfer other sockets to applications.
  1199. """
  1200. def setUp(self):
  1201. """
  1202. Create the boss to test, testdata and backup some functions.
  1203. """
  1204. self.__boss = BoB()
  1205. self.__select_backup = bind10_src.select.select
  1206. self.__select_called = None
  1207. self.__socket_data_called = None
  1208. self.__consumer_dead_called = None
  1209. self.__socket_request_handler_called = None
  1210. def tearDown(self):
  1211. """
  1212. Restore functions.
  1213. """
  1214. bind10_src.select.select = self.__select_backup
  1215. class __FalseSocket:
  1216. """
  1217. A mock socket for the select and accept and stuff like that.
  1218. """
  1219. def __init__(self, owner, fileno=42):
  1220. self.__owner = owner
  1221. self.__fileno = fileno
  1222. self.data = None
  1223. self.closed = False
  1224. def fileno(self):
  1225. return self.__fileno
  1226. def accept(self):
  1227. return (self.__class__(self.__owner, 13), "/path/to/socket")
  1228. def recv(self, bufsize, flags=0):
  1229. self.__owner.assertEqual(1, bufsize)
  1230. self.__owner.assertEqual(socket.MSG_DONTWAIT, flags)
  1231. if isinstance(self.data, socket.error):
  1232. raise self.data
  1233. elif self.data is not None:
  1234. if len(self.data):
  1235. result = self.data[0:1]
  1236. self.data = self.data[1:]
  1237. return result
  1238. else:
  1239. raise socket.error(errno.EAGAIN, "Would block")
  1240. else:
  1241. return b''
  1242. def close(self):
  1243. self.closed = True
  1244. class __CCS:
  1245. """
  1246. A mock CCS, just to provide the socket file number.
  1247. """
  1248. class __Socket:
  1249. def fileno(self):
  1250. return 1
  1251. def get_socket(self):
  1252. return self.__Socket()
  1253. def __select_accept(self, r, w, x, t):
  1254. self.__select_called = (r, w, x, t)
  1255. return ([42], [], [])
  1256. def __select_data(self, r, w, x, t):
  1257. self.__select_called = (r, w, x, t)
  1258. return ([13], [], [])
  1259. def __accept(self):
  1260. """
  1261. Hijact the accept method of the boss.
  1262. Notes down it was called and stops the boss.
  1263. """
  1264. self.__accept_called = True
  1265. self.__boss.runnable = False
  1266. def test_srv_accept_called(self):
  1267. """
  1268. Test that the _srv_accept method of boss is called when the listening
  1269. socket is readable.
  1270. """
  1271. self.__boss.runnable = True
  1272. self.__boss._srv_socket = self.__FalseSocket(self)
  1273. self.__boss._srv_accept = self.__accept
  1274. self.__boss.ccs = self.__CCS()
  1275. bind10_src.select.select = self.__select_accept
  1276. self.__boss.run(2)
  1277. # It called the accept
  1278. self.assertTrue(self.__accept_called)
  1279. # And the select had the right parameters
  1280. self.assertEqual(([2, 1, 42], [], [], None), self.__select_called)
  1281. def test_srv_accept(self):
  1282. """
  1283. Test how the _srv_accept method works.
  1284. """
  1285. self.__boss._srv_socket = self.__FalseSocket(self)
  1286. self.__boss._srv_accept()
  1287. # After we accepted, a new socket is added there
  1288. socket = self.__boss._unix_sockets[13][0]
  1289. # The socket is properly stored there
  1290. self.assertTrue(isinstance(socket, self.__FalseSocket))
  1291. # And the buffer (yet empty) is there
  1292. self.assertEqual({13: (socket, b'')}, self.__boss._unix_sockets)
  1293. def __socket_data(self, socket):
  1294. self.__boss.runnable = False
  1295. self.__socket_data_called = socket
  1296. def test_socket_data(self):
  1297. """
  1298. Test that a socket that wants attention gets it.
  1299. """
  1300. self.__boss._srv_socket = self.__FalseSocket(self)
  1301. self.__boss._socket_data = self.__socket_data
  1302. self.__boss.ccs = self.__CCS()
  1303. self.__boss._unix_sockets = {13: (self.__FalseSocket(self, 13), b'')}
  1304. self.__boss.runnable = True
  1305. bind10_src.select.select = self.__select_data
  1306. self.__boss.run(2)
  1307. self.assertEqual(13, self.__socket_data_called)
  1308. self.assertEqual(([2, 1, 42, 13], [], [], None), self.__select_called)
  1309. def __prepare_data(self, data):
  1310. socket = self.__FalseSocket(self, 13)
  1311. self.__boss._unix_sockets = {13: (socket, b'')}
  1312. socket.data = data
  1313. self.__boss.socket_consumer_dead = self.__consumer_dead
  1314. self.__boss.socket_request_handler = self.__socket_request_handler
  1315. return socket
  1316. def __consumer_dead(self, socket):
  1317. self.__consumer_dead_called = socket
  1318. def __socket_request_handler(self, token, socket):
  1319. self.__socket_request_handler_called = (token, socket)
  1320. def test_socket_closed(self):
  1321. """
  1322. Test that a socket is removed and the socket_consumer_dead is called
  1323. when it is closed.
  1324. """
  1325. socket = self.__prepare_data(None)
  1326. self.__boss._socket_data(13)
  1327. self.assertEqual(socket, self.__consumer_dead_called)
  1328. self.assertEqual({}, self.__boss._unix_sockets)
  1329. self.assertTrue(socket.closed)
  1330. def test_socket_short(self):
  1331. """
  1332. Test that if there's not enough data to get the whole socket, it is
  1333. kept there, but nothing is called.
  1334. """
  1335. socket = self.__prepare_data(b'tok')
  1336. self.__boss._socket_data(13)
  1337. self.assertEqual({13: (socket, b'tok')}, self.__boss._unix_sockets)
  1338. self.assertFalse(socket.closed)
  1339. self.assertIsNone(self.__consumer_dead_called)
  1340. self.assertIsNone(self.__socket_request_handler_called)
  1341. def test_socket_continue(self):
  1342. """
  1343. Test that we call the token handling function when the whole token
  1344. comes. This test pretends to continue reading where the previous one
  1345. stopped.
  1346. """
  1347. socket = self.__prepare_data(b"en\nanothe")
  1348. # The data to finish
  1349. self.__boss._unix_sockets[13] = (socket, b'tok')
  1350. self.__boss._socket_data(13)
  1351. self.assertEqual({13: (socket, b'anothe')}, self.__boss._unix_sockets)
  1352. self.assertFalse(socket.closed)
  1353. self.assertIsNone(self.__consumer_dead_called)
  1354. self.assertEqual((b'token', socket),
  1355. self.__socket_request_handler_called)
  1356. def test_broken_socket(self):
  1357. """
  1358. If the socket raises an exception during the read other than EAGAIN,
  1359. it is broken and we remove it.
  1360. """
  1361. sock = self.__prepare_data(socket.error(errno.ENOMEM,
  1362. "There's more memory available, but not for you"))
  1363. self.__boss._socket_data(13)
  1364. self.assertEqual(sock, self.__consumer_dead_called)
  1365. self.assertEqual({}, self.__boss._unix_sockets)
  1366. self.assertTrue(sock.closed)
  1367. class TestFunctions(unittest.TestCase):
  1368. def setUp(self):
  1369. self.lockfile_testpath = \
  1370. "@abs_top_builddir@/src/bin/bind10/tests/lockfile_test"
  1371. self.assertFalse(os.path.exists(self.lockfile_testpath))
  1372. os.mkdir(self.lockfile_testpath)
  1373. self.assertTrue(os.path.isdir(self.lockfile_testpath))
  1374. def tearDown(self):
  1375. os.rmdir(self.lockfile_testpath)
  1376. self.assertFalse(os.path.isdir(self.lockfile_testpath))
  1377. os.environ["B10_LOCKFILE_DIR_FROM_BUILD"] = "@abs_top_builddir@"
  1378. def test_remove_lock_files(self):
  1379. os.environ["B10_LOCKFILE_DIR_FROM_BUILD"] = self.lockfile_testpath
  1380. # create lockfiles for the testcase
  1381. lockfiles = ["logger_lockfile"]
  1382. for f in lockfiles:
  1383. fname = os.environ["B10_LOCKFILE_DIR_FROM_BUILD"] + '/' + f
  1384. self.assertFalse(os.path.exists(fname))
  1385. open(fname, "w").close()
  1386. self.assertTrue(os.path.isfile(fname))
  1387. # first call should clear up all the lockfiles
  1388. bind10_src.remove_lock_files()
  1389. # check if the lockfiles exist
  1390. for f in lockfiles:
  1391. fname = os.environ["B10_LOCKFILE_DIR_FROM_BUILD"] + '/' + f
  1392. self.assertFalse(os.path.isfile(fname))
  1393. # second call should not assert anyway
  1394. bind10_src.remove_lock_files()
  1395. if __name__ == '__main__':
  1396. # store os.environ for test_unchanged_environment
  1397. original_os_environ = copy.deepcopy(os.environ)
  1398. isc.log.resetUnitTestRootLogger()
  1399. unittest.main()