bind10_test.py.in 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905
  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. # Mock class for testing BoB's usage of ProcessInfo
  465. class MockProcessInfo:
  466. def __init__(self, name, args, env={}, dev_null_stdout=False,
  467. dev_null_stderr=False):
  468. self.name = name
  469. self.args = args
  470. self.env = env
  471. self.dev_null_stdout = dev_null_stdout
  472. self.dev_null_stderr = dev_null_stderr
  473. self.process = None
  474. self.pid = None
  475. def spawn(self):
  476. # set some pid (only used for testing that it is not None anymore)
  477. self.pid = 42147
  478. # Class for testing the BoB without actually starting processes.
  479. # This is used for testing the start/stop components routines and
  480. # the BoB commands.
  481. #
  482. # Testing that external processes start is outside the scope
  483. # of the unit test, by overriding the process start methods we can check
  484. # that the right processes are started depending on the configuration
  485. # options.
  486. class MockBob(BoB):
  487. def __init__(self):
  488. BoB.__init__(self)
  489. # Set flags as to which of the overridden methods has been run.
  490. self.msgq = False
  491. self.cfgmgr = False
  492. self.ccsession = False
  493. self.auth = False
  494. self.resolver = False
  495. self.xfrout = False
  496. self.xfrin = False
  497. self.zonemgr = False
  498. self.stats = False
  499. self.stats_httpd = False
  500. self.cmdctl = False
  501. self.dhcp6 = False
  502. self.dhcp4 = False
  503. self.c_channel_env = {}
  504. self.components = { }
  505. self.creator = False
  506. self.get_process_exit_status_called = False
  507. class MockSockCreator(isc.bind10.component.Component):
  508. def __init__(self, process, boss, kind, address=None, params=None):
  509. isc.bind10.component.Component.__init__(self, process, boss,
  510. kind, 'SockCreator')
  511. self._start_func = boss.start_creator
  512. specials = isc.bind10.special_component.get_specials()
  513. specials['sockcreator'] = MockSockCreator
  514. self._component_configurator = \
  515. isc.bind10.component.Configurator(self, specials)
  516. def start_creator(self):
  517. self.creator = True
  518. procinfo = ProcessInfo('b10-sockcreator', ['/bin/false'])
  519. procinfo.pid = 1
  520. return procinfo
  521. def _read_bind10_config(self):
  522. # Configuration options are set directly
  523. pass
  524. def start_msgq(self):
  525. self.msgq = True
  526. procinfo = ProcessInfo('b10-msgq', ['/bin/false'])
  527. procinfo.pid = 2
  528. return procinfo
  529. def start_ccsession(self, c_channel_env):
  530. # this is not a process, don't have to do anything with procinfo
  531. self.ccsession = True
  532. def start_cfgmgr(self):
  533. self.cfgmgr = True
  534. procinfo = ProcessInfo('b10-cfgmgr', ['/bin/false'])
  535. procinfo.pid = 3
  536. return procinfo
  537. def start_auth(self):
  538. self.auth = True
  539. procinfo = ProcessInfo('b10-auth', ['/bin/false'])
  540. procinfo.pid = 5
  541. return procinfo
  542. def start_resolver(self):
  543. self.resolver = True
  544. procinfo = ProcessInfo('b10-resolver', ['/bin/false'])
  545. procinfo.pid = 6
  546. return procinfo
  547. def start_simple(self, name):
  548. procmap = { 'b10-zonemgr': self.start_zonemgr,
  549. 'b10-stats': self.start_stats,
  550. 'b10-stats-httpd': self.start_stats_httpd,
  551. 'b10-cmdctl': self.start_cmdctl,
  552. 'b10-dhcp6': self.start_dhcp6,
  553. 'b10-dhcp4': self.start_dhcp4,
  554. 'b10-xfrin': self.start_xfrin,
  555. 'b10-xfrout': self.start_xfrout }
  556. return procmap[name]()
  557. def start_xfrout(self):
  558. self.xfrout = True
  559. procinfo = ProcessInfo('b10-xfrout', ['/bin/false'])
  560. procinfo.pid = 7
  561. return procinfo
  562. def start_xfrin(self):
  563. self.xfrin = True
  564. procinfo = ProcessInfo('b10-xfrin', ['/bin/false'])
  565. procinfo.pid = 8
  566. return procinfo
  567. def start_zonemgr(self):
  568. self.zonemgr = True
  569. procinfo = ProcessInfo('b10-zonemgr', ['/bin/false'])
  570. procinfo.pid = 9
  571. return procinfo
  572. def start_stats(self):
  573. self.stats = True
  574. procinfo = ProcessInfo('b10-stats', ['/bin/false'])
  575. procinfo.pid = 10
  576. return procinfo
  577. def start_stats_httpd(self):
  578. self.stats_httpd = True
  579. procinfo = ProcessInfo('b10-stats-httpd', ['/bin/false'])
  580. procinfo.pid = 11
  581. return procinfo
  582. def start_cmdctl(self):
  583. self.cmdctl = True
  584. procinfo = ProcessInfo('b10-cmdctl', ['/bin/false'])
  585. procinfo.pid = 12
  586. return procinfo
  587. def start_dhcp6(self):
  588. self.dhcp6 = True
  589. procinfo = ProcessInfo('b10-dhcp6', ['/bin/false'])
  590. procinfo.pid = 13
  591. return procinfo
  592. def start_dhcp4(self):
  593. self.dhcp4 = True
  594. procinfo = ProcessInfo('b10-dhcp4', ['/bin/false'])
  595. procinfo.pid = 14
  596. return procinfo
  597. def stop_process(self, process, recipient, pid):
  598. procmap = { 'b10-auth': self.stop_auth,
  599. 'b10-resolver': self.stop_resolver,
  600. 'b10-xfrout': self.stop_xfrout,
  601. 'b10-xfrin': self.stop_xfrin,
  602. 'b10-zonemgr': self.stop_zonemgr,
  603. 'b10-stats': self.stop_stats,
  604. 'b10-stats-httpd': self.stop_stats_httpd,
  605. 'b10-cmdctl': self.stop_cmdctl }
  606. procmap[process]()
  607. # Some functions to pretend we stop processes, use by stop_process
  608. def stop_msgq(self):
  609. if self.msgq:
  610. del self.components[2]
  611. self.msgq = False
  612. def stop_cfgmgr(self):
  613. if self.cfgmgr:
  614. del self.components[3]
  615. self.cfgmgr = False
  616. def stop_auth(self):
  617. if self.auth:
  618. del self.components[5]
  619. self.auth = False
  620. def stop_resolver(self):
  621. if self.resolver:
  622. del self.components[6]
  623. self.resolver = False
  624. def stop_xfrout(self):
  625. if self.xfrout:
  626. del self.components[7]
  627. self.xfrout = False
  628. def stop_xfrin(self):
  629. if self.xfrin:
  630. del self.components[8]
  631. self.xfrin = False
  632. def stop_zonemgr(self):
  633. if self.zonemgr:
  634. del self.components[9]
  635. self.zonemgr = False
  636. def stop_stats(self):
  637. if self.stats:
  638. del self.components[10]
  639. self.stats = False
  640. def stop_stats_httpd(self):
  641. if self.stats_httpd:
  642. del self.components[11]
  643. self.stats_httpd = False
  644. def stop_cmdctl(self):
  645. if self.cmdctl:
  646. del self.components[12]
  647. self.cmdctl = False
  648. def _get_process_exit_status(self):
  649. if self.get_process_exit_status_called:
  650. return (0, 0)
  651. self.get_process_exit_status_called = True
  652. return (53, 0)
  653. def _get_process_exit_status_unknown_pid(self):
  654. if self.get_process_exit_status_called:
  655. return (0, 0)
  656. self.get_process_exit_status_called = True
  657. return (42, 0)
  658. def _get_process_exit_status_raises_oserror_echild(self):
  659. raise OSError(errno.ECHILD, 'Mock error')
  660. def _get_process_exit_status_raises_oserror_other(self):
  661. raise OSError(0, 'Mock error')
  662. def _get_process_exit_status_raises_other(self):
  663. raise Exception('Mock error')
  664. def _make_mock_process_info(self, name, args, c_channel_env):
  665. return MockProcessInfo(name, args, c_channel_env)
  666. class MockBobSimple(BoB):
  667. def __init__(self):
  668. BoB.__init__(self)
  669. # Set which process has been started
  670. self.started_process_name = None
  671. self.started_process_args = None
  672. def start_process(self, name, args, c_channel_env, port=None, address=None):
  673. self.started_process_name = name
  674. self.started_process_args = args
  675. return None
  676. class TestStartStopProcessesBob(unittest.TestCase):
  677. """
  678. Check that the start_all_components method starts the right combination
  679. of components and that the right components are started and stopped
  680. according to changes in configuration.
  681. """
  682. def check_environment_unchanged(self):
  683. # Check whether the environment has not been changed
  684. self.assertEqual(original_os_environ, os.environ)
  685. def check_started(self, bob, core, auth, resolver):
  686. """
  687. Check that the right sets of services are started. The ones that
  688. should be running are specified by the core, auth and resolver parameters
  689. (they are groups of processes, eg. auth means b10-auth, -xfrout, -xfrin
  690. and -zonemgr).
  691. """
  692. self.assertEqual(bob.msgq, core)
  693. self.assertEqual(bob.cfgmgr, core)
  694. self.assertEqual(bob.ccsession, core)
  695. self.assertEqual(bob.creator, core)
  696. self.assertEqual(bob.auth, auth)
  697. self.assertEqual(bob.resolver, resolver)
  698. self.assertEqual(bob.xfrout, auth)
  699. self.assertEqual(bob.xfrin, auth)
  700. self.assertEqual(bob.zonemgr, auth)
  701. self.assertEqual(bob.stats, core)
  702. self.assertEqual(bob.stats_httpd, core)
  703. self.assertEqual(bob.cmdctl, core)
  704. self.check_environment_unchanged()
  705. def check_preconditions(self, bob):
  706. self.check_started(bob, False, False, False)
  707. def check_started_none(self, bob):
  708. """
  709. Check that the situation is according to configuration where no servers
  710. should be started. Some components still need to be running.
  711. """
  712. self.check_started(bob, True, False, False)
  713. self.check_environment_unchanged()
  714. def check_started_both(self, bob):
  715. """
  716. Check the situation is according to configuration where both servers
  717. (auth and resolver) are enabled.
  718. """
  719. self.check_started(bob, True, True, True)
  720. self.check_environment_unchanged()
  721. def check_started_auth(self, bob):
  722. """
  723. Check the set of components needed to run auth only is started.
  724. """
  725. self.check_started(bob, True, True, False)
  726. self.check_environment_unchanged()
  727. def check_started_resolver(self, bob):
  728. """
  729. Check the set of components needed to run resolver only is started.
  730. """
  731. self.check_started(bob, True, False, True)
  732. self.check_environment_unchanged()
  733. def check_started_dhcp(self, bob, v4, v6):
  734. """
  735. Check if proper combinations of DHCPv4 and DHCpv6 can be started
  736. """
  737. self.assertEqual(v4, bob.dhcp4)
  738. self.assertEqual(v6, bob.dhcp6)
  739. self.check_environment_unchanged()
  740. def construct_config(self, start_auth, start_resolver):
  741. # The things that are common, not turned on an off
  742. config = {}
  743. config['b10-stats'] = { 'kind': 'dispensable', 'address': 'Stats' }
  744. config['b10-stats-httpd'] = { 'kind': 'dispensable',
  745. 'address': 'StatsHttpd' }
  746. config['b10-cmdctl'] = { 'kind': 'needed', 'special': 'cmdctl' }
  747. if start_auth:
  748. config['b10-auth'] = { 'kind': 'needed', 'special': 'auth' }
  749. config['b10-xfrout'] = { 'kind': 'dispensable',
  750. 'address': 'Xfrout' }
  751. config['b10-xfrin'] = { 'kind': 'dispensable',
  752. 'address': 'Xfrin' }
  753. config['b10-zonemgr'] = { 'kind': 'dispensable',
  754. 'address': 'Zonemgr' }
  755. if start_resolver:
  756. config['b10-resolver'] = { 'kind': 'needed',
  757. 'special': 'resolver' }
  758. return {'components': config}
  759. def config_start_init(self, start_auth, start_resolver):
  760. """
  761. Test the configuration is loaded at the startup.
  762. """
  763. bob = MockBob()
  764. config = self.construct_config(start_auth, start_resolver)
  765. class CC:
  766. def get_full_config(self):
  767. return config
  768. # Provide the fake CC with data
  769. bob.ccs = CC()
  770. # And make sure it's not overwritten
  771. def start_ccsession():
  772. bob.ccsession = True
  773. bob.start_ccsession = lambda _: start_ccsession()
  774. # We need to return the original _read_bind10_config
  775. bob._read_bind10_config = lambda: BoB._read_bind10_config(bob)
  776. bob.start_all_components()
  777. self.check_started(bob, True, start_auth, start_resolver)
  778. self.check_environment_unchanged()
  779. def test_start_none(self):
  780. self.config_start_init(False, False)
  781. def test_start_resolver(self):
  782. self.config_start_init(False, True)
  783. def test_start_auth(self):
  784. self.config_start_init(True, False)
  785. def test_start_both(self):
  786. self.config_start_init(True, True)
  787. def test_config_start(self):
  788. """
  789. Test that the configuration starts and stops components according
  790. to configuration changes.
  791. """
  792. # Create BoB and ensure correct initialization
  793. bob = MockBob()
  794. self.check_preconditions(bob)
  795. bob.start_all_components()
  796. bob.runnable = True
  797. bob.config_handler(self.construct_config(False, False))
  798. self.check_started_none(bob)
  799. # Enable both at once
  800. bob.config_handler(self.construct_config(True, True))
  801. self.check_started_both(bob)
  802. # Not touched by empty change
  803. bob.config_handler({})
  804. self.check_started_both(bob)
  805. # Not touched by change to the same configuration
  806. bob.config_handler(self.construct_config(True, True))
  807. self.check_started_both(bob)
  808. # Turn them both off again
  809. bob.config_handler(self.construct_config(False, False))
  810. self.check_started_none(bob)
  811. # Not touched by empty change
  812. bob.config_handler({})
  813. self.check_started_none(bob)
  814. # Not touched by change to the same configuration
  815. bob.config_handler(self.construct_config(False, False))
  816. self.check_started_none(bob)
  817. # Start and stop auth separately
  818. bob.config_handler(self.construct_config(True, False))
  819. self.check_started_auth(bob)
  820. bob.config_handler(self.construct_config(False, False))
  821. self.check_started_none(bob)
  822. # Start and stop resolver separately
  823. bob.config_handler(self.construct_config(False, True))
  824. self.check_started_resolver(bob)
  825. bob.config_handler(self.construct_config(False, False))
  826. self.check_started_none(bob)
  827. # Alternate
  828. bob.config_handler(self.construct_config(True, False))
  829. self.check_started_auth(bob)
  830. bob.config_handler(self.construct_config(False, True))
  831. self.check_started_resolver(bob)
  832. bob.config_handler(self.construct_config(True, False))
  833. self.check_started_auth(bob)
  834. def test_config_start_once(self):
  835. """
  836. Tests that a component is started only once.
  837. """
  838. # Create BoB and ensure correct initialization
  839. bob = MockBob()
  840. self.check_preconditions(bob)
  841. bob.start_all_components()
  842. bob.runnable = True
  843. bob.config_handler(self.construct_config(True, True))
  844. self.check_started_both(bob)
  845. bob.start_auth = lambda: self.fail("Started auth again")
  846. bob.start_xfrout = lambda: self.fail("Started xfrout again")
  847. bob.start_xfrin = lambda: self.fail("Started xfrin again")
  848. bob.start_zonemgr = lambda: self.fail("Started zonemgr again")
  849. bob.start_resolver = lambda: self.fail("Started resolver again")
  850. # Send again we want to start them. Should not do it, as they are.
  851. bob.config_handler(self.construct_config(True, True))
  852. def test_config_not_started_early(self):
  853. """
  854. Test that components are not started by the config handler before
  855. startup.
  856. """
  857. bob = MockBob()
  858. self.check_preconditions(bob)
  859. bob.start_auth = lambda: self.fail("Started auth again")
  860. bob.start_xfrout = lambda: self.fail("Started xfrout again")
  861. bob.start_xfrin = lambda: self.fail("Started xfrin again")
  862. bob.start_zonemgr = lambda: self.fail("Started zonemgr again")
  863. bob.start_resolver = lambda: self.fail("Started resolver again")
  864. bob.config_handler({'start_auth': True, 'start_resolver': True})
  865. # Checks that DHCP (v4 and v6) components are started when expected
  866. def test_start_dhcp(self):
  867. # Create BoB and ensure correct initialization
  868. bob = MockBob()
  869. self.check_preconditions(bob)
  870. bob.start_all_components()
  871. bob.config_handler(self.construct_config(False, False))
  872. self.check_started_dhcp(bob, False, False)
  873. def test_start_dhcp_v6only(self):
  874. # Create BoB and ensure correct initialization
  875. bob = MockBob()
  876. self.check_preconditions(bob)
  877. # v6 only enabled
  878. bob.start_all_components()
  879. bob.runnable = True
  880. bob._BoB_started = True
  881. config = self.construct_config(False, False)
  882. config['components']['b10-dhcp6'] = { 'kind': 'needed',
  883. 'address': 'Dhcp6' }
  884. bob.config_handler(config)
  885. self.check_started_dhcp(bob, False, True)
  886. # uncomment when dhcpv4 becomes implemented
  887. # v4 only enabled
  888. #bob.cfg_start_dhcp6 = False
  889. #bob.cfg_start_dhcp4 = True
  890. #self.check_started_dhcp(bob, True, False)
  891. # both v4 and v6 enabled
  892. #bob.cfg_start_dhcp6 = True
  893. #bob.cfg_start_dhcp4 = True
  894. #self.check_started_dhcp(bob, True, True)
  895. class MockComponent:
  896. def __init__(self, name, pid, address=None):
  897. self.name = lambda: name
  898. self.pid = lambda: pid
  899. self.address = lambda: address
  900. self.restarted = False
  901. self.forceful = False
  902. self.running = True
  903. self.has_failed = False
  904. def get_restart_time(self):
  905. return 0 # arbitrary dummy value
  906. def restart(self, now):
  907. self.restarted = True
  908. return True
  909. def is_running(self):
  910. return self.running
  911. def failed(self, status):
  912. return self.has_failed
  913. def kill(self, forceful):
  914. self.forceful = forceful
  915. class TestBossCmd(unittest.TestCase):
  916. def test_ping(self):
  917. """
  918. Confirm simple ping command works.
  919. """
  920. bob = MockBob()
  921. answer = bob.command_handler("ping", None)
  922. self.assertEqual(answer, {'result': [0, 'pong']})
  923. def test_show_processes_empty(self):
  924. """
  925. Confirm getting a list of processes works.
  926. """
  927. bob = MockBob()
  928. answer = bob.command_handler("show_processes", None)
  929. self.assertEqual(answer, {'result': [0, []]})
  930. def test_show_processes(self):
  931. """
  932. Confirm getting a list of processes works.
  933. """
  934. bob = MockBob()
  935. bob.register_process(1, MockComponent('first', 1))
  936. bob.register_process(2, MockComponent('second', 2, 'Second'))
  937. answer = bob.command_handler("show_processes", None)
  938. processes = [[1, 'first', None],
  939. [2, 'second', 'Second']]
  940. self.assertEqual(answer, {'result': [0, processes]})
  941. class TestParseArgs(unittest.TestCase):
  942. """
  943. This tests parsing of arguments of the bind10 master process.
  944. """
  945. #TODO: Write tests for the original parsing, bad options, etc.
  946. def test_no_opts(self):
  947. """
  948. Test correct default values when no options are passed.
  949. """
  950. options = parse_args([], TestOptParser)
  951. self.assertEqual(None, options.data_path)
  952. self.assertEqual(None, options.config_file)
  953. self.assertEqual(None, options.cmdctl_port)
  954. def test_data_path(self):
  955. """
  956. Test it can parse the data path.
  957. """
  958. self.assertRaises(OptsError, parse_args, ['-p'], TestOptParser)
  959. self.assertRaises(OptsError, parse_args, ['--data-path'],
  960. TestOptParser)
  961. options = parse_args(['-p', '/data/path'], TestOptParser)
  962. self.assertEqual('/data/path', options.data_path)
  963. options = parse_args(['--data-path=/data/path'], TestOptParser)
  964. self.assertEqual('/data/path', options.data_path)
  965. def test_config_filename(self):
  966. """
  967. Test it can parse the config switch.
  968. """
  969. self.assertRaises(OptsError, parse_args, ['-c'], TestOptParser)
  970. self.assertRaises(OptsError, parse_args, ['--config-file'],
  971. TestOptParser)
  972. options = parse_args(['-c', 'config-file'], TestOptParser)
  973. self.assertEqual('config-file', options.config_file)
  974. options = parse_args(['--config-file=config-file'], TestOptParser)
  975. self.assertEqual('config-file', options.config_file)
  976. def test_clear_config(self):
  977. options = parse_args([], TestOptParser)
  978. self.assertEqual(False, options.clear_config)
  979. options = parse_args(['--clear-config'], TestOptParser)
  980. self.assertEqual(True, options.clear_config)
  981. def test_nokill(self):
  982. options = parse_args([], TestOptParser)
  983. self.assertEqual(False, options.nokill)
  984. options = parse_args(['--no-kill'], TestOptParser)
  985. self.assertEqual(True, options.nokill)
  986. options = parse_args([], TestOptParser)
  987. self.assertEqual(False, options.nokill)
  988. options = parse_args(['-i'], TestOptParser)
  989. self.assertEqual(True, options.nokill)
  990. def test_cmdctl_port(self):
  991. """
  992. Test it can parse the command control port.
  993. """
  994. self.assertRaises(OptsError, parse_args, ['--cmdctl-port=abc'],
  995. TestOptParser)
  996. self.assertRaises(OptsError, parse_args, ['--cmdctl-port=100000000'],
  997. TestOptParser)
  998. self.assertRaises(OptsError, parse_args, ['--cmdctl-port'],
  999. TestOptParser)
  1000. options = parse_args(['--cmdctl-port=1234'], TestOptParser)
  1001. self.assertEqual(1234, options.cmdctl_port)
  1002. class TestPIDFile(unittest.TestCase):
  1003. def setUp(self):
  1004. self.pid_file = '@builddir@' + os.sep + 'bind10.pid'
  1005. if os.path.exists(self.pid_file):
  1006. os.unlink(self.pid_file)
  1007. def tearDown(self):
  1008. if os.path.exists(self.pid_file):
  1009. os.unlink(self.pid_file)
  1010. def check_pid_file(self):
  1011. # dump PID to the file, and confirm the content is correct
  1012. dump_pid(self.pid_file)
  1013. my_pid = os.getpid()
  1014. with open(self.pid_file, "r") as f:
  1015. self.assertEqual(my_pid, int(f.read()))
  1016. def test_dump_pid(self):
  1017. self.check_pid_file()
  1018. # make sure any existing content will be removed
  1019. with open(self.pid_file, "w") as f:
  1020. f.write('dummy data\n')
  1021. self.check_pid_file()
  1022. def test_unlink_pid_file_notexist(self):
  1023. dummy_data = 'dummy_data\n'
  1024. with open(self.pid_file, "w") as f:
  1025. f.write(dummy_data)
  1026. unlink_pid_file("no_such_pid_file")
  1027. # the file specified for unlink_pid_file doesn't exist,
  1028. # and the original content of the file should be intact.
  1029. with open(self.pid_file, "r") as f:
  1030. self.assertEqual(dummy_data, f.read())
  1031. def test_dump_pid_with_none(self):
  1032. # Check the behavior of dump_pid() and unlink_pid_file() with None.
  1033. # This should be no-op.
  1034. dump_pid(None)
  1035. self.assertFalse(os.path.exists(self.pid_file))
  1036. dummy_data = 'dummy_data\n'
  1037. with open(self.pid_file, "w") as f:
  1038. f.write(dummy_data)
  1039. unlink_pid_file(None)
  1040. with open(self.pid_file, "r") as f:
  1041. self.assertEqual(dummy_data, f.read())
  1042. def test_dump_pid_failure(self):
  1043. # the attempt to open file will fail, which should result in exception.
  1044. self.assertRaises(IOError, dump_pid,
  1045. 'nonexistent_dir' + os.sep + 'bind10.pid')
  1046. class TestBossComponents(unittest.TestCase):
  1047. """
  1048. Test the boss propagates component configuration properly to the
  1049. component configurator and acts sane.
  1050. """
  1051. def setUp(self):
  1052. self.__param = None
  1053. self.__called = False
  1054. self.__compconfig = {
  1055. 'comp': {
  1056. 'kind': 'needed',
  1057. 'process': 'cat'
  1058. }
  1059. }
  1060. def __unary_hook(self, param):
  1061. """
  1062. A hook function that stores the parameter for later examination.
  1063. """
  1064. self.__param = param
  1065. def __nullary_hook(self):
  1066. """
  1067. A hook function that notes down it was called.
  1068. """
  1069. self.__called = True
  1070. def __check_core(self, config):
  1071. """
  1072. A function checking that the config contains parts for the valid
  1073. core component configuration.
  1074. """
  1075. self.assertIsNotNone(config)
  1076. for component in ['sockcreator', 'msgq', 'cfgmgr']:
  1077. self.assertTrue(component in config)
  1078. self.assertEqual(component, config[component]['special'])
  1079. self.assertEqual('core', config[component]['kind'])
  1080. def __check_extended(self, config):
  1081. """
  1082. This checks that the config contains the core and one more component.
  1083. """
  1084. self.__check_core(config)
  1085. self.assertTrue('comp' in config)
  1086. self.assertEqual('cat', config['comp']['process'])
  1087. self.assertEqual('needed', config['comp']['kind'])
  1088. self.assertEqual(4, len(config))
  1089. def test_correct_run(self):
  1090. """
  1091. Test the situation when we run in usual scenario, nothing fails,
  1092. we just start, reconfigure and then stop peacefully.
  1093. """
  1094. bob = MockBob()
  1095. # Start it
  1096. orig = bob._component_configurator.startup
  1097. bob._component_configurator.startup = self.__unary_hook
  1098. bob.start_all_components()
  1099. bob._component_configurator.startup = orig
  1100. self.__check_core(self.__param)
  1101. self.assertEqual(3, len(self.__param))
  1102. # Reconfigure it
  1103. self.__param = None
  1104. orig = bob._component_configurator.reconfigure
  1105. bob._component_configurator.reconfigure = self.__unary_hook
  1106. # Otherwise it does not work
  1107. bob.runnable = True
  1108. bob.config_handler({'components': self.__compconfig})
  1109. self.__check_extended(self.__param)
  1110. currconfig = self.__param
  1111. # If we reconfigure it, but it does not contain the components part,
  1112. # nothing is called
  1113. bob.config_handler({})
  1114. self.assertEqual(self.__param, currconfig)
  1115. self.__param = None
  1116. bob._component_configurator.reconfigure = orig
  1117. # Check a configuration that messes up the core components is rejected.
  1118. compconf = dict(self.__compconfig)
  1119. compconf['msgq'] = { 'process': 'echo' }
  1120. result = bob.config_handler({'components': compconf})
  1121. # Check it rejected it
  1122. self.assertEqual(1, result['result'][0])
  1123. # We can't call shutdown, that one relies on the stuff in main
  1124. # We check somewhere else that the shutdown is actually called
  1125. # from there (the test_kills).
  1126. def __real_test_kill(self, nokill=False, ex_on_kill=None):
  1127. """
  1128. Helper function that does the actual kill functionality testing.
  1129. """
  1130. bob = MockBob()
  1131. bob.nokill = nokill
  1132. killed = []
  1133. class ImmortalComponent:
  1134. """
  1135. An immortal component. It does not stop when it is told so
  1136. (anyway it is not told so). It does not die if it is killed
  1137. the first time. It dies only when killed forcefully.
  1138. """
  1139. def __init__(self):
  1140. # number of kill() calls, preventing infinite loop.
  1141. self.__call_count = 0
  1142. def kill(self, forceful=False):
  1143. self.__call_count += 1
  1144. if self.__call_count > 2:
  1145. raise Exception('Too many calls to ImmortalComponent.kill')
  1146. killed.append(forceful)
  1147. if ex_on_kill is not None:
  1148. # If exception is given by the test, raise it here.
  1149. # In the case of ESRCH, the process should have gone
  1150. # somehow, so we clear the components.
  1151. if ex_on_kill.errno == errno.ESRCH:
  1152. bob.components = {}
  1153. raise ex_on_kill
  1154. if forceful:
  1155. bob.components = {}
  1156. def pid(self):
  1157. return 1
  1158. def name(self):
  1159. return "Immortal"
  1160. bob.components = {}
  1161. bob.register_process(1, ImmortalComponent())
  1162. # While at it, we check the configurator shutdown is actually called
  1163. orig = bob._component_configurator.shutdown
  1164. bob._component_configurator.shutdown = self.__nullary_hook
  1165. self.__called = False
  1166. bob.ccs = MockModuleCCSession()
  1167. self.assertFalse(bob.ccs.stopped)
  1168. bob.shutdown()
  1169. self.assertTrue(bob.ccs.stopped)
  1170. # Here, killed is an array where False is added if SIGTERM
  1171. # should be sent, or True if SIGKILL should be sent, in order in
  1172. # which they're sent.
  1173. if nokill:
  1174. self.assertEqual([], killed)
  1175. else:
  1176. if ex_on_kill is not None:
  1177. self.assertEqual([False], killed)
  1178. else:
  1179. self.assertEqual([False, True], killed)
  1180. self.assertTrue(self.__called)
  1181. bob._component_configurator.shutdown = orig
  1182. def test_kills(self):
  1183. """
  1184. Test that the boss kills components which don't want to stop.
  1185. """
  1186. self.__real_test_kill()
  1187. def test_kill_fail(self):
  1188. """Test cases where kill() results in an exception due to OS error.
  1189. The behavior should be different for EPERM, so we test two cases.
  1190. """
  1191. ex = OSError()
  1192. ex.errno, ex.strerror = errno.ESRCH, 'No such process'
  1193. self.__real_test_kill(ex_on_kill=ex)
  1194. ex.errno, ex.strerror = errno.EPERM, 'Operation not permitted'
  1195. self.__real_test_kill(ex_on_kill=ex)
  1196. def test_nokill(self):
  1197. """
  1198. Test that the boss *doesn't* kill components which don't want to
  1199. stop, when asked not to (by passing the --no-kill option which
  1200. sets bob.nokill to True).
  1201. """
  1202. self.__real_test_kill(True)
  1203. def test_component_shutdown(self):
  1204. """
  1205. Test the component_shutdown sets all variables accordingly.
  1206. """
  1207. bob = MockBob()
  1208. self.assertRaises(Exception, bob.component_shutdown, 1)
  1209. self.assertEqual(1, bob.exitcode)
  1210. bob._BoB__started = True
  1211. bob.component_shutdown(2)
  1212. self.assertEqual(2, bob.exitcode)
  1213. self.assertFalse(bob.runnable)
  1214. def test_init_config(self):
  1215. """
  1216. Test initial configuration is loaded.
  1217. """
  1218. bob = MockBob()
  1219. # Start it
  1220. bob._component_configurator.reconfigure = self.__unary_hook
  1221. # We need to return the original read_bind10_config
  1222. bob._read_bind10_config = lambda: BoB._read_bind10_config(bob)
  1223. # And provide a session to read the data from
  1224. class CC:
  1225. pass
  1226. bob.ccs = CC()
  1227. bob.ccs.get_full_config = lambda: {'components': self.__compconfig}
  1228. bob.start_all_components()
  1229. self.__check_extended(self.__param)
  1230. def __setup_restart(self, bob, component):
  1231. '''Common procedure for restarting a component used below.'''
  1232. bob.components_to_restart = { component }
  1233. component.restarted = False
  1234. bob.restart_processes()
  1235. def test_restart_processes(self):
  1236. '''Check some behavior on restarting processes.'''
  1237. bob = MockBob()
  1238. bob.runnable = True
  1239. component = MockComponent('test', 53)
  1240. # A component to be restarted will actually be restarted iff it's
  1241. # in the configurator's configuration.
  1242. # We bruteforce the configurator internal below; ugly, but the easiest
  1243. # way for the test.
  1244. bob._component_configurator._components['test'] = (None, component)
  1245. self.__setup_restart(bob, component)
  1246. self.assertTrue(component.restarted)
  1247. self.assertFalse(component in bob.components_to_restart)
  1248. # Remove the component from the configuration. It won't be restarted
  1249. # even if scheduled, nor will remain in the to-be-restarted list.
  1250. del bob._component_configurator._components['test']
  1251. self.__setup_restart(bob, component)
  1252. self.assertFalse(component.restarted)
  1253. self.assertFalse(component in bob.components_to_restart)
  1254. def test_get_processes(self):
  1255. '''Test that procsses are returned correctly, sorted by pid.'''
  1256. bob = MockBob()
  1257. pids = []
  1258. pids.extend(range(0, 20))
  1259. random.shuffle(pids)
  1260. for i in range(0, 20):
  1261. pid = pids[i]
  1262. component = MockComponent('test' + str(pid), pid, 'Test' + str(pid))
  1263. bob.components[pid] = component
  1264. process_list = bob.get_processes()
  1265. self.assertEqual(20, len(process_list))
  1266. last_pid = -1
  1267. for process in process_list:
  1268. pid = process[0]
  1269. self.assertLessEqual(last_pid, pid)
  1270. last_pid = pid
  1271. self.assertEqual([pid, 'test' + str(pid), 'Test' + str(pid)], process)
  1272. def _test_reap_children_helper(self, runnable, is_running, failed):
  1273. '''Construct a BoB instance, set various data in it according to
  1274. passed args and check if the component was added to the list of
  1275. components to restart.'''
  1276. bob = MockBob()
  1277. bob.runnable = runnable
  1278. component = MockComponent('test', 53)
  1279. component.running = is_running
  1280. component.has_failed = failed
  1281. bob.components[53] = component
  1282. self.assertFalse(component in bob.components_to_restart)
  1283. bob.reap_children()
  1284. if runnable and is_running and not failed:
  1285. self.assertTrue(bob.components_to_restart)
  1286. else:
  1287. self.assertFalse(bob.components_to_restart)
  1288. def test_reap_children(self):
  1289. '''Test that children are queued to be restarted when they ask for it.'''
  1290. # test various combinations of 3 booleans
  1291. # (BoB.runnable, component.is_running(), component.failed())
  1292. self._test_reap_children_helper(False, False, False)
  1293. self._test_reap_children_helper(False, False, True)
  1294. self._test_reap_children_helper(False, True, False)
  1295. self._test_reap_children_helper(False, True, True)
  1296. self._test_reap_children_helper(True, False, False)
  1297. self._test_reap_children_helper(True, False, True)
  1298. self._test_reap_children_helper(True, True, False)
  1299. self._test_reap_children_helper(True, True, True)
  1300. # setup for more tests below
  1301. bob = MockBob()
  1302. bob.runnable = True
  1303. component = MockComponent('test', 53)
  1304. bob.components[53] = component
  1305. # case where the returned pid is unknown to us. nothing should
  1306. # happpen then.
  1307. bob.get_process_exit_status_called = False
  1308. bob._get_process_exit_status = bob._get_process_exit_status_unknown_pid
  1309. bob.components_to_restart = []
  1310. # this should do nothing as the pid is unknown
  1311. bob.reap_children()
  1312. self.assertFalse(bob.components_to_restart)
  1313. # case where bob._get_process_exit_status() raises OSError with errno.ECHILD
  1314. bob._get_process_exit_status = bob._get_process_exit_status_raises_oserror_echild
  1315. bob.components_to_restart = []
  1316. # this should catch and handle the OSError
  1317. bob.reap_children()
  1318. self.assertFalse(bob.components_to_restart)
  1319. # case where bob._get_process_exit_status() raises OSError with
  1320. # errno other than ECHILD
  1321. bob._get_process_exit_status = bob._get_process_exit_status_raises_oserror_other
  1322. with self.assertRaises(OSError):
  1323. bob.reap_children()
  1324. # case where bob._get_process_exit_status() raises something
  1325. # other than OSError
  1326. bob._get_process_exit_status = bob._get_process_exit_status_raises_other
  1327. with self.assertRaises(Exception):
  1328. bob.reap_children()
  1329. def test_kill_started_components(self):
  1330. '''Test that started components are killed.'''
  1331. bob = MockBob()
  1332. component = MockComponent('test', 53, 'Test')
  1333. bob.components[53] = component
  1334. self.assertEqual([[53, 'test', 'Test']], bob.get_processes())
  1335. bob.kill_started_components()
  1336. self.assertFalse(bob.get_processes())
  1337. self.assertTrue(component.forceful)
  1338. def test_start_process(self):
  1339. '''Test that processes can be started.'''
  1340. bob = MockBob()
  1341. # use the MockProcessInfo creator
  1342. bob._make_process_info = bob._make_mock_process_info
  1343. pi = bob.start_process('Test Process', ['/bin/true'], {})
  1344. self.assertEqual('Test Process', pi.name)
  1345. self.assertEqual(['/bin/true'], pi.args)
  1346. self.assertEqual({}, pi.env)
  1347. # this is set by ProcessInfo.spawn()
  1348. self.assertEqual(42147, pi.pid)
  1349. def test_register_process(self):
  1350. '''Test that processes can be registered with BoB.'''
  1351. bob = MockBob()
  1352. component = MockComponent('test', 53, 'Test')
  1353. self.assertFalse(53 in bob.components)
  1354. bob.register_process(53, component)
  1355. self.assertTrue(53 in bob.components)
  1356. def test_start_simple(self):
  1357. '''Test simple process startup.'''
  1358. bob = MockBobSimple()
  1359. bob.c_channel_env = {}
  1360. # non-verbose case
  1361. bob.verbose = False
  1362. bob.start_simple('/bin/true')
  1363. self.assertEqual('/bin/true', bob.started_process_name)
  1364. self.assertEqual(['/bin/true'], bob.started_process_args)
  1365. # verbose case
  1366. bob.verbose = True
  1367. bob.start_simple('/bin/true')
  1368. self.assertEqual('/bin/true', bob.started_process_name)
  1369. self.assertEqual(['/bin/true', '-v'], bob.started_process_args)
  1370. def test_start_auth(self):
  1371. '''Test that b10-auth is started.'''
  1372. bob = MockBobSimple()
  1373. bob.c_channel_env = {}
  1374. # non-verbose case
  1375. bob.verbose = False
  1376. bob.start_auth()
  1377. self.assertEqual('b10-auth', bob.started_process_name)
  1378. self.assertEqual(['b10-auth'], bob.started_process_args)
  1379. # verbose case
  1380. bob.verbose = True
  1381. bob.start_auth()
  1382. self.assertEqual('b10-auth', bob.started_process_name)
  1383. self.assertEqual(['b10-auth', '-v'], bob.started_process_args)
  1384. def test_start_resolver(self):
  1385. '''Test that b10-resolver is started.'''
  1386. bob = MockBobSimple()
  1387. bob.c_channel_env = {}
  1388. # non-verbose case
  1389. bob.verbose = False
  1390. bob.start_resolver()
  1391. self.assertEqual('b10-resolver', bob.started_process_name)
  1392. self.assertEqual(['b10-resolver'], bob.started_process_args)
  1393. # verbose case
  1394. bob.verbose = True
  1395. bob.start_resolver()
  1396. self.assertEqual('b10-resolver', bob.started_process_name)
  1397. self.assertEqual(['b10-resolver', '-v'], bob.started_process_args)
  1398. def test_start_cmdctl(self):
  1399. '''Test that b10-cmdctl is started.'''
  1400. bob = MockBobSimple()
  1401. bob.c_channel_env = {}
  1402. # non-verbose case
  1403. bob.verbose = False
  1404. bob.start_cmdctl()
  1405. self.assertEqual('b10-cmdctl', bob.started_process_name)
  1406. self.assertEqual(['b10-cmdctl'], bob.started_process_args)
  1407. # verbose case
  1408. bob.verbose = True
  1409. bob.start_cmdctl()
  1410. self.assertEqual('b10-cmdctl', bob.started_process_name)
  1411. self.assertEqual(['b10-cmdctl', '-v'], bob.started_process_args)
  1412. # with port
  1413. bob.verbose = True
  1414. bob.cmdctl_port = 9353
  1415. bob.start_cmdctl()
  1416. self.assertEqual('b10-cmdctl', bob.started_process_name)
  1417. self.assertEqual(['b10-cmdctl', '--port=9353', '-v'], bob.started_process_args)
  1418. class SocketSrvTest(unittest.TestCase):
  1419. """
  1420. This tests some methods of boss related to the unix domain sockets used
  1421. to transfer other sockets to applications.
  1422. """
  1423. def setUp(self):
  1424. """
  1425. Create the boss to test, testdata and backup some functions.
  1426. """
  1427. self.__boss = BoB()
  1428. self.__select_backup = bind10_src.select.select
  1429. self.__select_called = None
  1430. self.__socket_data_called = None
  1431. self.__consumer_dead_called = None
  1432. self.__socket_request_handler_called = None
  1433. def tearDown(self):
  1434. """
  1435. Restore functions.
  1436. """
  1437. bind10_src.select.select = self.__select_backup
  1438. class __FalseSocket:
  1439. """
  1440. A mock socket for the select and accept and stuff like that.
  1441. """
  1442. def __init__(self, owner, fileno=42):
  1443. self.__owner = owner
  1444. self.__fileno = fileno
  1445. self.data = None
  1446. self.closed = False
  1447. def fileno(self):
  1448. return self.__fileno
  1449. def accept(self):
  1450. return (self.__class__(self.__owner, 13), "/path/to/socket")
  1451. def recv(self, bufsize, flags=0):
  1452. self.__owner.assertEqual(1, bufsize)
  1453. self.__owner.assertEqual(socket.MSG_DONTWAIT, flags)
  1454. if isinstance(self.data, socket.error):
  1455. raise self.data
  1456. elif self.data is not None:
  1457. if len(self.data):
  1458. result = self.data[0:1]
  1459. self.data = self.data[1:]
  1460. return result
  1461. else:
  1462. raise socket.error(errno.EAGAIN, "Would block")
  1463. else:
  1464. return b''
  1465. def close(self):
  1466. self.closed = True
  1467. class __CCS:
  1468. """
  1469. A mock CCS, just to provide the socket file number.
  1470. """
  1471. class __Socket:
  1472. def fileno(self):
  1473. return 1
  1474. def get_socket(self):
  1475. return self.__Socket()
  1476. def __select_accept(self, r, w, x, t):
  1477. self.__select_called = (r, w, x, t)
  1478. return ([42], [], [])
  1479. def __select_data(self, r, w, x, t):
  1480. self.__select_called = (r, w, x, t)
  1481. return ([13], [], [])
  1482. def __accept(self):
  1483. """
  1484. Hijact the accept method of the boss.
  1485. Notes down it was called and stops the boss.
  1486. """
  1487. self.__accept_called = True
  1488. self.__boss.runnable = False
  1489. def test_srv_accept_called(self):
  1490. """
  1491. Test that the _srv_accept method of boss is called when the listening
  1492. socket is readable.
  1493. """
  1494. self.__boss.runnable = True
  1495. self.__boss._srv_socket = self.__FalseSocket(self)
  1496. self.__boss._srv_accept = self.__accept
  1497. self.__boss.ccs = self.__CCS()
  1498. bind10_src.select.select = self.__select_accept
  1499. self.__boss.run(2)
  1500. # It called the accept
  1501. self.assertTrue(self.__accept_called)
  1502. # And the select had the right parameters
  1503. self.assertEqual(([2, 1, 42], [], [], None), self.__select_called)
  1504. def test_srv_accept(self):
  1505. """
  1506. Test how the _srv_accept method works.
  1507. """
  1508. self.__boss._srv_socket = self.__FalseSocket(self)
  1509. self.__boss._srv_accept()
  1510. # After we accepted, a new socket is added there
  1511. socket = self.__boss._unix_sockets[13][0]
  1512. # The socket is properly stored there
  1513. self.assertTrue(isinstance(socket, self.__FalseSocket))
  1514. # And the buffer (yet empty) is there
  1515. self.assertEqual({13: (socket, b'')}, self.__boss._unix_sockets)
  1516. def __socket_data(self, socket):
  1517. self.__boss.runnable = False
  1518. self.__socket_data_called = socket
  1519. def test_socket_data(self):
  1520. """
  1521. Test that a socket that wants attention gets it.
  1522. """
  1523. self.__boss._srv_socket = self.__FalseSocket(self)
  1524. self.__boss._socket_data = self.__socket_data
  1525. self.__boss.ccs = self.__CCS()
  1526. self.__boss._unix_sockets = {13: (self.__FalseSocket(self, 13), b'')}
  1527. self.__boss.runnable = True
  1528. bind10_src.select.select = self.__select_data
  1529. self.__boss.run(2)
  1530. self.assertEqual(13, self.__socket_data_called)
  1531. self.assertEqual(([2, 1, 42, 13], [], [], None), self.__select_called)
  1532. def __prepare_data(self, data):
  1533. socket = self.__FalseSocket(self, 13)
  1534. self.__boss._unix_sockets = {13: (socket, b'')}
  1535. socket.data = data
  1536. self.__boss.socket_consumer_dead = self.__consumer_dead
  1537. self.__boss.socket_request_handler = self.__socket_request_handler
  1538. return socket
  1539. def __consumer_dead(self, socket):
  1540. self.__consumer_dead_called = socket
  1541. def __socket_request_handler(self, token, socket):
  1542. self.__socket_request_handler_called = (token, socket)
  1543. def test_socket_closed(self):
  1544. """
  1545. Test that a socket is removed and the socket_consumer_dead is called
  1546. when it is closed.
  1547. """
  1548. socket = self.__prepare_data(None)
  1549. self.__boss._socket_data(13)
  1550. self.assertEqual(socket, self.__consumer_dead_called)
  1551. self.assertEqual({}, self.__boss._unix_sockets)
  1552. self.assertTrue(socket.closed)
  1553. def test_socket_short(self):
  1554. """
  1555. Test that if there's not enough data to get the whole socket, it is
  1556. kept there, but nothing is called.
  1557. """
  1558. socket = self.__prepare_data(b'tok')
  1559. self.__boss._socket_data(13)
  1560. self.assertEqual({13: (socket, b'tok')}, self.__boss._unix_sockets)
  1561. self.assertFalse(socket.closed)
  1562. self.assertIsNone(self.__consumer_dead_called)
  1563. self.assertIsNone(self.__socket_request_handler_called)
  1564. def test_socket_continue(self):
  1565. """
  1566. Test that we call the token handling function when the whole token
  1567. comes. This test pretends to continue reading where the previous one
  1568. stopped.
  1569. """
  1570. socket = self.__prepare_data(b"en\nanothe")
  1571. # The data to finish
  1572. self.__boss._unix_sockets[13] = (socket, b'tok')
  1573. self.__boss._socket_data(13)
  1574. self.assertEqual({13: (socket, b'anothe')}, self.__boss._unix_sockets)
  1575. self.assertFalse(socket.closed)
  1576. self.assertIsNone(self.__consumer_dead_called)
  1577. self.assertEqual((b'token', socket),
  1578. self.__socket_request_handler_called)
  1579. def test_broken_socket(self):
  1580. """
  1581. If the socket raises an exception during the read other than EAGAIN,
  1582. it is broken and we remove it.
  1583. """
  1584. sock = self.__prepare_data(socket.error(errno.ENOMEM,
  1585. "There's more memory available, but not for you"))
  1586. self.__boss._socket_data(13)
  1587. self.assertEqual(sock, self.__consumer_dead_called)
  1588. self.assertEqual({}, self.__boss._unix_sockets)
  1589. self.assertTrue(sock.closed)
  1590. class TestFunctions(unittest.TestCase):
  1591. def setUp(self):
  1592. self.lockfile_testpath = \
  1593. "@abs_top_builddir@/src/bin/bind10/tests/lockfile_test"
  1594. self.assertFalse(os.path.exists(self.lockfile_testpath))
  1595. os.mkdir(self.lockfile_testpath)
  1596. self.assertTrue(os.path.isdir(self.lockfile_testpath))
  1597. def tearDown(self):
  1598. os.rmdir(self.lockfile_testpath)
  1599. self.assertFalse(os.path.isdir(self.lockfile_testpath))
  1600. os.environ["B10_LOCKFILE_DIR_FROM_BUILD"] = "@abs_top_builddir@"
  1601. def test_remove_lock_files(self):
  1602. os.environ["B10_LOCKFILE_DIR_FROM_BUILD"] = self.lockfile_testpath
  1603. # create lockfiles for the testcase
  1604. lockfiles = ["logger_lockfile"]
  1605. for f in lockfiles:
  1606. fname = os.environ["B10_LOCKFILE_DIR_FROM_BUILD"] + '/' + f
  1607. self.assertFalse(os.path.exists(fname))
  1608. open(fname, "w").close()
  1609. self.assertTrue(os.path.isfile(fname))
  1610. # first call should clear up all the lockfiles
  1611. bind10_src.remove_lock_files()
  1612. # check if the lockfiles exist
  1613. for f in lockfiles:
  1614. fname = os.environ["B10_LOCKFILE_DIR_FROM_BUILD"] + '/' + f
  1615. self.assertFalse(os.path.isfile(fname))
  1616. # second call should not assert anyway
  1617. bind10_src.remove_lock_files()
  1618. def test_get_signame(self):
  1619. # just test with some samples
  1620. signame = bind10_src.get_signame(signal.SIGTERM)
  1621. self.assertEqual('SIGTERM', signame)
  1622. signame = bind10_src.get_signame(signal.SIGKILL)
  1623. self.assertEqual('SIGKILL', signame)
  1624. # 59426 is hopefully an unused signal on most platforms
  1625. signame = bind10_src.get_signame(59426)
  1626. self.assertEqual('Unknown signal 59426', signame)
  1627. def test_fatal_signal(self):
  1628. self.assertIsNone(bind10_src.boss_of_bind)
  1629. bind10_src.boss_of_bind = BoB()
  1630. bind10_src.boss_of_bind.runnable = True
  1631. bind10_src.fatal_signal(signal.SIGTERM, None)
  1632. # Now, runnable must be False
  1633. self.assertFalse(bind10_src.boss_of_bind.runnable)
  1634. bind10_src.boss_of_bind = None
  1635. if __name__ == '__main__':
  1636. # store os.environ for test_unchanged_environment
  1637. original_os_environ = copy.deepcopy(os.environ)
  1638. isc.log.resetUnitTestRootLogger()
  1639. unittest.main()