c3lf-system-3/core/server.py
2024-11-23 01:35:29 +01:00

99 lines
2.7 KiB
Python
Executable file

#!/usr/bin/env python3
import logging
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')
import django
import uvicorn
django.setup()
from helper import init_loop
from mail.protocol import LMTPHandler
from mail.socket import UnixSocketLMTPController
from notifications.dispatch import NotificationDispatcher
class UvicornServer(uvicorn.Server):
def install_signal_handlers(self):
pass
async def web(loop):
log_config = uvicorn.config.LOGGING_CONFIG
log_config["handlers"]["default"] = {"class": "logging.FileHandler", "filename": "web.log", "formatter": "default"}
log_config["handlers"]["access"] = {"class": "logging.FileHandler", "filename": "web-access.log",
"formatter": "access"}
config = uvicorn.Config("core.asgi:application", uds="web.sock", log_config=log_config)
server = UvicornServer(config=config)
await server.serve()
async def lmtp(loop):
import grp
log = logging.getLogger('mail.log')
log.addHandler(logging.FileHandler('mail.log'))
# log.setLevel(logging.WARNING)
log.setLevel(logging.INFO)
log.info("Starting LMTP server")
server = await UnixSocketLMTPController(LMTPHandler(), unix_socket='lmtp.sock', loop=loop).serve()
addrs = ', '.join(str(sock.getsockname()) for sock in server.sockets)
log.info(f'Serving on {addrs}')
try:
os.chmod('lmtp.sock', 0o775)
current_uid = os.getuid()
posix_gid = grp.getgrnam('postfix').gr_gid
os.chown('lmtp.sock', current_uid, posix_gid)
except Exception as e:
log.error(e)
async with server:
await server.serve_forever()
log.info("LMTP done")
async def notifications(loop):
dispatcher = NotificationDispatcher()
await dispatcher.run_forever()
def main():
import sdnotify
import setproctitle
import os
setproctitle.setproctitle("c3lf-sys3")
log = logging.getLogger('server.log')
log.addHandler(logging.FileHandler('server.log'))
log.setLevel(logging.DEBUG)
log.info("Starting server")
loop = init_loop()
loop.create_task(web(loop))
# loop.create_task(tcp(loop))
loop.create_task(lmtp(loop))
loop.create_task(notifications(loop))
n = sdnotify.SystemdNotifier()
n.notify("READY=1")
log.info("Server ready")
try:
loop.run_forever()
finally:
loop.close()
try:
os.remove("lmtp.sock")
except Exception as e:
log.error(e)
try:
os.remove("web.sock")
except Exception as e:
log.error(e)
log.error(e)
logging.info("Server stopped")
logging.shutdown()
if __name__ == '__main__':
main()