bind10_test.py.in 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515
  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. { "owner": "Boss",
  383. "data": {
  384. 'boot_time': time.strftime('%Y-%m-%dT%H:%M:%SZ', _BASETIME)
  385. }}))
  386. # "sendstats" command
  387. self.assertEqual(bob.command_handler("sendstats", None),
  388. isc.config.ccsession.create_answer(0))
  389. self.assertEqual(bob.cc_session.group, "Stats")
  390. self.assertEqual(bob.cc_session.msg,
  391. isc.config.ccsession.create_command(
  392. "set", { "owner": "Boss",
  393. "data": {
  394. "boot_time": time.strftime("%Y-%m-%dT%H:%M:%SZ", _BASETIME)
  395. }}))
  396. # "ping" command
  397. self.assertEqual(bob.command_handler("ping", None),
  398. isc.config.ccsession.create_answer(0, "pong"))
  399. # "show_processes" command
  400. self.assertEqual(bob.command_handler("show_processes", None),
  401. isc.config.ccsession.create_answer(0,
  402. bob.get_processes()))
  403. # an unknown command
  404. self.assertEqual(bob.command_handler("__UNKNOWN__", None),
  405. isc.config.ccsession.create_answer(1, "Unknown command"))
  406. # Fake the get_token of cache and test the command works
  407. bob._socket_path = '/socket/path'
  408. class cache:
  409. def get_token(self, protocol, addr, port, share_mode, share_name):
  410. return str(addr) + ':' + str(port)
  411. bob._socket_cache = cache()
  412. args = {
  413. "port": 53,
  414. "address": "0.0.0.0",
  415. "protocol": "UDP",
  416. "share_mode": "ANY",
  417. "share_name": "app"
  418. }
  419. # at all and this is the easiest way to check.
  420. self.assertEqual({'result': [0, {'token': '0.0.0.0:53',
  421. 'path': '/socket/path'}]},
  422. bob.command_handler("get_socket", args))
  423. # The drop_socket is not tested here, but in TestCacheCommands.
  424. # It needs the cache mocks to be in place and they are there.
  425. def test_stop_process(self):
  426. """
  427. Test checking the stop_process method sends the right message over
  428. the message bus.
  429. """
  430. class DummySession():
  431. def group_sendmsg(self, msg, group, instance="*"):
  432. (self.msg, self.group, self.instance) = (msg, group, instance)
  433. bob = BoB()
  434. bob.cc_session = DummySession()
  435. bob.stop_process('process', 'address', 42)
  436. self.assertEqual('address', bob.cc_session.group)
  437. self.assertEqual('address', bob.cc_session.instance)
  438. self.assertEqual({'command': ['shutdown', {'pid': 42}]},
  439. bob.cc_session.msg)
  440. # Class for testing the BoB without actually starting processes.
  441. # This is used for testing the start/stop components routines and
  442. # the BoB commands.
  443. #
  444. # Testing that external processes start is outside the scope
  445. # of the unit test, by overriding the process start methods we can check
  446. # that the right processes are started depending on the configuration
  447. # options.
  448. class MockBob(BoB):
  449. def __init__(self):
  450. BoB.__init__(self)
  451. # Set flags as to which of the overridden methods has been run.
  452. self.msgq = False
  453. self.cfgmgr = False
  454. self.ccsession = False
  455. self.auth = False
  456. self.resolver = False
  457. self.xfrout = False
  458. self.xfrin = False
  459. self.zonemgr = False
  460. self.stats = False
  461. self.stats_httpd = False
  462. self.cmdctl = False
  463. self.dhcp6 = False
  464. self.dhcp4 = False
  465. self.c_channel_env = {}
  466. self.components = { }
  467. self.creator = False
  468. class MockSockCreator(isc.bind10.component.Component):
  469. def __init__(self, process, boss, kind, address=None, params=None):
  470. isc.bind10.component.Component.__init__(self, process, boss,
  471. kind, 'SockCreator')
  472. self._start_func = boss.start_creator
  473. specials = isc.bind10.special_component.get_specials()
  474. specials['sockcreator'] = MockSockCreator
  475. self._component_configurator = \
  476. isc.bind10.component.Configurator(self, specials)
  477. def start_creator(self):
  478. self.creator = True
  479. procinfo = ProcessInfo('b10-sockcreator', ['/bin/false'])
  480. procinfo.pid = 1
  481. return procinfo
  482. def _read_bind10_config(self):
  483. # Configuration options are set directly
  484. pass
  485. def start_msgq(self):
  486. self.msgq = True
  487. procinfo = ProcessInfo('b10-msgq', ['/bin/false'])
  488. procinfo.pid = 2
  489. return procinfo
  490. def start_ccsession(self, c_channel_env):
  491. # this is not a process, don't have to do anything with procinfo
  492. self.ccsession = True
  493. def start_cfgmgr(self):
  494. self.cfgmgr = True
  495. procinfo = ProcessInfo('b10-cfgmgr', ['/bin/false'])
  496. procinfo.pid = 3
  497. return procinfo
  498. def start_auth(self):
  499. self.auth = True
  500. procinfo = ProcessInfo('b10-auth', ['/bin/false'])
  501. procinfo.pid = 5
  502. return procinfo
  503. def start_resolver(self):
  504. self.resolver = True
  505. procinfo = ProcessInfo('b10-resolver', ['/bin/false'])
  506. procinfo.pid = 6
  507. return procinfo
  508. def start_simple(self, name):
  509. procmap = { 'b10-zonemgr': self.start_zonemgr,
  510. 'b10-stats': self.start_stats,
  511. 'b10-stats-httpd': self.start_stats_httpd,
  512. 'b10-cmdctl': self.start_cmdctl,
  513. 'b10-dhcp6': self.start_dhcp6,
  514. 'b10-dhcp4': self.start_dhcp4,
  515. 'b10-xfrin': self.start_xfrin,
  516. 'b10-xfrout': self.start_xfrout }
  517. return procmap[name]()
  518. def start_xfrout(self):
  519. self.xfrout = True
  520. procinfo = ProcessInfo('b10-xfrout', ['/bin/false'])
  521. procinfo.pid = 7
  522. return procinfo
  523. def start_xfrin(self):
  524. self.xfrin = True
  525. procinfo = ProcessInfo('b10-xfrin', ['/bin/false'])
  526. procinfo.pid = 8
  527. return procinfo
  528. def start_zonemgr(self):
  529. self.zonemgr = True
  530. procinfo = ProcessInfo('b10-zonemgr', ['/bin/false'])
  531. procinfo.pid = 9
  532. return procinfo
  533. def start_stats(self):
  534. self.stats = True
  535. procinfo = ProcessInfo('b10-stats', ['/bin/false'])
  536. procinfo.pid = 10
  537. return procinfo
  538. def start_stats_httpd(self):
  539. self.stats_httpd = True
  540. procinfo = ProcessInfo('b10-stats-httpd', ['/bin/false'])
  541. procinfo.pid = 11
  542. return procinfo
  543. def start_cmdctl(self):
  544. self.cmdctl = True
  545. procinfo = ProcessInfo('b10-cmdctl', ['/bin/false'])
  546. procinfo.pid = 12
  547. return procinfo
  548. def start_dhcp6(self):
  549. self.dhcp6 = True
  550. procinfo = ProcessInfo('b10-dhcp6', ['/bin/false'])
  551. procinfo.pid = 13
  552. return procinfo
  553. def start_dhcp4(self):
  554. self.dhcp4 = True
  555. procinfo = ProcessInfo('b10-dhcp4', ['/bin/false'])
  556. procinfo.pid = 14
  557. return procinfo
  558. def stop_process(self, process, recipient, pid):
  559. procmap = { 'b10-auth': self.stop_auth,
  560. 'b10-resolver': self.stop_resolver,
  561. 'b10-xfrout': self.stop_xfrout,
  562. 'b10-xfrin': self.stop_xfrin,
  563. 'b10-zonemgr': self.stop_zonemgr,
  564. 'b10-stats': self.stop_stats,
  565. 'b10-stats-httpd': self.stop_stats_httpd,
  566. 'b10-cmdctl': self.stop_cmdctl }
  567. procmap[process]()
  568. # Some functions to pretend we stop processes, use by stop_process
  569. def stop_msgq(self):
  570. if self.msgq:
  571. del self.components[2]
  572. self.msgq = False
  573. def stop_cfgmgr(self):
  574. if self.cfgmgr:
  575. del self.components[3]
  576. self.cfgmgr = False
  577. def stop_auth(self):
  578. if self.auth:
  579. del self.components[5]
  580. self.auth = False
  581. def stop_resolver(self):
  582. if self.resolver:
  583. del self.components[6]
  584. self.resolver = False
  585. def stop_xfrout(self):
  586. if self.xfrout:
  587. del self.components[7]
  588. self.xfrout = False
  589. def stop_xfrin(self):
  590. if self.xfrin:
  591. del self.components[8]
  592. self.xfrin = False
  593. def stop_zonemgr(self):
  594. if self.zonemgr:
  595. del self.components[9]
  596. self.zonemgr = False
  597. def stop_stats(self):
  598. if self.stats:
  599. del self.components[10]
  600. self.stats = False
  601. def stop_stats_httpd(self):
  602. if self.stats_httpd:
  603. del self.components[11]
  604. self.stats_httpd = False
  605. def stop_cmdctl(self):
  606. if self.cmdctl:
  607. del self.components[12]
  608. self.cmdctl = False
  609. class TestStartStopProcessesBob(unittest.TestCase):
  610. """
  611. Check that the start_all_components method starts the right combination
  612. of components and that the right components are started and stopped
  613. according to changes in configuration.
  614. """
  615. def check_environment_unchanged(self):
  616. # Check whether the environment has not been changed
  617. self.assertEqual(original_os_environ, os.environ)
  618. def check_started(self, bob, core, auth, resolver):
  619. """
  620. Check that the right sets of services are started. The ones that
  621. should be running are specified by the core, auth and resolver parameters
  622. (they are groups of processes, eg. auth means b10-auth, -xfrout, -xfrin
  623. and -zonemgr).
  624. """
  625. self.assertEqual(bob.msgq, core)
  626. self.assertEqual(bob.cfgmgr, core)
  627. self.assertEqual(bob.ccsession, core)
  628. self.assertEqual(bob.creator, core)
  629. self.assertEqual(bob.auth, auth)
  630. self.assertEqual(bob.resolver, resolver)
  631. self.assertEqual(bob.xfrout, auth)
  632. self.assertEqual(bob.xfrin, auth)
  633. self.assertEqual(bob.zonemgr, auth)
  634. self.assertEqual(bob.stats, core)
  635. self.assertEqual(bob.stats_httpd, core)
  636. self.assertEqual(bob.cmdctl, core)
  637. self.check_environment_unchanged()
  638. def check_preconditions(self, bob):
  639. self.check_started(bob, False, False, False)
  640. def check_started_none(self, bob):
  641. """
  642. Check that the situation is according to configuration where no servers
  643. should be started. Some components still need to be running.
  644. """
  645. self.check_started(bob, True, False, False)
  646. self.check_environment_unchanged()
  647. def check_started_both(self, bob):
  648. """
  649. Check the situation is according to configuration where both servers
  650. (auth and resolver) are enabled.
  651. """
  652. self.check_started(bob, True, True, True)
  653. self.check_environment_unchanged()
  654. def check_started_auth(self, bob):
  655. """
  656. Check the set of components needed to run auth only is started.
  657. """
  658. self.check_started(bob, True, True, False)
  659. self.check_environment_unchanged()
  660. def check_started_resolver(self, bob):
  661. """
  662. Check the set of components needed to run resolver only is started.
  663. """
  664. self.check_started(bob, True, False, True)
  665. self.check_environment_unchanged()
  666. def check_started_dhcp(self, bob, v4, v6):
  667. """
  668. Check if proper combinations of DHCPv4 and DHCpv6 can be started
  669. """
  670. self.assertEqual(v4, bob.dhcp4)
  671. self.assertEqual(v6, bob.dhcp6)
  672. self.check_environment_unchanged()
  673. def construct_config(self, start_auth, start_resolver):
  674. # The things that are common, not turned on an off
  675. config = {}
  676. config['b10-stats'] = { 'kind': 'dispensable', 'address': 'Stats' }
  677. config['b10-stats-httpd'] = { 'kind': 'dispensable',
  678. 'address': 'StatsHttpd' }
  679. config['b10-cmdctl'] = { 'kind': 'needed', 'special': 'cmdctl' }
  680. if start_auth:
  681. config['b10-auth'] = { 'kind': 'needed', 'special': 'auth' }
  682. config['b10-xfrout'] = { 'kind': 'dispensable',
  683. 'address': 'Xfrout' }
  684. config['b10-xfrin'] = { 'kind': 'dispensable',
  685. 'address': 'Xfrin' }
  686. config['b10-zonemgr'] = { 'kind': 'dispensable',
  687. 'address': 'Zonemgr' }
  688. if start_resolver:
  689. config['b10-resolver'] = { 'kind': 'needed',
  690. 'special': 'resolver' }
  691. return {'components': config}
  692. def config_start_init(self, start_auth, start_resolver):
  693. """
  694. Test the configuration is loaded at the startup.
  695. """
  696. bob = MockBob()
  697. config = self.construct_config(start_auth, start_resolver)
  698. class CC:
  699. def get_full_config(self):
  700. return config
  701. # Provide the fake CC with data
  702. bob.ccs = CC()
  703. # And make sure it's not overwritten
  704. def start_ccsession():
  705. bob.ccsession = True
  706. bob.start_ccsession = lambda _: start_ccsession()
  707. # We need to return the original _read_bind10_config
  708. bob._read_bind10_config = lambda: BoB._read_bind10_config(bob)
  709. bob.start_all_components()
  710. self.check_started(bob, True, start_auth, start_resolver)
  711. self.check_environment_unchanged()
  712. def test_start_none(self):
  713. self.config_start_init(False, False)
  714. def test_start_resolver(self):
  715. self.config_start_init(False, True)
  716. def test_start_auth(self):
  717. self.config_start_init(True, False)
  718. def test_start_both(self):
  719. self.config_start_init(True, True)
  720. def test_config_start(self):
  721. """
  722. Test that the configuration starts and stops components according
  723. to configuration changes.
  724. """
  725. # Create BoB and ensure correct initialization
  726. bob = MockBob()
  727. self.check_preconditions(bob)
  728. bob.start_all_components()
  729. bob.runnable = True
  730. bob.config_handler(self.construct_config(False, False))
  731. self.check_started_none(bob)
  732. # Enable both at once
  733. bob.config_handler(self.construct_config(True, True))
  734. self.check_started_both(bob)
  735. # Not touched by empty change
  736. bob.config_handler({})
  737. self.check_started_both(bob)
  738. # Not touched by change to the same configuration
  739. bob.config_handler(self.construct_config(True, True))
  740. self.check_started_both(bob)
  741. # Turn them both off again
  742. bob.config_handler(self.construct_config(False, False))
  743. self.check_started_none(bob)
  744. # Not touched by empty change
  745. bob.config_handler({})
  746. self.check_started_none(bob)
  747. # Not touched by change to the same configuration
  748. bob.config_handler(self.construct_config(False, False))
  749. self.check_started_none(bob)
  750. # Start and stop auth separately
  751. bob.config_handler(self.construct_config(True, False))
  752. self.check_started_auth(bob)
  753. bob.config_handler(self.construct_config(False, False))
  754. self.check_started_none(bob)
  755. # Start and stop resolver separately
  756. bob.config_handler(self.construct_config(False, True))
  757. self.check_started_resolver(bob)
  758. bob.config_handler(self.construct_config(False, False))
  759. self.check_started_none(bob)
  760. # Alternate
  761. bob.config_handler(self.construct_config(True, False))
  762. self.check_started_auth(bob)
  763. bob.config_handler(self.construct_config(False, True))
  764. self.check_started_resolver(bob)
  765. bob.config_handler(self.construct_config(True, False))
  766. self.check_started_auth(bob)
  767. def test_config_start_once(self):
  768. """
  769. Tests that a component is started only once.
  770. """
  771. # Create BoB and ensure correct initialization
  772. bob = MockBob()
  773. self.check_preconditions(bob)
  774. bob.start_all_components()
  775. bob.runnable = True
  776. bob.config_handler(self.construct_config(True, True))
  777. self.check_started_both(bob)
  778. bob.start_auth = lambda: self.fail("Started auth again")
  779. bob.start_xfrout = lambda: self.fail("Started xfrout again")
  780. bob.start_xfrin = lambda: self.fail("Started xfrin again")
  781. bob.start_zonemgr = lambda: self.fail("Started zonemgr again")
  782. bob.start_resolver = lambda: self.fail("Started resolver again")
  783. # Send again we want to start them. Should not do it, as they are.
  784. bob.config_handler(self.construct_config(True, True))
  785. def test_config_not_started_early(self):
  786. """
  787. Test that components are not started by the config handler before
  788. startup.
  789. """
  790. bob = MockBob()
  791. self.check_preconditions(bob)
  792. bob.start_auth = lambda: self.fail("Started auth again")
  793. bob.start_xfrout = lambda: self.fail("Started xfrout again")
  794. bob.start_xfrin = lambda: self.fail("Started xfrin again")
  795. bob.start_zonemgr = lambda: self.fail("Started zonemgr again")
  796. bob.start_resolver = lambda: self.fail("Started resolver again")
  797. bob.config_handler({'start_auth': True, 'start_resolver': True})
  798. # Checks that DHCP (v4 and v6) components are started when expected
  799. def test_start_dhcp(self):
  800. # Create BoB and ensure correct initialization
  801. bob = MockBob()
  802. self.check_preconditions(bob)
  803. bob.start_all_components()
  804. bob.config_handler(self.construct_config(False, False))
  805. self.check_started_dhcp(bob, False, False)
  806. def test_start_dhcp_v6only(self):
  807. # Create BoB and ensure correct initialization
  808. bob = MockBob()
  809. self.check_preconditions(bob)
  810. # v6 only enabled
  811. bob.start_all_components()
  812. bob.runnable = True
  813. bob._BoB_started = True
  814. config = self.construct_config(False, False)
  815. config['components']['b10-dhcp6'] = { 'kind': 'needed',
  816. 'address': 'Dhcp6' }
  817. bob.config_handler(config)
  818. self.check_started_dhcp(bob, False, True)
  819. # uncomment when dhcpv4 becomes implemented
  820. # v4 only enabled
  821. #bob.cfg_start_dhcp6 = False
  822. #bob.cfg_start_dhcp4 = True
  823. #self.check_started_dhcp(bob, True, False)
  824. # both v4 and v6 enabled
  825. #bob.cfg_start_dhcp6 = True
  826. #bob.cfg_start_dhcp4 = True
  827. #self.check_started_dhcp(bob, True, True)
  828. class MockComponent:
  829. def __init__(self, name, pid):
  830. self.name = lambda: name
  831. self.pid = lambda: pid
  832. class TestBossCmd(unittest.TestCase):
  833. def test_ping(self):
  834. """
  835. Confirm simple ping command works.
  836. """
  837. bob = MockBob()
  838. answer = bob.command_handler("ping", None)
  839. self.assertEqual(answer, {'result': [0, 'pong']})
  840. def test_show_processes_empty(self):
  841. """
  842. Confirm getting a list of processes works.
  843. """
  844. bob = MockBob()
  845. answer = bob.command_handler("show_processes", None)
  846. self.assertEqual(answer, {'result': [0, []]})
  847. def test_show_processes(self):
  848. """
  849. Confirm getting a list of processes works.
  850. """
  851. bob = MockBob()
  852. bob.register_process(1, MockComponent('first', 1))
  853. bob.register_process(2, MockComponent('second', 2))
  854. answer = bob.command_handler("show_processes", None)
  855. processes = [[1, 'first'],
  856. [2, 'second']]
  857. self.assertEqual(answer, {'result': [0, processes]})
  858. class TestParseArgs(unittest.TestCase):
  859. """
  860. This tests parsing of arguments of the bind10 master process.
  861. """
  862. #TODO: Write tests for the original parsing, bad options, etc.
  863. def test_no_opts(self):
  864. """
  865. Test correct default values when no options are passed.
  866. """
  867. options = parse_args([], TestOptParser)
  868. self.assertEqual(None, options.data_path)
  869. self.assertEqual(None, options.config_file)
  870. self.assertEqual(None, options.cmdctl_port)
  871. def test_data_path(self):
  872. """
  873. Test it can parse the data path.
  874. """
  875. self.assertRaises(OptsError, parse_args, ['-p'], TestOptParser)
  876. self.assertRaises(OptsError, parse_args, ['--data-path'],
  877. TestOptParser)
  878. options = parse_args(['-p', '/data/path'], TestOptParser)
  879. self.assertEqual('/data/path', options.data_path)
  880. options = parse_args(['--data-path=/data/path'], TestOptParser)
  881. self.assertEqual('/data/path', options.data_path)
  882. def test_config_filename(self):
  883. """
  884. Test it can parse the config switch.
  885. """
  886. self.assertRaises(OptsError, parse_args, ['-c'], TestOptParser)
  887. self.assertRaises(OptsError, parse_args, ['--config-file'],
  888. TestOptParser)
  889. options = parse_args(['-c', 'config-file'], TestOptParser)
  890. self.assertEqual('config-file', options.config_file)
  891. options = parse_args(['--config-file=config-file'], TestOptParser)
  892. self.assertEqual('config-file', options.config_file)
  893. def test_clear_config(self):
  894. options = parse_args([], TestOptParser)
  895. self.assertEqual(False, options.clear_config)
  896. options = parse_args(['--clear-config'], TestOptParser)
  897. self.assertEqual(True, options.clear_config)
  898. def test_nokill(self):
  899. options = parse_args([], TestOptParser)
  900. self.assertEqual(False, options.nokill)
  901. options = parse_args(['--no-kill'], TestOptParser)
  902. self.assertEqual(True, options.nokill)
  903. options = parse_args([], TestOptParser)
  904. self.assertEqual(False, options.nokill)
  905. options = parse_args(['-i'], TestOptParser)
  906. self.assertEqual(True, options.nokill)
  907. def test_cmdctl_port(self):
  908. """
  909. Test it can parse the command control port.
  910. """
  911. self.assertRaises(OptsError, parse_args, ['--cmdctl-port=abc'],
  912. TestOptParser)
  913. self.assertRaises(OptsError, parse_args, ['--cmdctl-port=100000000'],
  914. TestOptParser)
  915. self.assertRaises(OptsError, parse_args, ['--cmdctl-port'],
  916. TestOptParser)
  917. options = parse_args(['--cmdctl-port=1234'], TestOptParser)
  918. self.assertEqual(1234, options.cmdctl_port)
  919. class TestPIDFile(unittest.TestCase):
  920. def setUp(self):
  921. self.pid_file = '@builddir@' + os.sep + 'bind10.pid'
  922. if os.path.exists(self.pid_file):
  923. os.unlink(self.pid_file)
  924. def tearDown(self):
  925. if os.path.exists(self.pid_file):
  926. os.unlink(self.pid_file)
  927. def check_pid_file(self):
  928. # dump PID to the file, and confirm the content is correct
  929. dump_pid(self.pid_file)
  930. my_pid = os.getpid()
  931. with open(self.pid_file, "r") as f:
  932. self.assertEqual(my_pid, int(f.read()))
  933. def test_dump_pid(self):
  934. self.check_pid_file()
  935. # make sure any existing content will be removed
  936. with open(self.pid_file, "w") as f:
  937. f.write('dummy data\n')
  938. self.check_pid_file()
  939. def test_unlink_pid_file_notexist(self):
  940. dummy_data = 'dummy_data\n'
  941. with open(self.pid_file, "w") as f:
  942. f.write(dummy_data)
  943. unlink_pid_file("no_such_pid_file")
  944. # the file specified for unlink_pid_file doesn't exist,
  945. # and the original content of the file should be intact.
  946. with open(self.pid_file, "r") as f:
  947. self.assertEqual(dummy_data, f.read())
  948. def test_dump_pid_with_none(self):
  949. # Check the behavior of dump_pid() and unlink_pid_file() with None.
  950. # This should be no-op.
  951. dump_pid(None)
  952. self.assertFalse(os.path.exists(self.pid_file))
  953. dummy_data = 'dummy_data\n'
  954. with open(self.pid_file, "w") as f:
  955. f.write(dummy_data)
  956. unlink_pid_file(None)
  957. with open(self.pid_file, "r") as f:
  958. self.assertEqual(dummy_data, f.read())
  959. def test_dump_pid_failure(self):
  960. # the attempt to open file will fail, which should result in exception.
  961. self.assertRaises(IOError, dump_pid,
  962. 'nonexistent_dir' + os.sep + 'bind10.pid')
  963. class TestBossComponents(unittest.TestCase):
  964. """
  965. Test the boss propagates component configuration properly to the
  966. component configurator and acts sane.
  967. """
  968. def setUp(self):
  969. self.__param = None
  970. self.__called = False
  971. self.__compconfig = {
  972. 'comp': {
  973. 'kind': 'needed',
  974. 'process': 'cat'
  975. }
  976. }
  977. def __unary_hook(self, param):
  978. """
  979. A hook function that stores the parameter for later examination.
  980. """
  981. self.__param = param
  982. def __nullary_hook(self):
  983. """
  984. A hook function that notes down it was called.
  985. """
  986. self.__called = True
  987. def __check_core(self, config):
  988. """
  989. A function checking that the config contains parts for the valid
  990. core component configuration.
  991. """
  992. self.assertIsNotNone(config)
  993. for component in ['sockcreator', 'msgq', 'cfgmgr']:
  994. self.assertTrue(component in config)
  995. self.assertEqual(component, config[component]['special'])
  996. self.assertEqual('core', config[component]['kind'])
  997. def __check_extended(self, config):
  998. """
  999. This checks that the config contains the core and one more component.
  1000. """
  1001. self.__check_core(config)
  1002. self.assertTrue('comp' in config)
  1003. self.assertEqual('cat', config['comp']['process'])
  1004. self.assertEqual('needed', config['comp']['kind'])
  1005. self.assertEqual(4, len(config))
  1006. def test_correct_run(self):
  1007. """
  1008. Test the situation when we run in usual scenario, nothing fails,
  1009. we just start, reconfigure and then stop peacefully.
  1010. """
  1011. bob = MockBob()
  1012. # Start it
  1013. orig = bob._component_configurator.startup
  1014. bob._component_configurator.startup = self.__unary_hook
  1015. bob.start_all_components()
  1016. bob._component_configurator.startup = orig
  1017. self.__check_core(self.__param)
  1018. self.assertEqual(3, len(self.__param))
  1019. # Reconfigure it
  1020. self.__param = None
  1021. orig = bob._component_configurator.reconfigure
  1022. bob._component_configurator.reconfigure = self.__unary_hook
  1023. # Otherwise it does not work
  1024. bob.runnable = True
  1025. bob.config_handler({'components': self.__compconfig})
  1026. self.__check_extended(self.__param)
  1027. currconfig = self.__param
  1028. # If we reconfigure it, but it does not contain the components part,
  1029. # nothing is called
  1030. bob.config_handler({})
  1031. self.assertEqual(self.__param, currconfig)
  1032. self.__param = None
  1033. bob._component_configurator.reconfigure = orig
  1034. # Check a configuration that messes up the core components is rejected.
  1035. compconf = dict(self.__compconfig)
  1036. compconf['msgq'] = { 'process': 'echo' }
  1037. result = bob.config_handler({'components': compconf})
  1038. # Check it rejected it
  1039. self.assertEqual(1, result['result'][0])
  1040. # We can't call shutdown, that one relies on the stuff in main
  1041. # We check somewhere else that the shutdown is actually called
  1042. # from there (the test_kills).
  1043. def __real_test_kill(self, nokill = False):
  1044. """
  1045. Helper function that does the actual kill functionality testing.
  1046. """
  1047. bob = MockBob()
  1048. bob.nokill = nokill
  1049. killed = []
  1050. class ImmortalComponent:
  1051. """
  1052. An immortal component. It does not stop when it is told so
  1053. (anyway it is not told so). It does not die if it is killed
  1054. the first time. It dies only when killed forcefully.
  1055. """
  1056. def kill(self, forceful=False):
  1057. killed.append(forceful)
  1058. if forceful:
  1059. bob.components = {}
  1060. def pid(self):
  1061. return 1
  1062. def name(self):
  1063. return "Immortal"
  1064. bob.components = {}
  1065. bob.register_process(1, ImmortalComponent())
  1066. # While at it, we check the configurator shutdown is actually called
  1067. orig = bob._component_configurator.shutdown
  1068. bob._component_configurator.shutdown = self.__nullary_hook
  1069. self.__called = False
  1070. bob.ccs = MockModuleCCSession()
  1071. self.assertFalse(bob.ccs.stopped)
  1072. bob.shutdown()
  1073. self.assertTrue(bob.ccs.stopped)
  1074. # Here, killed is an array where False is added if SIGTERM
  1075. # should be sent, or True if SIGKILL should be sent, in order in
  1076. # which they're sent.
  1077. if nokill:
  1078. self.assertEqual([], killed)
  1079. else:
  1080. self.assertEqual([False, True], killed)
  1081. self.assertTrue(self.__called)
  1082. bob._component_configurator.shutdown = orig
  1083. def test_kills(self):
  1084. """
  1085. Test that the boss kills components which don't want to stop.
  1086. """
  1087. self.__real_test_kill()
  1088. def test_nokill(self):
  1089. """
  1090. Test that the boss *doesn't* kill components which don't want to
  1091. stop, when asked not to (by passing the --no-kill option which
  1092. sets bob.nokill to True).
  1093. """
  1094. self.__real_test_kill(True)
  1095. def test_component_shutdown(self):
  1096. """
  1097. Test the component_shutdown sets all variables accordingly.
  1098. """
  1099. bob = MockBob()
  1100. self.assertRaises(Exception, bob.component_shutdown, 1)
  1101. self.assertEqual(1, bob.exitcode)
  1102. bob._BoB__started = True
  1103. bob.component_shutdown(2)
  1104. self.assertEqual(2, bob.exitcode)
  1105. self.assertFalse(bob.runnable)
  1106. def test_init_config(self):
  1107. """
  1108. Test initial configuration is loaded.
  1109. """
  1110. bob = MockBob()
  1111. # Start it
  1112. bob._component_configurator.reconfigure = self.__unary_hook
  1113. # We need to return the original read_bind10_config
  1114. bob._read_bind10_config = lambda: BoB._read_bind10_config(bob)
  1115. # And provide a session to read the data from
  1116. class CC:
  1117. pass
  1118. bob.ccs = CC()
  1119. bob.ccs.get_full_config = lambda: {'components': self.__compconfig}
  1120. bob.start_all_components()
  1121. self.__check_extended(self.__param)
  1122. class SocketSrvTest(unittest.TestCase):
  1123. """
  1124. This tests some methods of boss related to the unix domain sockets used
  1125. to transfer other sockets to applications.
  1126. """
  1127. def setUp(self):
  1128. """
  1129. Create the boss to test, testdata and backup some functions.
  1130. """
  1131. self.__boss = BoB()
  1132. self.__select_backup = bind10_src.select.select
  1133. self.__select_called = None
  1134. self.__socket_data_called = None
  1135. self.__consumer_dead_called = None
  1136. self.__socket_request_handler_called = None
  1137. def tearDown(self):
  1138. """
  1139. Restore functions.
  1140. """
  1141. bind10_src.select.select = self.__select_backup
  1142. class __FalseSocket:
  1143. """
  1144. A mock socket for the select and accept and stuff like that.
  1145. """
  1146. def __init__(self, owner, fileno=42):
  1147. self.__owner = owner
  1148. self.__fileno = fileno
  1149. self.data = None
  1150. self.closed = False
  1151. def fileno(self):
  1152. return self.__fileno
  1153. def accept(self):
  1154. return (self.__class__(self.__owner, 13), "/path/to/socket")
  1155. def recv(self, bufsize, flags=0):
  1156. self.__owner.assertEqual(1, bufsize)
  1157. self.__owner.assertEqual(socket.MSG_DONTWAIT, flags)
  1158. if isinstance(self.data, socket.error):
  1159. raise self.data
  1160. elif self.data is not None:
  1161. if len(self.data):
  1162. result = self.data[0:1]
  1163. self.data = self.data[1:]
  1164. return result
  1165. else:
  1166. raise socket.error(errno.EAGAIN, "Would block")
  1167. else:
  1168. return b''
  1169. def close(self):
  1170. self.closed = True
  1171. class __CCS:
  1172. """
  1173. A mock CCS, just to provide the socket file number.
  1174. """
  1175. class __Socket:
  1176. def fileno(self):
  1177. return 1
  1178. def get_socket(self):
  1179. return self.__Socket()
  1180. def __select_accept(self, r, w, x, t):
  1181. self.__select_called = (r, w, x, t)
  1182. return ([42], [], [])
  1183. def __select_data(self, r, w, x, t):
  1184. self.__select_called = (r, w, x, t)
  1185. return ([13], [], [])
  1186. def __accept(self):
  1187. """
  1188. Hijact the accept method of the boss.
  1189. Notes down it was called and stops the boss.
  1190. """
  1191. self.__accept_called = True
  1192. self.__boss.runnable = False
  1193. def test_srv_accept_called(self):
  1194. """
  1195. Test that the _srv_accept method of boss is called when the listening
  1196. socket is readable.
  1197. """
  1198. self.__boss.runnable = True
  1199. self.__boss._srv_socket = self.__FalseSocket(self)
  1200. self.__boss._srv_accept = self.__accept
  1201. self.__boss.ccs = self.__CCS()
  1202. bind10_src.select.select = self.__select_accept
  1203. self.__boss.run(2)
  1204. # It called the accept
  1205. self.assertTrue(self.__accept_called)
  1206. # And the select had the right parameters
  1207. self.assertEqual(([2, 1, 42], [], [], None), self.__select_called)
  1208. def test_srv_accept(self):
  1209. """
  1210. Test how the _srv_accept method works.
  1211. """
  1212. self.__boss._srv_socket = self.__FalseSocket(self)
  1213. self.__boss._srv_accept()
  1214. # After we accepted, a new socket is added there
  1215. socket = self.__boss._unix_sockets[13][0]
  1216. # The socket is properly stored there
  1217. self.assertTrue(isinstance(socket, self.__FalseSocket))
  1218. # And the buffer (yet empty) is there
  1219. self.assertEqual({13: (socket, b'')}, self.__boss._unix_sockets)
  1220. def __socket_data(self, socket):
  1221. self.__boss.runnable = False
  1222. self.__socket_data_called = socket
  1223. def test_socket_data(self):
  1224. """
  1225. Test that a socket that wants attention gets it.
  1226. """
  1227. self.__boss._srv_socket = self.__FalseSocket(self)
  1228. self.__boss._socket_data = self.__socket_data
  1229. self.__boss.ccs = self.__CCS()
  1230. self.__boss._unix_sockets = {13: (self.__FalseSocket(self, 13), b'')}
  1231. self.__boss.runnable = True
  1232. bind10_src.select.select = self.__select_data
  1233. self.__boss.run(2)
  1234. self.assertEqual(13, self.__socket_data_called)
  1235. self.assertEqual(([2, 1, 42, 13], [], [], None), self.__select_called)
  1236. def __prepare_data(self, data):
  1237. socket = self.__FalseSocket(self, 13)
  1238. self.__boss._unix_sockets = {13: (socket, b'')}
  1239. socket.data = data
  1240. self.__boss.socket_consumer_dead = self.__consumer_dead
  1241. self.__boss.socket_request_handler = self.__socket_request_handler
  1242. return socket
  1243. def __consumer_dead(self, socket):
  1244. self.__consumer_dead_called = socket
  1245. def __socket_request_handler(self, token, socket):
  1246. self.__socket_request_handler_called = (token, socket)
  1247. def test_socket_closed(self):
  1248. """
  1249. Test that a socket is removed and the socket_consumer_dead is called
  1250. when it is closed.
  1251. """
  1252. socket = self.__prepare_data(None)
  1253. self.__boss._socket_data(13)
  1254. self.assertEqual(socket, self.__consumer_dead_called)
  1255. self.assertEqual({}, self.__boss._unix_sockets)
  1256. self.assertTrue(socket.closed)
  1257. def test_socket_short(self):
  1258. """
  1259. Test that if there's not enough data to get the whole socket, it is
  1260. kept there, but nothing is called.
  1261. """
  1262. socket = self.__prepare_data(b'tok')
  1263. self.__boss._socket_data(13)
  1264. self.assertEqual({13: (socket, b'tok')}, self.__boss._unix_sockets)
  1265. self.assertFalse(socket.closed)
  1266. self.assertIsNone(self.__consumer_dead_called)
  1267. self.assertIsNone(self.__socket_request_handler_called)
  1268. def test_socket_continue(self):
  1269. """
  1270. Test that we call the token handling function when the whole token
  1271. comes. This test pretends to continue reading where the previous one
  1272. stopped.
  1273. """
  1274. socket = self.__prepare_data(b"en\nanothe")
  1275. # The data to finish
  1276. self.__boss._unix_sockets[13] = (socket, b'tok')
  1277. self.__boss._socket_data(13)
  1278. self.assertEqual({13: (socket, b'anothe')}, self.__boss._unix_sockets)
  1279. self.assertFalse(socket.closed)
  1280. self.assertIsNone(self.__consumer_dead_called)
  1281. self.assertEqual((b'token', socket),
  1282. self.__socket_request_handler_called)
  1283. def test_broken_socket(self):
  1284. """
  1285. If the socket raises an exception during the read other than EAGAIN,
  1286. it is broken and we remove it.
  1287. """
  1288. sock = self.__prepare_data(socket.error(errno.ENOMEM,
  1289. "There's more memory available, but not for you"))
  1290. self.__boss._socket_data(13)
  1291. self.assertEqual(sock, self.__consumer_dead_called)
  1292. self.assertEqual({}, self.__boss._unix_sockets)
  1293. self.assertTrue(sock.closed)
  1294. class TestFunctions(unittest.TestCase):
  1295. def setUp(self):
  1296. self.lockfile_testpath = \
  1297. "@abs_top_builddir@/src/bin/bind10/tests/lockfile_test"
  1298. self.assertFalse(os.path.exists(self.lockfile_testpath))
  1299. os.mkdir(self.lockfile_testpath)
  1300. self.assertTrue(os.path.isdir(self.lockfile_testpath))
  1301. def tearDown(self):
  1302. os.rmdir(self.lockfile_testpath)
  1303. self.assertFalse(os.path.isdir(self.lockfile_testpath))
  1304. os.environ["B10_LOCKFILE_DIR_FROM_BUILD"] = "@abs_top_builddir@"
  1305. def test_remove_lock_files(self):
  1306. os.environ["B10_LOCKFILE_DIR_FROM_BUILD"] = self.lockfile_testpath
  1307. # create lockfiles for the testcase
  1308. lockfiles = ["logger_lockfile"]
  1309. for f in lockfiles:
  1310. fname = os.environ["B10_LOCKFILE_DIR_FROM_BUILD"] + '/' + f
  1311. self.assertFalse(os.path.exists(fname))
  1312. open(fname, "w").close()
  1313. self.assertTrue(os.path.isfile(fname))
  1314. # first call should clear up all the lockfiles
  1315. bind10_src.remove_lock_files()
  1316. # check if the lockfiles exist
  1317. for f in lockfiles:
  1318. fname = os.environ["B10_LOCKFILE_DIR_FROM_BUILD"] + '/' + f
  1319. self.assertFalse(os.path.isfile(fname))
  1320. # second call should not assert anyway
  1321. bind10_src.remove_lock_files()
  1322. if __name__ == '__main__':
  1323. # store os.environ for test_unchanged_environment
  1324. original_os_environ = copy.deepcopy(os.environ)
  1325. isc.log.resetUnitTestRootLogger()
  1326. unittest.main()