Commit 325a9f6c authored by Vitaly Lipatov's avatar Vitaly Lipatov

api: avoid restart loop on config errors

parent a295fb99
......@@ -7,6 +7,7 @@ Type=simple
ExecStart=/usr/bin/python3 /usr/share/eterban/eterban_api.py
Restart=always
RestartSec=5
RestartPreventExitStatus=78
[Install]
WantedBy=multi-user.target
......@@ -138,19 +138,23 @@ def main():
host = LISTEN_HOST
port = LISTEN_PORT
# Allow override from config
if os.path.exists(path_to_config):
config = configparser.ConfigParser()
config.read(path_to_config)
host = config.get('API', 'listen_host', fallback=LISTEN_HOST)
port = config.getint('API', 'listen_port', fallback=LISTEN_PORT)
API_TOKEN = config.get('API', 'api_token', fallback='').strip()
API_RATE_LIMIT = config.getint('API', 'rate_limit_per_minute', fallback=60)
if not is_loopback_host(host) and not API_TOKEN:
raise RuntimeError('API token is required for a non-loopback listen_host')
if API_RATE_LIMIT < 1:
raise RuntimeError('API rate_limit_per_minute must be positive')
try:
# Allow override from config
if os.path.exists(path_to_config):
config = configparser.ConfigParser()
config.read(path_to_config)
host = config.get('API', 'listen_host', fallback=LISTEN_HOST)
port = config.getint('API', 'listen_port', fallback=LISTEN_PORT)
API_TOKEN = config.get('API', 'api_token', fallback='').strip()
API_RATE_LIMIT = config.getint('API', 'rate_limit_per_minute', fallback=60)
if not is_loopback_host(host) and not API_TOKEN:
raise ValueError('API token is required for a non-loopback listen_host')
if API_RATE_LIMIT < 1:
raise ValueError('API rate_limit_per_minute must be positive')
except (ValueError, configparser.Error) as error:
print('Invalid Eterban API configuration: ' + str(error), file=sys.stderr)
raise SystemExit(78)
server = http.server.HTTPServer((host, port), EterbanAPIHandler)
print(f"Eterban API listening on {host}:{port}")
......
......@@ -41,3 +41,14 @@ if [ "$status" -ne 78 ]; then
echo "internal service without configuration returned $status, expected 78" >&2
exit 1
fi
if printf '%s\n' '[API]' 'rate_limit_per_minute = 0' | (cd gateway/usr/share/eterban && python3 -c 'from pathlib import Path; p = Path("eterban_api.py"); code = p.read_text().replace("/etc/eterban/settings.ini", "/proc/self/fd/0"); exec(compile(code, str(p), "exec"))') >/dev/null 2>&1; then
echo 'API service with invalid configuration must fail' >&2
exit 1
else
status=$?
fi
if [ "$status" -ne 78 ]; then
echo "API service with invalid configuration returned $status, expected 78" >&2
exit 1
fi
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment