bind10_src.py.in 46 KB

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