bind10_src.py.in 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296
  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 copy
  56. from bind10_config import LIBEXECPATH
  57. import bind10_config
  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. import libutil_io_python
  67. import tempfile
  68. isc.log.init("b10-boss", buffer=True)
  69. logger = isc.log.Logger("boss")
  70. # Pending system-wide debug level definitions, the ones we
  71. # use here are hardcoded for now
  72. DBG_PROCESS = logger.DBGLVL_TRACE_BASIC
  73. DBG_COMMANDS = logger.DBGLVL_TRACE_DETAIL
  74. # Messages sent over the unix domain socket to indicate if it is followed by a real socket
  75. CREATOR_SOCKET_OK = b"1\n"
  76. CREATOR_SOCKET_UNAVAILABLE = b"0\n"
  77. # RCodes of known exceptions for the get_token command
  78. CREATOR_SOCKET_ERROR = 2
  79. CREATOR_SHARE_ERROR = 3
  80. # Assign this process some longer name
  81. isc.util.process.rename(sys.argv[0])
  82. # This is the version that gets displayed to the user.
  83. # The VERSION string consists of the module name, the module version
  84. # number, and the overall BIND 10 version number (set in configure.ac).
  85. VERSION = "bind10 20110223 (BIND 10 @PACKAGE_VERSION@)"
  86. # This is for boot_time of Boss
  87. _BASETIME = time.gmtime()
  88. class ProcessInfoError(Exception): pass
  89. class ChangeUserError(Exception):
  90. '''Exception raised when setuid/setgid fails.
  91. When raised, it's expected to be propagated via underlying component
  92. management modules to the top level so that it will help provide useful
  93. fatal error message.
  94. '''
  95. pass
  96. class ProcessInfo:
  97. """Information about a process"""
  98. dev_null = open(os.devnull, "w")
  99. def __init__(self, name, args, env={}, dev_null_stdout=False,
  100. dev_null_stderr=False):
  101. self.name = name
  102. self.args = args
  103. self.env = env
  104. self.dev_null_stdout = dev_null_stdout
  105. self.dev_null_stderr = dev_null_stderr
  106. self.process = None
  107. self.pid = None
  108. def _preexec_work(self):
  109. """Function used before running a program that needs to run as a
  110. different user."""
  111. # First, put us into a separate process group so we don't get
  112. # SIGINT signals on Ctrl-C (the boss will shut everthing down by
  113. # other means).
  114. os.setpgrp()
  115. def _spawn(self):
  116. if self.dev_null_stdout:
  117. spawn_stdout = self.dev_null
  118. else:
  119. spawn_stdout = None
  120. if self.dev_null_stderr:
  121. spawn_stderr = self.dev_null
  122. else:
  123. spawn_stderr = None
  124. # Environment variables for the child process will be a copy of those
  125. # of the boss process with any additional specific variables given
  126. # on construction (self.env).
  127. spawn_env = copy.deepcopy(os.environ)
  128. spawn_env.update(self.env)
  129. spawn_env['PATH'] = LIBEXECPATH + ':' + spawn_env['PATH']
  130. self.process = subprocess.Popen(self.args,
  131. stdin=subprocess.PIPE,
  132. stdout=spawn_stdout,
  133. stderr=spawn_stderr,
  134. close_fds=True,
  135. env=spawn_env,
  136. preexec_fn=self._preexec_work)
  137. self.pid = self.process.pid
  138. # spawn() and respawn() are the same for now, but in the future they
  139. # may have different functionality
  140. def spawn(self):
  141. self._spawn()
  142. def respawn(self):
  143. self._spawn()
  144. class CChannelConnectError(Exception): pass
  145. class ProcessStartError(Exception): pass
  146. class BoB:
  147. """Boss of BIND class."""
  148. def __init__(self, msgq_socket_file=None, data_path=None,
  149. config_filename=None, clear_config=False,
  150. verbose=False, nokill=False, setuid=None, setgid=None,
  151. username=None, cmdctl_port=None, wait_time=10):
  152. """
  153. Initialize the Boss of BIND. This is a singleton (only one can run).
  154. The msgq_socket_file specifies the UNIX domain socket file that the
  155. msgq process listens on. If verbose is True, then the boss reports
  156. what it is doing.
  157. Data path and config filename are passed through to config manager
  158. (if provided) and specify the config file to be used.
  159. The cmdctl_port is passed to cmdctl and specify on which port it
  160. should listen.
  161. wait_time controls the amount of time (in seconds) that Boss waits
  162. for selected processes to initialize before continuing with the
  163. initialization. Currently this is only the configuration manager.
  164. """
  165. self.cc_session = None
  166. self.ccs = None
  167. self.curproc = None
  168. self.msgq_socket_file = msgq_socket_file
  169. self.component_config = {}
  170. # Some time in future, it may happen that a single component has
  171. # multple processes (like a pipeline-like component). If so happens,
  172. # name "components" may be inapropriate. But as the code isn't probably
  173. # completely ready for it, we leave it at components for now. We also
  174. # want to support multiple instances of a single component. If it turns
  175. # out that we'll have a single component with multiple same processes
  176. # or if we start multiple components with the same configuration (we do
  177. # this now, but it might change) is an open question.
  178. self.components = {}
  179. # Simply list of components that died and need to wait for a
  180. # restart. Components manage their own restart schedule now
  181. self.components_to_restart = []
  182. self.runnable = False
  183. self.__uid = setuid
  184. self.__gid = setgid
  185. self.username = username
  186. self.verbose = verbose
  187. self.nokill = nokill
  188. self.data_path = data_path
  189. self.config_filename = config_filename
  190. self.clear_config = clear_config
  191. self.cmdctl_port = cmdctl_port
  192. self.wait_time = wait_time
  193. self.msgq_timeout = 5
  194. # _run_under_unittests is only meant to be used when testing. It
  195. # bypasses execution of some code to help with testing.
  196. self._run_under_unittests = False
  197. self._component_configurator = isc.bind10.component.Configurator(self,
  198. isc.bind10.special_component.get_specials())
  199. # The priorities here make them start in the correct order. First
  200. # the socket creator (which would drop root privileges by then),
  201. # then message queue and after that the config manager (which uses
  202. # the config manager)
  203. self.__core_components = {
  204. 'sockcreator': {
  205. 'kind': 'core',
  206. 'special': 'sockcreator',
  207. 'priority': 200
  208. },
  209. 'msgq': {
  210. 'kind': 'core',
  211. 'special': 'msgq',
  212. 'priority': 199
  213. },
  214. 'cfgmgr': {
  215. 'kind': 'core',
  216. 'special': 'cfgmgr',
  217. 'priority': 198
  218. }
  219. }
  220. self.__started = False
  221. self.exitcode = 0
  222. # If -v was set, enable full debug logging.
  223. if self.verbose:
  224. logger.set_severity("DEBUG", 99)
  225. # This is set in init_socket_srv
  226. self._socket_path = None
  227. self._socket_cache = None
  228. self._tmpdir = None
  229. self._srv_socket = None
  230. self._unix_sockets = {}
  231. def __propagate_component_config(self, config):
  232. comps = dict(config)
  233. # Fill in the core components, so they stay alive
  234. for comp in self.__core_components:
  235. if comp in comps:
  236. raise Exception(comp + " is core component managed by " +
  237. "bind10 boss, do not set it")
  238. comps[comp] = self.__core_components[comp]
  239. # Update the configuration
  240. self._component_configurator.reconfigure(comps)
  241. def change_user(self):
  242. '''Change the user and group to those specified on construction.
  243. This method is expected to be called by a component on initial
  244. startup when the system is ready to switch the user and group
  245. (i.e., once all components that need the privilege of the original
  246. user have started).
  247. '''
  248. try:
  249. if self.__gid is not None:
  250. logger.info(BIND10_SETGID, self.__gid)
  251. posix.setgid(self.__gid)
  252. except Exception as ex:
  253. raise ChangeUserError('failed to change group: ' + str(ex))
  254. try:
  255. if self.__uid is not None:
  256. posix.setuid(self.__uid)
  257. # We use one-shot logger after setuid here. This will
  258. # detect any permission issue regarding logging due to the
  259. # result of setuid at the earliest opportunity.
  260. isc.log.Logger("boss").info(BIND10_SETUID, self.__uid)
  261. except Exception as ex:
  262. raise ChangeUserError('failed to change user: ' + str(ex))
  263. def config_handler(self, new_config):
  264. # If this is initial update, don't do anything now, leave it to startup
  265. if not self.runnable:
  266. return
  267. logger.debug(DBG_COMMANDS, BIND10_RECEIVED_NEW_CONFIGURATION,
  268. new_config)
  269. try:
  270. if 'components' in new_config:
  271. self.__propagate_component_config(new_config['components'])
  272. return isc.config.ccsession.create_answer(0)
  273. except Exception as e:
  274. return isc.config.ccsession.create_answer(1, str(e))
  275. def get_processes(self):
  276. pids = list(self.components.keys())
  277. pids.sort()
  278. process_list = [ ]
  279. for pid in pids:
  280. process_list.append([pid, self.components[pid].name(),
  281. self.components[pid].address()])
  282. return process_list
  283. def _get_stats_data(self):
  284. return { 'boot_time':
  285. time.strftime('%Y-%m-%dT%H:%M:%SZ', _BASETIME)
  286. }
  287. def command_handler(self, command, args):
  288. logger.debug(DBG_COMMANDS, BIND10_RECEIVED_COMMAND, command)
  289. answer = isc.config.ccsession.create_answer(1, "command not implemented")
  290. if type(command) != str:
  291. answer = isc.config.ccsession.create_answer(1, "bad command")
  292. else:
  293. if command == "shutdown":
  294. self.runnable = False
  295. answer = isc.config.ccsession.create_answer(0)
  296. elif command == "getstats":
  297. answer = isc.config.ccsession.create_answer(
  298. 0, self._get_stats_data())
  299. elif command == "ping":
  300. answer = isc.config.ccsession.create_answer(0, "pong")
  301. elif command == "show_processes":
  302. answer = isc.config.ccsession. \
  303. create_answer(0, self.get_processes())
  304. elif command == "get_socket":
  305. answer = self._get_socket(args)
  306. elif command == "drop_socket":
  307. if "token" not in args:
  308. answer = isc.config.ccsession. \
  309. create_answer(1, "Missing token parameter")
  310. else:
  311. try:
  312. self._socket_cache.drop_socket(args["token"])
  313. answer = isc.config.ccsession.create_answer(0)
  314. except Exception as e:
  315. answer = isc.config.ccsession.create_answer(1, str(e))
  316. else:
  317. answer = isc.config.ccsession.create_answer(1,
  318. "Unknown command")
  319. return answer
  320. def kill_started_components(self):
  321. """
  322. Called as part of the exception handling when a process fails to
  323. start, this runs through the list of started processes, killing
  324. each one. It then clears that list.
  325. """
  326. logger.info(BIND10_KILLING_ALL_PROCESSES)
  327. self.__kill_children(True)
  328. self.components = {}
  329. def _read_bind10_config(self):
  330. """
  331. Reads the parameters associated with the BoB module itself.
  332. This means the list of components we should start now.
  333. This could easily be combined into start_all_processes, but
  334. it stays because of historical reasons and because the tests
  335. replace the method sometimes.
  336. """
  337. logger.info(BIND10_READING_BOSS_CONFIGURATION)
  338. config_data = self.ccs.get_full_config()
  339. self.__propagate_component_config(config_data['components'])
  340. def log_starting(self, process, port = None, address = None):
  341. """
  342. A convenience function to output a "Starting xxx" message if the
  343. logging is set to DEBUG with debuglevel DBG_PROCESS or higher.
  344. Putting this into a separate method ensures
  345. that the output form is consistent across all processes.
  346. The process name (passed as the first argument) is put into
  347. self.curproc, and is used to indicate which process failed to
  348. start if there is an error (and is used in the "Started" message
  349. on success). The optional port and address information are
  350. appended to the message (if present).
  351. """
  352. self.curproc = process
  353. if port is None and address is None:
  354. logger.info(BIND10_STARTING_PROCESS, self.curproc)
  355. elif address is None:
  356. logger.info(BIND10_STARTING_PROCESS_PORT, self.curproc,
  357. port)
  358. else:
  359. logger.info(BIND10_STARTING_PROCESS_PORT_ADDRESS,
  360. self.curproc, address, port)
  361. def log_started(self, pid = None):
  362. """
  363. A convenience function to output a 'Started xxxx (PID yyyy)'
  364. message. As with starting_message(), this ensures a consistent
  365. format.
  366. """
  367. if pid is None:
  368. logger.debug(DBG_PROCESS, BIND10_STARTED_PROCESS, self.curproc)
  369. else:
  370. logger.debug(DBG_PROCESS, BIND10_STARTED_PROCESS_PID, self.curproc, pid)
  371. def process_running(self, msg, who):
  372. """
  373. Some processes return a message to the Boss after they have
  374. started to indicate that they are running. The form of the
  375. message is a dictionary with contents {"running:", "<process>"}.
  376. This method checks the passed message and returns True if the
  377. "who" process is contained in the message (so is presumably
  378. running). It returns False for all other conditions and will
  379. log an error if appropriate.
  380. """
  381. if msg is not None:
  382. try:
  383. if msg["running"] == who:
  384. return True
  385. else:
  386. logger.error(BIND10_STARTUP_UNEXPECTED_MESSAGE, msg)
  387. except:
  388. logger.error(BIND10_STARTUP_UNRECOGNISED_MESSAGE, msg)
  389. return False
  390. # The next few methods start the individual processes of BIND-10. They
  391. # are called via start_all_processes(). If any fail, an exception is
  392. # raised which is caught by the caller of start_all_processes(); this kills
  393. # processes started up to that point before terminating the program.
  394. def _make_process_info(self, name, args, env,
  395. dev_null_stdout=False, dev_null_stderr=False):
  396. """
  397. Wrapper around ProcessInfo(), useful to override
  398. ProcessInfo() creation during testing.
  399. """
  400. return ProcessInfo(name, args, env, dev_null_stdout, dev_null_stderr)
  401. def start_msgq(self):
  402. """
  403. Start the message queue and connect to the command channel.
  404. """
  405. self.log_starting("b10-msgq")
  406. msgq_proc = self._make_process_info("b10-msgq", ["b10-msgq"],
  407. self.c_channel_env,
  408. True, not self.verbose)
  409. msgq_proc.spawn()
  410. self.log_started(msgq_proc.pid)
  411. # Now connect to the c-channel
  412. cc_connect_start = time.time()
  413. while self.cc_session is None:
  414. # if we are run under unittests, break
  415. if self._run_under_unittests:
  416. break
  417. # if we have been trying for "a while" give up
  418. if (time.time() - cc_connect_start) > self.msgq_timeout:
  419. logger.error(BIND10_CONNECTING_TO_CC_FAIL)
  420. raise CChannelConnectError("Unable to connect to c-channel after 5 seconds")
  421. # try to connect, and if we can't wait a short while
  422. try:
  423. self.cc_session = isc.cc.Session(self.msgq_socket_file)
  424. except isc.cc.session.SessionError:
  425. time.sleep(0.1)
  426. # Subscribe to the message queue. The only messages we expect to receive
  427. # on this channel are once relating to process startup.
  428. if self.cc_session is not None:
  429. self.cc_session.group_subscribe("Boss")
  430. return msgq_proc
  431. def start_cfgmgr(self):
  432. """
  433. Starts the configuration manager process
  434. """
  435. self.log_starting("b10-cfgmgr")
  436. args = ["b10-cfgmgr"]
  437. if self.data_path is not None:
  438. args.append("--data-path=" + self.data_path)
  439. if self.config_filename is not None:
  440. args.append("--config-filename=" + self.config_filename)
  441. if self.clear_config:
  442. args.append("--clear-config")
  443. bind_cfgd = self._make_process_info("b10-cfgmgr", args,
  444. self.c_channel_env)
  445. bind_cfgd.spawn()
  446. self.log_started(bind_cfgd.pid)
  447. # Wait for the configuration manager to start up as
  448. # subsequent initialization cannot proceed without it. The
  449. # time to wait can be set on the command line.
  450. time_remaining = self.wait_time
  451. msg, env = self.cc_session.group_recvmsg()
  452. while time_remaining > 0 and not self.process_running(msg, "ConfigManager"):
  453. logger.debug(DBG_PROCESS, BIND10_WAIT_CFGMGR)
  454. time.sleep(1)
  455. time_remaining = time_remaining - 1
  456. msg, env = self.cc_session.group_recvmsg()
  457. if not self.process_running(msg, "ConfigManager"):
  458. raise ProcessStartError("Configuration manager process has not started")
  459. return bind_cfgd
  460. def start_ccsession(self, c_channel_env):
  461. """
  462. Start the CC Session
  463. The argument c_channel_env is unused but is supplied to keep the
  464. argument list the same for all start_xxx methods.
  465. With regards to logging, note that as the CC session is not a
  466. process, the log_starting/log_started methods are not used.
  467. """
  468. logger.info(BIND10_STARTING_CC)
  469. self.ccs = isc.config.ModuleCCSession(SPECFILE_LOCATION,
  470. self.config_handler,
  471. self.command_handler,
  472. socket_file = self.msgq_socket_file)
  473. self.ccs.start()
  474. logger.debug(DBG_PROCESS, BIND10_STARTED_CC)
  475. # A couple of utility methods for starting processes...
  476. def start_process(self, name, args, c_channel_env, port=None, address=None):
  477. """
  478. Given a set of command arguments, start the process and output
  479. appropriate log messages. If the start is successful, the process
  480. is added to the list of started processes.
  481. The port and address arguments are for log messages only.
  482. """
  483. self.log_starting(name, port, address)
  484. newproc = self._make_process_info(name, args, c_channel_env)
  485. newproc.spawn()
  486. self.log_started(newproc.pid)
  487. return newproc
  488. def register_process(self, pid, component):
  489. """
  490. Put another process into boss to watch over it. When the process
  491. dies, the component.failed() is called with the exit code.
  492. It is expected the info is a isc.bind10.component.BaseComponent
  493. subclass (or anything having the same interface).
  494. """
  495. self.components[pid] = component
  496. def start_simple(self, name):
  497. """
  498. Most of the BIND-10 processes are started with the command:
  499. <process-name> [-v]
  500. ... where -v is appended if verbose is enabled. This method
  501. generates the arguments from the name and starts the process.
  502. The port and address arguments are for log messages only.
  503. """
  504. # Set up the command arguments.
  505. args = [name]
  506. if self.verbose:
  507. args += ['-v']
  508. # ... and start the process
  509. return self.start_process(name, args, self.c_channel_env)
  510. # The next few methods start up the rest of the BIND-10 processes.
  511. # Although many of these methods are little more than a call to
  512. # start_simple, they are retained (a) for testing reasons and (b) as a place
  513. # where modifications can be made if the process start-up sequence changes
  514. # for a given process.
  515. def start_auth(self):
  516. """
  517. Start the Authoritative server
  518. """
  519. authargs = ['b10-auth']
  520. if self.verbose:
  521. authargs += ['-v']
  522. # ... and start
  523. return self.start_process("b10-auth", authargs, self.c_channel_env)
  524. def start_resolver(self):
  525. """
  526. Start the Resolver. At present, all these arguments and switches
  527. are pure speculation. As with the auth daemon, they should be
  528. read from the configuration database.
  529. """
  530. if self.__uid is not None and self.__started:
  531. logger.warn(BIND10_START_AS_NON_ROOT_RESOLVER)
  532. self.curproc = "b10-resolver"
  533. # XXX: this must be read from the configuration manager in the future
  534. resargs = ['b10-resolver']
  535. if self.verbose:
  536. resargs += ['-v']
  537. # ... and start
  538. return self.start_process("b10-resolver", resargs, self.c_channel_env)
  539. def start_cmdctl(self):
  540. """
  541. Starts the command control process
  542. """
  543. args = ["b10-cmdctl"]
  544. if self.cmdctl_port is not None:
  545. args.append("--port=" + str(self.cmdctl_port))
  546. if self.verbose:
  547. args.append("-v")
  548. return self.start_process("b10-cmdctl", args, self.c_channel_env,
  549. self.cmdctl_port)
  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:
  578. self.cc_session = isc.cc.Session(self.msgq_socket_file)
  579. logger.fatal(BIND10_MSGQ_ALREADY_RUNNING)
  580. return "b10-msgq already running, or socket file not cleaned , cannot start"
  581. except isc.cc.session.SessionError:
  582. # this is the case we want, where the msgq is not running
  583. pass
  584. # Start all components. If any one fails to start, kill all started
  585. # components and exit with an error indication.
  586. try:
  587. self.c_channel_env = c_channel_env
  588. self.start_all_components()
  589. except Exception as e:
  590. self.kill_started_components()
  591. return "Unable to start " + self.curproc + ": " + str(e)
  592. # Started successfully
  593. self.runnable = True
  594. self.__started = True
  595. return None
  596. def stop_process(self, process, recipient, pid):
  597. """
  598. Stop the given process, friendly-like. The process is the name it has
  599. (in logs, etc), the recipient is the address on msgq. The pid is the
  600. pid of the process (if we have multiple processes of the same name,
  601. it might want to choose if it is for this one).
  602. """
  603. logger.info(BIND10_STOP_PROCESS, process)
  604. self.cc_session.group_sendmsg(isc.config.ccsession.
  605. create_command('shutdown', {'pid': pid}),
  606. recipient, recipient)
  607. def component_shutdown(self, exitcode=0):
  608. """
  609. Stop the Boss instance from a components' request. The exitcode
  610. indicates the desired exit code.
  611. If we did not start yet, it raises an exception, which is meant
  612. to propagate through the component and configurator to the startup
  613. routine and abort the startup immediately. If it is started up already,
  614. we just mark it so we terminate soon.
  615. It does set the exit code in both cases.
  616. """
  617. self.exitcode = exitcode
  618. if not self.__started:
  619. raise Exception("Component failed during startup");
  620. else:
  621. self.runnable = False
  622. def shutdown(self):
  623. """Stop the BoB instance."""
  624. logger.info(BIND10_SHUTDOWN)
  625. # If ccsession is still there, inform rest of the system this module
  626. # is stopping. Since everything will be stopped shortly, this is not
  627. # really necessary, but this is done to reflect that boss is also
  628. # 'just' a module.
  629. self.ccs.send_stopping()
  630. # try using the BIND 10 request to stop
  631. try:
  632. self._component_configurator.shutdown()
  633. except:
  634. pass
  635. # XXX: some delay probably useful... how much is uncertain
  636. # I have changed the delay from 0.5 to 1, but sometime it's
  637. # still not enough.
  638. time.sleep(1)
  639. self.reap_children()
  640. # Send TERM and KILL signals to modules if we're not prevented
  641. # from doing so
  642. if not self.nokill:
  643. # next try sending a SIGTERM
  644. self.__kill_children(False)
  645. # finally, send SIGKILL (unmaskable termination) until everybody
  646. # dies
  647. while self.components:
  648. # XXX: some delay probably useful... how much is uncertain
  649. time.sleep(0.1)
  650. self.reap_children()
  651. self.__kill_children(True)
  652. logger.info(BIND10_SHUTDOWN_COMPLETE)
  653. def __kill_children(self, forceful):
  654. '''Terminate remaining subprocesses by sending a signal.
  655. The forceful paramter will be passed Component.kill().
  656. This is a dedicated subroutine of shutdown(), just to unify two
  657. similar cases.
  658. '''
  659. logmsg = BIND10_SEND_SIGKILL if forceful else BIND10_SEND_SIGTERM
  660. # We need to make a copy of values as the components may be modified
  661. # in the loop.
  662. for component in list(self.components.values()):
  663. logger.info(logmsg, component.name(), component.pid())
  664. try:
  665. component.kill(forceful)
  666. except OSError as ex:
  667. # If kill() failed due to EPERM, it doesn't make sense to
  668. # keep trying, so we just log the fact and forget that
  669. # component. Ignore other OSErrors (usually ESRCH because
  670. # the child finally exited)
  671. signame = "SIGKILL" if forceful else "SIGTERM"
  672. logger.info(BIND10_SEND_SIGNAL_FAIL, signame,
  673. component.name(), component.pid(), ex)
  674. if ex.errno == errno.EPERM:
  675. del self.components[component.pid()]
  676. def _get_process_exit_status(self):
  677. return os.waitpid(-1, os.WNOHANG)
  678. def reap_children(self):
  679. """Check to see if any of our child processes have exited,
  680. and note this for later handling.
  681. """
  682. while True:
  683. try:
  684. (pid, exit_status) = self._get_process_exit_status()
  685. except OSError as o:
  686. if o.errno == errno.ECHILD:
  687. break
  688. # XXX: should be impossible to get any other error here
  689. raise
  690. if pid == 0:
  691. break
  692. if pid in self.components:
  693. # One of the components we know about. Get information on it.
  694. component = self.components.pop(pid)
  695. logger.info(BIND10_PROCESS_ENDED, component.name(), pid,
  696. exit_status)
  697. if component.is_running() and self.runnable:
  698. # Tell it it failed. But only if it matters (we are
  699. # not shutting down and the component considers itself
  700. # to be running.
  701. component_restarted = component.failed(exit_status);
  702. # if the process wants to be restarted, but not just yet,
  703. # it returns False
  704. if not component_restarted:
  705. self.components_to_restart.append(component)
  706. else:
  707. logger.info(BIND10_UNKNOWN_CHILD_PROCESS_ENDED, pid)
  708. def restart_processes(self):
  709. """
  710. Restart any dead processes:
  711. * Returns the time when the next process is ready to be restarted.
  712. * If the server is shutting down, returns 0.
  713. * If there are no processes, returns None.
  714. The values returned can be safely passed into select() as the
  715. timeout value.
  716. """
  717. if not self.runnable:
  718. return 0
  719. still_dead = []
  720. # keep track of the first time we need to check this queue again,
  721. # if at all
  722. next_restart_time = None
  723. now = time.time()
  724. for component in self.components_to_restart:
  725. # If the component was removed from the configurator between since
  726. # scheduled to restart, just ignore it. The object will just be
  727. # dropped here.
  728. if not self._component_configurator.has_component(component):
  729. logger.info(BIND10_RESTART_COMPONENT_SKIPPED, component.name())
  730. elif not component.restart(now):
  731. still_dead.append(component)
  732. if next_restart_time is None or\
  733. next_restart_time > component.get_restart_time():
  734. next_restart_time = component.get_restart_time()
  735. self.components_to_restart = still_dead
  736. return next_restart_time
  737. def _get_socket(self, args):
  738. """
  739. Implementation of the get_socket CC command. It asks the cache
  740. to provide the token and sends the information back.
  741. """
  742. try:
  743. try:
  744. addr = isc.net.parse.addr_parse(args['address'])
  745. port = isc.net.parse.port_parse(args['port'])
  746. protocol = args['protocol']
  747. if protocol not in ['UDP', 'TCP']:
  748. raise ValueError("Protocol must be either UDP or TCP")
  749. share_mode = args['share_mode']
  750. if share_mode not in ['ANY', 'SAMEAPP', 'NO']:
  751. raise ValueError("Share mode must be one of ANY, SAMEAPP" +
  752. " or NO")
  753. share_name = args['share_name']
  754. except KeyError as ke:
  755. return \
  756. isc.config.ccsession.create_answer(1,
  757. "Missing parameter " +
  758. str(ke))
  759. # FIXME: This call contains blocking IPC. It is expected to be
  760. # short, but if it turns out to be problem, we'll need to do
  761. # something about it.
  762. token = self._socket_cache.get_token(protocol, addr, port,
  763. share_mode, share_name)
  764. return isc.config.ccsession.create_answer(0, {
  765. 'token': token,
  766. 'path': self._socket_path
  767. })
  768. except isc.bind10.socket_cache.SocketError as e:
  769. return isc.config.ccsession.create_answer(CREATOR_SOCKET_ERROR,
  770. str(e))
  771. except isc.bind10.socket_cache.ShareError as e:
  772. return isc.config.ccsession.create_answer(CREATOR_SHARE_ERROR,
  773. str(e))
  774. except Exception as e:
  775. return isc.config.ccsession.create_answer(1, str(e))
  776. def socket_request_handler(self, token, unix_socket):
  777. """
  778. This function handles a token that comes over a unix_domain socket.
  779. The function looks into the _socket_cache and sends the socket
  780. identified by the token back over the unix_socket.
  781. """
  782. try:
  783. token = str(token, 'ASCII') # Convert from bytes to str
  784. fd = self._socket_cache.get_socket(token, unix_socket.fileno())
  785. # FIXME: These two calls are blocking in their nature. An OS-level
  786. # buffer is likely to be large enough to hold all these data, but
  787. # if it wasn't and the remote application got stuck, we would have
  788. # a problem. If there appear such problems, we should do something
  789. # about it.
  790. unix_socket.sendall(CREATOR_SOCKET_OK)
  791. libutil_io_python.send_fd(unix_socket.fileno(), fd)
  792. except Exception as e:
  793. logger.info(BIND10_NO_SOCKET, token, e)
  794. unix_socket.sendall(CREATOR_SOCKET_UNAVAILABLE)
  795. def socket_consumer_dead(self, unix_socket):
  796. """
  797. This function handles when a unix_socket closes. This means all
  798. sockets sent to it are to be considered closed. This function signals
  799. so to the _socket_cache.
  800. """
  801. logger.info(BIND10_LOST_SOCKET_CONSUMER, unix_socket.fileno())
  802. try:
  803. self._socket_cache.drop_application(unix_socket.fileno())
  804. except ValueError:
  805. # This means the application holds no sockets. It's harmless, as it
  806. # can happen in real life - for example, it requests a socket, but
  807. # get_socket doesn't find it, so the application dies. It should be
  808. # rare, though.
  809. pass
  810. def set_creator(self, creator):
  811. """
  812. Registeres a socket creator into the boss. The socket creator is not
  813. used directly, but through a cache. The cache is created in this
  814. method.
  815. If called more than once, it raises a ValueError.
  816. """
  817. if self._socket_cache is not None:
  818. raise ValueError("A creator was inserted previously")
  819. self._socket_cache = isc.bind10.socket_cache.Cache(creator)
  820. def init_socket_srv(self):
  821. """
  822. Creates and listens on a unix-domain socket to be able to send out
  823. the sockets.
  824. This method should be called after switching user, or the switched
  825. applications won't be able to access the socket.
  826. """
  827. self._srv_socket = socket.socket(socket.AF_UNIX)
  828. # We create a temporary directory somewhere safe and unique, to avoid
  829. # the need to find the place ourself or bother users. Also, this
  830. # secures the socket on some platforms, as it creates a private
  831. # directory.
  832. self._tmpdir = tempfile.mkdtemp(prefix='sockcreator-')
  833. # Get the name
  834. self._socket_path = os.path.join(self._tmpdir, "sockcreator")
  835. # And bind the socket to the name
  836. self._srv_socket.bind(self._socket_path)
  837. self._srv_socket.listen(5)
  838. def remove_socket_srv(self):
  839. """
  840. Closes and removes the listening socket and the directory where it
  841. lives, as we created both.
  842. It does nothing if the _srv_socket is not set (eg. it was not yet
  843. initialized).
  844. """
  845. if self._srv_socket is not None:
  846. self._srv_socket.close()
  847. if os.path.exists(self._socket_path):
  848. os.remove(self._socket_path)
  849. if os.path.isdir(self._tmpdir):
  850. os.rmdir(self._tmpdir)
  851. def _srv_accept(self):
  852. """
  853. Accept a socket from the unix domain socket server and put it to the
  854. others we care about.
  855. """
  856. (socket, conn) = self._srv_socket.accept()
  857. self._unix_sockets[socket.fileno()] = (socket, b'')
  858. def _socket_data(self, socket_fileno):
  859. """
  860. This is called when a socket identified by the socket_fileno needs
  861. attention. We try to read data from there. If it is closed, we remove
  862. it.
  863. """
  864. (sock, previous) = self._unix_sockets[socket_fileno]
  865. while True:
  866. try:
  867. data = sock.recv(1, socket.MSG_DONTWAIT)
  868. except socket.error as se:
  869. # These two might be different on some systems
  870. if se.errno == errno.EAGAIN or se.errno == errno.EWOULDBLOCK:
  871. # No more data now. Oh, well, just store what we have.
  872. self._unix_sockets[socket_fileno] = (sock, previous)
  873. return
  874. else:
  875. data = b'' # Pretend it got closed
  876. if len(data) == 0: # The socket got to it's end
  877. del self._unix_sockets[socket_fileno]
  878. self.socket_consumer_dead(sock)
  879. sock.close()
  880. return
  881. else:
  882. if data == b"\n":
  883. # Handle this token and clear it
  884. self.socket_request_handler(previous, sock)
  885. previous = b''
  886. else:
  887. previous += data
  888. def run(self, wakeup_fd):
  889. """
  890. The main loop, waiting for sockets, commands and dead processes.
  891. Runs as long as the runnable is true.
  892. The wakeup_fd descriptor is the read end of pipe where CHLD signal
  893. handler writes.
  894. """
  895. ccs_fd = self.ccs.get_socket().fileno()
  896. while self.runnable:
  897. # clean up any processes that exited
  898. self.reap_children()
  899. next_restart = self.restart_processes()
  900. if next_restart is None:
  901. wait_time = None
  902. else:
  903. wait_time = max(next_restart - time.time(), 0)
  904. # select() can raise EINTR when a signal arrives,
  905. # even if they are resumable, so we have to catch
  906. # the exception
  907. try:
  908. (rlist, wlist, xlist) = \
  909. select.select([wakeup_fd, ccs_fd,
  910. self._srv_socket.fileno()] +
  911. list(self._unix_sockets.keys()), [], [],
  912. wait_time)
  913. except select.error as err:
  914. if err.args[0] == errno.EINTR:
  915. (rlist, wlist, xlist) = ([], [], [])
  916. else:
  917. logger.fatal(BIND10_SELECT_ERROR, err)
  918. break
  919. for fd in rlist + xlist:
  920. if fd == ccs_fd:
  921. try:
  922. self.ccs.check_command()
  923. except isc.cc.session.ProtocolError:
  924. logger.fatal(BIND10_MSGQ_DISAPPEARED)
  925. self.runnable = False
  926. break
  927. elif fd == wakeup_fd:
  928. os.read(wakeup_fd, 32)
  929. elif fd == self._srv_socket.fileno():
  930. self._srv_accept()
  931. elif fd in self._unix_sockets:
  932. self._socket_data(fd)
  933. # global variables, needed for signal handlers
  934. options = None
  935. boss_of_bind = None
  936. def reaper(signal_number, stack_frame):
  937. """A child process has died (SIGCHLD received)."""
  938. # don't do anything...
  939. # the Python signal handler has been set up to write
  940. # down a pipe, waking up our select() bit
  941. pass
  942. def get_signame(signal_number):
  943. """Return the symbolic name for a signal."""
  944. for sig in dir(signal):
  945. if sig.startswith("SIG") and sig[3].isalnum():
  946. if getattr(signal, sig) == signal_number:
  947. return sig
  948. return "Unknown signal %d" % signal_number
  949. # XXX: perhaps register atexit() function and invoke that instead
  950. def fatal_signal(signal_number, stack_frame):
  951. """We need to exit (SIGINT or SIGTERM received)."""
  952. global options
  953. global boss_of_bind
  954. logger.info(BIND10_RECEIVED_SIGNAL, get_signame(signal_number))
  955. signal.signal(signal.SIGCHLD, signal.SIG_DFL)
  956. boss_of_bind.runnable = False
  957. def process_rename(option, opt_str, value, parser):
  958. """Function that renames the process if it is requested by a option."""
  959. isc.util.process.rename(value)
  960. def parse_args(args=sys.argv[1:], Parser=OptionParser):
  961. """
  962. Function for parsing command line arguments. Returns the
  963. options object from OptionParser.
  964. """
  965. parser = Parser(version=VERSION)
  966. parser.add_option("-m", "--msgq-socket-file", dest="msgq_socket_file",
  967. type="string", default=None,
  968. help="UNIX domain socket file the b10-msgq daemon will use")
  969. parser.add_option("-i", "--no-kill", action="store_true", dest="nokill",
  970. default=False, help="do not send SIGTERM and SIGKILL signals to modules during shutdown")
  971. parser.add_option("-u", "--user", dest="user", type="string", default=None,
  972. help="Change user after startup (must run as root)")
  973. parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
  974. help="display more about what is going on")
  975. parser.add_option("--pretty-name", type="string", action="callback",
  976. callback=process_rename,
  977. help="Set the process name (displayed in ps, top, ...)")
  978. parser.add_option("-c", "--config-file", action="store",
  979. dest="config_file", default=None,
  980. help="Configuration database filename")
  981. parser.add_option("--clear-config", action="store_true",
  982. dest="clear_config", default=False,
  983. help="Create backup of the configuration file and " +
  984. "start with a clean configuration")
  985. parser.add_option("-p", "--data-path", dest="data_path",
  986. help="Directory to search for configuration files",
  987. default=None)
  988. parser.add_option("--cmdctl-port", dest="cmdctl_port", type="int",
  989. default=None, help="Port of command control")
  990. parser.add_option("--pid-file", dest="pid_file", type="string",
  991. default=None,
  992. help="file to dump the PID of the BIND 10 process")
  993. parser.add_option("-w", "--wait", dest="wait_time", type="int",
  994. default=10, help="Time (in seconds) to wait for config manager to start up")
  995. (options, args) = parser.parse_args(args)
  996. if options.cmdctl_port is not None:
  997. try:
  998. isc.net.parse.port_parse(options.cmdctl_port)
  999. except ValueError as e:
  1000. parser.error(e)
  1001. if args:
  1002. parser.print_help()
  1003. sys.exit(1)
  1004. return options
  1005. def dump_pid(pid_file):
  1006. """
  1007. Dump the PID of the current process to the specified file. If the given
  1008. file is None this function does nothing. If the file already exists,
  1009. the existing content will be removed. If a system error happens in
  1010. creating or writing to the file, the corresponding exception will be
  1011. propagated to the caller.
  1012. """
  1013. if pid_file is None:
  1014. return
  1015. f = open(pid_file, "w")
  1016. f.write('%d\n' % os.getpid())
  1017. f.close()
  1018. def unlink_pid_file(pid_file):
  1019. """
  1020. Remove the given file, which is basically expected to be the PID file
  1021. created by dump_pid(). The specified may or may not exist; if it
  1022. doesn't this function does nothing. Other system level errors in removing
  1023. the file will be propagated as the corresponding exception.
  1024. """
  1025. if pid_file is None:
  1026. return
  1027. try:
  1028. os.unlink(pid_file)
  1029. except OSError as error:
  1030. if error.errno is not errno.ENOENT:
  1031. raise
  1032. def remove_lock_files():
  1033. """
  1034. Remove various lock files which were created by code such as in the
  1035. logger. This function should be called after BIND 10 shutdown.
  1036. """
  1037. lockfiles = ["logger_lockfile"]
  1038. lpath = bind10_config.DATA_PATH
  1039. if "B10_FROM_BUILD" in os.environ:
  1040. lpath = os.environ["B10_FROM_BUILD"]
  1041. if "B10_FROM_SOURCE_LOCALSTATEDIR" in os.environ:
  1042. lpath = os.environ["B10_FROM_SOURCE_LOCALSTATEDIR"]
  1043. if "B10_LOCKFILE_DIR_FROM_BUILD" in os.environ:
  1044. lpath = os.environ["B10_LOCKFILE_DIR_FROM_BUILD"]
  1045. for f in lockfiles:
  1046. fname = lpath + '/' + f
  1047. if os.path.isfile(fname):
  1048. os.unlink(fname)
  1049. return
  1050. def main():
  1051. global options
  1052. global boss_of_bind
  1053. # Enforce line buffering on stdout, even when not a TTY
  1054. sys.stdout = io.TextIOWrapper(sys.stdout.detach(), line_buffering=True)
  1055. options = parse_args()
  1056. # Announce startup. Making this is the first log message.
  1057. try:
  1058. logger.info(BIND10_STARTING, VERSION)
  1059. except RuntimeError as e:
  1060. sys.stderr.write('ERROR: failed to write the initial log: %s\n' %
  1061. str(e))
  1062. sys.stderr.write("""\
  1063. TIP: if this is about permission error for a lock file, check if the directory
  1064. of the file is writable for the user of the bind10 process; often you need
  1065. to start bind10 as a super user. Also, if you specify the -u option to
  1066. change the user and group, the directory must be writable for the group,
  1067. and the created lock file must be writable for that user.
  1068. """)
  1069. sys.exit(1)
  1070. # Check user ID.
  1071. setuid = None
  1072. setgid = None
  1073. username = None
  1074. if options.user:
  1075. # Try getting information about the user, assuming UID passed.
  1076. try:
  1077. pw_ent = pwd.getpwuid(int(options.user))
  1078. setuid = pw_ent.pw_uid
  1079. setgid = pw_ent.pw_gid
  1080. username = pw_ent.pw_name
  1081. except ValueError:
  1082. pass
  1083. except KeyError:
  1084. pass
  1085. # Next try getting information about the user, assuming user name
  1086. # passed.
  1087. # If the information is both a valid user name and user number, we
  1088. # prefer the name because we try it second. A minor point, hopefully.
  1089. try:
  1090. pw_ent = pwd.getpwnam(options.user)
  1091. setuid = pw_ent.pw_uid
  1092. setgid = pw_ent.pw_gid
  1093. username = pw_ent.pw_name
  1094. except KeyError:
  1095. pass
  1096. if setuid is None:
  1097. logger.fatal(BIND10_INVALID_USER, options.user)
  1098. sys.exit(1)
  1099. # Create wakeup pipe for signal handlers
  1100. wakeup_pipe = os.pipe()
  1101. signal.set_wakeup_fd(wakeup_pipe[1])
  1102. # Set signal handlers for catching child termination, as well
  1103. # as our own demise.
  1104. signal.signal(signal.SIGCHLD, reaper)
  1105. signal.siginterrupt(signal.SIGCHLD, False)
  1106. signal.signal(signal.SIGINT, fatal_signal)
  1107. signal.signal(signal.SIGTERM, fatal_signal)
  1108. # Block SIGPIPE, as we don't want it to end this process
  1109. signal.signal(signal.SIGPIPE, signal.SIG_IGN)
  1110. try:
  1111. # Go bob!
  1112. boss_of_bind = BoB(options.msgq_socket_file, options.data_path,
  1113. options.config_file, options.clear_config,
  1114. options.verbose, options.nokill,
  1115. setuid, setgid, username, options.cmdctl_port,
  1116. options.wait_time)
  1117. startup_result = boss_of_bind.startup()
  1118. if startup_result:
  1119. logger.fatal(BIND10_STARTUP_ERROR, startup_result)
  1120. sys.exit(1)
  1121. boss_of_bind.init_socket_srv()
  1122. logger.info(BIND10_STARTUP_COMPLETE)
  1123. dump_pid(options.pid_file)
  1124. # Let it run
  1125. boss_of_bind.run(wakeup_pipe[0])
  1126. # shutdown
  1127. signal.signal(signal.SIGCHLD, signal.SIG_DFL)
  1128. boss_of_bind.shutdown()
  1129. finally:
  1130. # Clean up the filesystem
  1131. unlink_pid_file(options.pid_file)
  1132. remove_lock_files()
  1133. if boss_of_bind is not None:
  1134. boss_of_bind.remove_socket_srv()
  1135. sys.exit(boss_of_bind.exitcode)
  1136. if __name__ == "__main__":
  1137. main()