bind10_src.py.in 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166
  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. ADD_LIBEXEC_PATH = False
  40. else:
  41. PREFIX = "@prefix@"
  42. DATAROOTDIR = "@datarootdir@"
  43. SPECFILE_LOCATION = "@datadir@/@PACKAGE@/bob.spec".replace("${datarootdir}", DATAROOTDIR).replace("${prefix}", PREFIX)
  44. ADD_LIBEXEC_PATH = True
  45. import subprocess
  46. import signal
  47. import re
  48. import errno
  49. import time
  50. import select
  51. import random
  52. import socket
  53. from optparse import OptionParser, OptionValueError
  54. import io
  55. import pwd
  56. import posix
  57. import copy
  58. import isc.cc
  59. import isc.util.process
  60. import isc.net.parse
  61. import isc.log
  62. from isc.log_messages.bind10_messages import *
  63. import isc.bind10.sockcreator
  64. isc.log.init("b10-boss")
  65. logger = isc.log.Logger("boss")
  66. # Pending system-wide debug level definitions, the ones we
  67. # use here are hardcoded for now
  68. DBG_PROCESS = logger.DBGLVL_TRACE_BASIC
  69. DBG_COMMANDS = logger.DBGLVL_TRACE_DETAIL
  70. # Assign this process some longer name
  71. isc.util.process.rename(sys.argv[0])
  72. # This is the version that gets displayed to the user.
  73. # The VERSION string consists of the module name, the module version
  74. # number, and the overall BIND 10 version number (set in configure.ac).
  75. VERSION = "bind10 20110223 (BIND 10 @PACKAGE_VERSION@)"
  76. # This is for boot_time of Boss
  77. _BASETIME = time.gmtime()
  78. class RestartSchedule:
  79. """
  80. Keeps state when restarting something (in this case, a process).
  81. When a process dies unexpectedly, we need to restart it. However, if
  82. it fails to restart for some reason, then we should not simply keep
  83. restarting it at high speed.
  84. A more sophisticated algorithm can be developed, but for now we choose
  85. a simple set of rules:
  86. * If a process was been running for >=10 seconds, we restart it
  87. right away.
  88. * If a process was running for <10 seconds, we wait until 10 seconds
  89. after it was started.
  90. To avoid programs getting into lockstep, we use a normal distribution
  91. to avoid being restarted at exactly 10 seconds."""
  92. def __init__(self, restart_frequency=10.0):
  93. self.restart_frequency = restart_frequency
  94. self.run_start_time = None
  95. self.run_stop_time = None
  96. self.restart_time = None
  97. def set_run_start_time(self, when=None):
  98. if when is None:
  99. when = time.time()
  100. self.run_start_time = when
  101. sigma = self.restart_frequency * 0.05
  102. self.restart_time = when + random.normalvariate(self.restart_frequency,
  103. sigma)
  104. def set_run_stop_time(self, when=None):
  105. """We don't actually do anything with stop time now, but it
  106. might be useful for future algorithms."""
  107. if when is None:
  108. when = time.time()
  109. self.run_stop_time = when
  110. def get_restart_time(self, when=None):
  111. if when is None:
  112. when = time.time()
  113. return max(when, self.restart_time)
  114. class ProcessInfoError(Exception): pass
  115. class ProcessInfo:
  116. """Information about a process"""
  117. dev_null = open(os.devnull, "w")
  118. def __init__(self, name, args, env={}, dev_null_stdout=False,
  119. dev_null_stderr=False, uid=None, username=None):
  120. self.name = name
  121. self.args = args
  122. self.env = env
  123. self.dev_null_stdout = dev_null_stdout
  124. self.dev_null_stderr = dev_null_stderr
  125. self.restart_schedule = RestartSchedule()
  126. self.uid = uid
  127. self.username = username
  128. self.process = None
  129. self.pid = None
  130. def _preexec_work(self):
  131. """Function used before running a program that needs to run as a
  132. different user."""
  133. # First, put us into a separate process group so we don't get
  134. # SIGINT signals on Ctrl-C (the boss will shut everthing down by
  135. # other means).
  136. os.setpgrp()
  137. # Second, set the user ID if one has been specified
  138. if self.uid is not None:
  139. try:
  140. posix.setuid(self.uid)
  141. except OSError as e:
  142. if e.errno == errno.EPERM:
  143. # if we failed to change user due to permission report that
  144. raise ProcessInfoError("Unable to change to user %s (uid %d)" % (self.username, self.uid))
  145. else:
  146. # otherwise simply re-raise whatever error we found
  147. raise
  148. def _spawn(self):
  149. if self.dev_null_stdout:
  150. spawn_stdout = self.dev_null
  151. else:
  152. spawn_stdout = None
  153. if self.dev_null_stderr:
  154. spawn_stderr = self.dev_null
  155. else:
  156. spawn_stderr = None
  157. # Environment variables for the child process will be a copy of those
  158. # of the boss process with any additional specific variables given
  159. # on construction (self.env).
  160. spawn_env = copy.deepcopy(os.environ)
  161. spawn_env.update(self.env)
  162. if ADD_LIBEXEC_PATH:
  163. spawn_env['PATH'] = "@@LIBEXECDIR@@:" + spawn_env['PATH']
  164. self.process = subprocess.Popen(self.args,
  165. stdin=subprocess.PIPE,
  166. stdout=spawn_stdout,
  167. stderr=spawn_stderr,
  168. close_fds=True,
  169. env=spawn_env,
  170. preexec_fn=self._preexec_work)
  171. self.pid = self.process.pid
  172. self.restart_schedule.set_run_start_time()
  173. # spawn() and respawn() are the same for now, but in the future they
  174. # may have different functionality
  175. def spawn(self):
  176. self._spawn()
  177. def respawn(self):
  178. self._spawn()
  179. class CChannelConnectError(Exception): pass
  180. class ProcessStartError(Exception): pass
  181. class BoB:
  182. """Boss of BIND class."""
  183. def __init__(self, msgq_socket_file=None, data_path=None,
  184. config_filename=None, nocache=False, verbose=False, setuid=None,
  185. username=None, cmdctl_port=None, brittle=False, wait_time=10):
  186. """
  187. Initialize the Boss of BIND. This is a singleton (only one can run).
  188. The msgq_socket_file specifies the UNIX domain socket file that the
  189. msgq process listens on. If verbose is True, then the boss reports
  190. what it is doing.
  191. Data path and config filename are passed through to config manager
  192. (if provided) and specify the config file to be used.
  193. The cmdctl_port is passed to cmdctl and specify on which port it
  194. should listen.
  195. brittle is a debug option that controls whether the Boss shuts down
  196. after any process dies.
  197. wait_time controls the amount of time (in seconds) that Boss waits
  198. for selected processes to initialize before continuing with the
  199. initialization. Currently this is only the configuration manager.
  200. """
  201. self.cc_session = None
  202. self.ccs = None
  203. self.cfg_start_auth = True
  204. self.cfg_start_resolver = False
  205. self.cfg_start_dhcp6 = False
  206. self.cfg_start_dhcp4 = False
  207. self.started_auth_family = False
  208. self.started_resolver_family = False
  209. self.curproc = None
  210. self.dead_processes = {}
  211. self.msgq_socket_file = msgq_socket_file
  212. self.nocache = nocache
  213. self.processes = {}
  214. self.expected_shutdowns = {}
  215. self.runnable = False
  216. self.uid = setuid
  217. self.username = username
  218. self.verbose = verbose
  219. self.data_path = data_path
  220. self.config_filename = config_filename
  221. self.cmdctl_port = cmdctl_port
  222. self.brittle = brittle
  223. self.wait_time = wait_time
  224. self.sockcreator = None
  225. # If -v was set, enable full debug logging.
  226. if self.verbose:
  227. logger.set_severity("DEBUG", 99)
  228. def config_handler(self, new_config):
  229. # If this is initial update, don't do anything now, leave it to startup
  230. if not self.runnable:
  231. return
  232. # Now we declare few functions used only internally here. Besides the
  233. # benefit of not polluting the name space, they are closures, so we
  234. # don't need to pass some variables
  235. def start_stop(name, started, start, stop):
  236. if not'start_' + name in new_config:
  237. return
  238. if new_config['start_' + name]:
  239. if not started:
  240. if self.uid is not None:
  241. logger.info(BIND10_START_AS_NON_ROOT, name)
  242. start()
  243. else:
  244. stop()
  245. # These four functions are passed to start_stop (smells like functional
  246. # programming little bit)
  247. def resolver_on():
  248. self.start_resolver(self.c_channel_env)
  249. self.started_resolver_family = True
  250. def resolver_off():
  251. self.stop_resolver()
  252. self.started_resolver_family = False
  253. def auth_on():
  254. self.start_auth(self.c_channel_env)
  255. self.start_xfrout(self.c_channel_env)
  256. self.start_xfrin(self.c_channel_env)
  257. self.start_zonemgr(self.c_channel_env)
  258. self.started_auth_family = True
  259. def auth_off():
  260. self.stop_zonemgr()
  261. self.stop_xfrin()
  262. self.stop_xfrout()
  263. self.stop_auth()
  264. self.started_auth_family = False
  265. # The real code of the config handler function follows here
  266. logger.debug(DBG_COMMANDS, BIND10_RECEIVED_NEW_CONFIGURATION,
  267. new_config)
  268. start_stop('resolver', self.started_resolver_family, resolver_on,
  269. resolver_off)
  270. start_stop('auth', self.started_auth_family, auth_on, auth_off)
  271. answer = isc.config.ccsession.create_answer(0)
  272. return answer
  273. def get_processes(self):
  274. pids = list(self.processes.keys())
  275. pids.sort()
  276. process_list = [ ]
  277. for pid in pids:
  278. process_list.append([pid, self.processes[pid].name])
  279. return process_list
  280. def _get_stats_data(self):
  281. return { "owner": "Boss",
  282. "data": { 'boot_time':
  283. time.strftime('%Y-%m-%dT%H:%M:%SZ', _BASETIME)
  284. }
  285. }
  286. def command_handler(self, command, args):
  287. logger.debug(DBG_COMMANDS, BIND10_RECEIVED_COMMAND, command)
  288. answer = isc.config.ccsession.create_answer(1, "command not implemented")
  289. if type(command) != str:
  290. answer = isc.config.ccsession.create_answer(1, "bad command")
  291. else:
  292. if command == "shutdown":
  293. self.runnable = False
  294. answer = isc.config.ccsession.create_answer(0)
  295. elif command == "getstats":
  296. answer = isc.config.ccsession.create_answer(0, self._get_stats_data())
  297. elif command == "sendstats":
  298. # send statistics data to the stats daemon immediately
  299. stats_data = self._get_stats_data()
  300. valid = self.ccs.get_module_spec().validate_statistics(
  301. True, stats_data["data"])
  302. if valid:
  303. cmd = isc.config.ccsession.create_command('set', stats_data)
  304. seq = self.cc_session.group_sendmsg(cmd, 'Stats')
  305. # Consume the answer, in case it becomes a orphan message.
  306. try:
  307. self.cc_session.group_recvmsg(False, seq)
  308. except isc.cc.session.SessionTimeout:
  309. pass
  310. answer = isc.config.ccsession.create_answer(0)
  311. else:
  312. logger.fatal(BIND10_INVALID_STATISTICS_DATA);
  313. answer = isc.config.ccsession.create_answer(
  314. 1, "specified statistics data is invalid")
  315. elif command == "ping":
  316. answer = isc.config.ccsession.create_answer(0, "pong")
  317. elif command == "show_processes":
  318. answer = isc.config.ccsession. \
  319. create_answer(0, self.get_processes())
  320. else:
  321. answer = isc.config.ccsession.create_answer(1,
  322. "Unknown command")
  323. return answer
  324. def start_creator(self):
  325. self.curproc = 'b10-sockcreator'
  326. creator_path = os.environ['PATH']
  327. if ADD_LIBEXEC_PATH:
  328. creator_path = "@@LIBEXECDIR@@:" + creator_path
  329. self.sockcreator = isc.bind10.sockcreator.Creator(creator_path)
  330. def stop_creator(self, kill=False):
  331. if self.sockcreator is None:
  332. return
  333. if kill:
  334. self.sockcreator.kill()
  335. else:
  336. self.sockcreator.terminate()
  337. self.sockcreator = None
  338. def kill_started_processes(self):
  339. """
  340. Called as part of the exception handling when a process fails to
  341. start, this runs through the list of started processes, killing
  342. each one. It then clears that list.
  343. """
  344. logger.info(BIND10_KILLING_ALL_PROCESSES)
  345. self.stop_creator(True)
  346. for pid in self.processes:
  347. logger.info(BIND10_KILL_PROCESS, self.processes[pid].name)
  348. self.processes[pid].process.kill()
  349. self.processes = {}
  350. def read_bind10_config(self):
  351. """
  352. Reads the parameters associated with the BoB module itself.
  353. At present these are the components to start although arguably this
  354. information should be in the configuration for the appropriate
  355. module itself. (However, this would cause difficulty in the case of
  356. xfrin/xfrout and zone manager as we don't need to start those if we
  357. are not running the authoritative server.)
  358. """
  359. logger.info(BIND10_READING_BOSS_CONFIGURATION)
  360. config_data = self.ccs.get_full_config()
  361. self.cfg_start_auth = config_data.get("start_auth")
  362. self.cfg_start_resolver = config_data.get("start_resolver")
  363. logger.info(BIND10_CONFIGURATION_START_AUTH, self.cfg_start_auth)
  364. logger.info(BIND10_CONFIGURATION_START_RESOLVER, self.cfg_start_resolver)
  365. def log_starting(self, process, port = None, address = None):
  366. """
  367. A convenience function to output a "Starting xxx" message if the
  368. logging is set to DEBUG with debuglevel DBG_PROCESS or higher.
  369. Putting this into a separate method ensures
  370. that the output form is consistent across all processes.
  371. The process name (passed as the first argument) is put into
  372. self.curproc, and is used to indicate which process failed to
  373. start if there is an error (and is used in the "Started" message
  374. on success). The optional port and address information are
  375. appended to the message (if present).
  376. """
  377. self.curproc = process
  378. if port is None and address is None:
  379. logger.info(BIND10_STARTING_PROCESS, self.curproc)
  380. elif address is None:
  381. logger.info(BIND10_STARTING_PROCESS_PORT, self.curproc,
  382. port)
  383. else:
  384. logger.info(BIND10_STARTING_PROCESS_PORT_ADDRESS,
  385. self.curproc, address, port)
  386. def log_started(self, pid = None):
  387. """
  388. A convenience function to output a 'Started xxxx (PID yyyy)'
  389. message. As with starting_message(), this ensures a consistent
  390. format.
  391. """
  392. if pid is None:
  393. logger.debug(DBG_PROCESS, BIND10_STARTED_PROCESS, self.curproc)
  394. else:
  395. logger.debug(DBG_PROCESS, BIND10_STARTED_PROCESS_PID, self.curproc, pid)
  396. def process_running(self, msg, who):
  397. """
  398. Some processes return a message to the Boss after they have
  399. started to indicate that they are running. The form of the
  400. message is a dictionary with contents {"running:", "<process>"}.
  401. This method checks the passed message and returns True if the
  402. "who" process is contained in the message (so is presumably
  403. running). It returns False for all other conditions and will
  404. log an error if appropriate.
  405. """
  406. if msg is not None:
  407. try:
  408. if msg["running"] == who:
  409. return True
  410. else:
  411. logger.error(BIND10_STARTUP_UNEXPECTED_MESSAGE, msg)
  412. except:
  413. logger.error(BIND10_STARTUP_UNRECOGNISED_MESSAGE, msg)
  414. return False
  415. # The next few methods start the individual processes of BIND-10. They
  416. # are called via start_all_processes(). If any fail, an exception is
  417. # raised which is caught by the caller of start_all_processes(); this kills
  418. # processes started up to that point before terminating the program.
  419. def start_msgq(self, c_channel_env):
  420. """
  421. Start the message queue and connect to the command channel.
  422. """
  423. self.log_starting("b10-msgq")
  424. c_channel = ProcessInfo("b10-msgq", ["b10-msgq"], c_channel_env,
  425. True, not self.verbose, uid=self.uid,
  426. username=self.username)
  427. c_channel.spawn()
  428. self.processes[c_channel.pid] = c_channel
  429. self.log_started(c_channel.pid)
  430. # Now connect to the c-channel
  431. cc_connect_start = time.time()
  432. while self.cc_session is None:
  433. # if we have been trying for "a while" give up
  434. if (time.time() - cc_connect_start) > 5:
  435. raise CChannelConnectError("Unable to connect to c-channel after 5 seconds")
  436. # try to connect, and if we can't wait a short while
  437. try:
  438. self.cc_session = isc.cc.Session(self.msgq_socket_file)
  439. except isc.cc.session.SessionError:
  440. time.sleep(0.1)
  441. # Subscribe to the message queue. The only messages we expect to receive
  442. # on this channel are once relating to process startup.
  443. self.cc_session.group_subscribe("Boss")
  444. def start_cfgmgr(self, c_channel_env):
  445. """
  446. Starts the configuration manager process
  447. """
  448. self.log_starting("b10-cfgmgr")
  449. args = ["b10-cfgmgr"]
  450. if self.data_path is not None:
  451. args.append("--data-path=" + self.data_path)
  452. if self.config_filename is not None:
  453. args.append("--config-filename=" + self.config_filename)
  454. bind_cfgd = ProcessInfo("b10-cfgmgr", args,
  455. c_channel_env, uid=self.uid,
  456. username=self.username)
  457. bind_cfgd.spawn()
  458. self.processes[bind_cfgd.pid] = bind_cfgd
  459. self.log_started(bind_cfgd.pid)
  460. # Wait for the configuration manager to start up as subsequent initialization
  461. # cannot proceed without it. The time to wait can be set on the command line.
  462. time_remaining = self.wait_time
  463. msg, env = self.cc_session.group_recvmsg()
  464. while time_remaining > 0 and not self.process_running(msg, "ConfigManager"):
  465. logger.debug(DBG_PROCESS, BIND10_WAIT_CFGMGR)
  466. time.sleep(1)
  467. time_remaining = time_remaining - 1
  468. msg, env = self.cc_session.group_recvmsg()
  469. if not self.process_running(msg, "ConfigManager"):
  470. raise ProcessStartError("Configuration manager process has not started")
  471. def start_ccsession(self, c_channel_env):
  472. """
  473. Start the CC Session
  474. The argument c_channel_env is unused but is supplied to keep the
  475. argument list the same for all start_xxx methods.
  476. With regards to logging, note that as the CC session is not a
  477. process, the log_starting/log_started methods are not used.
  478. """
  479. logger.info(BIND10_STARTING_CC)
  480. self.ccs = isc.config.ModuleCCSession(SPECFILE_LOCATION,
  481. self.config_handler,
  482. self.command_handler,
  483. socket_file = self.msgq_socket_file)
  484. self.ccs.start()
  485. logger.debug(DBG_PROCESS, BIND10_STARTED_CC)
  486. # A couple of utility methods for starting processes...
  487. def start_process(self, name, args, c_channel_env, port=None, address=None):
  488. """
  489. Given a set of command arguments, start the process and output
  490. appropriate log messages. If the start is successful, the process
  491. is added to the list of started processes.
  492. The port and address arguments are for log messages only.
  493. """
  494. self.log_starting(name, port, address)
  495. newproc = ProcessInfo(name, args, c_channel_env)
  496. newproc.spawn()
  497. self.processes[newproc.pid] = newproc
  498. self.log_started(newproc.pid)
  499. def start_simple(self, name, c_channel_env, port=None, address=None):
  500. """
  501. Most of the BIND-10 processes are started with the command:
  502. <process-name> [-v]
  503. ... where -v is appended if verbose is enabled. This method
  504. generates the arguments from the name and starts the process.
  505. The port and address arguments are for log messages only.
  506. """
  507. # Set up the command arguments.
  508. args = [name]
  509. if self.verbose:
  510. args += ['-v']
  511. # ... and start the process
  512. self.start_process(name, args, c_channel_env, port, address)
  513. # The next few methods start up the rest of the BIND-10 processes.
  514. # Although many of these methods are little more than a call to
  515. # start_simple, they are retained (a) for testing reasons and (b) as a place
  516. # where modifications can be made if the process start-up sequence changes
  517. # for a given process.
  518. def start_auth(self, c_channel_env):
  519. """
  520. Start the Authoritative server
  521. """
  522. authargs = ['b10-auth']
  523. if self.nocache:
  524. authargs += ['-n']
  525. if self.uid:
  526. authargs += ['-u', str(self.uid)]
  527. if self.verbose:
  528. authargs += ['-v']
  529. # ... and start
  530. self.start_process("b10-auth", authargs, c_channel_env)
  531. def start_resolver(self, c_channel_env):
  532. """
  533. Start the Resolver. At present, all these arguments and switches
  534. are pure speculation. As with the auth daemon, they should be
  535. read from the configuration database.
  536. """
  537. self.curproc = "b10-resolver"
  538. # XXX: this must be read from the configuration manager in the future
  539. resargs = ['b10-resolver']
  540. if self.uid:
  541. resargs += ['-u', str(self.uid)]
  542. if self.verbose:
  543. resargs += ['-v']
  544. # ... and start
  545. self.start_process("b10-resolver", resargs, c_channel_env)
  546. def start_xfrout(self, c_channel_env):
  547. self.start_simple("b10-xfrout", c_channel_env)
  548. def start_xfrin(self, c_channel_env):
  549. # XXX: a quick-hack workaround. xfrin will implicitly use dynamically
  550. # loadable data source modules, which will be installed in $(libdir).
  551. # On some OSes (including MacOS X and *BSDs) the main process (python)
  552. # cannot find the modules unless they are located in a common shared
  553. # object path or a path in the (DY)LD_LIBRARY_PATH. We should seek
  554. # a cleaner solution, but for a short term workaround we specify the
  555. # path here, unconditionally, and without even bothering which
  556. # environment variable should be used.
  557. #
  558. # We reuse the ADD_LIBEXEC_PATH variable to see whether we need to
  559. # do this, as the conditions that make this workaround needed are
  560. # the same as for the libexec path addition
  561. if ADD_LIBEXEC_PATH:
  562. cur_path = os.getenv('DYLD_LIBRARY_PATH')
  563. cur_path = '' if cur_path is None else ':' + cur_path
  564. c_channel_env['DYLD_LIBRARY_PATH'] = "@@LIBDIR@@" + cur_path
  565. cur_path = os.getenv('LD_LIBRARY_PATH')
  566. cur_path = '' if cur_path is None else ':' + cur_path
  567. c_channel_env['LD_LIBRARY_PATH'] = "@@LIBDIR@@" + cur_path
  568. self.start_simple("b10-xfrin", c_channel_env)
  569. def start_zonemgr(self, c_channel_env):
  570. self.start_simple("b10-zonemgr", c_channel_env)
  571. def start_stats(self, c_channel_env):
  572. self.start_simple("b10-stats", c_channel_env)
  573. def start_stats_httpd(self, c_channel_env):
  574. self.start_simple("b10-stats-httpd", c_channel_env)
  575. def start_dhcp6(self, c_channel_env):
  576. self.start_simple("b10-dhcp6", c_channel_env)
  577. def start_cmdctl(self, c_channel_env):
  578. """
  579. Starts the command control process
  580. """
  581. args = ["b10-cmdctl"]
  582. if self.cmdctl_port is not None:
  583. args.append("--port=" + str(self.cmdctl_port))
  584. self.start_process("b10-cmdctl", args, c_channel_env, self.cmdctl_port)
  585. def start_all_processes(self):
  586. """
  587. Starts up all the processes. Any exception generated during the
  588. starting of the processes is handled by the caller.
  589. """
  590. # The socket creator first, as it is the only thing that needs root
  591. self.start_creator()
  592. # TODO: Once everything uses the socket creator, we can drop root
  593. # privileges right now
  594. c_channel_env = self.c_channel_env
  595. self.start_msgq(c_channel_env)
  596. self.start_cfgmgr(c_channel_env)
  597. self.start_ccsession(c_channel_env)
  598. # Extract the parameters associated with Bob. This can only be
  599. # done after the CC Session is started. Note that the logging
  600. # configuration may override the "-v" switch set on the command line.
  601. self.read_bind10_config()
  602. # Continue starting the processes. The authoritative server (if
  603. # selected):
  604. if self.cfg_start_auth:
  605. self.start_auth(c_channel_env)
  606. # ... and resolver (if selected):
  607. if self.cfg_start_resolver:
  608. self.start_resolver(c_channel_env)
  609. self.started_resolver_family = True
  610. # Everything after the main components can run as non-root.
  611. # TODO: this is only temporary - once the privileged socket creator is
  612. # fully working, nothing else will run as root.
  613. if self.uid is not None:
  614. posix.setuid(self.uid)
  615. # xfrin/xfrout and the zone manager are only meaningful if the
  616. # authoritative server has been started.
  617. if self.cfg_start_auth:
  618. self.start_xfrout(c_channel_env)
  619. self.start_xfrin(c_channel_env)
  620. self.start_zonemgr(c_channel_env)
  621. self.started_auth_family = True
  622. # ... and finally start the remaining processes
  623. self.start_stats(c_channel_env)
  624. self.start_stats_httpd(c_channel_env)
  625. self.start_cmdctl(c_channel_env)
  626. if self.cfg_start_dhcp6:
  627. self.start_dhcp6(c_channel_env)
  628. def startup(self):
  629. """
  630. Start the BoB instance.
  631. Returns None if successful, otherwise an string describing the
  632. problem.
  633. """
  634. # Try to connect to the c-channel daemon, to see if it is already
  635. # running
  636. c_channel_env = {}
  637. if self.msgq_socket_file is not None:
  638. c_channel_env["BIND10_MSGQ_SOCKET_FILE"] = self.msgq_socket_file
  639. logger.debug(DBG_PROCESS, BIND10_CHECK_MSGQ_ALREADY_RUNNING)
  640. # try to connect, and if we can't wait a short while
  641. try:
  642. self.cc_session = isc.cc.Session(self.msgq_socket_file)
  643. logger.fatal(BIND10_MSGQ_ALREADY_RUNNING)
  644. return "b10-msgq already running, or socket file not cleaned , cannot start"
  645. except isc.cc.session.SessionError:
  646. # this is the case we want, where the msgq is not running
  647. pass
  648. # Start all processes. If any one fails to start, kill all started
  649. # processes and exit with an error indication.
  650. try:
  651. self.c_channel_env = c_channel_env
  652. self.start_all_processes()
  653. except Exception as e:
  654. self.kill_started_processes()
  655. return "Unable to start " + self.curproc + ": " + str(e)
  656. # Started successfully
  657. self.runnable = True
  658. return None
  659. def stop_all_processes(self):
  660. """Stop all processes."""
  661. cmd = { "command": ['shutdown']}
  662. self.cc_session.group_sendmsg(cmd, 'Cmdctl', 'Cmdctl')
  663. self.cc_session.group_sendmsg(cmd, "ConfigManager", "ConfigManager")
  664. self.cc_session.group_sendmsg(cmd, "Auth", "Auth")
  665. self.cc_session.group_sendmsg(cmd, "Resolver", "Resolver")
  666. self.cc_session.group_sendmsg(cmd, "Xfrout", "Xfrout")
  667. self.cc_session.group_sendmsg(cmd, "Xfrin", "Xfrin")
  668. self.cc_session.group_sendmsg(cmd, "Zonemgr", "Zonemgr")
  669. self.cc_session.group_sendmsg(cmd, "Stats", "Stats")
  670. self.cc_session.group_sendmsg(cmd, "StatsHttpd", "StatsHttpd")
  671. # Terminate the creator last
  672. self.stop_creator()
  673. def stop_process(self, process, recipient):
  674. """
  675. Stop the given process, friendly-like. The process is the name it has
  676. (in logs, etc), the recipient is the address on msgq.
  677. """
  678. logger.info(BIND10_STOP_PROCESS, process)
  679. # TODO: Some timeout to solve processes that don't want to die would
  680. # help. We can even store it in the dict, it is used only as a set
  681. self.expected_shutdowns[process] = 1
  682. # Ask the process to die willingly
  683. self.cc_session.group_sendmsg({'command': ['shutdown']}, recipient,
  684. recipient)
  685. # Series of stop_process wrappers
  686. def stop_resolver(self):
  687. self.stop_process('b10-resolver', 'Resolver')
  688. def stop_auth(self):
  689. self.stop_process('b10-auth', 'Auth')
  690. def stop_xfrout(self):
  691. self.stop_process('b10-xfrout', 'Xfrout')
  692. def stop_xfrin(self):
  693. self.stop_process('b10-xfrin', 'Xfrin')
  694. def stop_zonemgr(self):
  695. self.stop_process('b10-zonemgr', 'Zonemgr')
  696. def shutdown(self):
  697. """Stop the BoB instance."""
  698. logger.info(BIND10_SHUTDOWN)
  699. # first try using the BIND 10 request to stop
  700. try:
  701. self.stop_all_processes()
  702. except:
  703. pass
  704. # XXX: some delay probably useful... how much is uncertain
  705. # I have changed the delay from 0.5 to 1, but sometime it's
  706. # still not enough.
  707. time.sleep(1)
  708. self.reap_children()
  709. # next try sending a SIGTERM
  710. processes_to_stop = list(self.processes.values())
  711. for proc_info in processes_to_stop:
  712. logger.info(BIND10_SEND_SIGTERM, proc_info.name,
  713. proc_info.pid)
  714. try:
  715. proc_info.process.terminate()
  716. except OSError:
  717. # ignore these (usually ESRCH because the child
  718. # finally exited)
  719. pass
  720. # finally, send SIGKILL (unmaskable termination) until everybody dies
  721. while self.processes:
  722. # XXX: some delay probably useful... how much is uncertain
  723. time.sleep(0.1)
  724. self.reap_children()
  725. processes_to_stop = list(self.processes.values())
  726. for proc_info in processes_to_stop:
  727. logger.info(BIND10_SEND_SIGKILL, proc_info.name,
  728. proc_info.pid)
  729. try:
  730. proc_info.process.kill()
  731. except OSError:
  732. # ignore these (usually ESRCH because the child
  733. # finally exited)
  734. pass
  735. logger.info(BIND10_SHUTDOWN_COMPLETE)
  736. def _get_process_exit_status(self):
  737. return os.waitpid(-1, os.WNOHANG)
  738. def reap_children(self):
  739. """Check to see if any of our child processes have exited,
  740. and note this for later handling.
  741. """
  742. while True:
  743. try:
  744. (pid, exit_status) = self._get_process_exit_status()
  745. except OSError as o:
  746. if o.errno == errno.ECHILD: break
  747. # XXX: should be impossible to get any other error here
  748. raise
  749. if pid == 0: break
  750. if self.sockcreator is not None and self.sockcreator.pid() == pid:
  751. # This is the socket creator, started and terminated
  752. # differently. This can't be restarted.
  753. if self.runnable:
  754. logger.fatal(BIND10_SOCKCREATOR_CRASHED)
  755. self.sockcreator = None
  756. self.runnable = False
  757. elif pid in self.processes:
  758. # One of the processes we know about. Get information on it.
  759. proc_info = self.processes.pop(pid)
  760. proc_info.restart_schedule.set_run_stop_time()
  761. self.dead_processes[proc_info.pid] = proc_info
  762. # Write out message, but only if in the running state:
  763. # During startup and shutdown, these messages are handled
  764. # elsewhere.
  765. if self.runnable:
  766. if exit_status is None:
  767. logger.warn(BIND10_PROCESS_ENDED_NO_EXIT_STATUS,
  768. proc_info.name, proc_info.pid)
  769. else:
  770. logger.warn(BIND10_PROCESS_ENDED_WITH_EXIT_STATUS,
  771. proc_info.name, proc_info.pid,
  772. exit_status)
  773. # Was it a special process?
  774. if proc_info.name == "b10-msgq":
  775. logger.fatal(BIND10_MSGQ_DAEMON_ENDED)
  776. self.runnable = False
  777. # If we're in 'brittle' mode, we want to shutdown after
  778. # any process dies.
  779. if self.brittle:
  780. self.runnable = False
  781. else:
  782. logger.info(BIND10_UNKNOWN_CHILD_PROCESS_ENDED, pid)
  783. def restart_processes(self):
  784. """
  785. Restart any dead processes:
  786. * Returns the time when the next process is ready to be restarted.
  787. * If the server is shutting down, returns 0.
  788. * If there are no processes, returns None.
  789. The values returned can be safely passed into select() as the
  790. timeout value.
  791. """
  792. next_restart = None
  793. # if we're shutting down, then don't restart
  794. if not self.runnable:
  795. return 0
  796. # otherwise look through each dead process and try to restart
  797. still_dead = {}
  798. now = time.time()
  799. for proc_info in self.dead_processes.values():
  800. if proc_info.name in self.expected_shutdowns:
  801. # We don't restart, we wanted it to die
  802. del self.expected_shutdowns[proc_info.name]
  803. continue
  804. restart_time = proc_info.restart_schedule.get_restart_time(now)
  805. if restart_time > now:
  806. if (next_restart is None) or (next_restart > restart_time):
  807. next_restart = restart_time
  808. still_dead[proc_info.pid] = proc_info
  809. else:
  810. logger.info(BIND10_RESURRECTING_PROCESS, proc_info.name)
  811. try:
  812. proc_info.respawn()
  813. self.processes[proc_info.pid] = proc_info
  814. logger.info(BIND10_RESURRECTED_PROCESS, proc_info.name, proc_info.pid)
  815. except:
  816. still_dead[proc_info.pid] = proc_info
  817. # remember any processes that refuse to be resurrected
  818. self.dead_processes = still_dead
  819. # return the time when the next process is ready to be restarted
  820. return next_restart
  821. # global variables, needed for signal handlers
  822. options = None
  823. boss_of_bind = None
  824. def reaper(signal_number, stack_frame):
  825. """A child process has died (SIGCHLD received)."""
  826. # don't do anything...
  827. # the Python signal handler has been set up to write
  828. # down a pipe, waking up our select() bit
  829. pass
  830. def get_signame(signal_number):
  831. """Return the symbolic name for a signal."""
  832. for sig in dir(signal):
  833. if sig.startswith("SIG") and sig[3].isalnum():
  834. if getattr(signal, sig) == signal_number:
  835. return sig
  836. return "Unknown signal %d" % signal_number
  837. # XXX: perhaps register atexit() function and invoke that instead
  838. def fatal_signal(signal_number, stack_frame):
  839. """We need to exit (SIGINT or SIGTERM received)."""
  840. global options
  841. global boss_of_bind
  842. logger.info(BIND10_RECEIVED_SIGNAL, get_signame(signal_number))
  843. signal.signal(signal.SIGCHLD, signal.SIG_DFL)
  844. boss_of_bind.runnable = False
  845. def process_rename(option, opt_str, value, parser):
  846. """Function that renames the process if it is requested by a option."""
  847. isc.util.process.rename(value)
  848. def parse_args(args=sys.argv[1:], Parser=OptionParser):
  849. """
  850. Function for parsing command line arguments. Returns the
  851. options object from OptionParser.
  852. """
  853. parser = Parser(version=VERSION)
  854. parser.add_option("-m", "--msgq-socket-file", dest="msgq_socket_file",
  855. type="string", default=None,
  856. help="UNIX domain socket file the b10-msgq daemon will use")
  857. parser.add_option("-n", "--no-cache", action="store_true", dest="nocache",
  858. default=False, help="disable hot-spot cache in authoritative DNS server")
  859. parser.add_option("-u", "--user", dest="user", type="string", default=None,
  860. help="Change user after startup (must run as root)")
  861. parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
  862. help="display more about what is going on")
  863. parser.add_option("--pretty-name", type="string", action="callback",
  864. callback=process_rename,
  865. help="Set the process name (displayed in ps, top, ...)")
  866. parser.add_option("-c", "--config-file", action="store",
  867. dest="config_file", default=None,
  868. help="Configuration database filename")
  869. parser.add_option("-p", "--data-path", dest="data_path",
  870. help="Directory to search for configuration files",
  871. default=None)
  872. parser.add_option("--cmdctl-port", dest="cmdctl_port", type="int",
  873. default=None, help="Port of command control")
  874. parser.add_option("--pid-file", dest="pid_file", type="string",
  875. default=None,
  876. help="file to dump the PID of the BIND 10 process")
  877. parser.add_option("--brittle", dest="brittle", action="store_true",
  878. help="debugging flag: exit if any component dies")
  879. parser.add_option("-w", "--wait", dest="wait_time", type="int",
  880. default=10, help="Time (in seconds) to wait for config manager to start up")
  881. (options, args) = parser.parse_args(args)
  882. if options.cmdctl_port is not None:
  883. try:
  884. isc.net.parse.port_parse(options.cmdctl_port)
  885. except ValueError as e:
  886. parser.error(e)
  887. if args:
  888. parser.print_help()
  889. sys.exit(1)
  890. return options
  891. def dump_pid(pid_file):
  892. """
  893. Dump the PID of the current process to the specified file. If the given
  894. file is None this function does nothing. If the file already exists,
  895. the existing content will be removed. If a system error happens in
  896. creating or writing to the file, the corresponding exception will be
  897. propagated to the caller.
  898. """
  899. if pid_file is None:
  900. return
  901. f = open(pid_file, "w")
  902. f.write('%d\n' % os.getpid())
  903. f.close()
  904. def unlink_pid_file(pid_file):
  905. """
  906. Remove the given file, which is basically expected to be the PID file
  907. created by dump_pid(). The specified may or may not exist; if it
  908. doesn't this function does nothing. Other system level errors in removing
  909. the file will be propagated as the corresponding exception.
  910. """
  911. if pid_file is None:
  912. return
  913. try:
  914. os.unlink(pid_file)
  915. except OSError as error:
  916. if error.errno is not errno.ENOENT:
  917. raise
  918. def main():
  919. global options
  920. global boss_of_bind
  921. # Enforce line buffering on stdout, even when not a TTY
  922. sys.stdout = io.TextIOWrapper(sys.stdout.detach(), line_buffering=True)
  923. options = parse_args()
  924. # Check user ID.
  925. setuid = None
  926. username = None
  927. if options.user:
  928. # Try getting information about the user, assuming UID passed.
  929. try:
  930. pw_ent = pwd.getpwuid(int(options.user))
  931. setuid = pw_ent.pw_uid
  932. username = pw_ent.pw_name
  933. except ValueError:
  934. pass
  935. except KeyError:
  936. pass
  937. # Next try getting information about the user, assuming user name
  938. # passed.
  939. # If the information is both a valid user name and user number, we
  940. # prefer the name because we try it second. A minor point, hopefully.
  941. try:
  942. pw_ent = pwd.getpwnam(options.user)
  943. setuid = pw_ent.pw_uid
  944. username = pw_ent.pw_name
  945. except KeyError:
  946. pass
  947. if setuid is None:
  948. logger.fatal(BIND10_INVALID_USER, options.user)
  949. sys.exit(1)
  950. # Announce startup.
  951. logger.info(BIND10_STARTING, VERSION)
  952. # Create wakeup pipe for signal handlers
  953. wakeup_pipe = os.pipe()
  954. signal.set_wakeup_fd(wakeup_pipe[1])
  955. # Set signal handlers for catching child termination, as well
  956. # as our own demise.
  957. signal.signal(signal.SIGCHLD, reaper)
  958. signal.siginterrupt(signal.SIGCHLD, False)
  959. signal.signal(signal.SIGINT, fatal_signal)
  960. signal.signal(signal.SIGTERM, fatal_signal)
  961. # Block SIGPIPE, as we don't want it to end this process
  962. signal.signal(signal.SIGPIPE, signal.SIG_IGN)
  963. # Go bob!
  964. boss_of_bind = BoB(options.msgq_socket_file, options.data_path,
  965. options.config_file, options.nocache, options.verbose,
  966. setuid, username, options.cmdctl_port, options.brittle,
  967. options.wait_time)
  968. startup_result = boss_of_bind.startup()
  969. if startup_result:
  970. logger.fatal(BIND10_STARTUP_ERROR, startup_result)
  971. sys.exit(1)
  972. logger.info(BIND10_STARTUP_COMPLETE)
  973. dump_pid(options.pid_file)
  974. # In our main loop, we check for dead processes or messages
  975. # on the c-channel.
  976. wakeup_fd = wakeup_pipe[0]
  977. ccs_fd = boss_of_bind.ccs.get_socket().fileno()
  978. while boss_of_bind.runnable:
  979. # clean up any processes that exited
  980. boss_of_bind.reap_children()
  981. next_restart = boss_of_bind.restart_processes()
  982. if next_restart is None:
  983. wait_time = None
  984. else:
  985. wait_time = max(next_restart - time.time(), 0)
  986. # select() can raise EINTR when a signal arrives,
  987. # even if they are resumable, so we have to catch
  988. # the exception
  989. try:
  990. (rlist, wlist, xlist) = select.select([wakeup_fd, ccs_fd], [], [],
  991. wait_time)
  992. except select.error as err:
  993. if err.args[0] == errno.EINTR:
  994. (rlist, wlist, xlist) = ([], [], [])
  995. else:
  996. logger.fatal(BIND10_SELECT_ERROR, err)
  997. break
  998. for fd in rlist + xlist:
  999. if fd == ccs_fd:
  1000. try:
  1001. boss_of_bind.ccs.check_command()
  1002. except isc.cc.session.ProtocolError:
  1003. logger.fatal(BIND10_MSGQ_DISAPPEARED)
  1004. self.runnable = False
  1005. break
  1006. elif fd == wakeup_fd:
  1007. os.read(wakeup_fd, 32)
  1008. # shutdown
  1009. signal.signal(signal.SIGCHLD, signal.SIG_DFL)
  1010. boss_of_bind.shutdown()
  1011. unlink_pid_file(options.pid_file)
  1012. sys.exit(0)
  1013. if __name__ == "__main__":
  1014. main()