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