Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(certs): capture ACME error message #83

Merged
merged 4 commits into from
Feb 24, 2025
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions imageroot/actions/delete-certificate/20writeconfig
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,22 @@ import sys
import os
import cert_helpers
import agent
import datetime

def main():
tstart = datetime.datetime.now(datetime.UTC)
request = json.load(sys.stdin)
fqdn = request['fqdn']
if fqdn in cert_helpers.read_custom_cert_names():
cert_helpers.remove_custom_cert(fqdn)
elif fqdn in cert_helpers.read_default_cert_names():
cert_helpers.remove_default_certificate_name(fqdn)
obtained = cert_helpers.wait_acmejson_sync(timeout=request.get('sync_timeout', 30))
if not obtained:
acme_error = cert_helpers.traefik_last_acme_error_since(tstart)
for errline in acme_error.split("\n"):
print(agent.SD_ERR + errline, file=sys.stderr)
exit(3)
else:
agent.set_status('validation-failed')
json.dump([{'field': 'fqdn','parameter':'fqdn','value': fqdn,'error':'certificate_not_found'}], fp=sys.stdout)
Expand Down
8 changes: 7 additions & 1 deletion imageroot/actions/set-certificate/20writeconfig
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,22 @@ import json
import sys
import os
import cert_helpers
import agent
import datetime

def main():
tstart = datetime.datetime.now(datetime.UTC)
request = json.load(sys.stdin)
cert_helpers.add_default_certificate_name(request['fqdn'])
if request.get('sync'):
obtained = cert_helpers.wait_acmejson_sync(timeout=request.get('sync_timeout', 120))
obtained = cert_helpers.wait_acmejson_sync(timeout=request.get('sync_timeout', 30))
else:
obtained = False
json.dump({"obtained": obtained}, fp=sys.stdout)
if request.get('sync') is not None and obtained is False:
acme_error = cert_helpers.traefik_last_acme_error_since(tstart)
for errline in acme_error.split('\n'):
print(agent.SD_ERR + errline, file=sys.stderr)
exit(2)

if __name__ == "__main__":
Expand Down
56 changes: 46 additions & 10 deletions imageroot/pypkg/cert_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
import json
import time
import glob
import subprocess
import datetime

def read_default_cert_names():
"""Return the list of host names configured in the
Expand Down Expand Up @@ -51,21 +53,28 @@ def remove_custom_cert(name):

def has_acmejson_name(name):
"""Return True if name is found among acme.json Certificates."""
with open('acme/acme.json', 'r') as fp:
acmejson = json.load(fp)
for ocert in acmejson['acmeServer']["Certificates"] or []:
if ocert["domain"]["main"] == name or name in ocert["domain"].get("sans", []):
return True
try:
with open('acme/acme.json', 'r') as fp:
acmejson = json.load(fp)
for ocert in acmejson['acmeServer']["Certificates"] or []:
if ocert["domain"]["main"] == name or name in ocert["domain"].get("sans", []):
return True
except (FileNotFoundError, KeyError):
pass
return False

def has_acmejson_cert(main, sans=[]):
"""Return True if a certificate matching main and sans is found among
acme.json Certificates."""
with open('acme/acme.json', 'r') as fp:
acmejson = json.load(fp)
for ocert in acmejson['acmeServer']["Certificates"] or []:
if ocert["domain"]["main"] == main and set(ocert["domain"].get("sans", [])) == set(sans):
return True
try:
with open('acme/acme.json', 'r') as fp:
acmejson = json.load(fp)
for ocert in acmejson['acmeServer']["Certificates"] or []:
if ocert["domain"]["main"] == main and set(ocert["domain"].get("sans", [])) == set(sans):
return True
return False
except (FileNotFoundError, KeyError):
pass
return False

def wait_acmejson_sync(timeout=120, interval=2.1, names=[]):
Expand All @@ -77,6 +86,8 @@ def wait_acmejson_sync(timeout=120, interval=2.1, names=[]):
if not names:
# Wait for the default certificate.
names = read_default_cert_names()
if not names:
return True # Consider as obtained, if no names are set.
elapsed = 0.0
while elapsed < timeout:
time.sleep(interval)
Expand Down Expand Up @@ -165,3 +176,28 @@ def parse_yaml_config(path):
with open(path, 'r') as fp:
conf = yaml.safe_load(fp)
return conf

def traefik_last_acme_error_since(tstart):
"""Get the last Traefik error related to ACME from Loki.

:param tstart: a ISO8601 string with TZ offset
:return: string
"""
try:
acme_error = subprocess.check_output([
"logcli",
"query",
"--limit=1",
"--from=" + tstart.isoformat(),
"--timezone=Local", # use system timezone for output
"--quiet",
"--no-labels",
'{module_id=~"traefik.+"} | json | line_format "{{.MESSAGE}}"' + \
'| logfmt | providerName="acmeServer.acme" and error!=""' + \
'| line_format "{{.error}}"',
], timeout=15, text=True)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a quite long timeout for a UI call!

Copy link
Member Author

@DavidePrincipi DavidePrincipi Feb 24, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

True, I can lower it a bit in a future PR, however consider it's a remote network call to the leader node which may be slow on busy systems.

except subprocess.TimeoutExpired as ex:
acme_error = 'traefik_last_acme_error_since(): logcli timeout - ' + str(ex)
except subprocess.CalledProcessError as ex:
acme_error = 'traefik_last_acme_error_since(): logcli error - ' + str(ex)
return acme_error
Loading