pypubsub.py 18 KB

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