pypubsub.py 18 KB

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