pypubsub.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. #!/usr/bin/env python3
  2. # Licensed to the Apache Software Foundation (ASF) under one
  3. # or more contributor license agreements. See the NOTICE file
  4. # distributed with this work for additional information
  5. # regarding copyright ownership. The ASF licenses this file
  6. # to you under the Apache License, Version 2.0 (the
  7. # "License"); you may not use this file except in compliance
  8. # with the License. You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing,
  13. # software distributed under the License is distributed on an
  14. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. # KIND, either express or implied. See the License for the
  16. # specific language governing permissions and limitations
  17. # under the License.
  18. """PyPubSub - a simple publisher/subscriber service written in Python 3"""
  19. import asyncio
  20. import aiohttp.web
  21. import time
  22. import json
  23. import yaml
  24. import netaddr
  25. import binascii
  26. import base64
  27. import argparse
  28. import plugins.ldap
  29. # Some consts
  30. PUBSUB_VERSION = '0.4.6'
  31. PUBSUB_CONTENT_TYPE = 'application/vnd.pypubsub-stream'
  32. PUBSUB_DEFAULT_MAX_PAYLOAD_SIZE = 102400
  33. PUBSUB_DEFAULT_BACKLOG_SIZE = 0
  34. PUBSUB_BAD_REQUEST = "I could not understand your request, sorry! Please see https://pubsub.apache.org/api.html \
  35. for usage documentation.\n"
  36. PUBSUB_PAYLOAD_RECEIVED = "Payload received, thank you very much!\n"
  37. PUBSUB_NOT_ALLOWED = "You are not authorized to deliver payloads!\n"
  38. PUBSUB_BAD_PAYLOAD = "Bad payload type. Payloads must be JSON dictionary objects, {..}!\n"
  39. PUBSUB_PAYLOAD_TOO_LARGE = "Payload is too large for me to serve, please make it shorter.\n"
  40. class Server:
  41. """Main server class, responsible for handling requests and publishing events """
  42. def __init__(self, args):
  43. self.config = yaml.safe_load(open(args.config))
  44. self.lconfig = None
  45. self.subscribers = []
  46. self.pending_events = []
  47. self.backlog = []
  48. self.last_ping = time.time()
  49. self.server = None
  50. if 'ldap' in self.config.get('clients', {}):
  51. self.lconfig = self.config['clients']['ldap']
  52. plugins.ldap.vet_settings(self.lconfig)
  53. self.acl = {}
  54. try:
  55. self.acl = yaml.safe_load(open(args.acl))
  56. except FileNotFoundError:
  57. print(f"ACL configuration file {args.acl} not found, private events will not be broadcast.")
  58. self.payloaders = [netaddr.IPNetwork(x) for x in self.config['clients']['payloaders']]
  59. async def poll(self):
  60. """Polls for new stuff to publish, and if found, publishes to whomever wants it."""
  61. while True:
  62. for payload in self.pending_events:
  63. bad_subs = await payload.publish(self.subscribers)
  64. # Cull subscribers we couldn't deliver payload to.
  65. for bad_sub in bad_subs:
  66. print("Culling %r due to connection errors" % bad_sub)
  67. self.subscribers.remove(bad_sub)
  68. self.pending_events = []
  69. await asyncio.sleep(0.5)
  70. async def handle_request(self, request):
  71. """Generic handler for all incoming HTTP requests"""
  72. # Define response headers first...
  73. headers = {
  74. 'Server': 'PyPubSub/%s' % PUBSUB_VERSION,
  75. 'X-Subscribers': str(len(self.subscribers)),
  76. 'X-Requests': str(self.server.requests_count),
  77. }
  78. # Are we handling a publisher payload request? (PUT/POST)
  79. if request.method in ['PUT', 'POST']:
  80. ip = netaddr.IPAddress(request.remote)
  81. allowed = False
  82. for network in self.payloaders:
  83. if ip in network:
  84. allowed = True
  85. break
  86. if not allowed:
  87. resp = aiohttp.web.Response(headers=headers, status=403, text=PUBSUB_NOT_ALLOWED)
  88. return resp
  89. if request.can_read_body:
  90. try:
  91. if request.content_length > self.config['clients'].get('max_payload_size',
  92. PUBSUB_DEFAULT_MAX_PAYLOAD_SIZE):
  93. resp = aiohttp.web.Response(headers=headers, status=400, text=PUBSUB_PAYLOAD_TOO_LARGE)
  94. return resp
  95. body = await request.text()
  96. as_json = json.loads(body)
  97. assert isinstance(as_json, dict) # Payload MUST be an dictionary object, {...}
  98. pl = Payload(request.path, as_json)
  99. self.pending_events.append(pl)
  100. backlog_size = self.config['clients'].get('payload_backlog_size', PUBSUB_DEFAULT_BACKLOG_SIZE)
  101. if backlog_size > 0:
  102. self.backlog.append(pl)
  103. # If backlog has grown too large, delete the first (oldest) item in it.
  104. if len(self.backlog) > backlog_size:
  105. del self.backlog[0]
  106. resp = aiohttp.web.Response(headers=headers, status=202, text=PUBSUB_PAYLOAD_RECEIVED)
  107. return resp
  108. except json.decoder.JSONDecodeError:
  109. resp = aiohttp.web.Response(headers=headers, status=400, text=PUBSUB_BAD_REQUEST)
  110. return resp
  111. except AssertionError:
  112. resp = aiohttp.web.Response(headers=headers, status=400, text=PUBSUB_BAD_PAYLOAD)
  113. return resp
  114. # Is this a subscriber request? (GET)
  115. elif request.method == 'GET':
  116. resp = aiohttp.web.StreamResponse(headers=headers)
  117. # We do not support HTTP 1.0 here...
  118. if request.version.major == 1 and request.version.minor == 0:
  119. return resp
  120. subscriber = Subscriber(self, resp, request)
  121. # Is there a basic auth in this request? If so, set up ACL
  122. auth = request.headers.get('Authorization')
  123. if auth:
  124. subscriber.acl = await subscriber.parse_acl(auth)
  125. # Subscribe the user before we deal with the potential backlog request and pings
  126. self.subscribers.append(subscriber)
  127. resp.content_type = PUBSUB_CONTENT_TYPE
  128. try:
  129. resp.enable_chunked_encoding()
  130. await resp.prepare(request)
  131. # Is the client requesting a backlog of items?
  132. backlog = request.headers.get('X-Fetch-Since')
  133. if backlog:
  134. try:
  135. backlog_ts = int(backlog)
  136. except ValueError: # Default to 0 if we can't parse the epoch
  137. backlog_ts = 0
  138. # For each item, publish to client if new enough.
  139. for item in self.backlog:
  140. if item.timestamp >= backlog_ts:
  141. await item.publish([subscriber])
  142. while True:
  143. await subscriber.ping()
  144. if subscriber not in self.subscribers: # If we got dislodged somehow, end session
  145. break
  146. await asyncio.sleep(5)
  147. # We may get exception types we don't have imported, so grab ANY exception and kick out the subscriber
  148. except:
  149. pass
  150. if subscriber in self.subscribers:
  151. self.subscribers.remove(subscriber)
  152. return resp
  153. elif request.method == 'HEAD':
  154. resp = aiohttp.web.Response(headers=headers, status=204, text="")
  155. return resp
  156. # I don't know this type of request :/ (DELETE, PATCH, etc)
  157. else:
  158. resp = aiohttp.web.Response(headers=headers, status=400, text=PUBSUB_BAD_REQUEST)
  159. return resp
  160. async def server_loop(self):
  161. self.server = aiohttp.web.Server(self.handle_request)
  162. runner = aiohttp.web.ServerRunner(self.server)
  163. await runner.setup()
  164. site = aiohttp.web.TCPSite(runner, self.config['server']['bind'], self.config['server']['port'])
  165. await site.start()
  166. print("==== PyPubSub v/%s starting... ====" % PUBSUB_VERSION)
  167. print("==== Serving up PubSub goodness at %s:%s ====" % (self.config['server']['bind'], self.config['server']['port']))
  168. await self.poll()
  169. def run(self):
  170. loop = asyncio.get_event_loop()
  171. try:
  172. loop.run_until_complete(self.server_loop())
  173. except KeyboardInterrupt:
  174. pass
  175. loop.close()
  176. class Subscriber:
  177. """Basic subscriber (client) class. Holds information about the connection and ACL"""
  178. def __init__(self, server, connection, request):
  179. self.connection = connection
  180. self.acl = {}
  181. self.server = server
  182. # Set topics subscribed to
  183. self.topics = [x for x in request.path.split('/') if x]
  184. # Is the client old and expecting zero-terminators?
  185. self.old_school = False
  186. for ua in self.server.config['clients'].get('oldschoolers', []):
  187. if ua in request.headers.get('User-Agent', ''):
  188. self.old_school = True
  189. break
  190. async def parse_acl(self, basic):
  191. """Sets the ACL if possible, based on Basic Auth"""
  192. try:
  193. decoded = str(base64.decodebytes(bytes(basic.replace('Basic ', ''), 'ascii')), 'utf-8')
  194. u, p = decoded.split(':', 1)
  195. if u in self.server.acl:
  196. acl_pass = self.server.acl[u].get('password')
  197. if acl_pass and acl_pass == p:
  198. acl = self.server.acl[u].get('acl', {})
  199. # Vet ACL for user
  200. assert isinstance(acl, dict), f"ACL for user {u} " \
  201. f"must be a dictionary of sub-IDs and topics, but is not."
  202. # Make sure each ACL segment is a list of topics
  203. for k, v in acl.items():
  204. assert isinstance(v, list), f"ACL segment {k} for user {u} is not a list of topics!"
  205. print(f"Client {u} successfully authenticated (and ACL is valid).")
  206. return acl
  207. elif self.server.lconfig:
  208. acl = {}
  209. groups = await plugins.ldap.get_groups(self.server.lconfig, u, p)
  210. # Make sure each ACL segment is a list of topics
  211. for k, v in self.server.lconfig['acl'].items():
  212. if k in groups:
  213. assert isinstance(v, dict), f"ACL segment {k} for user {u} is not a dictionary of segments!"
  214. for segment, topics in v.items():
  215. print(f"Enabling ACL segment {segment} for user {u}")
  216. assert isinstance(topics, list), f"ACL segment {segment} for user {u} is not a list of topics!"
  217. acl[segment] = topics
  218. return acl
  219. except binascii.Error as e:
  220. pass # Bad Basic Auth params, bail quietly
  221. except AssertionError as e:
  222. print(e)
  223. print(f"ACL configuration error: ACL scheme for {u} contains errors, setting ACL to nothing.")
  224. except Exception as e:
  225. print(f"Basic unknown exception occurred: {e}")
  226. return {}
  227. async def ping(self):
  228. """Generic ping-back to the client"""
  229. js = b"%s\n" % json.dumps({"stillalive": time.time()}).encode('utf-8')
  230. if self.old_school:
  231. js += b"\0"
  232. await self.connection.write(js)
  233. class Payload:
  234. """A payload (event) object sent by a registered publisher."""
  235. def __init__(self, path, data):
  236. self.json = data
  237. self.timestamp = time.time()
  238. self.topics = [x for x in path.split('/') if x]
  239. self.private = False
  240. # Private payload?
  241. if self.topics and self.topics[0] == 'private':
  242. self.private = True
  243. del self.topics[0] # Remove the private bit from topics now.
  244. self.json['pubsub_timestamp'] = self.timestamp
  245. self.json['pubsub_topics'] = self.topics
  246. self.json['pubsub_path'] = path
  247. async def publish(self, subscribers):
  248. """Publishes an object to all subscribers using those topics (or a sub-set thereof)"""
  249. js = b"%s\n" % json.dumps(self.json).encode('utf-8')
  250. ojs = js + b"\0"
  251. bad_subs = []
  252. for sub in subscribers:
  253. # If a private payload, check ACL and bail if not a match
  254. if self.private:
  255. can_see = False
  256. for key, private_topics in sub.acl.items():
  257. if all(el in self.topics for el in private_topics):
  258. can_see = True
  259. break
  260. if not can_see:
  261. continue
  262. # If subscribed to all the topics, tell a subscriber about this
  263. if all(el in self.topics for el in sub.topics):
  264. try:
  265. if sub.old_school:
  266. await sub.connection.write(ojs)
  267. else:
  268. await sub.connection.write(js)
  269. except Exception:
  270. bad_subs.append(sub)
  271. return bad_subs
  272. if __name__ == '__main__':
  273. parser = argparse.ArgumentParser()
  274. parser.add_argument("--config", help="Configuration file to load (default: pypubsub.yaml)", default="pypubsub.yaml")
  275. parser.add_argument("--acl", help="ACL Configuration file to load (default: pypubsub_acl.yaml)", default="pypubsub_acl.yaml")
  276. cliargs = parser.parse_args()
  277. pubsub_server = Server(cliargs)
  278. pubsub_server.run()