bind10.py.in 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  1. #!@PYTHON@
  2. # Copyright (C) 2010 Internet Systems Consortium.
  3. #
  4. # Permission to use, copy, modify, and distribute this software for any
  5. # purpose with or without fee is hereby granted, provided that the above
  6. # copyright notice and this permission notice appear in all copies.
  7. #
  8. # THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SYSTEMS CONSORTIUM
  9. # DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
  10. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
  11. # INTERNET SYSTEMS CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
  12. # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
  13. # FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  14. # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
  15. # WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. """
  17. This file implements the Boss of Bind (BoB, or bob) program.
  18. Its purpose is to start up the BIND 10 system, and then manage the
  19. processes, by starting and stopping processes, plus restarting
  20. processes that exit.
  21. To start the system, it first runs the c-channel program (msgq), then
  22. connects to that. It then runs the configuration manager, and reads
  23. its own configuration. Then it proceeds to starting other modules.
  24. The Python subprocess module is used for starting processes, but
  25. because this is not efficient for managing groups of processes,
  26. SIGCHLD signals are caught and processed using the signal module.
  27. Most of the logic is contained in the BoB class. However, since Python
  28. requires that signal processing happen in the main thread, we do
  29. signal handling outside of that class, in the code running for
  30. __main__.
  31. """
  32. import sys; sys.path.append ('@@PYTHONPATH@@')
  33. import os
  34. # If B10_FROM_SOURCE is set in the environment, we use data files
  35. # from a directory relative to that, otherwise we use the ones
  36. # installed on the system
  37. if "B10_FROM_SOURCE" in os.environ:
  38. SPECFILE_LOCATION = os.environ["B10_FROM_SOURCE"] + "/src/bin/bind10/bob.spec"
  39. else:
  40. PREFIX = "@prefix@"
  41. DATAROOTDIR = "@datarootdir@"
  42. SPECFILE_LOCATION = "@datadir@/@PACKAGE@/bob.spec".replace("${datarootdir}", DATAROOTDIR).replace("${prefix}", PREFIX)
  43. import subprocess
  44. import signal
  45. import re
  46. import errno
  47. import time
  48. import select
  49. import random
  50. import socket
  51. from optparse import OptionParser, OptionValueError
  52. import io
  53. import pwd
  54. import posix
  55. import isc.cc
  56. import isc.util.process
  57. import isc.net.parse
  58. # Assign this process some longer name
  59. isc.util.process.rename(sys.argv[0])
  60. # This is the version that gets displayed to the user.
  61. # The VERSION string consists of the module name, the module version
  62. # number, and the overall BIND 10 version number (set in configure.ac).
  63. VERSION = "bind10 20110223 (BIND 10 @PACKAGE_VERSION@)"
  64. # This is for bind10.boottime of stats module
  65. _BASETIME = time.gmtime()
  66. class RestartSchedule:
  67. """
  68. Keeps state when restarting something (in this case, a process).
  69. When a process dies unexpectedly, we need to restart it. However, if
  70. it fails to restart for some reason, then we should not simply keep
  71. restarting it at high speed.
  72. A more sophisticated algorithm can be developed, but for now we choose
  73. a simple set of rules:
  74. * If a process was been running for >=10 seconds, we restart it
  75. right away.
  76. * If a process was running for <10 seconds, we wait until 10 seconds
  77. after it was started.
  78. To avoid programs getting into lockstep, we use a normal distribution
  79. to avoid being restarted at exactly 10 seconds."""
  80. def __init__(self, restart_frequency=10.0):
  81. self.restart_frequency = restart_frequency
  82. self.run_start_time = None
  83. self.run_stop_time = None
  84. self.restart_time = None
  85. def set_run_start_time(self, when=None):
  86. if when is None:
  87. when = time.time()
  88. self.run_start_time = when
  89. sigma = self.restart_frequency * 0.05
  90. self.restart_time = when + random.normalvariate(self.restart_frequency,
  91. sigma)
  92. def set_run_stop_time(self, when=None):
  93. """We don't actually do anything with stop time now, but it
  94. might be useful for future algorithms."""
  95. if when is None:
  96. when = time.time()
  97. self.run_stop_time = when
  98. def get_restart_time(self, when=None):
  99. if when is None:
  100. when = time.time()
  101. return max(when, self.restart_time)
  102. class ProcessInfoError(Exception): pass
  103. class ProcessInfo:
  104. """Information about a process"""
  105. dev_null = open(os.devnull, "w")
  106. def __init__(self, name, args, env={}, dev_null_stdout=False,
  107. dev_null_stderr=False, uid=None, username=None):
  108. self.name = name
  109. self.args = args
  110. self.env = env
  111. self.dev_null_stdout = dev_null_stdout
  112. self.dev_null_stderr = dev_null_stderr
  113. self.restart_schedule = RestartSchedule()
  114. self.uid = uid
  115. self.username = username
  116. self._spawn()
  117. def _preexec_work(self):
  118. """Function used before running a program that needs to run as a
  119. different user."""
  120. # First, put us into a separate process group so we don't get
  121. # SIGINT signals on Ctrl-C (the boss will shut everthing down by
  122. # other means).
  123. os.setpgrp()
  124. # Second, set the user ID if one has been specified
  125. if self.uid is not None:
  126. try:
  127. posix.setuid(self.uid)
  128. except OSError as e:
  129. if e.errno == errno.EPERM:
  130. # if we failed to change user due to permission report that
  131. raise ProcessInfoError("Unable to change to user %s (uid %d)" % (self.username, self.uid))
  132. else:
  133. # otherwise simply re-raise whatever error we found
  134. raise
  135. def _spawn(self):
  136. if self.dev_null_stdout:
  137. spawn_stdout = self.dev_null
  138. else:
  139. spawn_stdout = None
  140. if self.dev_null_stderr:
  141. spawn_stderr = self.dev_null
  142. else:
  143. spawn_stderr = None
  144. # Environment variables for the child process will be a copy of those
  145. # of the boss process with any additional specific variables given
  146. # on construction (self.env).
  147. spawn_env = os.environ
  148. spawn_env.update(self.env)
  149. if 'B10_FROM_SOURCE' not in os.environ:
  150. spawn_env['PATH'] = "@@LIBEXECDIR@@:" + spawn_env['PATH']
  151. self.process = subprocess.Popen(self.args,
  152. stdin=subprocess.PIPE,
  153. stdout=spawn_stdout,
  154. stderr=spawn_stderr,
  155. close_fds=True,
  156. env=spawn_env,
  157. preexec_fn=self._preexec_work)
  158. self.pid = self.process.pid
  159. self.restart_schedule.set_run_start_time()
  160. def respawn(self):
  161. self._spawn()
  162. class CChannelConnectError(Exception): pass
  163. class BoB:
  164. """Boss of BIND class."""
  165. def __init__(self, msgq_socket_file=None, data_path=None,
  166. config_filename=None, nocache=False, verbose=False, setuid=None,
  167. username=None, cmdctl_port=None):
  168. """
  169. Initialize the Boss of BIND. This is a singleton (only one can run).
  170. The msgq_socket_file specifies the UNIX domain socket file that the
  171. msgq process listens on. If verbose is True, then the boss reports
  172. what it is doing.
  173. Data path and config filename are passed trough to config manager
  174. (if provided) and specify the config file to be used.
  175. The cmdctl_port is passed to cmdctl and specify on which port it
  176. should listen.
  177. """
  178. self.cc_session = None
  179. self.ccs = None
  180. self.cfg_start_auth = True
  181. self.cfg_start_resolver = False
  182. self.started_auth_family = False
  183. self.started_resolver_family = False
  184. self.curproc = None
  185. self.dead_processes = {}
  186. self.msgq_socket_file = msgq_socket_file
  187. self.nocache = nocache
  188. self.processes = {}
  189. self.expected_shutdowns = {}
  190. self.runnable = False
  191. self.uid = setuid
  192. self.username = username
  193. self.verbose = verbose
  194. self.data_path = data_path
  195. self.config_filename = config_filename
  196. self.cmdctl_port = cmdctl_port
  197. def config_handler(self, new_config):
  198. # If this is initial update, don't do anything now, leave it to startup
  199. if not self.runnable:
  200. return
  201. # Now we declare few functions used only internally here. Besides the
  202. # benefit of not polluting the name space, they are closures, so we
  203. # don't need to pass some variables
  204. def start_stop(name, started, start, stop):
  205. if not'start_' + name in new_config:
  206. return
  207. if new_config['start_' + name]:
  208. if not started:
  209. if self.uid is not None:
  210. sys.stderr.write("[bind10] Starting " + name + " as " +
  211. "a user, not root. This might fail.\n")
  212. start()
  213. else:
  214. stop()
  215. # These four functions are passed to start_stop (smells like functional
  216. # programming little bit)
  217. def resolver_on():
  218. self.start_resolver(self.c_channel_env)
  219. self.started_resolver_family = True
  220. def resolver_off():
  221. self.stop_resolver()
  222. self.started_resolver_family = False
  223. def auth_on():
  224. self.start_auth(self.c_channel_env)
  225. self.start_xfrout(self.c_channel_env)
  226. self.start_xfrin(self.c_channel_env)
  227. self.start_zonemgr(self.c_channel_env)
  228. self.started_auth_family = True
  229. def auth_off():
  230. self.stop_zonemgr()
  231. self.stop_xfrin()
  232. self.stop_xfrout()
  233. self.stop_auth()
  234. self.started_auth_family = False
  235. # The real code of the config handler function follows here
  236. if self.verbose:
  237. sys.stdout.write("[bind10] Handling new configuration: " +
  238. str(new_config) + "\n")
  239. start_stop('resolver', self.started_resolver_family, resolver_on,
  240. resolver_off)
  241. start_stop('auth', self.started_auth_family, auth_on, auth_off)
  242. answer = isc.config.ccsession.create_answer(0)
  243. return answer
  244. def command_handler(self, command, args):
  245. if self.verbose:
  246. sys.stdout.write("[bind10] Boss got command: " + command + "\n")
  247. answer = isc.config.ccsession.create_answer(1, "command not implemented")
  248. if type(command) != str:
  249. answer = isc.config.ccsession.create_answer(1, "bad command")
  250. else:
  251. if command == "shutdown":
  252. self.runnable = False
  253. answer = isc.config.ccsession.create_answer(0)
  254. else:
  255. answer = isc.config.ccsession.create_answer(1,
  256. "Unknown command")
  257. return answer
  258. def kill_started_processes(self):
  259. """
  260. Called as part of the exception handling when a process fails to
  261. start, this runs through the list of started processes, killing
  262. each one. It then clears that list.
  263. """
  264. if self.verbose:
  265. sys.stdout.write("[bind10] killing started processes:\n")
  266. for pid in self.processes:
  267. if self.verbose:
  268. sys.stdout.write("[bind10] - %s\n" % self.processes[pid].name)
  269. self.processes[pid].process.kill()
  270. self.processes = {}
  271. def read_bind10_config(self):
  272. """
  273. Reads the parameters associated with the BoB module itself.
  274. At present these are the components to start although arguably this
  275. information should be in the configuration for the appropriate
  276. module itself. (However, this would cause difficulty in the case of
  277. xfrin/xfrout and zone manager as we don't need to start those if we
  278. are not running the authoritative server.)
  279. """
  280. if self.verbose:
  281. sys.stdout.write("[bind10] Reading Boss configuration:\n")
  282. config_data = self.ccs.get_full_config()
  283. self.cfg_start_auth = config_data.get("start_auth")
  284. self.cfg_start_resolver = config_data.get("start_resolver")
  285. if self.verbose:
  286. sys.stdout.write("[bind10] - start_auth: %s\n" %
  287. str(self.cfg_start_auth))
  288. sys.stdout.write("[bind10] - start_resolver: %s\n" %
  289. str(self.cfg_start_resolver))
  290. def log_starting(self, process, port = None, address = None):
  291. """
  292. A convenience function to output a "Starting xxx" message if the
  293. verbose option is set. Putting this into a separate method ensures
  294. that the output form is consistent across all processes.
  295. The process name (passed as the first argument) is put into
  296. self.curproc, and is used to indicate which process failed to
  297. start if there is an error (and is used in the "Started" message
  298. on success). The optional port and address information are
  299. appended to the message (if present).
  300. """
  301. self.curproc = process
  302. if self.verbose:
  303. sys.stdout.write("[bind10] Starting %s" % self.curproc)
  304. if port is not None:
  305. sys.stdout.write(" on port %d" % port)
  306. if address is not None:
  307. sys.stdout.write(" (address %s)" % str(address))
  308. sys.stdout.write("\n")
  309. def log_started(self, pid = None):
  310. """
  311. A convenience function to output a 'Started xxxx (PID yyyy)'
  312. message. As with starting_message(), this ensures a consistent
  313. format.
  314. """
  315. if self.verbose:
  316. sys.stdout.write("[bind10] Started %s" % self.curproc)
  317. if pid is not None:
  318. sys.stdout.write(" (PID %d)" % pid)
  319. sys.stdout.write("\n")
  320. # The next few methods start the individual processes of BIND-10. They
  321. # are called via start_all_processes(). If any fail, an exception is
  322. # raised which is caught by the caller of start_all_processes(); this kills
  323. # processes started up to that point before terminating the program.
  324. def start_msgq(self, c_channel_env):
  325. """
  326. Start the message queue and connect to the command channel.
  327. """
  328. self.log_starting("b10-msgq")
  329. c_channel = ProcessInfo("b10-msgq", ["b10-msgq"], c_channel_env,
  330. True, not self.verbose, uid=self.uid,
  331. username=self.username)
  332. self.processes[c_channel.pid] = c_channel
  333. self.log_started(c_channel.pid)
  334. # Now connect to the c-channel
  335. cc_connect_start = time.time()
  336. while self.cc_session is None:
  337. # if we have been trying for "a while" give up
  338. if (time.time() - cc_connect_start) > 5:
  339. raise CChannelConnectError("Unable to connect to c-channel after 5 seconds")
  340. # try to connect, and if we can't wait a short while
  341. try:
  342. self.cc_session = isc.cc.Session(self.msgq_socket_file)
  343. except isc.cc.session.SessionError:
  344. time.sleep(0.1)
  345. def start_cfgmgr(self, c_channel_env):
  346. """
  347. Starts the configuration manager process
  348. """
  349. self.log_starting("b10-cfgmgr")
  350. args = ["b10-cfgmgr"]
  351. if self.data_path is not None:
  352. args.append("--data-path=" + self.data_path)
  353. if self.config_filename is not None:
  354. args.append("--config-filename=" + self.config_filename)
  355. bind_cfgd = ProcessInfo("b10-cfgmgr", args,
  356. c_channel_env, uid=self.uid,
  357. username=self.username)
  358. self.processes[bind_cfgd.pid] = bind_cfgd
  359. self.log_started(bind_cfgd.pid)
  360. # sleep until b10-cfgmgr is fully up and running, this is a good place
  361. # to have a (short) timeout on synchronized groupsend/receive
  362. # TODO: replace the sleep by a listen for ConfigManager started
  363. # message
  364. time.sleep(1)
  365. def start_ccsession(self, c_channel_env):
  366. """
  367. Start the CC Session
  368. The argument c_channel_env is unused but is supplied to keep the
  369. argument list the same for all start_xxx methods.
  370. """
  371. self.log_starting("ccsession")
  372. self.ccs = isc.config.ModuleCCSession(SPECFILE_LOCATION,
  373. self.config_handler, self.command_handler)
  374. self.ccs.start()
  375. self.log_started()
  376. # A couple of utility methods for starting processes...
  377. def start_process(self, name, args, c_channel_env, port=None, address=None):
  378. """
  379. Given a set of command arguments, start the process and output
  380. appropriate log messages. If the start is successful, the process
  381. is added to the list of started processes.
  382. The port and address arguments are for log messages only.
  383. """
  384. self.log_starting(name, port, address)
  385. newproc = ProcessInfo(name, args, c_channel_env)
  386. self.processes[newproc.pid] = newproc
  387. self.log_started(newproc.pid)
  388. def start_simple(self, name, c_channel_env, port=None, address=None):
  389. """
  390. Most of the BIND-10 processes are started with the command:
  391. <process-name> [-v]
  392. ... where -v is appended if verbose is enabled. This method
  393. generates the arguments from the name and starts the process.
  394. The port and address arguments are for log messages only.
  395. """
  396. # Set up the command arguments.
  397. args = [name]
  398. if self.verbose:
  399. args += ['-v']
  400. # ... and start the process
  401. self.start_process(name, args, c_channel_env, port, address)
  402. # The next few methods start up the rest of the BIND-10 processes.
  403. # Although many of these methods are little more than a call to
  404. # start_simple, they are retained (a) for testing reasons and (b) as a place
  405. # where modifications can be made if the process start-up sequence changes
  406. # for a given process.
  407. def start_auth(self, c_channel_env):
  408. """
  409. Start the Authoritative server
  410. """
  411. authargs = ['b10-auth']
  412. if self.nocache:
  413. authargs += ['-n']
  414. if self.uid:
  415. authargs += ['-u', str(self.uid)]
  416. if self.verbose:
  417. authargs += ['-v']
  418. # ... and start
  419. self.start_process("b10-auth", authargs, c_channel_env)
  420. def start_resolver(self, c_channel_env):
  421. """
  422. Start the Resolver. At present, all these arguments and switches
  423. are pure speculation. As with the auth daemon, they should be
  424. read from the configuration database.
  425. """
  426. self.curproc = "b10-resolver"
  427. # XXX: this must be read from the configuration manager in the future
  428. resargs = ['b10-resolver']
  429. if self.uid:
  430. resargs += ['-u', str(self.uid)]
  431. if self.verbose:
  432. resargs += ['-v']
  433. # ... and start
  434. self.start_process("b10-resolver", resargs, c_channel_env)
  435. def start_xfrout(self, c_channel_env):
  436. self.start_simple("b10-xfrout", c_channel_env)
  437. def start_xfrin(self, c_channel_env):
  438. self.start_simple("b10-xfrin", c_channel_env)
  439. def start_zonemgr(self, c_channel_env):
  440. self.start_simple("b10-zonemgr", c_channel_env)
  441. def start_stats(self, c_channel_env):
  442. self.start_simple("b10-stats", c_channel_env)
  443. def start_cmdctl(self, c_channel_env):
  444. """
  445. Starts the command control process
  446. """
  447. args = ["b10-cmdctl"]
  448. if self.cmdctl_port is not None:
  449. args.append("--port=" + str(self.cmdctl_port))
  450. self.start_process("b10-cmdctl", args, c_channel_env, self.cmdctl_port)
  451. def start_all_processes(self):
  452. """
  453. Starts up all the processes. Any exception generated during the
  454. starting of the processes is handled by the caller.
  455. """
  456. c_channel_env = self.c_channel_env
  457. self.start_msgq(c_channel_env)
  458. self.start_cfgmgr(c_channel_env)
  459. self.start_ccsession(c_channel_env)
  460. # Extract the parameters associated with Bob. This can only be
  461. # done after the CC Session is started.
  462. self.read_bind10_config()
  463. # Continue starting the processes. The authoritative server (if
  464. # selected):
  465. if self.cfg_start_auth:
  466. self.start_auth(c_channel_env)
  467. # ... and resolver (if selected):
  468. if self.cfg_start_resolver:
  469. self.start_resolver(c_channel_env)
  470. self.started_resolver_family = True
  471. # Everything after the main components can run as non-root.
  472. # TODO: this is only temporary - once the privileged socket creator is
  473. # fully working, nothing else will run as root.
  474. if self.uid is not None:
  475. posix.setuid(self.uid)
  476. # xfrin/xfrout and the zone manager are only meaningful if the
  477. # authoritative server has been started.
  478. if self.cfg_start_auth:
  479. self.start_xfrout(c_channel_env)
  480. self.start_xfrin(c_channel_env)
  481. self.start_zonemgr(c_channel_env)
  482. self.started_auth_family = True
  483. # ... and finally start the remaining processes
  484. self.start_stats(c_channel_env)
  485. self.start_cmdctl(c_channel_env)
  486. def startup(self):
  487. """
  488. Start the BoB instance.
  489. Returns None if successful, otherwise an string describing the
  490. problem.
  491. """
  492. # Try to connect to the c-channel daemon, to see if it is already
  493. # running
  494. c_channel_env = {}
  495. if self.msgq_socket_file is not None:
  496. c_channel_env["BIND10_MSGQ_SOCKET_FILE"] = self.msgq_socket_file
  497. if self.verbose:
  498. sys.stdout.write("[bind10] Checking for already running b10-msgq\n")
  499. # try to connect, and if we can't wait a short while
  500. try:
  501. self.cc_session = isc.cc.Session(self.msgq_socket_file)
  502. return "b10-msgq already running, or socket file not cleaned , cannot start"
  503. except isc.cc.session.SessionError:
  504. # this is the case we want, where the msgq is not running
  505. pass
  506. # Start all processes. If any one fails to start, kill all started
  507. # processes and exit with an error indication.
  508. try:
  509. self.c_channel_env = c_channel_env
  510. self.start_all_processes()
  511. except Exception as e:
  512. self.kill_started_processes()
  513. return "Unable to start " + self.curproc + ": " + str(e)
  514. # Started successfully
  515. self.runnable = True
  516. return None
  517. def stop_all_processes(self):
  518. """Stop all processes."""
  519. cmd = { "command": ['shutdown']}
  520. self.cc_session.group_sendmsg(cmd, 'Cmdctl', 'Cmdctl')
  521. self.cc_session.group_sendmsg(cmd, "ConfigManager", "ConfigManager")
  522. self.cc_session.group_sendmsg(cmd, "Auth", "Auth")
  523. self.cc_session.group_sendmsg(cmd, "Resolver", "Resolver")
  524. self.cc_session.group_sendmsg(cmd, "Xfrout", "Xfrout")
  525. self.cc_session.group_sendmsg(cmd, "Xfrin", "Xfrin")
  526. self.cc_session.group_sendmsg(cmd, "Zonemgr", "Zonemgr")
  527. self.cc_session.group_sendmsg(cmd, "Stats", "Stats")
  528. def stop_process(self, process, recipient):
  529. """
  530. Stop the given process, friendly-like. The process is the name it has
  531. (in logs, etc), the recipient is the address on msgq.
  532. """
  533. if self.verbose:
  534. sys.stdout.write("[bind10] Asking %s to terminate\n" % process)
  535. # TODO: Some timeout to solve processes that don't want to die would
  536. # help. We can even store it in the dict, it is used only as a set
  537. self.expected_shutdowns[process] = 1
  538. # Ask the process to die willingly
  539. self.cc_session.group_sendmsg({'command': ['shutdown']}, recipient,
  540. recipient)
  541. # Series of stop_process wrappers
  542. def stop_resolver(self):
  543. self.stop_process('b10-resolver', 'Resolver')
  544. def stop_auth(self):
  545. self.stop_process('b10-auth', 'Auth')
  546. def stop_xfrout(self):
  547. self.stop_process('b10-xfrout', 'Xfrout')
  548. def stop_xfrin(self):
  549. self.stop_process('b10-xfrin', 'Xfrin')
  550. def stop_zonemgr(self):
  551. self.stop_process('b10-zonemgr', 'Zonemgr')
  552. def shutdown(self):
  553. """Stop the BoB instance."""
  554. if self.verbose:
  555. sys.stdout.write("[bind10] Stopping the server.\n")
  556. # first try using the BIND 10 request to stop
  557. try:
  558. self.stop_all_processes()
  559. except:
  560. pass
  561. # XXX: some delay probably useful... how much is uncertain
  562. # I have changed the delay from 0.5 to 1, but sometime it's
  563. # still not enough.
  564. time.sleep(1)
  565. self.reap_children()
  566. # next try sending a SIGTERM
  567. processes_to_stop = list(self.processes.values())
  568. for proc_info in processes_to_stop:
  569. if self.verbose:
  570. sys.stdout.write("[bind10] Sending SIGTERM to %s (PID %d).\n" %
  571. (proc_info.name, proc_info.pid))
  572. try:
  573. proc_info.process.terminate()
  574. except OSError:
  575. # ignore these (usually ESRCH because the child
  576. # finally exited)
  577. pass
  578. # finally, send SIGKILL (unmaskable termination) until everybody dies
  579. while self.processes:
  580. # XXX: some delay probably useful... how much is uncertain
  581. time.sleep(0.1)
  582. self.reap_children()
  583. processes_to_stop = list(self.processes.values())
  584. for proc_info in processes_to_stop:
  585. if self.verbose:
  586. sys.stdout.write("[bind10] Sending SIGKILL to %s (PID %d).\n" %
  587. (proc_info.name, proc_info.pid))
  588. try:
  589. proc_info.process.kill()
  590. except OSError:
  591. # ignore these (usually ESRCH because the child
  592. # finally exited)
  593. pass
  594. if self.verbose:
  595. sys.stdout.write("[bind10] All processes ended, server done.\n")
  596. def reap_children(self):
  597. """Check to see if any of our child processes have exited,
  598. and note this for later handling.
  599. """
  600. while True:
  601. try:
  602. (pid, exit_status) = os.waitpid(-1, os.WNOHANG)
  603. except OSError as o:
  604. if o.errno == errno.ECHILD: break
  605. # XXX: should be impossible to get any other error here
  606. raise
  607. if pid == 0: break
  608. if pid in self.processes:
  609. # One of the processes we know about. Get information on it.
  610. proc_info = self.processes.pop(pid)
  611. proc_info.restart_schedule.set_run_stop_time()
  612. self.dead_processes[proc_info.pid] = proc_info
  613. # Write out message, but only if in the running state:
  614. # During startup and shutdown, these messages are handled
  615. # elsewhere.
  616. if self.runnable:
  617. if exit_status is None:
  618. sys.stdout.write(
  619. "[bind10] Process %s (PID %d) died: exit status not available" %
  620. (proc_info.name, proc_info.pid))
  621. else:
  622. sys.stdout.write(
  623. "[bind10] Process %s (PID %d) terminated, exit status = %d\n" %
  624. (proc_info.name, proc_info.pid, exit_status))
  625. # Was it a special process?
  626. if proc_info.name == "b10-msgq":
  627. sys.stdout.write(
  628. "[bind10] The b10-msgq process died, shutting down.\n")
  629. self.runnable = False
  630. else:
  631. sys.stdout.write("[bind10] Unknown child pid %d exited.\n" % pid)
  632. def restart_processes(self):
  633. """
  634. Restart any dead processes:
  635. * Returns the time when the next process is ready to be restarted.
  636. * If the server is shutting down, returns 0.
  637. * If there are no processes, returns None.
  638. The values returned can be safely passed into select() as the
  639. timeout value.
  640. """
  641. next_restart = None
  642. # if we're shutting down, then don't restart
  643. if not self.runnable:
  644. return 0
  645. # otherwise look through each dead process and try to restart
  646. still_dead = {}
  647. now = time.time()
  648. for proc_info in self.dead_processes.values():
  649. if proc_info.name in self.expected_shutdowns:
  650. # We don't restart, we wanted it to die
  651. del self.expected_shutdowns[proc_info.name]
  652. continue
  653. restart_time = proc_info.restart_schedule.get_restart_time(now)
  654. if restart_time > now:
  655. if (next_restart is None) or (next_restart > restart_time):
  656. next_restart = restart_time
  657. still_dead[proc_info.pid] = proc_info
  658. else:
  659. if self.verbose:
  660. sys.stdout.write("[bind10] Resurrecting dead %s process...\n" %
  661. proc_info.name)
  662. try:
  663. proc_info.respawn()
  664. self.processes[proc_info.pid] = proc_info
  665. sys.stdout.write("[bind10] Resurrected %s (PID %d)\n" %
  666. (proc_info.name, proc_info.pid))
  667. except:
  668. still_dead[proc_info.pid] = proc_info
  669. # remember any processes that refuse to be resurrected
  670. self.dead_processes = still_dead
  671. # return the time when the next process is ready to be restarted
  672. return next_restart
  673. # global variables, needed for signal handlers
  674. options = None
  675. boss_of_bind = None
  676. def reaper(signal_number, stack_frame):
  677. """A child process has died (SIGCHLD received)."""
  678. # don't do anything...
  679. # the Python signal handler has been set up to write
  680. # down a pipe, waking up our select() bit
  681. pass
  682. def get_signame(signal_number):
  683. """Return the symbolic name for a signal."""
  684. for sig in dir(signal):
  685. if sig.startswith("SIG") and sig[3].isalnum():
  686. if getattr(signal, sig) == signal_number:
  687. return sig
  688. return "Unknown signal %d" % signal_number
  689. # XXX: perhaps register atexit() function and invoke that instead
  690. def fatal_signal(signal_number, stack_frame):
  691. """We need to exit (SIGINT or SIGTERM received)."""
  692. global options
  693. global boss_of_bind
  694. if options.verbose:
  695. sys.stdout.write("[bind10] Received %s.\n" % get_signame(signal_number))
  696. signal.signal(signal.SIGCHLD, signal.SIG_DFL)
  697. boss_of_bind.runnable = False
  698. def process_rename(option, opt_str, value, parser):
  699. """Function that renames the process if it is requested by a option."""
  700. isc.util.process.rename(value)
  701. def parse_args(args=sys.argv[1:], Parser=OptionParser):
  702. """
  703. Function for parsing command line arguments. Returns the
  704. options object from OptionParser.
  705. """
  706. parser = Parser(version=VERSION)
  707. parser.add_option("-m", "--msgq-socket-file", dest="msgq_socket_file",
  708. type="string", default=None,
  709. help="UNIX domain socket file the b10-msgq daemon will use")
  710. parser.add_option("-n", "--no-cache", action="store_true", dest="nocache",
  711. default=False, help="disable hot-spot cache in authoritative DNS server")
  712. parser.add_option("-u", "--user", dest="user", type="string", default=None,
  713. help="Change user after startup (must run as root)")
  714. parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
  715. help="display more about what is going on")
  716. parser.add_option("--pretty-name", type="string", action="callback",
  717. callback=process_rename,
  718. help="Set the process name (displayed in ps, top, ...)")
  719. parser.add_option("-c", "--config-file", action="store",
  720. dest="config_file", default=None,
  721. help="Configuration database filename")
  722. parser.add_option("-p", "--data-path", dest="data_path",
  723. help="Directory to search for configuration files",
  724. default=None)
  725. parser.add_option("--cmdctl-port", dest="cmdctl_port", type="int",
  726. default=None, help="Port of command control")
  727. parser.add_option("--pid-file", dest="pid_file", type="string",
  728. default=None,
  729. help="file to dump the PID of the BIND 10 process")
  730. (options, args) = parser.parse_args(args)
  731. if options.cmdctl_port is not None:
  732. try:
  733. isc.net.parse.port_parse(options.cmdctl_port)
  734. except ValueError as e:
  735. parser.error(e)
  736. if args:
  737. parser.print_help()
  738. sys.exit(1)
  739. return options
  740. def dump_pid(pid_file):
  741. """
  742. Dump the PID of the current process to the specified file. If the given
  743. file is None this function does nothing. If the file already exists,
  744. the existing content will be removed. If a system error happens in
  745. creating or writing to the file, the corresponding exception will be
  746. propagated to the caller.
  747. """
  748. if pid_file is None:
  749. return
  750. f = open(pid_file, "w")
  751. f.write('%d\n' % os.getpid())
  752. f.close()
  753. def unlink_pid_file(pid_file):
  754. """
  755. Remove the given file, which is basically expected to be the PID file
  756. created by dump_pid(). The specified may or may not exist; if it
  757. doesn't this function does nothing. Other system level errors in removing
  758. the file will be propagated as the corresponding exception.
  759. """
  760. if pid_file is None:
  761. return
  762. try:
  763. os.unlink(pid_file)
  764. except OSError as error:
  765. if error.errno is not errno.ENOENT:
  766. raise
  767. def main():
  768. global options
  769. global boss_of_bind
  770. # Enforce line buffering on stdout, even when not a TTY
  771. sys.stdout = io.TextIOWrapper(sys.stdout.detach(), line_buffering=True)
  772. options = parse_args()
  773. # Check user ID.
  774. setuid = None
  775. username = None
  776. if options.user:
  777. # Try getting information about the user, assuming UID passed.
  778. try:
  779. pw_ent = pwd.getpwuid(int(options.user))
  780. setuid = pw_ent.pw_uid
  781. username = pw_ent.pw_name
  782. except ValueError:
  783. pass
  784. except KeyError:
  785. pass
  786. # Next try getting information about the user, assuming user name
  787. # passed.
  788. # If the information is both a valid user name and user number, we
  789. # prefer the name because we try it second. A minor point, hopefully.
  790. try:
  791. pw_ent = pwd.getpwnam(options.user)
  792. setuid = pw_ent.pw_uid
  793. username = pw_ent.pw_name
  794. except KeyError:
  795. pass
  796. if setuid is None:
  797. sys.stderr.write("bind10: invalid user: '%s'\n" % options.user)
  798. sys.exit(1)
  799. # Announce startup.
  800. if options.verbose:
  801. sys.stdout.write("%s\n" % VERSION)
  802. # Create wakeup pipe for signal handlers
  803. wakeup_pipe = os.pipe()
  804. signal.set_wakeup_fd(wakeup_pipe[1])
  805. # Set signal handlers for catching child termination, as well
  806. # as our own demise.
  807. signal.signal(signal.SIGCHLD, reaper)
  808. signal.siginterrupt(signal.SIGCHLD, False)
  809. signal.signal(signal.SIGINT, fatal_signal)
  810. signal.signal(signal.SIGTERM, fatal_signal)
  811. # Block SIGPIPE, as we don't want it to end this process
  812. signal.signal(signal.SIGPIPE, signal.SIG_IGN)
  813. # Go bob!
  814. boss_of_bind = BoB(options.msgq_socket_file, options.data_path,
  815. options.config_file, options.nocache, options.verbose,
  816. setuid, username, options.cmdctl_port)
  817. startup_result = boss_of_bind.startup()
  818. if startup_result:
  819. sys.stderr.write("[bind10] Error on startup: %s\n" % startup_result)
  820. sys.exit(1)
  821. sys.stdout.write("[bind10] BIND 10 started\n")
  822. dump_pid(options.pid_file)
  823. # send "bind10.boot_time" to b10-stats
  824. time.sleep(1) # wait a second
  825. if options.verbose:
  826. sys.stdout.write("[bind10] send \"bind10.boot_time\" to b10-stats\n")
  827. cmd = isc.config.ccsession.create_command('set',
  828. { "stats_data": {
  829. 'bind10.boot_time': time.strftime('%Y-%m-%dT%H:%M:%SZ', _BASETIME)
  830. }
  831. })
  832. boss_of_bind.cc_session.group_sendmsg(cmd, 'Stats')
  833. # In our main loop, we check for dead processes or messages
  834. # on the c-channel.
  835. wakeup_fd = wakeup_pipe[0]
  836. ccs_fd = boss_of_bind.ccs.get_socket().fileno()
  837. while boss_of_bind.runnable:
  838. # clean up any processes that exited
  839. boss_of_bind.reap_children()
  840. next_restart = boss_of_bind.restart_processes()
  841. if next_restart is None:
  842. wait_time = None
  843. else:
  844. wait_time = max(next_restart - time.time(), 0)
  845. # select() can raise EINTR when a signal arrives,
  846. # even if they are resumable, so we have to catch
  847. # the exception
  848. try:
  849. (rlist, wlist, xlist) = select.select([wakeup_fd, ccs_fd], [], [],
  850. wait_time)
  851. except select.error as err:
  852. if err.args[0] == errno.EINTR:
  853. (rlist, wlist, xlist) = ([], [], [])
  854. else:
  855. sys.stderr.write("[bind10] Error with select(); %s\n" % err)
  856. break
  857. for fd in rlist + xlist:
  858. if fd == ccs_fd:
  859. try:
  860. boss_of_bind.ccs.check_command()
  861. except isc.cc.session.ProtocolError:
  862. if options.verbose:
  863. sys.stderr.write("[bind10] msgq channel disappeared.\n")
  864. break
  865. elif fd == wakeup_fd:
  866. os.read(wakeup_fd, 32)
  867. # shutdown
  868. signal.signal(signal.SIGCHLD, signal.SIG_DFL)
  869. boss_of_bind.shutdown()
  870. sys.stdout.write("[bind10] BIND 10 exiting\n");
  871. unlink_pid_file(options.pid_file)
  872. sys.exit(0)
  873. if __name__ == "__main__":
  874. main()