bind10_src.py.in 48 KB

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