2
0

pypubsub.py 21 KB

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