msgq.py.in 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  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 random
  28. from optparse import OptionParser, OptionValueError
  29. import isc.util.process
  30. import isc.cc
  31. isc.util.process.rename()
  32. # This is the version that gets displayed to the user.
  33. # The VERSION string consists of the module name, the module version
  34. # number, and the overall BIND 10 version number (set in configure.ac).
  35. VERSION = "b10-msgq 20110127 (BIND 10 @PACKAGE_VERSION@)"
  36. class MsgQReceiveError(Exception): pass
  37. class SubscriptionManager:
  38. def __init__(self):
  39. self.subscriptions = {}
  40. def subscribe(self, group, instance, socket):
  41. """Add a subscription."""
  42. target = ( group, instance )
  43. if target in self.subscriptions:
  44. print("[b10-msgq] Appending to existing target")
  45. if socket not in self.subscriptions[target]:
  46. self.subscriptions[target].append(socket)
  47. else:
  48. print("[b10-msgq] Creating new target")
  49. self.subscriptions[target] = [ socket ]
  50. def unsubscribe(self, group, instance, socket):
  51. """Remove the socket from the one specific subscription."""
  52. target = ( group, instance )
  53. if target in self.subscriptions:
  54. if socket in self.subscriptions[target]:
  55. self.subscriptions[target].remove(socket)
  56. def unsubscribe_all(self, socket):
  57. """Remove the socket from all subscriptions."""
  58. for socklist in self.subscriptions.values():
  59. if socket in socklist:
  60. socklist.remove(socket)
  61. def find_sub(self, group, instance):
  62. """Return an array of sockets which want this specific group,
  63. instance."""
  64. target = (group, instance)
  65. if target in self.subscriptions:
  66. return self.subscriptions[target]
  67. else:
  68. return []
  69. def find(self, group, instance):
  70. """Return an array of sockets who should get something sent to
  71. this group, instance pair. This includes wildcard subscriptions."""
  72. target = (group, instance)
  73. partone = self.find_sub(group, instance)
  74. parttwo = self.find_sub(group, "*")
  75. return list(set(partone + parttwo))
  76. class MsgQ:
  77. """Message Queue class."""
  78. # did we find a better way to do this?
  79. SOCKET_FILE = os.path.join("@localstatedir@",
  80. "@PACKAGE_NAME@",
  81. "msgq_socket").replace("${prefix}",
  82. "@prefix@")
  83. def __init__(self, socket_file=None, verbose=False):
  84. """Initialize the MsgQ master.
  85. The socket_file specifies the path to the UNIX domain socket
  86. that the msgq process listens on. If it is None, the
  87. environment variable BIND10_MSGQ_SOCKET_FILE is used. If that
  88. is not set, it will default to
  89. @localstatedir@/@PACKAGE_NAME@/msg_socket.
  90. If verbose is True, then the MsgQ reports
  91. what it is doing.
  92. """
  93. if socket_file is None:
  94. if "BIND10_MSGQ_SOCKET_FILE" in os.environ:
  95. self.socket_file = os.environ["BIND10_MSGQ_SOCKET_FILE"]
  96. else:
  97. self.socket_file = self.SOCKET_FILE
  98. else:
  99. self.socket_file = socket_file
  100. self.verbose = verbose
  101. self.poller = None
  102. self.kqueue = None
  103. self.runnable = False
  104. self.listen_socket = False
  105. self.sockets = {}
  106. self.connection_counter = random.random()
  107. self.hostname = socket.gethostname()
  108. self.subs = SubscriptionManager()
  109. self.lnames = {}
  110. self.sendbuffs = {}
  111. self.running = False
  112. def setup_poller(self):
  113. """Set up the poll thing. Internal function."""
  114. try:
  115. self.kqueue = select.kqueue()
  116. except AttributeError:
  117. self.poller = select.poll()
  118. def add_kqueue_socket(self, socket, write_filter=False):
  119. """Add a kquque filter for a socket. By default the read
  120. filter is used; if write_filter is set to True, the write
  121. filter is used. We use a boolean value instead of a specific
  122. filter constant, because kqueue filter values do not seem to
  123. be defined on some systems. The use of boolean makes the
  124. interface restrictive because there are other filters, but this
  125. method is mostly only for our internal use, so it should be
  126. acceptable at least for now."""
  127. filter_type = select.KQ_FILTER_WRITE if write_filter else \
  128. select.KQ_FILTER_READ
  129. event = select.kevent(socket.fileno(), filter_type,
  130. select.KQ_EV_ADD | select.KQ_EV_ENABLE)
  131. self.kqueue.control([event], 0)
  132. def delete_kqueue_socket(self, socket, write_filter=False):
  133. """Delete a kqueue filter for socket. See add_kqueue_socket()
  134. for the semantics and notes about write_filter."""
  135. filter_type = select.KQ_FILTER_WRITE if write_filter else \
  136. select.KQ_FILTER_READ
  137. event = select.kevent(socket.fileno(), filter_type,
  138. select.KQ_EV_DELETE)
  139. self.kqueue.control([event], 0)
  140. def setup_listener(self):
  141. """Set up the listener socket. Internal function."""
  142. if self.verbose:
  143. sys.stdout.write("[b10-msgq] Setting up socket at %s\n" %
  144. self.socket_file)
  145. self.listen_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  146. if os.path.exists(self.socket_file):
  147. os.remove(self.socket_file)
  148. try:
  149. self.listen_socket.bind(self.socket_file)
  150. self.listen_socket.listen(1024)
  151. except Exception as e:
  152. # remove the file again if something goes wrong
  153. # (note this is a catch-all, but we reraise it)
  154. if os.path.exists(self.socket_file):
  155. os.remove(self.socket_file)
  156. self.listen_socket.close()
  157. sys.stderr.write("[b10-msgq] failed to setup listener on %s: %s\n"
  158. % (self.socket_file, str(e)))
  159. raise e
  160. if self.poller:
  161. self.poller.register(self.listen_socket, select.POLLIN)
  162. else:
  163. self.add_kqueue_socket(self.listen_socket)
  164. def setup(self):
  165. """Configure listener socket, polling, etc.
  166. Raises a socket.error if the socket_file cannot be
  167. created.
  168. """
  169. self.setup_poller()
  170. self.setup_listener()
  171. if self.verbose:
  172. sys.stdout.write("[b10-msgq] Listening\n")
  173. self.runnable = True
  174. def process_accept(self):
  175. """Process an accept on the listening socket."""
  176. newsocket, ipaddr = self.listen_socket.accept()
  177. # TODO: When we have logging, we might want
  178. # to add a debug message here that a new connection
  179. # was made
  180. self.register_socket(newsocket)
  181. def register_socket(self, newsocket):
  182. """
  183. Internal function to insert a socket. Used by process_accept and some tests.
  184. """
  185. self.sockets[newsocket.fileno()] = newsocket
  186. lname = self.newlname()
  187. self.lnames[lname] = newsocket
  188. if self.poller:
  189. self.poller.register(newsocket, select.POLLIN)
  190. else:
  191. self.add_kqueue_socket(newsocket)
  192. def process_socket(self, fd):
  193. """Process a read on a socket."""
  194. if not fd in self.sockets:
  195. sys.stderr.write("[b10-msgq] Got read on Strange Socket fd %d\n" % fd)
  196. return
  197. sock = self.sockets[fd]
  198. # sys.stderr.write("[b10-msgq] Got read on fd %d\n" %fd)
  199. self.process_packet(fd, sock)
  200. def kill_socket(self, fd, sock):
  201. """Fully close down the socket."""
  202. if self.poller:
  203. self.poller.unregister(sock)
  204. self.subs.unsubscribe_all(sock)
  205. lname = [ k for k, v in self.lnames.items() if v == sock ][0]
  206. del self.lnames[lname]
  207. sock.shutdown(socket.SHUT_RDWR)
  208. sock.close()
  209. del self.sockets[fd]
  210. if fd in self.sendbuffs:
  211. del self.sendbuffs[fd]
  212. sys.stderr.write("[b10-msgq] Closing socket fd %d\n" % fd)
  213. def getbytes(self, fd, sock, length):
  214. """Get exactly the requested bytes, or raise an exception if
  215. EOF."""
  216. received = b''
  217. while len(received) < length:
  218. try:
  219. data = sock.recv(length - len(received))
  220. except socket.error:
  221. raise MsgQReceiveError(socket.error)
  222. if len(data) == 0:
  223. raise MsgQReceiveError("EOF")
  224. received += data
  225. return received
  226. def read_packet(self, fd, sock):
  227. """Read a correctly formatted packet. Will raise exceptions if
  228. something fails."""
  229. lengths = self.getbytes(fd, sock, 6)
  230. overall_length, routing_length = struct.unpack(">IH", lengths)
  231. if overall_length < 2:
  232. raise MsgQReceiveError("overall_length < 2")
  233. overall_length -= 2
  234. if routing_length > overall_length:
  235. raise MsgQReceiveError("routing_length > overall_length")
  236. if routing_length == 0:
  237. raise MsgQReceiveError("routing_length == 0")
  238. data_length = overall_length - routing_length
  239. # probably need to sanity check lengths here...
  240. routing = self.getbytes(fd, sock, routing_length)
  241. if data_length > 0:
  242. data = self.getbytes(fd, sock, data_length)
  243. else:
  244. data = None
  245. return (routing, data)
  246. def process_packet(self, fd, sock):
  247. """Process one packet."""
  248. try:
  249. routing, data = self.read_packet(fd, sock)
  250. except MsgQReceiveError as err:
  251. self.kill_socket(fd, sock)
  252. sys.stderr.write("[b10-msgq] Receive error: %s\n" % err)
  253. return
  254. try:
  255. routingmsg = isc.cc.message.from_wire(routing)
  256. except DecodeError as err:
  257. self.kill_socket(fd, sock)
  258. sys.stderr.write("[b10-msgq] Routing decode error: %s\n" % err)
  259. return
  260. self.process_command(fd, sock, routingmsg, data)
  261. def process_command(self, fd, sock, routing, data):
  262. """Process a single command. This will split out into one of the
  263. other functions."""
  264. # TODO: A print statement got removed here (one that prints the
  265. # routing envelope). When we have logging with multiple levels,
  266. # we might want to re-add that on a high debug verbosity.
  267. cmd = routing["type"]
  268. if cmd == 'send':
  269. self.process_command_send(sock, routing, data)
  270. elif cmd == 'subscribe':
  271. self.process_command_subscribe(sock, routing, data)
  272. elif cmd == 'unsubscribe':
  273. self.process_command_unsubscribe(sock, routing, data)
  274. elif cmd == 'getlname':
  275. self.process_command_getlname(sock, routing, data)
  276. elif cmd == 'ping':
  277. # Command for testing purposes
  278. self.process_command_ping(sock, routing, data)
  279. elif cmd == 'stop':
  280. self.stop()
  281. else:
  282. sys.stderr.write("[b10-msgq] Invalid command: %s\n" % cmd)
  283. def preparemsg(self, env, msg = None):
  284. if type(env) == dict:
  285. env = isc.cc.message.to_wire(env)
  286. if type(msg) == dict:
  287. msg = isc.cc.message.to_wire(msg)
  288. length = 2 + len(env);
  289. if msg:
  290. length += len(msg)
  291. ret = struct.pack("!IH", length, len(env))
  292. ret += env
  293. if msg:
  294. ret += msg
  295. return ret
  296. def sendmsg(self, sock, env, msg = None):
  297. self.send_prepared_msg(sock, self.preparemsg(env, msg))
  298. def __send_data(self, sock, data):
  299. """
  300. Send a piece of data to the given socket.
  301. Parameters:
  302. sock: The socket to send to
  303. data: The list of bytes to send
  304. Returns:
  305. An integer or None. If an integer (which can be 0), it signals
  306. the number of bytes sent. If None, the socket appears to have
  307. been closed on the other end, and it has been killed on this
  308. side too.
  309. """
  310. try:
  311. # We set the socket nonblocking, MSG_DONTWAIT doesn't exist
  312. # on some OSes
  313. sock.setblocking(0)
  314. return sock.send(data)
  315. except socket.error as e:
  316. if e.errno in [ errno.EAGAIN,
  317. errno.EWOULDBLOCK,
  318. errno.EINTR ]:
  319. return 0
  320. elif e.errno in [ errno.EPIPE,
  321. errno.ECONNRESET,
  322. errno.ENOBUFS ]:
  323. print("[b10-msgq] " + errno.errorcode[e.errno] +
  324. " on send, dropping message and closing connection")
  325. self.kill_socket(sock.fileno(), sock)
  326. return None
  327. else:
  328. raise e
  329. finally:
  330. # And set it back again
  331. sock.setblocking(1)
  332. def send_prepared_msg(self, sock, msg):
  333. # Try to send the data, but only if there's nothing waiting
  334. fileno = sock.fileno()
  335. if fileno in self.sendbuffs:
  336. amount_sent = 0
  337. else:
  338. amount_sent = self.__send_data(sock, msg)
  339. if amount_sent is None:
  340. # Socket has been killed, drop the send
  341. return
  342. # Still something to send, add it to outgoing queue
  343. if amount_sent < len(msg):
  344. now = time.clock()
  345. # Append it to buffer (but check the data go away)
  346. if fileno in self.sendbuffs:
  347. (last_sent, buff) = self.sendbuffs[fileno]
  348. if now - last_sent > 0.1:
  349. self.kill_socket(fileno, sock)
  350. return
  351. buff += msg
  352. else:
  353. buff = msg[amount_sent:]
  354. last_sent = now
  355. if self.poller:
  356. self.poller.register(fileno, select.POLLIN |
  357. select.POLLOUT)
  358. else:
  359. self.add_kqueue_socket(sock, True)
  360. self.sendbuffs[fileno] = (last_sent, buff)
  361. def __process_write(self, fileno):
  362. # Try to send some data from the buffer
  363. (_, msg) = self.sendbuffs[fileno]
  364. sock = self.sockets[fileno]
  365. amount_sent = self.__send_data(sock, msg)
  366. if amount_sent is not None:
  367. # Keep the rest
  368. msg = msg[amount_sent:]
  369. if len(msg) == 0:
  370. # If there's no more, stop requesting for write availability
  371. if self.poller:
  372. self.poller.register(fileno, select.POLLIN)
  373. else:
  374. self.delete_kqueue_socket(sock, True)
  375. del self.sendbuffs[fileno]
  376. else:
  377. self.sendbuffs[fileno] = (time.clock(), msg)
  378. def newlname(self):
  379. """Generate a unique connection identifier for this socket.
  380. This is done by using an increasing counter and the current
  381. time."""
  382. self.connection_counter += 1
  383. return "%x_%x@%s" % (time.time(), self.connection_counter, self.hostname)
  384. def process_command_ping(self, sock, routing, data):
  385. self.sendmsg(sock, { "type" : "pong" }, data)
  386. def process_command_getlname(self, sock, routing, data):
  387. lname = [ k for k, v in self.lnames.items() if v == sock ][0]
  388. self.sendmsg(sock, { "type" : "getlname" }, { "lname" : lname })
  389. def process_command_send(self, sock, routing, data):
  390. group = routing["group"]
  391. instance = routing["instance"]
  392. to = routing["to"]
  393. if group == None or instance == None:
  394. return # ignore invalid packets entirely
  395. if to == "*":
  396. sockets = self.subs.find(group, instance)
  397. else:
  398. if to in self.lnames:
  399. sockets = [ self.lnames[to] ]
  400. else:
  401. return # recipient doesn't exist
  402. msg = self.preparemsg(routing, data)
  403. if sock in sockets:
  404. sockets.remove(sock)
  405. for socket in sockets:
  406. self.send_prepared_msg(socket, msg)
  407. def process_command_subscribe(self, sock, routing, data):
  408. group = routing["group"]
  409. instance = routing["instance"]
  410. if group == None or instance == None:
  411. return # ignore invalid packets entirely
  412. self.subs.subscribe(group, instance, sock)
  413. def process_command_unsubscribe(self, sock, routing, data):
  414. group = routing["group"]
  415. instance = routing["instance"]
  416. if group == None or instance == None:
  417. return # ignore invalid packets entirely
  418. self.subs.unsubscribe(group, instance, sock)
  419. def run(self):
  420. """Process messages. Forever. Mostly."""
  421. self.running = True
  422. if self.poller:
  423. self.run_poller()
  424. else:
  425. self.run_kqueue()
  426. def run_poller(self):
  427. while self.running:
  428. try:
  429. # Poll with a timeout so that every once in a while,
  430. # the loop checks for self.running.
  431. events = self.poller.poll()
  432. except select.error as err:
  433. if err.args[0] == errno.EINTR:
  434. events = []
  435. else:
  436. sys.stderr.write("[b10-msgq] Error with poll(): %s\n" % err)
  437. break
  438. for (fd, event) in events:
  439. if fd == self.listen_socket.fileno():
  440. self.process_accept()
  441. else:
  442. if event & select.POLLOUT:
  443. self.__process_write(fd)
  444. elif event & select.POLLIN:
  445. self.process_socket(fd)
  446. else:
  447. print("[XX] UNKNOWN EVENT")
  448. def run_kqueue(self):
  449. while self.running:
  450. # Check with a timeout so that every once in a while,
  451. # the loop checks for self.running.
  452. events = self.kqueue.control(None, 10)
  453. if not events:
  454. raise RuntimeError('serve: kqueue returned no events')
  455. for event in events:
  456. if event.ident == self.listen_socket.fileno():
  457. self.process_accept()
  458. else:
  459. if event.filter == select.KQ_FILTER_WRITE:
  460. self.__process_write(event.ident)
  461. if event.filter == select.KQ_FILTER_READ and \
  462. event.data > 0:
  463. self.process_socket(event.ident)
  464. elif event.flags & select.KQ_EV_EOF:
  465. self.kill_socket(event.ident,
  466. self.sockets[event.ident])
  467. def stop(self):
  468. self.running = False
  469. def shutdown(self):
  470. """Stop the MsgQ master."""
  471. if self.verbose:
  472. sys.stdout.write("[b10-msgq] Stopping the server.\n")
  473. self.listen_socket.close()
  474. if os.path.exists(self.socket_file):
  475. os.remove(self.socket_file)
  476. # can signal handling and calling a destructor be done without a
  477. # global variable?
  478. msgq = None
  479. def signal_handler(signal, frame):
  480. if msgq:
  481. msgq.shutdown()
  482. sys.exit(0)
  483. if __name__ == "__main__":
  484. def check_port(option, opt_str, value, parser):
  485. """Function to insure that the port we are passed is actually
  486. a valid port number. Used by OptionParser() on startup."""
  487. intval = int(value)
  488. if (intval < 0) or (intval > 65535):
  489. raise OptionValueError("%s requires a port number (0-65535)" % opt_str)
  490. parser.values.msgq_port = intval
  491. # Parse any command-line options.
  492. parser = OptionParser(version=VERSION)
  493. parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
  494. help="display more about what is going on")
  495. parser.add_option("-s", "--socket-file", dest="msgq_socket_file",
  496. type="string", default=None,
  497. help="UNIX domain socket file the msgq daemon will use")
  498. (options, args) = parser.parse_args()
  499. signal.signal(signal.SIGTERM, signal_handler)
  500. # Announce startup.
  501. if options.verbose:
  502. sys.stdout.write("[b10-msgq] %s\n" % VERSION)
  503. msgq = MsgQ(options.msgq_socket_file, options.verbose)
  504. try:
  505. msgq.setup()
  506. except Exception as e:
  507. sys.stderr.write("[b10-msgq] Error on startup: %s\n" % str(e))
  508. sys.exit(1)
  509. try:
  510. msgq.run()
  511. except KeyboardInterrupt:
  512. pass
  513. msgq.shutdown()