pypubsub.py 15 KB

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