bind10_src.py.in 47 KB

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