pypubsub.py 14 KB

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