bind10.py.in 40 KB

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