bind10.py.in 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. #!@PYTHON@
  2. import sys; sys.path.append ('@@PYTHONPATH@@')
  3. import os
  4. """\
  5. This file implements the Boss of Bind (BoB, or bob) program.
  6. It's purpose is to start up the BIND 10 system, and then manage the
  7. processes, by starting and stopping processes, plus restarting
  8. processes that exit.
  9. To start the system, it first runs the c-channel program (msgq), then
  10. connects to that. It then runs the configuration manager, and reads
  11. its own configuration. Then it proceeds to starting other modules.
  12. The Python subprocess module is used for starting processes, but
  13. because this is not efficient for managing groups of processes,
  14. SIGCHLD signals are caught and processed using the signal module.
  15. Most of the logic is contained in the BoB class. However, since Python
  16. requires that signal processing happen in the main thread, we do
  17. signal handling outside of that class, in the code running for
  18. __main__.
  19. """
  20. # If B10_FROM_SOURCE is set in the environment, we use data files
  21. # from a directory relative to that, otherwise we use the ones
  22. # installed on the system
  23. if "B10_FROM_SOURCE" in os.environ:
  24. SPECFILE_LOCATION = os.environ["B10_FROM_SOURCE"] + "/src/bin/bind10/bob.spec"
  25. else:
  26. PREFIX = "@prefix@"
  27. DATAROOTDIR = "@datarootdir@"
  28. SPECFILE_LOCATION = "@datadir@/@PACKAGE@/bob.spec".replace("${datarootdir}", DATAROOTDIR).replace("${prefix}", PREFIX)
  29. # TODO: start up statistics thingy
  30. import subprocess
  31. import signal
  32. import os
  33. import re
  34. import errno
  35. import time
  36. import select
  37. import pprint
  38. from optparse import OptionParser, OptionValueError
  39. import isc.cc
  40. import isc
  41. # This is the version that gets displayed to the user.
  42. __version__ = "v20091030 (Paving the DNS Parking Lot)"
  43. # Nothing at all to do with the 1990-12-10 article here:
  44. # http://www.subgenius.com/subg-digest/v2/0056.html
  45. class ProcessInfo:
  46. """Information about a process"""
  47. dev_null = open("/dev/null", "w")
  48. def _spawn(self):
  49. if self.dev_null_stdout:
  50. spawn_stdout = self.dev_null
  51. else:
  52. spawn_stdout = None
  53. spawn_env = self.env
  54. spawn_env['PATH'] = os.environ['PATH']
  55. if 'B10_FROM_SOURCE' in os.environ:
  56. spawn_env['B10_FROM_SOURCE'] = os.environ['B10_FROM_SOURCE']
  57. else:
  58. spawn_env['PATH'] = "@@LIBEXECDIR@@:" + spawn_env['PATH']
  59. if 'PYTHON_EXEC' in os.environ:
  60. spawn_env['PYTHON_EXEC'] = os.environ['PYTHON_EXEC']
  61. if 'PYTHONPATH' in os.environ:
  62. spawn_env['PYTHONPATH'] = os.environ['PYTHONPATH']
  63. self.process = subprocess.Popen(self.args,
  64. stdin=subprocess.PIPE,
  65. stdout=spawn_stdout,
  66. stderr=spawn_stdout,
  67. close_fds=True,
  68. env=spawn_env,)
  69. self.pid = self.process.pid
  70. def __init__(self, name, args, env={}, dev_null_stdout=False):
  71. self.name = name
  72. self.args = args
  73. self.env = env
  74. self.dev_null_stdout = dev_null_stdout
  75. self._spawn()
  76. def respawn(self):
  77. self._spawn()
  78. class BoB:
  79. """Boss of BIND class."""
  80. def __init__(self, c_channel_port=9912, verbose=False):
  81. """Initialize the Boss of BIND. This is a singleton (only one
  82. can run).
  83. The c_channel_port specifies the TCP/IP port that the msgq
  84. process listens on. If verbose is True, then the boss reports
  85. what it is doing.
  86. """
  87. self.verbose = verbose
  88. self.c_channel_port = c_channel_port
  89. self.cc_session = None
  90. self.ccs = None
  91. self.processes = {}
  92. self.dead_processes = {}
  93. self.runnable = False
  94. def config_handler(self, new_config):
  95. if self.verbose:
  96. print("[XX] handling new config:")
  97. print(new_config)
  98. errors = []
  99. if self.ccs.get_config_data().get_specification().validate(False, new_config, errors):
  100. print("[XX] new config validated")
  101. self.ccs.set_config(new_config)
  102. answer = isc.config.ccsession.create_answer(0)
  103. else:
  104. print("[XX] new config validation failure")
  105. if len(errors) > 0:
  106. answer = isc.config.ccsession.create_answer(1, " ".join(errors))
  107. else:
  108. answer = isc.config.ccsession.create_answer(1, "Unknown error in validation")
  109. return answer
  110. # TODO
  111. def command_handler(self, command):
  112. # a command is of the form [ "command", { "arg1": arg1, "arg2": arg2 } ]
  113. if self.verbose:
  114. print("[XX] Boss got command:")
  115. print(command)
  116. answer = [ 1, "Command not implemented" ]
  117. if type(command) != list or len(command) == 0:
  118. answer = isc.config.ccsession.create_answer(1, "bad command")
  119. else:
  120. cmd = command[0]
  121. if cmd == "shutdown":
  122. print("[XX] got shutdown command")
  123. self.runnable = False
  124. answer = isc.config.ccsession.create_answer(0)
  125. elif cmd == "print_message":
  126. if len(command) > 1 and type(command[1]) == dict and "message" in command[1]:
  127. print(command[1]["message"])
  128. answer = isc.config.ccsession.create_answer(0)
  129. elif cmd == "print_settings":
  130. print("Config:")
  131. print(self.ccs.get_config())
  132. answer = isc.config.ccsession.create_answer(0)
  133. else:
  134. answer = isc.config.ccsession.create_answer(1, "Unknown command")
  135. return answer
  136. def startup(self):
  137. """Start the BoB instance.
  138. Returns None if successful, otherwise an string describing the
  139. problem.
  140. """
  141. # start the c-channel daemon
  142. if self.verbose:
  143. sys.stdout.write("Starting msgq using port %d\n" %
  144. self.c_channel_port)
  145. c_channel_env = { "ISC_MSGQ_PORT": str(self.c_channel_port), }
  146. try:
  147. c_channel = ProcessInfo("msgq", "msgq", c_channel_env, True)
  148. except Exception as e:
  149. return "Unable to start msgq; " + str(e)
  150. self.processes[c_channel.pid] = c_channel
  151. if self.verbose:
  152. sys.stdout.write("Started msgq (PID %d)\n" % c_channel.pid)
  153. # now connect to the c-channel
  154. cc_connect_start = time.time()
  155. while self.cc_session is None:
  156. # if we have been trying for "a while" give up
  157. if (time.time() - cc_connect_start) > 5:
  158. c_channel.process.kill()
  159. return "Unable to connect to c-channel after 5 seconds"
  160. # try to connect, and if we can't wait a short while
  161. try:
  162. self.cc_session = isc.cc.Session(self.c_channel_port)
  163. except isc.cc.session.SessionError:
  164. time.sleep(0.1)
  165. #self.cc_session.group_subscribe("Boss", "boss")
  166. # start the configuration manager
  167. if self.verbose:
  168. sys.stdout.write("Starting b10-cfgmgr\n")
  169. try:
  170. bind_cfgd = ProcessInfo("b10-cfgmgr", "b10-cfgmgr")
  171. except Exception as e:
  172. c_channel.process.kill()
  173. return "Unable to start b10-cfgmgr; " + str(e)
  174. self.processes[bind_cfgd.pid] = bind_cfgd
  175. if self.verbose:
  176. sys.stdout.write("Started b10-cfgmgr (PID %d)\n" % bind_cfgd.pid)
  177. # TODO: once this interface is done, replace self.cc_session
  178. # by this one
  179. # sleep until b10-cfgmgr is fully up and running, this is a good place
  180. # to have a (short) timeout on synchronized groupsend/receive
  181. time.sleep(1)
  182. if self.verbose:
  183. print("[XX] starting ccsession")
  184. self.ccs = isc.config.CCSession(SPECFILE_LOCATION, self.config_handler, self.command_handler)
  185. self.ccs.start()
  186. if self.verbose:
  187. print("[XX] ccsession started")
  188. # start the parking lot
  189. # XXX: this must be read from the configuration manager in the future
  190. # XXX: we hardcode port 5300
  191. if self.verbose:
  192. sys.stdout.write("Starting b10-auth on port 5300\n")
  193. try:
  194. auth = ProcessInfo("b10-auth", ["b10-auth", "-p", "5300"])
  195. except Exception as e:
  196. c_channel.process.kill()
  197. bind_cfgd.process.kill()
  198. return "Unable to start b10-auth; " + str(e)
  199. self.processes[auth.pid] = auth
  200. if self.verbose:
  201. sys.stdout.write("Started b10-auth (PID %d)\n" % auth.pid)
  202. # start the b10-cmdctl
  203. # XXX: we hardcode port 8080
  204. if self.verbose:
  205. sys.stdout.write("Starting b10-cmdctl on port 8080\n")
  206. try:
  207. cmd_ctrld = ProcessInfo("b10-cmdctl", ['b10-cmdctl'])
  208. except Exception as e:
  209. c_channel.process.kill()
  210. bind_cfgd.process.kill()
  211. auth.process.kill()
  212. return "Unable to start b10-cmdctl; " + str(e)
  213. self.processes[cmd_ctrld.pid] = cmd_ctrld
  214. if self.verbose:
  215. sys.stdout.write("Started b10-cmdctl (PID %d)\n" % cmd_ctrld.pid)
  216. self.runnable = True
  217. return None
  218. def stop_all_processes(self):
  219. """Stop all processes."""
  220. cmd = { "command": ['shutdown']}
  221. self.cc_session.group_sendmsg(cmd, 'Boss', 'Cmd-Ctrld')
  222. self.cc_session.group_sendmsg(cmd, "Boss", "ConfigManager")
  223. self.cc_session.group_sendmsg(cmd, "Boss", "ParkingLot")
  224. def stop_process(self, process):
  225. """Stop the given process, friendly-like."""
  226. # XXX nothing yet
  227. pass
  228. def shutdown(self):
  229. """Stop the BoB instance."""
  230. if self.verbose:
  231. sys.stdout.write("Stopping the server.\n")
  232. # first try using the BIND 10 request to stop
  233. try:
  234. self.stop_all_processes()
  235. except:
  236. pass
  237. # XXX: some delay probably useful... how much is uncertain
  238. time.sleep(0.1)
  239. self.reap_children()
  240. # next try sending a SIGTERM
  241. processes_to_stop = list(self.processes.values())
  242. unstopped_processes = []
  243. for proc_info in processes_to_stop:
  244. if self.verbose:
  245. sys.stdout.write("Sending SIGTERM to %s (PID %d).\n" %
  246. (proc_info.name, proc_info.pid))
  247. try:
  248. proc_info.process.terminate()
  249. except OSError as o:
  250. # ignore these (usually ESRCH because the child
  251. # finally exited)
  252. pass
  253. # XXX: some delay probably useful... how much is uncertain
  254. time.sleep(0.1)
  255. self.reap_children()
  256. # finally, send a SIGKILL (unmaskable termination)
  257. processes_to_stop = unstopped_processes
  258. for proc_info in processes_to_stop:
  259. if self.verbose:
  260. sys.stdout.write("Sending SIGKILL to %s (PID %d).\n" %
  261. (proc_info.name, proc_info.pid))
  262. try:
  263. proc_info.process.kill()
  264. except OSError as o:
  265. # ignore these (usually ESRCH because the child
  266. # finally exited)
  267. pass
  268. if self.verbose:
  269. sys.stdout.write("All processes ended, server done.\n")
  270. def reap_children(self):
  271. """Check to see if any of our child processes have exited,
  272. and note this for later handling.
  273. """
  274. while True:
  275. try:
  276. (pid, exit_status) = os.waitpid(-1, os.WNOHANG)
  277. except OSError as o:
  278. if o.errno == errno.ECHILD: break
  279. # XXX: should be impossible to get any other error here
  280. raise
  281. if pid == 0: break
  282. if pid in self.processes:
  283. proc_info = self.processes.pop(pid)
  284. self.dead_processes[proc_info.pid] = proc_info
  285. if self.verbose:
  286. sys.stdout.write("Process %s (PID %d) died.\n" %
  287. (proc_info.name, proc_info.pid))
  288. if proc_info.name == "msgq":
  289. if self.verbose:
  290. sys.stdout.write(
  291. "The msgq process died, shutting down.\n")
  292. self.runnable = False
  293. else:
  294. sys.stdout.write("Unknown child pid %d exited.\n" % pid)
  295. # 'old' command style, uncommented for now
  296. # move the handling below move to command_handler please
  297. #def recv_and_process_cc_msg(self):
  298. #"""Receive and process the next message on the c-channel,
  299. #if any."""
  300. #self.ccs.checkCommand()
  301. #msg, envelope = self.cc_session.group_recvmsg(False)
  302. #print(msg)
  303. #if msg is None:
  304. # return
  305. #if not ((type(msg) is dict) and (type(envelope) is dict)):
  306. # if self.verbose:
  307. # sys.stdout.write("Non-dictionary message\n")
  308. # return
  309. #if not "command" in msg:
  310. # if self.verbose:
  311. # if "msg" in envelope:
  312. # del envelope['msg']
  313. # sys.stdout.write("Unknown message received\n")
  314. # sys.stdout.write(pprint.pformat(envelope) + "\n")
  315. # sys.stdout.write(pprint.pformat(msg) + "\n")
  316. # return
  317. #cmd = msg['command']
  318. #if not (type(cmd) is list):
  319. # if self.verbose:
  320. # sys.stdout.write("Non-list command\n")
  321. # return
  322. #
  323. # done checking and extracting... time to execute the command
  324. #if cmd[0] == "shutdown":
  325. # if self.verbose:
  326. # sys.stdout.write("shutdown command received\n")
  327. # self.runnable = False
  328. # # XXX: reply here?
  329. #elif cmd[0] == "getProcessList":
  330. # if self.verbose:
  331. # sys.stdout.write("getProcessList command received\n")
  332. # live_processes = [ ]
  333. # for proc_info in processes:
  334. # live_processes.append({ "name": proc_info.name,
  335. # "args": proc_info.args,
  336. # "pid": proc_info.pid, })
  337. # dead_processes = [ ]
  338. # for proc_info in dead_processes:
  339. # dead_processes.append({ "name": proc_info.name,
  340. # "args": proc_info.args, })
  341. # cc.group_reply(envelope, { "response": cmd,
  342. # "sent": msg["sent"],
  343. # "live_processes": live_processes,
  344. # "dead_processes": dead_processes, })
  345. #else:
  346. # if self.verbose:
  347. # sys.stdout.write("Unknown command %s\n" % str(cmd))
  348. def restart_processes(self):
  349. """Restart any dead processes."""
  350. # XXX: this needs a back-off algorithm
  351. # if we're shutting down, then don't restart
  352. if not self.runnable:
  353. return
  354. # otherwise look through each dead process and try to restart
  355. still_dead = {}
  356. for proc_info in self.dead_processes.values():
  357. if self.verbose:
  358. sys.stdout.write("Resurrecting dead %s process...\n" %
  359. proc_info.name)
  360. try:
  361. proc_info.respawn()
  362. self.processes[proc_info.pid] = proc_info
  363. if self.verbose:
  364. sys.stdout.write("Resurrected %s (PID %d)\n" %
  365. (proc_info.name, proc_info.pid))
  366. except:
  367. still_dead[proc_info.pid] = proc_info
  368. # remember any processes that refuse to be resurrected
  369. self.dead_processes = still_dead
  370. def reaper(signal_number, stack_frame):
  371. """A child process has died (SIGCHLD received)."""
  372. # don't do anything...
  373. # the Python signal handler has been set up to write
  374. # down a pipe, waking up our select() bit
  375. pass
  376. def get_signame(signal_number):
  377. """Return the symbolic name for a signal."""
  378. for sig in dir(signal):
  379. if sig.startswith("SIG") and sig[3].isalnum():
  380. if getattr(signal, sig) == signal_number:
  381. return sig
  382. return "Unknown signal %d" % signal_number
  383. # XXX: perhaps register atexit() function and invoke that instead
  384. def fatal_signal(signal_number, stack_frame):
  385. """We need to exit (SIGINT or SIGTERM received)."""
  386. global options
  387. global boss_of_bind
  388. if options.verbose:
  389. sys.stdout.write("Received %s.\n" % get_signame(signal_number))
  390. signal.signal(signal.SIGCHLD, signal.SIG_DFL)
  391. boss_of_bind.runnable = False
  392. def check_port(option, opt_str, value, parser):
  393. """Function to insure that the port we are passed is actually
  394. a valid port number. Used by OptionParser() on startup."""
  395. if not re.match('^(6553[0-5]|655[0-2]\d|65[0-4]\d\d|6[0-4]\d{3}|[1-5]\d{4}|[1-9]\d{0,3}|0)$', value):
  396. raise OptionValueError("%s requires a port number (0-65535)" % opt_str)
  397. parser.values.msgq_port = value
  398. def main():
  399. global options
  400. global boss_of_bind
  401. # Parse any command-line options.
  402. parser = OptionParser(version=__version__)
  403. parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
  404. help="display more about what is going on")
  405. parser.add_option("-m", "--msgq-port", dest="msgq_port", type="string",
  406. action="callback", callback=check_port, default="9912",
  407. help="port the msgq daemon will use")
  408. (options, args) = parser.parse_args()
  409. # Announce startup.
  410. if options.verbose:
  411. sys.stdout.write("BIND 10 %s\n" % __version__)
  412. # TODO: set process name, perhaps by:
  413. # http://code.google.com/p/procname/
  414. # http://github.com/lericson/procname/
  415. # Create wakeup pipe for signal handlers
  416. wakeup_pipe = os.pipe()
  417. signal.set_wakeup_fd(wakeup_pipe[1])
  418. # Set signal handlers for catching child termination, as well
  419. # as our own demise.
  420. signal.signal(signal.SIGCHLD, reaper)
  421. signal.siginterrupt(signal.SIGCHLD, False)
  422. signal.signal(signal.SIGINT, fatal_signal)
  423. signal.signal(signal.SIGTERM, fatal_signal)
  424. # Go bob!
  425. boss_of_bind = BoB(int(options.msgq_port), options.verbose)
  426. startup_result = boss_of_bind.startup()
  427. if startup_result:
  428. sys.stderr.write("Error on startup: %s\n" % startup_result)
  429. sys.exit(1)
  430. # In our main loop, we check for dead processes or messages
  431. # on the c-channel.
  432. wakeup_fd = wakeup_pipe[0]
  433. ccs_fd = boss_of_bind.ccs.get_socket().fileno()
  434. while boss_of_bind.runnable:
  435. # XXX: get time for next restart for timeout
  436. # select() can raise EINTR when a signal arrives,
  437. # even if they are resumable, so we have to catch
  438. # the exception
  439. try:
  440. (rlist, wlist, xlist) = select.select([wakeup_fd, ccs_fd], [], [])
  441. except select.error as err:
  442. if err.args[0] == errno.EINTR:
  443. (rlist, wlist, xlist) = ([], [], [])
  444. else:
  445. sys.stderr.write("Error with select(); %s\n" % err)
  446. break
  447. for fd in rlist + xlist:
  448. if fd == ccs_fd:
  449. boss_of_bind.ccs.check_command()
  450. elif fd == wakeup_fd:
  451. os.read(wakeup_fd, 32)
  452. # clean up any processes that exited
  453. boss_of_bind.reap_children()
  454. boss_of_bind.restart_processes()
  455. # shutdown
  456. signal.signal(signal.SIGCHLD, signal.SIG_DFL)
  457. boss_of_bind.shutdown()
  458. if __name__ == "__main__":
  459. main()