bind10_test.py.in 68 KB

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