bind10_src.py.in 41 KB

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