bind10_test.py.in 51 KB

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