bind10.py.in 18 KB

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