msgq.py.in 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. #!@PYTHON@
  2. # Copyright (C) 2010 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. import sys; sys.path.append ('@@PYTHONPATH@@')
  17. """This code implements the msgq daemon."""
  18. import subprocess
  19. import signal
  20. import os
  21. import socket
  22. import sys
  23. import struct
  24. import errno
  25. import time
  26. import select
  27. import pprint
  28. import random
  29. from optparse import OptionParser, OptionValueError
  30. import isc.util.process
  31. import isc.cc
  32. isc.util.process.rename()
  33. # This is the version that gets displayed to the user.
  34. # The VERSION string consists of the module name, the module version
  35. # number, and the overall BIND 10 version number (set in configure.ac).
  36. VERSION = "b10-msgq 20100818 (BIND 10 @PACKAGE_VERSION@)"
  37. class MsgQReceiveError(Exception): pass
  38. class SubscriptionManager:
  39. def __init__(self):
  40. self.subscriptions = {}
  41. def subscribe(self, group, instance, socket):
  42. """Add a subscription."""
  43. target = ( group, instance )
  44. if target in self.subscriptions:
  45. print("[b10-msgq] Appending to existing target")
  46. if socket not in self.subscriptions[target]:
  47. self.subscriptions[target].append(socket)
  48. else:
  49. print("[b10-msgq] Creating new target")
  50. self.subscriptions[target] = [ socket ]
  51. def unsubscribe(self, group, instance, socket):
  52. """Remove the socket from the one specific subscription."""
  53. target = ( group, instance )
  54. if target in self.subscriptions:
  55. if socket in self.subscriptions[target]:
  56. self.subscriptions[target].remove(socket)
  57. def unsubscribe_all(self, socket):
  58. """Remove the socket from all subscriptions."""
  59. for socklist in self.subscriptions.values():
  60. if socket in socklist:
  61. socklist.remove(socket)
  62. def find_sub(self, group, instance):
  63. """Return an array of sockets which want this specific group,
  64. instance."""
  65. target = (group, instance)
  66. if target in self.subscriptions:
  67. return self.subscriptions[target]
  68. else:
  69. return []
  70. def find(self, group, instance):
  71. """Return an array of sockets who should get something sent to
  72. this group, instance pair. This includes wildcard subscriptions."""
  73. target = (group, instance)
  74. partone = self.find_sub(group, instance)
  75. parttwo = self.find_sub(group, "*")
  76. return list(set(partone + parttwo))
  77. class MsgQ:
  78. """Message Queue class."""
  79. # did we find a better way to do this?
  80. SOCKET_FILE = os.path.join("@localstatedir@",
  81. "@PACKAGE_NAME@",
  82. "msgq_socket").replace("${prefix}",
  83. "@prefix@")
  84. def __init__(self, socket_file=None, verbose=False):
  85. """Initialize the MsgQ master.
  86. The socket_file specifies the path to the UNIX domain socket
  87. that the msgq process listens on. If it is None, the
  88. environment variable BIND10_MSGQ_SOCKET_FILE is used. If that
  89. is not set, it will default to
  90. @localstatedir@/@PACKAGE_NAME@/msg_socket.
  91. If verbose is True, then the MsgQ reports
  92. what it is doing.
  93. """
  94. if socket_file is None:
  95. if "BIND10_MSGQ_SOCKET_FILE" in os.environ:
  96. self.socket_file = os.environ["BIND10_MSGQ_SOCKET_FILE"]
  97. else:
  98. self.socket_file = self.SOCKET_FILE
  99. else:
  100. self.socket_file = socket_file
  101. self.verbose = verbose
  102. self.poller = None
  103. self.kqueue = None
  104. self.runnable = False
  105. self.listen_socket = False
  106. self.sockets = {}
  107. self.connection_counter = random.random()
  108. self.hostname = socket.gethostname()
  109. self.subs = SubscriptionManager()
  110. self.lnames = {}
  111. def setup_poller(self):
  112. """Set up the poll thing. Internal function."""
  113. try:
  114. self.poller = select.poll()
  115. except AttributeError:
  116. self.kqueue = select.kqueue()
  117. def add_kqueue_socket(self, socket):
  118. event = select.kevent(socket.fileno(),
  119. select.KQ_FILTER_READ,
  120. select.KQ_EV_ADD | select.KQ_EV_ENABLE)
  121. self.kqueue.control([event], 0)
  122. def setup_listener(self):
  123. """Set up the listener socket. Internal function."""
  124. if self.verbose:
  125. sys.stdout.write("[b10-msgq] Setting up socket at %s\n" %
  126. self.socket_file)
  127. self.listen_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  128. if os.path.exists(self.socket_file):
  129. os.remove(self.socket_file)
  130. try:
  131. self.listen_socket.bind(self.socket_file)
  132. self.listen_socket.listen(1024)
  133. except Exception as e:
  134. # remove the file again if something goes wrong
  135. # (note this is a catch-all, but we reraise it)
  136. if os.path.exists(self.socket_file):
  137. os.remove(self.socket_file)
  138. raise e
  139. if self.poller:
  140. self.poller.register(self.listen_socket, select.POLLIN)
  141. else:
  142. self.add_kqueue_socket(self.listen_socket)
  143. def setup(self):
  144. """Configure listener socket, polling, etc.
  145. Raises a socket.error if the socket_file cannot be
  146. created.
  147. """
  148. self.setup_poller()
  149. self.setup_listener()
  150. if self.verbose:
  151. sys.stdout.write("[b10-msgq] Listening\n")
  152. self.runnable = True
  153. def process_accept(self):
  154. """Process an accept on the listening socket."""
  155. newsocket, ipaddr = self.listen_socket.accept()
  156. # TODO: When we have logging, we might want
  157. # to add a debug message here that a new connection
  158. # was made
  159. self.sockets[newsocket.fileno()] = newsocket
  160. lname = self.newlname()
  161. self.lnames[lname] = newsocket
  162. if self.poller:
  163. self.poller.register(newsocket, select.POLLIN)
  164. else:
  165. self.add_kqueue_socket(newsocket)
  166. def process_socket(self, fd):
  167. """Process a read on a socket."""
  168. sock = self.sockets[fd]
  169. if sock == None:
  170. sys.stderr.write("[b10-msgq] Got read on Strange Socket fd %d\n" % fd)
  171. return
  172. # sys.stderr.write("[b10-msgq] Got read on fd %d\n" %fd)
  173. self.process_packet(fd, sock)
  174. def kill_socket(self, fd, sock):
  175. """Fully close down the socket."""
  176. if self.poller:
  177. self.poller.unregister(sock)
  178. self.subs.unsubscribe_all(sock)
  179. lname = [ k for k, v in self.lnames.items() if v == sock ][0]
  180. del self.lnames[lname]
  181. sock.close()
  182. self.sockets[fd] = None
  183. sys.stderr.write("[b10-msgq] Closing socket fd %d\n" % fd)
  184. def getbytes(self, fd, sock, length):
  185. """Get exactly the requested bytes, or raise an exception if
  186. EOF."""
  187. received = b''
  188. while len(received) < length:
  189. try:
  190. data = sock.recv(length - len(received))
  191. except socket.error:
  192. raise MsgQReceiveError(socket.error)
  193. if len(data) == 0:
  194. raise MsgQReceiveError("EOF")
  195. received += data
  196. return received
  197. def read_packet(self, fd, sock):
  198. """Read a correctly formatted packet. Will raise exceptions if
  199. something fails."""
  200. lengths = self.getbytes(fd, sock, 6)
  201. overall_length, routing_length = struct.unpack(">IH", lengths)
  202. if overall_length < 2:
  203. raise MsgQReceiveError("overall_length < 2")
  204. overall_length -= 2
  205. if routing_length > overall_length:
  206. raise MsgQReceiveError("routing_length > overall_length")
  207. if routing_length == 0:
  208. raise MsgQReceiveError("routing_length == 0")
  209. data_length = overall_length - routing_length
  210. # probably need to sanity check lengths here...
  211. routing = self.getbytes(fd, sock, routing_length)
  212. if data_length > 0:
  213. data = self.getbytes(fd, sock, data_length)
  214. else:
  215. data = None
  216. return (routing, data)
  217. def process_packet(self, fd, sock):
  218. """Process one packet."""
  219. try:
  220. routing, data = self.read_packet(fd, sock)
  221. except MsgQReceiveError as err:
  222. self.kill_socket(fd, sock)
  223. sys.stderr.write("[b10-msgq] Receive error: %s\n" % err)
  224. return
  225. try:
  226. routingmsg = isc.cc.message.from_wire(routing)
  227. except DecodeError as err:
  228. self.kill_socket(fd, sock)
  229. sys.stderr.write("[b10-msgq] Routing decode error: %s\n" % err)
  230. return
  231. # sys.stdout.write("\t" + pprint.pformat(routingmsg) + "\n")
  232. # sys.stdout.write("\t" + pprint.pformat(data) + "\n")
  233. self.process_command(fd, sock, routingmsg, data)
  234. def process_command(self, fd, sock, routing, data):
  235. """Process a single command. This will split out into one of the
  236. other functions."""
  237. # TODO: A print statement got removed here (one that prints the
  238. # routing envelope). When we have logging with multiple levels,
  239. # we might want to re-add that on a high debug verbosity.
  240. cmd = routing["type"]
  241. if cmd == 'send':
  242. self.process_command_send(sock, routing, data)
  243. elif cmd == 'subscribe':
  244. self.process_command_subscribe(sock, routing, data)
  245. elif cmd == 'unsubscribe':
  246. self.process_command_unsubscribe(sock, routing, data)
  247. elif cmd == 'getlname':
  248. self.process_command_getlname(sock, routing, data)
  249. else:
  250. sys.stderr.write("[b10-msgq] Invalid command: %s\n" % cmd)
  251. def preparemsg(self, env, msg = None):
  252. if type(env) == dict:
  253. env = isc.cc.message.to_wire(env)
  254. if type(msg) == dict:
  255. msg = isc.cc.message.to_wire(msg)
  256. length = 2 + len(env);
  257. if msg:
  258. length += len(msg)
  259. ret = struct.pack("!IH", length, len(env))
  260. ret += env
  261. if msg:
  262. ret += msg
  263. return ret
  264. def sendmsg(self, sock, env, msg = None):
  265. sock.send(self.preparemsg(env, msg))
  266. def send_prepared_msg(self, sock, msg):
  267. sock.send(msg)
  268. def newlname(self):
  269. """Generate a unique connection identifier for this socket.
  270. This is done by using an increasing counter and the current
  271. time."""
  272. self.connection_counter += 1
  273. return "%x_%x@%s" % (time.time(), self.connection_counter, self.hostname)
  274. def process_command_getlname(self, sock, routing, data):
  275. lname = [ k for k, v in self.lnames.items() if v == sock ][0]
  276. self.sendmsg(sock, { "type" : "getlname" }, { "lname" : lname })
  277. def process_command_send(self, sock, routing, data):
  278. group = routing["group"]
  279. instance = routing["instance"]
  280. to = routing["to"]
  281. if group == None or instance == None:
  282. return # ignore invalid packets entirely
  283. if to == "*":
  284. sockets = self.subs.find(group, instance)
  285. else:
  286. if to in self.lnames:
  287. sockets = [ self.lnames[to] ]
  288. else:
  289. return # recipient doesn't exist
  290. msg = self.preparemsg(routing, data)
  291. if sock in sockets:
  292. sockets.remove(sock)
  293. for socket in sockets:
  294. self.send_prepared_msg(socket, msg)
  295. def process_command_subscribe(self, sock, routing, data):
  296. group = routing["group"]
  297. instance = routing["instance"]
  298. if group == None or instance == None:
  299. return # ignore invalid packets entirely
  300. self.subs.subscribe(group, instance, sock)
  301. def process_command_unsubscribe(self, sock, routing, data):
  302. group = routing["group"]
  303. instance = routing["instance"]
  304. if group == None or instance == None:
  305. return # ignore invalid packets entirely
  306. self.subs.unsubscribe(group, instance, sock)
  307. def run(self):
  308. """Process messages. Forever. Mostly."""
  309. if self.poller:
  310. self.run_poller()
  311. else:
  312. self.run_kqueue()
  313. def run_poller(self):
  314. while True:
  315. try:
  316. events = self.poller.poll()
  317. except select.error as err:
  318. if err.args[0] == errno.EINTR:
  319. events = []
  320. else:
  321. sys.stderr.write("[b10-msgq] Error with poll(): %s\n" % err)
  322. break
  323. for (fd, event) in events:
  324. if fd == self.listen_socket.fileno():
  325. self.process_accept()
  326. else:
  327. self.process_socket(fd)
  328. def run_kqueue(self):
  329. while True:
  330. events = self.kqueue.control(None, 10)
  331. if not events:
  332. raise RuntimeError('serve: kqueue returned no events')
  333. for event in events:
  334. if event.ident == self.listen_socket.fileno():
  335. self.process_accept()
  336. else:
  337. if event.flags & select.KQ_FILTER_READ and event.data > 0:
  338. self.process_socket(event.ident)
  339. elif event.flags & select.KQ_EV_EOF:
  340. self.kill_socket(event.ident, self.sockets[event.ident])
  341. def shutdown(self):
  342. """Stop the MsgQ master."""
  343. if self.verbose:
  344. sys.stdout.write("[b10-msgq] Stopping the server.\n")
  345. self.listen_socket.close()
  346. if os.path.exists(self.socket_file):
  347. os.remove(self.socket_file)
  348. # can signal handling and calling a destructor be done without a
  349. # global variable?
  350. msgq = None
  351. def signal_handler(signal, frame):
  352. if msgq:
  353. msgq.shutdown()
  354. sys.exit(0)
  355. if __name__ == "__main__":
  356. def check_port(option, opt_str, value, parser):
  357. """Function to insure that the port we are passed is actually
  358. a valid port number. Used by OptionParser() on startup."""
  359. intval = int(value)
  360. if (intval < 0) or (intval > 65535):
  361. raise OptionValueError("%s requires a port number (0-65535)" % opt_str)
  362. parser.values.msgq_port = intval
  363. # Parse any command-line options.
  364. parser = OptionParser(version=VERSION)
  365. parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
  366. help="display more about what is going on")
  367. parser.add_option("-s", "--socket-file", dest="msgq_socket_file",
  368. type="string", default=None,
  369. help="UNIX domain socket file the msgq daemon will use")
  370. (options, args) = parser.parse_args()
  371. signal.signal(signal.SIGTERM, signal_handler)
  372. # Announce startup.
  373. if options.verbose:
  374. sys.stdout.write("[b10-msgq] %s\n" % VERSION)
  375. msgq = MsgQ(options.msgq_socket_file, options.verbose)
  376. setup_result = msgq.setup()
  377. if setup_result:
  378. sys.stderr.write("[b10-msgq] Error on startup: %s\n" % setup_result)
  379. sys.exit(1)
  380. try:
  381. msgq.run()
  382. except KeyboardInterrupt:
  383. pass
  384. msgq.shutdown()