c3lf-system-3/core/server.py

100 lines
2.7 KiB
Python
Raw Permalink Normal View History

#!/usr/bin/env python3
import logging
2023-11-23 22:17:20 +00:00
import os
2023-11-27 00:20:32 +00:00
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')
import django
import uvicorn
2023-11-27 00:20:32 +00:00
django.setup()
2024-01-07 16:26:20 +00:00
from helper import init_loop
2023-11-27 00:38:43 +00:00
from mail.protocol import LMTPHandler
from mail.socket import UnixSocketLMTPController
from notifications.dispatch import NotificationDispatcher
2023-11-27 00:38:43 +00:00
class UvicornServer(uvicorn.Server):
def install_signal_handlers(self):
pass
2023-11-23 22:17:20 +00:00
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()
2023-11-23 22:17:20 +00:00
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}')
2023-11-23 22:17:20 +00:00
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
2023-11-23 22:17:20 +00:00
import os
setproctitle.setproctitle("c3lf-sys3")
2023-11-23 22:17:20 +00:00
log = logging.getLogger('server.log')
log.addHandler(logging.FileHandler('server.log'))
log.setLevel(logging.DEBUG)
log.info("Starting server")
2023-11-23 22:17:20 +00:00
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()
2023-11-23 22:17:20 +00:00
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")
2023-11-23 22:17:20 +00:00
logging.shutdown()
if __name__ == '__main__':
main()