pypubsub.py 20 KB

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