You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
mailu/core/base/libs/socrate/socrate/system.py

45 lines
1.5 KiB
Python

import hmac
import logging as log
import os
import socket
import tenacity
@tenacity.retry(stop=tenacity.stop_after_attempt(100),
wait=tenacity.wait_random(min=2, max=5))
def resolve_hostname(hostname):
""" This function uses system DNS to resolve a hostname.
It is capable of retrying in case the host is not immediately available
"""
try:
return sorted(socket.getaddrinfo(hostname, None, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE), key=lambda s:s[0])[0][4][0]
except Exception as e:
log.warn("Unable to lookup '%s': %s",hostname,e)
raise e
SERVICE = {
'ADMIN': 'admin',
'FRONT': 'front',
'SMTP': 'smtp',
'IMAP': 'imap',
'REDIS': 'redis',
'ANTIVIRUS:': 'antivirus',
'ANTISPAM': 'antispam',
'WEBMAIL': 'webmail',
'WEBDAV': 'webdav',
}
def set_env(required_secrets=[]):
""" This will set all the environment variables and retains only the secrets we need """
for service in SERVICE:
if not os.environ.get(f'{service}_ADDRESS'):
os.environ[f'{service}_ADDRESS'] = f'{SERVICE[service]}'
secret_key = os.environ.get('SECRET_KEY')
clean_env()
# derive the keys we need
for secret in required_secrets:
os.environ[f'{secret}_KEY'] = hmac.new(bytearray(secret_key, 'utf-8'), bytearray(secret, 'utf-8'), 'sha256').hexdigest()
def clean_env():
""" remove all secret keys """
[os.environ.pop(key, None) for key in os.environ.keys() if key.endswith("_KEY")]