__init__.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import logging
  2. from time import sleep
  3. from concurrent import futures
  4. import threading
  5. import psycopg
  6. import pika
  7. import grpc
  8. from grpc_health.v1 import health_pb2, health, health_pb2_grpc
  9. from . import lily_pb2_grpc, excel, tex
  10. VERSION = '2023.9.29'
  11. def _health_checker(servicer, name):
  12. while True:
  13. servicer.set(name, health_pb2.HealthCheckResponse.SERVING)
  14. sleep(5)
  15. def _setup_health_thread(server):
  16. servicer = health.HealthServicer(
  17. experimental_non_blocking=True,
  18. experimental_thread_pool=futures.ThreadPoolExecutor(max_workers=2)
  19. )
  20. health_pb2_grpc.add_HealthServicer_to_server(servicer, server)
  21. health_checker_thread = threading.Thread(
  22. target=_health_checker,
  23. args=(servicer, 'palm.lily'),
  24. daemon=True
  25. )
  26. health_checker_thread.start()
  27. def start_server(addr, workers):
  28. server = grpc.server(futures.ThreadPoolExecutor(max_workers=workers))
  29. lily_pb2_grpc.add_ExcelServicer_to_server(excel.Service(), server)
  30. lily_pb2_grpc.add_TexServicer_to_server(tex.Service(), server)
  31. _setup_health_thread(server)
  32. server.add_insecure_port(addr)
  33. server.start()
  34. logging.info(
  35. "Lily gRPC server started, listening on %s with %d threads", addr, workers)
  36. try:
  37. server.wait_for_termination()
  38. except KeyboardInterrupt:
  39. logging.warn('exited...')
  40. server.stop(0)
  41. # https://pika.readthedocs.io/en/stable/modules/parameters.html
  42. def rabbitmq_parameters(config):
  43. credentials = pika.PlainCredentials(config['user'], config['password'])
  44. parameters = pika.ConnectionParameters(
  45. config['host'],
  46. config['port'],
  47. config['virtual-host'],
  48. credentials)
  49. return parameters
  50. # https://www.postgresql.org/docs/current/libpq-connect.html
  51. def postgresql_url(config):
  52. logging.debug('open postgresql://%s@%s:%d/%s',
  53. config['user'], config['host'], config['port'], config['name'])
  54. url = 'host=%s port=%d user=%s password=%s dbname=%s sslmode=disable' % (
  55. config['host'], config['port'], config['user'], config['password'], config['name'])
  56. with psycopg.connect(url) as db:
  57. cur = db.cursor()
  58. cur.execute('SELECT VERSION(), CURRENT_TIMESTAMP')
  59. row = cur.fetchone()
  60. if row:
  61. logging.debug("%s %s", row[0], row[1])
  62. return url