bind10_test.py.in 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066
  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. dev_null_stdout=False, dev_null_stderr=False):
  666. return MockProcessInfo(name, args, c_channel_env,
  667. dev_null_stdout, dev_null_stderr)
  668. class MockBobSimple(BoB):
  669. def __init__(self):
  670. BoB.__init__(self)
  671. # Set which process has been started
  672. self.started_process_name = None
  673. self.started_process_args = None
  674. def _make_mock_process_info(self, name, args, c_channel_env,
  675. dev_null_stdout=False, dev_null_stderr=False):
  676. return MockProcessInfo(name, args, c_channel_env,
  677. dev_null_stdout, dev_null_stderr)
  678. def start_process(self, name, args, c_channel_env, port=None, address=None):
  679. self.started_process_name = name
  680. self.started_process_args = args
  681. return None
  682. class TestStartStopProcessesBob(unittest.TestCase):
  683. """
  684. Check that the start_all_components method starts the right combination
  685. of components and that the right components are started and stopped
  686. according to changes in configuration.
  687. """
  688. def check_environment_unchanged(self):
  689. # Check whether the environment has not been changed
  690. self.assertEqual(original_os_environ, os.environ)
  691. def check_started(self, bob, core, auth, resolver):
  692. """
  693. Check that the right sets of services are started. The ones that
  694. should be running are specified by the core, auth and resolver parameters
  695. (they are groups of processes, eg. auth means b10-auth, -xfrout, -xfrin
  696. and -zonemgr).
  697. """
  698. self.assertEqual(bob.msgq, core)
  699. self.assertEqual(bob.cfgmgr, core)
  700. self.assertEqual(bob.ccsession, core)
  701. self.assertEqual(bob.creator, core)
  702. self.assertEqual(bob.auth, auth)
  703. self.assertEqual(bob.resolver, resolver)
  704. self.assertEqual(bob.xfrout, auth)
  705. self.assertEqual(bob.xfrin, auth)
  706. self.assertEqual(bob.zonemgr, auth)
  707. self.assertEqual(bob.stats, core)
  708. self.assertEqual(bob.stats_httpd, core)
  709. self.assertEqual(bob.cmdctl, core)
  710. self.check_environment_unchanged()
  711. def check_preconditions(self, bob):
  712. self.check_started(bob, False, False, False)
  713. def check_started_none(self, bob):
  714. """
  715. Check that the situation is according to configuration where no servers
  716. should be started. Some components still need to be running.
  717. """
  718. self.check_started(bob, True, False, False)
  719. self.check_environment_unchanged()
  720. def check_started_both(self, bob):
  721. """
  722. Check the situation is according to configuration where both servers
  723. (auth and resolver) are enabled.
  724. """
  725. self.check_started(bob, True, True, True)
  726. self.check_environment_unchanged()
  727. def check_started_auth(self, bob):
  728. """
  729. Check the set of components needed to run auth only is started.
  730. """
  731. self.check_started(bob, True, True, False)
  732. self.check_environment_unchanged()
  733. def check_started_resolver(self, bob):
  734. """
  735. Check the set of components needed to run resolver only is started.
  736. """
  737. self.check_started(bob, True, False, True)
  738. self.check_environment_unchanged()
  739. def check_started_dhcp(self, bob, v4, v6):
  740. """
  741. Check if proper combinations of DHCPv4 and DHCpv6 can be started
  742. """
  743. self.assertEqual(v4, bob.dhcp4)
  744. self.assertEqual(v6, bob.dhcp6)
  745. self.check_environment_unchanged()
  746. def construct_config(self, start_auth, start_resolver):
  747. # The things that are common, not turned on an off
  748. config = {}
  749. config['b10-stats'] = { 'kind': 'dispensable', 'address': 'Stats' }
  750. config['b10-stats-httpd'] = { 'kind': 'dispensable',
  751. 'address': 'StatsHttpd' }
  752. config['b10-cmdctl'] = { 'kind': 'needed', 'special': 'cmdctl' }
  753. if start_auth:
  754. config['b10-auth'] = { 'kind': 'needed', 'special': 'auth' }
  755. config['b10-xfrout'] = { 'kind': 'dispensable',
  756. 'address': 'Xfrout' }
  757. config['b10-xfrin'] = { 'kind': 'dispensable',
  758. 'address': 'Xfrin' }
  759. config['b10-zonemgr'] = { 'kind': 'dispensable',
  760. 'address': 'Zonemgr' }
  761. if start_resolver:
  762. config['b10-resolver'] = { 'kind': 'needed',
  763. 'special': 'resolver' }
  764. return {'components': config}
  765. def config_start_init(self, start_auth, start_resolver):
  766. """
  767. Test the configuration is loaded at the startup.
  768. """
  769. bob = MockBob()
  770. config = self.construct_config(start_auth, start_resolver)
  771. class CC:
  772. def get_full_config(self):
  773. return config
  774. # Provide the fake CC with data
  775. bob.ccs = CC()
  776. # And make sure it's not overwritten
  777. def start_ccsession():
  778. bob.ccsession = True
  779. bob.start_ccsession = lambda _: start_ccsession()
  780. # We need to return the original _read_bind10_config
  781. bob._read_bind10_config = lambda: BoB._read_bind10_config(bob)
  782. bob.start_all_components()
  783. self.check_started(bob, True, start_auth, start_resolver)
  784. self.check_environment_unchanged()
  785. def test_start_none(self):
  786. self.config_start_init(False, False)
  787. def test_start_resolver(self):
  788. self.config_start_init(False, True)
  789. def test_start_auth(self):
  790. self.config_start_init(True, False)
  791. def test_start_both(self):
  792. self.config_start_init(True, True)
  793. def test_config_start(self):
  794. """
  795. Test that the configuration starts and stops components according
  796. to configuration changes.
  797. """
  798. # Create BoB and ensure correct initialization
  799. bob = MockBob()
  800. self.check_preconditions(bob)
  801. bob.start_all_components()
  802. bob.runnable = True
  803. bob.config_handler(self.construct_config(False, False))
  804. self.check_started_none(bob)
  805. # Enable both at once
  806. bob.config_handler(self.construct_config(True, True))
  807. self.check_started_both(bob)
  808. # Not touched by empty change
  809. bob.config_handler({})
  810. self.check_started_both(bob)
  811. # Not touched by change to the same configuration
  812. bob.config_handler(self.construct_config(True, True))
  813. self.check_started_both(bob)
  814. # Turn them both off again
  815. bob.config_handler(self.construct_config(False, False))
  816. self.check_started_none(bob)
  817. # Not touched by empty change
  818. bob.config_handler({})
  819. self.check_started_none(bob)
  820. # Not touched by change to the same configuration
  821. bob.config_handler(self.construct_config(False, False))
  822. self.check_started_none(bob)
  823. # Start and stop auth separately
  824. bob.config_handler(self.construct_config(True, False))
  825. self.check_started_auth(bob)
  826. bob.config_handler(self.construct_config(False, False))
  827. self.check_started_none(bob)
  828. # Start and stop resolver separately
  829. bob.config_handler(self.construct_config(False, True))
  830. self.check_started_resolver(bob)
  831. bob.config_handler(self.construct_config(False, False))
  832. self.check_started_none(bob)
  833. # Alternate
  834. bob.config_handler(self.construct_config(True, False))
  835. self.check_started_auth(bob)
  836. bob.config_handler(self.construct_config(False, True))
  837. self.check_started_resolver(bob)
  838. bob.config_handler(self.construct_config(True, False))
  839. self.check_started_auth(bob)
  840. def test_config_start_once(self):
  841. """
  842. Tests that a component is started only once.
  843. """
  844. # Create BoB and ensure correct initialization
  845. bob = MockBob()
  846. self.check_preconditions(bob)
  847. bob.start_all_components()
  848. bob.runnable = True
  849. bob.config_handler(self.construct_config(True, True))
  850. self.check_started_both(bob)
  851. bob.start_auth = lambda: self.fail("Started auth again")
  852. bob.start_xfrout = lambda: self.fail("Started xfrout again")
  853. bob.start_xfrin = lambda: self.fail("Started xfrin again")
  854. bob.start_zonemgr = lambda: self.fail("Started zonemgr again")
  855. bob.start_resolver = lambda: self.fail("Started resolver again")
  856. # Send again we want to start them. Should not do it, as they are.
  857. bob.config_handler(self.construct_config(True, True))
  858. def test_config_not_started_early(self):
  859. """
  860. Test that components are not started by the config handler before
  861. startup.
  862. """
  863. bob = MockBob()
  864. self.check_preconditions(bob)
  865. bob.start_auth = lambda: self.fail("Started auth again")
  866. bob.start_xfrout = lambda: self.fail("Started xfrout again")
  867. bob.start_xfrin = lambda: self.fail("Started xfrin again")
  868. bob.start_zonemgr = lambda: self.fail("Started zonemgr again")
  869. bob.start_resolver = lambda: self.fail("Started resolver again")
  870. bob.config_handler({'start_auth': True, 'start_resolver': True})
  871. # Checks that DHCP (v4 and v6) components are started when expected
  872. def test_start_dhcp(self):
  873. # Create BoB and ensure correct initialization
  874. bob = MockBob()
  875. self.check_preconditions(bob)
  876. bob.start_all_components()
  877. bob.config_handler(self.construct_config(False, False))
  878. self.check_started_dhcp(bob, False, False)
  879. def test_start_dhcp_v6only(self):
  880. # Create BoB and ensure correct initialization
  881. bob = MockBob()
  882. self.check_preconditions(bob)
  883. # v6 only enabled
  884. bob.start_all_components()
  885. bob.runnable = True
  886. bob._BoB_started = True
  887. config = self.construct_config(False, False)
  888. config['components']['b10-dhcp6'] = { 'kind': 'needed',
  889. 'address': 'Dhcp6' }
  890. bob.config_handler(config)
  891. self.check_started_dhcp(bob, False, True)
  892. # uncomment when dhcpv4 becomes implemented
  893. # v4 only enabled
  894. #bob.cfg_start_dhcp6 = False
  895. #bob.cfg_start_dhcp4 = True
  896. #self.check_started_dhcp(bob, True, False)
  897. # both v4 and v6 enabled
  898. #bob.cfg_start_dhcp6 = True
  899. #bob.cfg_start_dhcp4 = True
  900. #self.check_started_dhcp(bob, True, True)
  901. class MockComponent:
  902. def __init__(self, name, pid, address=None):
  903. self.name = lambda: name
  904. self.pid = lambda: pid
  905. self.address = lambda: address
  906. self.restarted = False
  907. self.forceful = False
  908. self.running = True
  909. self.has_failed = False
  910. def get_restart_time(self):
  911. return 0 # arbitrary dummy value
  912. def restart(self, now):
  913. self.restarted = True
  914. return True
  915. def is_running(self):
  916. return self.running
  917. def failed(self, status):
  918. return self.has_failed
  919. def kill(self, forceful):
  920. self.forceful = forceful
  921. class TestBossCmd(unittest.TestCase):
  922. def test_ping(self):
  923. """
  924. Confirm simple ping command works.
  925. """
  926. bob = MockBob()
  927. answer = bob.command_handler("ping", None)
  928. self.assertEqual(answer, {'result': [0, 'pong']})
  929. def test_show_processes_empty(self):
  930. """
  931. Confirm getting a list of processes works.
  932. """
  933. bob = MockBob()
  934. answer = bob.command_handler("show_processes", None)
  935. self.assertEqual(answer, {'result': [0, []]})
  936. def test_show_processes(self):
  937. """
  938. Confirm getting a list of processes works.
  939. """
  940. bob = MockBob()
  941. bob.register_process(1, MockComponent('first', 1))
  942. bob.register_process(2, MockComponent('second', 2, 'Second'))
  943. answer = bob.command_handler("show_processes", None)
  944. processes = [[1, 'first', None],
  945. [2, 'second', 'Second']]
  946. self.assertEqual(answer, {'result': [0, processes]})
  947. class TestParseArgs(unittest.TestCase):
  948. """
  949. This tests parsing of arguments of the bind10 master process.
  950. """
  951. #TODO: Write tests for the original parsing, bad options, etc.
  952. def test_no_opts(self):
  953. """
  954. Test correct default values when no options are passed.
  955. """
  956. options = parse_args([], TestOptParser)
  957. self.assertEqual(None, options.data_path)
  958. self.assertEqual(None, options.config_file)
  959. self.assertEqual(None, options.cmdctl_port)
  960. def test_data_path(self):
  961. """
  962. Test it can parse the data path.
  963. """
  964. self.assertRaises(OptsError, parse_args, ['-p'], TestOptParser)
  965. self.assertRaises(OptsError, parse_args, ['--data-path'],
  966. TestOptParser)
  967. options = parse_args(['-p', '/data/path'], TestOptParser)
  968. self.assertEqual('/data/path', options.data_path)
  969. options = parse_args(['--data-path=/data/path'], TestOptParser)
  970. self.assertEqual('/data/path', options.data_path)
  971. def test_config_filename(self):
  972. """
  973. Test it can parse the config switch.
  974. """
  975. self.assertRaises(OptsError, parse_args, ['-c'], TestOptParser)
  976. self.assertRaises(OptsError, parse_args, ['--config-file'],
  977. TestOptParser)
  978. options = parse_args(['-c', 'config-file'], TestOptParser)
  979. self.assertEqual('config-file', options.config_file)
  980. options = parse_args(['--config-file=config-file'], TestOptParser)
  981. self.assertEqual('config-file', options.config_file)
  982. def test_clear_config(self):
  983. options = parse_args([], TestOptParser)
  984. self.assertEqual(False, options.clear_config)
  985. options = parse_args(['--clear-config'], TestOptParser)
  986. self.assertEqual(True, options.clear_config)
  987. def test_nokill(self):
  988. options = parse_args([], TestOptParser)
  989. self.assertEqual(False, options.nokill)
  990. options = parse_args(['--no-kill'], TestOptParser)
  991. self.assertEqual(True, options.nokill)
  992. options = parse_args([], TestOptParser)
  993. self.assertEqual(False, options.nokill)
  994. options = parse_args(['-i'], TestOptParser)
  995. self.assertEqual(True, options.nokill)
  996. def test_cmdctl_port(self):
  997. """
  998. Test it can parse the command control port.
  999. """
  1000. self.assertRaises(OptsError, parse_args, ['--cmdctl-port=abc'],
  1001. TestOptParser)
  1002. self.assertRaises(OptsError, parse_args, ['--cmdctl-port=100000000'],
  1003. TestOptParser)
  1004. self.assertRaises(OptsError, parse_args, ['--cmdctl-port'],
  1005. TestOptParser)
  1006. options = parse_args(['--cmdctl-port=1234'], TestOptParser)
  1007. self.assertEqual(1234, options.cmdctl_port)
  1008. class TestPIDFile(unittest.TestCase):
  1009. def setUp(self):
  1010. self.pid_file = '@builddir@' + os.sep + 'bind10.pid'
  1011. if os.path.exists(self.pid_file):
  1012. os.unlink(self.pid_file)
  1013. def tearDown(self):
  1014. if os.path.exists(self.pid_file):
  1015. os.unlink(self.pid_file)
  1016. def check_pid_file(self):
  1017. # dump PID to the file, and confirm the content is correct
  1018. dump_pid(self.pid_file)
  1019. my_pid = os.getpid()
  1020. with open(self.pid_file, "r") as f:
  1021. self.assertEqual(my_pid, int(f.read()))
  1022. def test_dump_pid(self):
  1023. self.check_pid_file()
  1024. # make sure any existing content will be removed
  1025. with open(self.pid_file, "w") as f:
  1026. f.write('dummy data\n')
  1027. self.check_pid_file()
  1028. def test_unlink_pid_file_notexist(self):
  1029. dummy_data = 'dummy_data\n'
  1030. with open(self.pid_file, "w") as f:
  1031. f.write(dummy_data)
  1032. unlink_pid_file("no_such_pid_file")
  1033. # the file specified for unlink_pid_file doesn't exist,
  1034. # and the original content of the file should be intact.
  1035. with open(self.pid_file, "r") as f:
  1036. self.assertEqual(dummy_data, f.read())
  1037. def test_dump_pid_with_none(self):
  1038. # Check the behavior of dump_pid() and unlink_pid_file() with None.
  1039. # This should be no-op.
  1040. dump_pid(None)
  1041. self.assertFalse(os.path.exists(self.pid_file))
  1042. dummy_data = 'dummy_data\n'
  1043. with open(self.pid_file, "w") as f:
  1044. f.write(dummy_data)
  1045. unlink_pid_file(None)
  1046. with open(self.pid_file, "r") as f:
  1047. self.assertEqual(dummy_data, f.read())
  1048. def test_dump_pid_failure(self):
  1049. # the attempt to open file will fail, which should result in exception.
  1050. self.assertRaises(IOError, dump_pid,
  1051. 'nonexistent_dir' + os.sep + 'bind10.pid')
  1052. class TestBossComponents(unittest.TestCase):
  1053. """
  1054. Test the boss propagates component configuration properly to the
  1055. component configurator and acts sane.
  1056. """
  1057. def setUp(self):
  1058. self.__param = None
  1059. self.__called = False
  1060. self.__compconfig = {
  1061. 'comp': {
  1062. 'kind': 'needed',
  1063. 'process': 'cat'
  1064. }
  1065. }
  1066. def __unary_hook(self, param):
  1067. """
  1068. A hook function that stores the parameter for later examination.
  1069. """
  1070. self.__param = param
  1071. def __nullary_hook(self):
  1072. """
  1073. A hook function that notes down it was called.
  1074. """
  1075. self.__called = True
  1076. def __check_core(self, config):
  1077. """
  1078. A function checking that the config contains parts for the valid
  1079. core component configuration.
  1080. """
  1081. self.assertIsNotNone(config)
  1082. for component in ['sockcreator', 'msgq', 'cfgmgr']:
  1083. self.assertTrue(component in config)
  1084. self.assertEqual(component, config[component]['special'])
  1085. self.assertEqual('core', config[component]['kind'])
  1086. def __check_extended(self, config):
  1087. """
  1088. This checks that the config contains the core and one more component.
  1089. """
  1090. self.__check_core(config)
  1091. self.assertTrue('comp' in config)
  1092. self.assertEqual('cat', config['comp']['process'])
  1093. self.assertEqual('needed', config['comp']['kind'])
  1094. self.assertEqual(4, len(config))
  1095. def test_correct_run(self):
  1096. """
  1097. Test the situation when we run in usual scenario, nothing fails,
  1098. we just start, reconfigure and then stop peacefully.
  1099. """
  1100. bob = MockBob()
  1101. # Start it
  1102. orig = bob._component_configurator.startup
  1103. bob._component_configurator.startup = self.__unary_hook
  1104. bob.start_all_components()
  1105. bob._component_configurator.startup = orig
  1106. self.__check_core(self.__param)
  1107. self.assertEqual(3, len(self.__param))
  1108. # Reconfigure it
  1109. self.__param = None
  1110. orig = bob._component_configurator.reconfigure
  1111. bob._component_configurator.reconfigure = self.__unary_hook
  1112. # Otherwise it does not work
  1113. bob.runnable = True
  1114. bob.config_handler({'components': self.__compconfig})
  1115. self.__check_extended(self.__param)
  1116. currconfig = self.__param
  1117. # If we reconfigure it, but it does not contain the components part,
  1118. # nothing is called
  1119. bob.config_handler({})
  1120. self.assertEqual(self.__param, currconfig)
  1121. self.__param = None
  1122. bob._component_configurator.reconfigure = orig
  1123. # Check a configuration that messes up the core components is rejected.
  1124. compconf = dict(self.__compconfig)
  1125. compconf['msgq'] = { 'process': 'echo' }
  1126. result = bob.config_handler({'components': compconf})
  1127. # Check it rejected it
  1128. self.assertEqual(1, result['result'][0])
  1129. # We can't call shutdown, that one relies on the stuff in main
  1130. # We check somewhere else that the shutdown is actually called
  1131. # from there (the test_kills).
  1132. def __real_test_kill(self, nokill=False, ex_on_kill=None):
  1133. """
  1134. Helper function that does the actual kill functionality testing.
  1135. """
  1136. bob = MockBob()
  1137. bob.nokill = nokill
  1138. killed = []
  1139. class ImmortalComponent:
  1140. """
  1141. An immortal component. It does not stop when it is told so
  1142. (anyway it is not told so). It does not die if it is killed
  1143. the first time. It dies only when killed forcefully.
  1144. """
  1145. def __init__(self):
  1146. # number of kill() calls, preventing infinite loop.
  1147. self.__call_count = 0
  1148. def kill(self, forceful=False):
  1149. self.__call_count += 1
  1150. if self.__call_count > 2:
  1151. raise Exception('Too many calls to ImmortalComponent.kill')
  1152. killed.append(forceful)
  1153. if ex_on_kill is not None:
  1154. # If exception is given by the test, raise it here.
  1155. # In the case of ESRCH, the process should have gone
  1156. # somehow, so we clear the components.
  1157. if ex_on_kill.errno == errno.ESRCH:
  1158. bob.components = {}
  1159. raise ex_on_kill
  1160. if forceful:
  1161. bob.components = {}
  1162. def pid(self):
  1163. return 1
  1164. def name(self):
  1165. return "Immortal"
  1166. bob.components = {}
  1167. bob.register_process(1, ImmortalComponent())
  1168. # While at it, we check the configurator shutdown is actually called
  1169. orig = bob._component_configurator.shutdown
  1170. bob._component_configurator.shutdown = self.__nullary_hook
  1171. self.__called = False
  1172. bob.ccs = MockModuleCCSession()
  1173. self.assertFalse(bob.ccs.stopped)
  1174. bob.shutdown()
  1175. self.assertTrue(bob.ccs.stopped)
  1176. # Here, killed is an array where False is added if SIGTERM
  1177. # should be sent, or True if SIGKILL should be sent, in order in
  1178. # which they're sent.
  1179. if nokill:
  1180. self.assertEqual([], killed)
  1181. else:
  1182. if ex_on_kill is not None:
  1183. self.assertEqual([False], killed)
  1184. else:
  1185. self.assertEqual([False, True], killed)
  1186. self.assertTrue(self.__called)
  1187. bob._component_configurator.shutdown = orig
  1188. def test_kills(self):
  1189. """
  1190. Test that the boss kills components which don't want to stop.
  1191. """
  1192. self.__real_test_kill()
  1193. def test_kill_fail(self):
  1194. """Test cases where kill() results in an exception due to OS error.
  1195. The behavior should be different for EPERM, so we test two cases.
  1196. """
  1197. ex = OSError()
  1198. ex.errno, ex.strerror = errno.ESRCH, 'No such process'
  1199. self.__real_test_kill(ex_on_kill=ex)
  1200. ex.errno, ex.strerror = errno.EPERM, 'Operation not permitted'
  1201. self.__real_test_kill(ex_on_kill=ex)
  1202. def test_nokill(self):
  1203. """
  1204. Test that the boss *doesn't* kill components which don't want to
  1205. stop, when asked not to (by passing the --no-kill option which
  1206. sets bob.nokill to True).
  1207. """
  1208. self.__real_test_kill(True)
  1209. def test_component_shutdown(self):
  1210. """
  1211. Test the component_shutdown sets all variables accordingly.
  1212. """
  1213. bob = MockBob()
  1214. self.assertRaises(Exception, bob.component_shutdown, 1)
  1215. self.assertEqual(1, bob.exitcode)
  1216. bob._BoB__started = True
  1217. bob.component_shutdown(2)
  1218. self.assertEqual(2, bob.exitcode)
  1219. self.assertFalse(bob.runnable)
  1220. def test_init_config(self):
  1221. """
  1222. Test initial configuration is loaded.
  1223. """
  1224. bob = MockBob()
  1225. # Start it
  1226. bob._component_configurator.reconfigure = self.__unary_hook
  1227. # We need to return the original read_bind10_config
  1228. bob._read_bind10_config = lambda: BoB._read_bind10_config(bob)
  1229. # And provide a session to read the data from
  1230. class CC:
  1231. pass
  1232. bob.ccs = CC()
  1233. bob.ccs.get_full_config = lambda: {'components': self.__compconfig}
  1234. bob.start_all_components()
  1235. self.__check_extended(self.__param)
  1236. def __setup_restart(self, bob, component):
  1237. '''Common procedure for restarting a component used below.'''
  1238. bob.components_to_restart = { component }
  1239. component.restarted = False
  1240. bob.restart_processes()
  1241. def test_restart_processes(self):
  1242. '''Check some behavior on restarting processes.'''
  1243. bob = MockBob()
  1244. bob.runnable = True
  1245. component = MockComponent('test', 53)
  1246. # A component to be restarted will actually be restarted iff it's
  1247. # in the configurator's configuration.
  1248. # We bruteforce the configurator internal below; ugly, but the easiest
  1249. # way for the test.
  1250. bob._component_configurator._components['test'] = (None, component)
  1251. self.__setup_restart(bob, component)
  1252. self.assertTrue(component.restarted)
  1253. self.assertFalse(component in bob.components_to_restart)
  1254. # Remove the component from the configuration. It won't be restarted
  1255. # even if scheduled, nor will remain in the to-be-restarted list.
  1256. del bob._component_configurator._components['test']
  1257. self.__setup_restart(bob, component)
  1258. self.assertFalse(component.restarted)
  1259. self.assertFalse(component in bob.components_to_restart)
  1260. def test_get_processes(self):
  1261. '''Test that procsses are returned correctly, sorted by pid.'''
  1262. bob = MockBob()
  1263. pids = []
  1264. pids.extend(range(0, 20))
  1265. random.shuffle(pids)
  1266. for i in range(0, 20):
  1267. pid = pids[i]
  1268. component = MockComponent('test' + str(pid), pid, 'Test' + str(pid))
  1269. bob.components[pid] = component
  1270. process_list = bob.get_processes()
  1271. self.assertEqual(20, len(process_list))
  1272. last_pid = -1
  1273. for process in process_list:
  1274. pid = process[0]
  1275. self.assertLessEqual(last_pid, pid)
  1276. last_pid = pid
  1277. self.assertEqual([pid, 'test' + str(pid), 'Test' + str(pid)], process)
  1278. def _test_reap_children_helper(self, runnable, is_running, failed):
  1279. '''Construct a BoB instance, set various data in it according to
  1280. passed args and check if the component was added to the list of
  1281. components to restart.'''
  1282. bob = MockBob()
  1283. bob.runnable = runnable
  1284. component = MockComponent('test', 53)
  1285. component.running = is_running
  1286. component.has_failed = failed
  1287. bob.components[53] = component
  1288. self.assertFalse(component in bob.components_to_restart)
  1289. bob.reap_children()
  1290. if runnable and is_running and not failed:
  1291. self.assertTrue(bob.components_to_restart)
  1292. else:
  1293. self.assertFalse(bob.components_to_restart)
  1294. def test_reap_children(self):
  1295. '''Test that children are queued to be restarted when they ask for it.'''
  1296. # test various combinations of 3 booleans
  1297. # (BoB.runnable, component.is_running(), component.failed())
  1298. self._test_reap_children_helper(False, False, False)
  1299. self._test_reap_children_helper(False, False, True)
  1300. self._test_reap_children_helper(False, True, False)
  1301. self._test_reap_children_helper(False, True, True)
  1302. self._test_reap_children_helper(True, False, False)
  1303. self._test_reap_children_helper(True, False, True)
  1304. self._test_reap_children_helper(True, True, False)
  1305. self._test_reap_children_helper(True, True, True)
  1306. # setup for more tests below
  1307. bob = MockBob()
  1308. bob.runnable = True
  1309. component = MockComponent('test', 53)
  1310. bob.components[53] = component
  1311. # case where the returned pid is unknown to us. nothing should
  1312. # happpen then.
  1313. bob.get_process_exit_status_called = False
  1314. bob._get_process_exit_status = bob._get_process_exit_status_unknown_pid
  1315. bob.components_to_restart = []
  1316. # this should do nothing as the pid is unknown
  1317. bob.reap_children()
  1318. self.assertFalse(bob.components_to_restart)
  1319. # case where bob._get_process_exit_status() raises OSError with errno.ECHILD
  1320. bob._get_process_exit_status = bob._get_process_exit_status_raises_oserror_echild
  1321. bob.components_to_restart = []
  1322. # this should catch and handle the OSError
  1323. bob.reap_children()
  1324. self.assertFalse(bob.components_to_restart)
  1325. # case where bob._get_process_exit_status() raises OSError with
  1326. # errno other than ECHILD
  1327. bob._get_process_exit_status = bob._get_process_exit_status_raises_oserror_other
  1328. with self.assertRaises(OSError):
  1329. bob.reap_children()
  1330. # case where bob._get_process_exit_status() raises something
  1331. # other than OSError
  1332. bob._get_process_exit_status = bob._get_process_exit_status_raises_other
  1333. with self.assertRaises(Exception):
  1334. bob.reap_children()
  1335. def test_kill_started_components(self):
  1336. '''Test that started components are killed.'''
  1337. bob = MockBob()
  1338. component = MockComponent('test', 53, 'Test')
  1339. bob.components[53] = component
  1340. self.assertEqual([[53, 'test', 'Test']], bob.get_processes())
  1341. bob.kill_started_components()
  1342. self.assertFalse(bob.get_processes())
  1343. self.assertTrue(component.forceful)
  1344. def test_start_msgq(self):
  1345. '''Test that b10-msgq is started.'''
  1346. bob = MockBobSimple()
  1347. bob.c_channel_env = {}
  1348. bob.msgq_timeout = 0
  1349. # use the MockProcessInfo creator
  1350. bob._make_process_info = bob._make_mock_process_info
  1351. # non-verbose case
  1352. bob.verbose = False
  1353. pi = bob.start_msgq()
  1354. self.assertEqual('b10-msgq', pi.name)
  1355. self.assertEqual(['b10-msgq'], pi.args)
  1356. self.assertTrue(pi.dev_null_stdout)
  1357. self.assertTrue(pi.dev_null_stderr)
  1358. self.assertEqual({}, pi.env)
  1359. # this is set by ProcessInfo.spawn()
  1360. self.assertEqual(42147, pi.pid)
  1361. # verbose case
  1362. bob.verbose = True
  1363. pi = bob.start_msgq()
  1364. self.assertEqual('b10-msgq', pi.name)
  1365. self.assertEqual(['b10-msgq'], pi.args)
  1366. self.assertTrue(pi.dev_null_stdout)
  1367. self.assertFalse(pi.dev_null_stderr)
  1368. self.assertEqual({}, pi.env)
  1369. # this is set by ProcessInfo.spawn()
  1370. self.assertEqual(42147, pi.pid)
  1371. def test_start_msgq_timeout(self):
  1372. '''Test that b10-msgq startup attempts connections several times
  1373. and times out eventually.'''
  1374. bob = MockBobSimple()
  1375. bob.c_channel_env = {}
  1376. # keep the timeout small for the test to complete quickly
  1377. bob.msgq_timeout = 1
  1378. # use the MockProcessInfo creator
  1379. bob._make_process_info = bob._make_mock_process_info
  1380. global attempts
  1381. attempts = 0
  1382. tmp_time = time.time
  1383. def _my_time():
  1384. global attempts
  1385. attempts += 1
  1386. return tmp_time()
  1387. time.time = _my_time
  1388. thrown = False
  1389. # An exception will be thrown here when it eventually times out.
  1390. try:
  1391. pi = bob.start_msgq()
  1392. except bind10_src.CChannelConnectError as e:
  1393. thrown = True
  1394. # We just check that an exception was thrown, and that several
  1395. # attempts were made to connect.
  1396. self.assertTrue(thrown)
  1397. # 1 second of attempts every 0.1 seconds should result in at least 5 attempts
  1398. self.assertGreater(attempts, 5)
  1399. time.time = tmp_time
  1400. def test_start_cfgmgr(self):
  1401. '''Test that b10-cfgmgr is started.'''
  1402. class DummySession():
  1403. def group_recvmsg(self):
  1404. return (None, None)
  1405. bob = MockBobSimple()
  1406. bob.c_channel_env = {}
  1407. bob.cc_session = DummySession()
  1408. bob.wait_time = 0
  1409. # use the MockProcessInfo creator
  1410. bob._make_process_info = bob._make_mock_process_info
  1411. # defaults
  1412. pi = bob.start_cfgmgr()
  1413. self.assertEqual('b10-cfgmgr', pi.name)
  1414. self.assertEqual(['b10-cfgmgr'], pi.args)
  1415. self.assertEqual({}, pi.env)
  1416. # this is set by ProcessInfo.spawn()
  1417. self.assertEqual(42147, pi.pid)
  1418. # data_path is specified
  1419. bob.data_path = '/var/lib/test'
  1420. pi = bob.start_cfgmgr()
  1421. self.assertEqual('b10-cfgmgr', pi.name)
  1422. self.assertEqual(['b10-cfgmgr',
  1423. '--data-path=/var/lib/test'],
  1424. pi.args)
  1425. self.assertEqual({}, pi.env)
  1426. # this is set by ProcessInfo.spawn()
  1427. self.assertEqual(42147, pi.pid)
  1428. # config_filename is specified
  1429. bob.config_filename = 'foo.cfg'
  1430. pi = bob.start_cfgmgr()
  1431. self.assertEqual('b10-cfgmgr', pi.name)
  1432. self.assertEqual(['b10-cfgmgr',
  1433. '--data-path=/var/lib/test',
  1434. '--config-filename=foo.cfg'],
  1435. pi.args)
  1436. self.assertEqual({}, pi.env)
  1437. # this is set by ProcessInfo.spawn()
  1438. self.assertEqual(42147, pi.pid)
  1439. # clear_config is specified
  1440. bob.clear_config = True
  1441. pi = bob.start_cfgmgr()
  1442. self.assertEqual('b10-cfgmgr', pi.name)
  1443. self.assertEqual(['b10-cfgmgr',
  1444. '--data-path=/var/lib/test',
  1445. '--config-filename=foo.cfg',
  1446. '--clear-config'],
  1447. pi.args)
  1448. self.assertEqual({}, pi.env)
  1449. # this is set by ProcessInfo.spawn()
  1450. self.assertEqual(42147, pi.pid)
  1451. def test_start_ccsession(self):
  1452. '''Test that CC session is started.'''
  1453. class DummySession():
  1454. def __init__(self, specfile, config_handler, command_handler,
  1455. socket_file):
  1456. self.specfile = specfile
  1457. self.config_handler = config_handler
  1458. self.command_handler = command_handler
  1459. self.socket_file = socket_file
  1460. self.started = False
  1461. def start(self):
  1462. self.started = True
  1463. bob = MockBobSimple()
  1464. tmp = isc.config.ModuleCCSession
  1465. isc.config.ModuleCCSession = DummySession
  1466. ccs = bob.start_ccsession({})
  1467. self.assertEqual(bind10_src.SPECFILE_LOCATION, ccs.specfile)
  1468. self.assertEqual(bob.config_handler, ccs.config_handler)
  1469. self.assertEqual(bob.command_handler, ccs.command_handler)
  1470. self.assertEqual(bob.msgq_socket_file, ccs.socket_file)
  1471. self.assertTrue(ccs.started)
  1472. isc.config.ModuleCCSession = tmp
  1473. def test_start_process(self):
  1474. '''Test that processes can be started.'''
  1475. bob = MockBob()
  1476. # use the MockProcessInfo creator
  1477. bob._make_process_info = bob._make_mock_process_info
  1478. pi = bob.start_process('Test Process', ['/bin/true'], {})
  1479. self.assertEqual('Test Process', pi.name)
  1480. self.assertEqual(['/bin/true'], pi.args)
  1481. self.assertEqual({}, pi.env)
  1482. # this is set by ProcessInfo.spawn()
  1483. self.assertEqual(42147, pi.pid)
  1484. def test_register_process(self):
  1485. '''Test that processes can be registered with BoB.'''
  1486. bob = MockBob()
  1487. component = MockComponent('test', 53, 'Test')
  1488. self.assertFalse(53 in bob.components)
  1489. bob.register_process(53, component)
  1490. self.assertTrue(53 in bob.components)
  1491. def test_start_simple(self):
  1492. '''Test simple process startup.'''
  1493. bob = MockBobSimple()
  1494. bob.c_channel_env = {}
  1495. # non-verbose case
  1496. bob.verbose = False
  1497. bob.start_simple('/bin/true')
  1498. self.assertEqual('/bin/true', bob.started_process_name)
  1499. self.assertEqual(['/bin/true'], bob.started_process_args)
  1500. # verbose case
  1501. bob.verbose = True
  1502. bob.start_simple('/bin/true')
  1503. self.assertEqual('/bin/true', bob.started_process_name)
  1504. self.assertEqual(['/bin/true', '-v'], bob.started_process_args)
  1505. def test_start_auth(self):
  1506. '''Test that b10-auth is started.'''
  1507. bob = MockBobSimple()
  1508. bob.c_channel_env = {}
  1509. # non-verbose case
  1510. bob.verbose = False
  1511. bob.start_auth()
  1512. self.assertEqual('b10-auth', bob.started_process_name)
  1513. self.assertEqual(['b10-auth'], bob.started_process_args)
  1514. # verbose case
  1515. bob.verbose = True
  1516. bob.start_auth()
  1517. self.assertEqual('b10-auth', bob.started_process_name)
  1518. self.assertEqual(['b10-auth', '-v'], bob.started_process_args)
  1519. def test_start_resolver(self):
  1520. '''Test that b10-resolver is started.'''
  1521. bob = MockBobSimple()
  1522. bob.c_channel_env = {}
  1523. # non-verbose case
  1524. bob.verbose = False
  1525. bob.start_resolver()
  1526. self.assertEqual('b10-resolver', bob.started_process_name)
  1527. self.assertEqual(['b10-resolver'], bob.started_process_args)
  1528. # verbose case
  1529. bob.verbose = True
  1530. bob.start_resolver()
  1531. self.assertEqual('b10-resolver', bob.started_process_name)
  1532. self.assertEqual(['b10-resolver', '-v'], bob.started_process_args)
  1533. def test_start_cmdctl(self):
  1534. '''Test that b10-cmdctl is started.'''
  1535. bob = MockBobSimple()
  1536. bob.c_channel_env = {}
  1537. # non-verbose case
  1538. bob.verbose = False
  1539. bob.start_cmdctl()
  1540. self.assertEqual('b10-cmdctl', bob.started_process_name)
  1541. self.assertEqual(['b10-cmdctl'], bob.started_process_args)
  1542. # verbose case
  1543. bob.verbose = True
  1544. bob.start_cmdctl()
  1545. self.assertEqual('b10-cmdctl', bob.started_process_name)
  1546. self.assertEqual(['b10-cmdctl', '-v'], bob.started_process_args)
  1547. # with port
  1548. bob.verbose = True
  1549. bob.cmdctl_port = 9353
  1550. bob.start_cmdctl()
  1551. self.assertEqual('b10-cmdctl', bob.started_process_name)
  1552. self.assertEqual(['b10-cmdctl', '--port=9353', '-v'], bob.started_process_args)
  1553. class SocketSrvTest(unittest.TestCase):
  1554. """
  1555. This tests some methods of boss related to the unix domain sockets used
  1556. to transfer other sockets to applications.
  1557. """
  1558. def setUp(self):
  1559. """
  1560. Create the boss to test, testdata and backup some functions.
  1561. """
  1562. self.__boss = BoB()
  1563. self.__select_backup = bind10_src.select.select
  1564. self.__select_called = None
  1565. self.__socket_data_called = None
  1566. self.__consumer_dead_called = None
  1567. self.__socket_request_handler_called = None
  1568. def tearDown(self):
  1569. """
  1570. Restore functions.
  1571. """
  1572. bind10_src.select.select = self.__select_backup
  1573. class __FalseSocket:
  1574. """
  1575. A mock socket for the select and accept and stuff like that.
  1576. """
  1577. def __init__(self, owner, fileno=42):
  1578. self.__owner = owner
  1579. self.__fileno = fileno
  1580. self.data = None
  1581. self.closed = False
  1582. def fileno(self):
  1583. return self.__fileno
  1584. def accept(self):
  1585. return (self.__class__(self.__owner, 13), "/path/to/socket")
  1586. def recv(self, bufsize, flags=0):
  1587. self.__owner.assertEqual(1, bufsize)
  1588. self.__owner.assertEqual(socket.MSG_DONTWAIT, flags)
  1589. if isinstance(self.data, socket.error):
  1590. raise self.data
  1591. elif self.data is not None:
  1592. if len(self.data):
  1593. result = self.data[0:1]
  1594. self.data = self.data[1:]
  1595. return result
  1596. else:
  1597. raise socket.error(errno.EAGAIN, "Would block")
  1598. else:
  1599. return b''
  1600. def close(self):
  1601. self.closed = True
  1602. class __CCS:
  1603. """
  1604. A mock CCS, just to provide the socket file number.
  1605. """
  1606. class __Socket:
  1607. def fileno(self):
  1608. return 1
  1609. def get_socket(self):
  1610. return self.__Socket()
  1611. def __select_accept(self, r, w, x, t):
  1612. self.__select_called = (r, w, x, t)
  1613. return ([42], [], [])
  1614. def __select_data(self, r, w, x, t):
  1615. self.__select_called = (r, w, x, t)
  1616. return ([13], [], [])
  1617. def __accept(self):
  1618. """
  1619. Hijact the accept method of the boss.
  1620. Notes down it was called and stops the boss.
  1621. """
  1622. self.__accept_called = True
  1623. self.__boss.runnable = False
  1624. def test_srv_accept_called(self):
  1625. """
  1626. Test that the _srv_accept method of boss is called when the listening
  1627. socket is readable.
  1628. """
  1629. self.__boss.runnable = True
  1630. self.__boss._srv_socket = self.__FalseSocket(self)
  1631. self.__boss._srv_accept = self.__accept
  1632. self.__boss.ccs = self.__CCS()
  1633. bind10_src.select.select = self.__select_accept
  1634. self.__boss.run(2)
  1635. # It called the accept
  1636. self.assertTrue(self.__accept_called)
  1637. # And the select had the right parameters
  1638. self.assertEqual(([2, 1, 42], [], [], None), self.__select_called)
  1639. def test_srv_accept(self):
  1640. """
  1641. Test how the _srv_accept method works.
  1642. """
  1643. self.__boss._srv_socket = self.__FalseSocket(self)
  1644. self.__boss._srv_accept()
  1645. # After we accepted, a new socket is added there
  1646. socket = self.__boss._unix_sockets[13][0]
  1647. # The socket is properly stored there
  1648. self.assertTrue(isinstance(socket, self.__FalseSocket))
  1649. # And the buffer (yet empty) is there
  1650. self.assertEqual({13: (socket, b'')}, self.__boss._unix_sockets)
  1651. def __socket_data(self, socket):
  1652. self.__boss.runnable = False
  1653. self.__socket_data_called = socket
  1654. def test_socket_data(self):
  1655. """
  1656. Test that a socket that wants attention gets it.
  1657. """
  1658. self.__boss._srv_socket = self.__FalseSocket(self)
  1659. self.__boss._socket_data = self.__socket_data
  1660. self.__boss.ccs = self.__CCS()
  1661. self.__boss._unix_sockets = {13: (self.__FalseSocket(self, 13), b'')}
  1662. self.__boss.runnable = True
  1663. bind10_src.select.select = self.__select_data
  1664. self.__boss.run(2)
  1665. self.assertEqual(13, self.__socket_data_called)
  1666. self.assertEqual(([2, 1, 42, 13], [], [], None), self.__select_called)
  1667. def __prepare_data(self, data):
  1668. socket = self.__FalseSocket(self, 13)
  1669. self.__boss._unix_sockets = {13: (socket, b'')}
  1670. socket.data = data
  1671. self.__boss.socket_consumer_dead = self.__consumer_dead
  1672. self.__boss.socket_request_handler = self.__socket_request_handler
  1673. return socket
  1674. def __consumer_dead(self, socket):
  1675. self.__consumer_dead_called = socket
  1676. def __socket_request_handler(self, token, socket):
  1677. self.__socket_request_handler_called = (token, socket)
  1678. def test_socket_closed(self):
  1679. """
  1680. Test that a socket is removed and the socket_consumer_dead is called
  1681. when it is closed.
  1682. """
  1683. socket = self.__prepare_data(None)
  1684. self.__boss._socket_data(13)
  1685. self.assertEqual(socket, self.__consumer_dead_called)
  1686. self.assertEqual({}, self.__boss._unix_sockets)
  1687. self.assertTrue(socket.closed)
  1688. def test_socket_short(self):
  1689. """
  1690. Test that if there's not enough data to get the whole socket, it is
  1691. kept there, but nothing is called.
  1692. """
  1693. socket = self.__prepare_data(b'tok')
  1694. self.__boss._socket_data(13)
  1695. self.assertEqual({13: (socket, b'tok')}, self.__boss._unix_sockets)
  1696. self.assertFalse(socket.closed)
  1697. self.assertIsNone(self.__consumer_dead_called)
  1698. self.assertIsNone(self.__socket_request_handler_called)
  1699. def test_socket_continue(self):
  1700. """
  1701. Test that we call the token handling function when the whole token
  1702. comes. This test pretends to continue reading where the previous one
  1703. stopped.
  1704. """
  1705. socket = self.__prepare_data(b"en\nanothe")
  1706. # The data to finish
  1707. self.__boss._unix_sockets[13] = (socket, b'tok')
  1708. self.__boss._socket_data(13)
  1709. self.assertEqual({13: (socket, b'anothe')}, self.__boss._unix_sockets)
  1710. self.assertFalse(socket.closed)
  1711. self.assertIsNone(self.__consumer_dead_called)
  1712. self.assertEqual((b'token', socket),
  1713. self.__socket_request_handler_called)
  1714. def test_broken_socket(self):
  1715. """
  1716. If the socket raises an exception during the read other than EAGAIN,
  1717. it is broken and we remove it.
  1718. """
  1719. sock = self.__prepare_data(socket.error(errno.ENOMEM,
  1720. "There's more memory available, but not for you"))
  1721. self.__boss._socket_data(13)
  1722. self.assertEqual(sock, self.__consumer_dead_called)
  1723. self.assertEqual({}, self.__boss._unix_sockets)
  1724. self.assertTrue(sock.closed)
  1725. class TestFunctions(unittest.TestCase):
  1726. def setUp(self):
  1727. self.lockfile_testpath = \
  1728. "@abs_top_builddir@/src/bin/bind10/tests/lockfile_test"
  1729. self.assertFalse(os.path.exists(self.lockfile_testpath))
  1730. os.mkdir(self.lockfile_testpath)
  1731. self.assertTrue(os.path.isdir(self.lockfile_testpath))
  1732. def tearDown(self):
  1733. os.rmdir(self.lockfile_testpath)
  1734. self.assertFalse(os.path.isdir(self.lockfile_testpath))
  1735. os.environ["B10_LOCKFILE_DIR_FROM_BUILD"] = "@abs_top_builddir@"
  1736. def test_remove_lock_files(self):
  1737. os.environ["B10_LOCKFILE_DIR_FROM_BUILD"] = self.lockfile_testpath
  1738. # create lockfiles for the testcase
  1739. lockfiles = ["logger_lockfile"]
  1740. for f in lockfiles:
  1741. fname = os.environ["B10_LOCKFILE_DIR_FROM_BUILD"] + '/' + f
  1742. self.assertFalse(os.path.exists(fname))
  1743. open(fname, "w").close()
  1744. self.assertTrue(os.path.isfile(fname))
  1745. # first call should clear up all the lockfiles
  1746. bind10_src.remove_lock_files()
  1747. # check if the lockfiles exist
  1748. for f in lockfiles:
  1749. fname = os.environ["B10_LOCKFILE_DIR_FROM_BUILD"] + '/' + f
  1750. self.assertFalse(os.path.isfile(fname))
  1751. # second call should not assert anyway
  1752. bind10_src.remove_lock_files()
  1753. def test_get_signame(self):
  1754. # just test with some samples
  1755. signame = bind10_src.get_signame(signal.SIGTERM)
  1756. self.assertEqual('SIGTERM', signame)
  1757. signame = bind10_src.get_signame(signal.SIGKILL)
  1758. self.assertEqual('SIGKILL', signame)
  1759. # 59426 is hopefully an unused signal on most platforms
  1760. signame = bind10_src.get_signame(59426)
  1761. self.assertEqual('Unknown signal 59426', signame)
  1762. def test_fatal_signal(self):
  1763. self.assertIsNone(bind10_src.boss_of_bind)
  1764. bind10_src.boss_of_bind = BoB()
  1765. bind10_src.boss_of_bind.runnable = True
  1766. bind10_src.fatal_signal(signal.SIGTERM, None)
  1767. # Now, runnable must be False
  1768. self.assertFalse(bind10_src.boss_of_bind.runnable)
  1769. bind10_src.boss_of_bind = None
  1770. if __name__ == '__main__':
  1771. # store os.environ for test_unchanged_environment
  1772. original_os_environ = copy.deepcopy(os.environ)
  1773. isc.log.resetUnitTestRootLogger()
  1774. unittest.main()