Skip to content
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
executable file 918 lines (732 sloc) 33.7 KB
#!/usr/bin/env python3
""" Maintain your LE infrastructure with config files and behaviors.
This was originally a shell script but got converted to python as
more conditions and exceptions became necessary.
lematt generates both rsa keys/certs AND ec keys/certs because modern systems
accept them all at once. You'll end up with two certs and two keys generated for
each input domain you configure.
Brief (very brief) overview of acronyms and terms:
- LE: Let's Encrypt - CA issuing free DV certs, subject to rate limits
- CA: Certificate Authority - an issuer/signer of certificates
- DV: Domain Validated - just verifies you can control hosting and/or email
- SAN: subjectAltName - how one certificate supports multiple domain names
- SNI: Server Name Indication - TLS virtual hosting by giving clients SANs
- TLS: Transport Layer Security - the "s" in "https" allowing encryption
- UCC: Unified Communications Certificate - X.509 TLS certificate with SANs
- X.509: an archaic, but sadly universal, file format for certificates
- CSR: Certificate Signing Request - how CAs sign public keys and domains
- PEM: "Privacy-Enhanced E-Mail" - a file format for base64 encoded data
- RSA: historically standard Internet-wide public key encryption system
- EC: Elliptic Curve - a more modern public key encryption system
- OCSP: Online Certificate Status Protocol - realtime CRL; signed responses
- Staple: include CA-signed OCSP status with your cert when clients connect
- CRL: Certificate Revocation List - a way to check if certs are revoked
import multiprocessing
import configparser
import collections
import subprocess
import itertools
import argparse
import datetime
import pathlib
import socket
import json
import ssl
import sys
import os
import acme_tiny # distributed with lematt
from datetime import timedelta # make some lines shorter
MIN_VERSION = (3, 6)
if sys.version_info < MIN_VERSION:
# Why only 3.6 or later? 3.6 introduced F-strings we
# use for f"hello {var}" formatting everywhere.
# Sure, we could have used one of the other 20 kinds of
# python string formatting methods, but we didn't.
print("Sorry, lematt requires Python 3.6 or later.")
def log(what, mode="", update=False):
# If requesting more than just a newline separator...
if what:
prefix = "[TEST] "
prefix = "> "
prefix = ""
if mode:
mode = f"[{mode}]"
if not IS_CRON or update:
print(f"{prefix}{mode} {what}")
def getSubdir(subdir):
base = "test/"
base = "prod/"
return base + subdir
def loadDomainActions():
""" Read actions.conf and parse actions into usable dicts. """
domainActions = {}
domainActionNames = {}
updaters = configparser.ConfigParser()"{configBase}/actions.conf")
def extractAndPopulate(sectionName, override, actions):
if sectionName in override:
commands = json.loads(override[sectionName])
actions[sectionName] = commands
defaultOCSP = False
if 'ocspStapleRequired' in updaters['default']:
defaultOCSP = updaters['default']['ocspStapleRequired']
def errIfIn(what, things, sect):
if what in things:
print(f"Error: '{what}' entry not allowed in section [{sect}]")
# Usage sanity check
for uda in ['default', 'every']:
preActions = updaters[uda]
errIfIn('domains', preActions, uda)
if uda == 'every':
errIfIn('ocspStapleRequired', preActions, uda)
# Use ConfigParser magic to make a global dict 'default' for this key
# so we don't have to guard "if val in dict" everywhere.
updaters['DEFAULT'] = {'ocspStapleRequired': defaultOCSP}
# Use '.sections()' here because if we iterate 'updaters' directly,
# we get the meta 'DEFAULT' key which we don't want to process.
# '.sections()' only returns user-created sections.
for uda in updaters.sections():
preActions = updaters[uda]
actions = {'actionName': uda}
domainActionNames[uda] = actions
if not (uda == 'default' or uda == 'every'):
# If not in the default section, get domains this override
# should apply towards.
domains = preActions['domains'].split()
# Extract override sections present (all optional)
extractAndPopulate('prepare', preActions, actions)
extractAndPopulate('update', preActions, actions)
extractAndPopulate('uploadCerts', preActions, actions)
extractAndPopulate('uploadKeys', preActions, actions)
# Irrelevant for section 'every', but no harm done:
actions['ocspStapleRequired'] = preActions.getboolean(
# If default section, populate default domainActions
if uda == 'default' or uda == 'every':
domainActions[uda] = actions
# else, attach actions to each domain inside this override
for domain in domains:
# log(f"Populating exceptions for {domain} as: {actions}")
domainActions[domain] = actions
return domainActions, domainActionNames
def gendir(subname):
""" Create a directory hierarchy but don't complain if already exists """
adir = pathlib.Path("{}/{}".format(configBase, subname))
adir.mkdir(parents=True, exist_ok=True)
def run(thing, shell=False, output=True, stdinSend=None):
""" Run any string as a command (maybe as shell for env/expansion too) """
log(f"Running: {thing}", "CMD", update=True)
if stdinSend:
# use 'repr' because we want to print the string with visible \n
# instead of exploding the formatted string across ten lines
log(f"WITH STDIN: {repr(stdinSend)}", "CMD", update=True)
# If running with shell=True, command must be a single string
# the shell itself will parse and do glob expansion, etc.
# If running with shell=False, command must be a list of strings
# where command[0] is the executable and command[1:] will be
# the command's argv array.
command = thing
if not shell:
command = thing.split()
input=stdinSend.encode() if stdinSend else None,
# note: we could use 'text=True' here to avoid .encode(),
# but text=True is only Python 3.7 and as of right now we
# work fine in Python 3.6. Seems adding one line invaliding
# our entire current Python version is a bit extreme.
def runAsync(thing, shell=False):
log(f"Running: {thing}", "CMD-ASYNC", update=True)
command = thing
if not shell:
command = thing.split()
return subprocess.Popen(command, shell=shell)
def runAndWrite(thing, writeTo, perm=0o644, shell=False, stdinSend=None):
ran = run(thing, shell=shell, stdinSend=stdinSend)
# Python doesn't have a clean way of opening files with
# pre-determined file permissions, so we get to do this instead...
with os.fdopen(, os.O_WRONLY | os.O_CREAT, perm), 'w') as w:
def customizeName(subdir, name, subtype, enctype, ext="pem"):
assert enctype == "rsa" or enctype == "ec"
return "{}/{}/{}-{}.{}{}.{}".format(configBase,
RSA_TAG if enctype == "rsa" else CURVE_TAG,
".test" if IS_TEST else "",
def generateCSR(privateKey, domains, outfile):
useSAN = len(domains) > 1
def needsOCSP():
def required(domain):
if domain in domainActions:
return domainActions[domain]['ocspStapleRequired']
return domainActions['default']['ocspStapleRequired']
# do a quick loop to make sure all SAN domains have
# the same 'ocspStapleRequired' value.
# Since OCSP is a value of the entire certificate, we can't
# mix and match domain configs and OCSP values.
# Mixing can be dangerous because some servers don't staple,
# but if the cert requires it, the service would be unusable
# (i.e. dovecot and postfix don't staple, but nginx does)
hasOCSP = required(domains[0])
for domain in domains[1:]:
if required(domain) != hasOCSP:
print("Error: All SAN domains don't have the same OCSP config!")
print(f"Verify all domains have same OCSP settings: {domains}")
return hasOCSP
subjectAltNames = ""
cmdSAN = ""
if useSAN:
# Assemble list of all domains (including the primary CN) for SANing
altNames = [f"DNS:{domain}" for domain in domains]
subjectAltNames = ",".join(altNames)
cmdSAN = "-reqexts SAN"
# Use first domain as the primary common name
domain = domains[0]
ocspRequired = ""
if needsOCSP():
ocspRequired = " = DER:30:03:02:01:05"
# openssl >= 1.1 supports the cleaner syntax below instead of OIDs,
# but we can't guarantee most users have a compatible version yet:
# ocspRequired = "tlsfeature = status_request"
# Mock an in-line config real quick...
# This is a bit weird because openssl doesn't support alt names
# on the command line — it only supports them by reading a file
# or by reading from stdin, so we mock a config file on stdin
# for openssl to parse.
# If you're curious about the contents of the CSR itself, re-create the
# generated command line with a given stdin and append -text to get
# a human text representation of the CSR.
f"openssl req -new -sha256 -key {privateKey} -subj /CN={domain} "
f"{cmdSAN} -config -", outfile,
def generateCSRSingleDomain(privateKey, domain, outfile):
assert isinstance(domain, str)
generateCSR(privateKey, [domain], outfile)
def generateCSRWithSAN(privateKey, domains, outfile):
assert isinstance(domains, list)
generateCSR(privateKey, domains, outfile)
# unused, but may be useful in the future
def certFromNetwork(hostname):
""" Get cert expiration against a live server """
context = ssl.create_default_context()
conn = context.wrap_socket(
conn.connect((hostname, 443))
ssl_info = conn.getpeercert()
assert isinstance(ssl_info, dict)
return ssl_info
def certFromFile(certPath):
""" Get cert expiration from local file """
# If cert doesn't exist, it must be requested...
certExists = os.path.isfile(certPath)
if not certExists:
return True
# This is an internal Python API. Not guaranteed to exist across releases.
certDetails = ssl._ssl._test_decode_cert(certPath)
assert isinstance(certDetails, dict)
return certDetails
def certNeedsRenewal(certDetails, utcnow):
# The first check guards against True from 'certFromFile()'.
# (if cert doesn't exist, we obviously need to request one)
if not isinstance(certDetails, dict):
return True
def timeRemaining(expires):
return expires - utcnow
def needsRenewNow(expires):
remaining = timeRemaining(expires)
if remaining < timedelta(days=0):
# cert has already expired!
return True
return True
return False
# Future - Past (now), ideally
ssl_date_fmt = r'%b %d %H:%M:%S %Y %Z'
expirationAsDate = datetime.datetime.strptime(
certDetails['notAfter'], ssl_date_fmt)
return needsRenewNow(expirationAsDate)
def requestCert(csr, outCert, isTest=False):
if isTest:
directory = STAGING
directory = PRODUCTION
# This is where we can plug in different cert request methods.
# Right now we just pulled in acme_tiny which is a simple
# http-01 wrapper around openssl subprocesses.
# We can add dns-01 fairly easily if we add a way to injest
# DNS API credentials then integrate with both DNS APIs themselves
# (can easily adapt from other LE requesting systems) then
# send acme dns-01 requests to LE too.
signedCert = acme_tiny.get_crt(ACCOUNT_KEY, csr, CHALLENGE_DIR,
with open(outCert, 'w') as writeMe:
def prepareDomainForUpdate(domain):
if domain in domainActions:
actions = domainActions[domain]
actions = domainActions['default']
if 'every' in domainActions:
allActions = domainActions['every']
allActions = []
def prepare(acts):
return [runAsync(X.replace('DOMAIN', domain)) for X in acts['prepare']]
prepared = []
if 'prepare' in actions:
if 'prepare' in allActions:
return prepared
def prepareDomainsForUpdate(domains):
prepared = []
for domain in domains:
prepare = prepareDomainForUpdate(domain)
if prepare:
return prepared
def unprepareDomainForUpdate(prepared):
if prepared:
for prepare in prepared:
# Why does printing stdout from Popen cause our
# terminal session to go all weird?
# Reset terminal semantics...
run("stty sane")
except BaseException:
# This may not work if run detatched
# from a shell (like via cron)? Just ignore any
# stty failures.
def generateKeysAndCertsAndRequestSignedCerts(
configuredDomain, domainActions, keyType):
# Now do the cert update (or cert generation, along with key generation) for
# both RSA and EC keys:
updatedCerts = {}
# Use timestamp for detecting expired certs or certs needing renewal soon
utcnow = datetime.datetime.utcnow()
def updateDomainForKeyType(domain, keyType):
# If this is a SAN request, combine all domains for filenames
if isinstance(domain, list):
# Do our best to preserve the order of SAN domains even
# if they change.
# Otherwise, if the order gets rearranged, we would generate
# entirely new keys and certs even though they cover the
# same set of domains.
# Basically: convert SANs into a set, sort it, use that as
# filename appended to the CN name for persisting set uniqueness.
deduplicatedSANs = list(set(domain[1:]))
deduplicatedSANs.insert(0, domain[0])
domains = deduplicatedSANs
domain = "_".join(domains) # "_" <-- eyelashes bot supreme
domains = None
assert "." in domain, f"Domain ({domain}) isn't a domain name?"
privateKey = customizeName("key", domain, "key", keyType)
cert = customizeName("cert", domain, "cert-combined", keyType)
csr = customizeName("csr", domain, "csr", keyType, "csr")
isEC = keyType == "ec"
def generateKey():
""" Either: use key if exists or create new if requested """
if ALWAYS_NEW_KEYS or not os.path.isfile(privateKey):
if isEC:
log(f"Generating EC {CURVE} key...", keyType)
"openssl ecparam -genkey -name {}".format(CURVE),
privateKey, 0o600)
log(f"Generating RSA {KEYBITS_RSA} key...", keyType)
"openssl genrsa {}".format(KEYBITS_RSA),
privateKey, 0o600)
def generateCSR_():
""" Either: use CSR if exists or create new if requested """
if ALWAYS_NEW_KEYS or not os.path.isfile(csr):
log("Generating CSR...", keyType)
if domains:
generateCSRWithSAN(privateKey, domains, csr)
generateCSRSingleDomain(privateKey, domain, csr)
log(f"Checking certificate for {domain}...", keyType)
if not certNeedsRenewal(certFromFile(cert), utcnow):
log("Not renewing!", keyType)
log(f"Renewing {domain}!", keyType, update=True)
if domains:
prepared = prepareDomainsForUpdate(domains)
prepared = prepareDomainForUpdate(domain)
requestCert(csr, cert, IS_TEST)
# NOTE: if you have DUPLICATE certificates like a single
# domain certificate with the same in another cert's SANs,
# you will trigger actions for whichever domain is processed last.
# e.g.
# The above would generate keys and certs for twice
# (with the second key being on the SAN cert of,
# but your triggered actions would deliver* keys and certs
# to
if domains:
# attach all domains to our update dict so we can report on why
# update actions are happening per-domain
# We use tuples here because tuples can be members of
# sets, which lets us easily deduplicate repeated SAN-vs-CN
# mappings later (lists can't be members of sets).
for d in domains:
updatedCerts[d] = tuple(domains)
updatedCerts[domain] = tuple([domain])
assert keyType == "rsa" or keyType == "ec", f"Invalid keyType {keyType}!"
updateDomainForKeyType(configuredDomain, keyType)
log("") # visually break with a newline between processed domains
return updatedCerts
def sortByDomain(x):
# Sort domain names by their top-down sort order, but ignore actual TLD.
# e.g. will get a sort tuple of:
# (there hello mail)
parts = x.split('.')
return tuple(parts[1:])
# 'domainActions' is a map of domain names -> action description maps
# 'domainActionNames' is a map of action names -> action description maps
# action maps have element 'actionName' to map domainActions->domainNameActions
# for deduplicating final cert/key copying and update actions.
def updateKeysAndCertsAndServices(
# No updated certs? No need to update anything!
if not updatedCerts:
# If certs were updated, run their associated update actions...
def runUploadsAndUpdates(updatedDomains, actions):
assert isinstance(actions, dict)
firstDomains = []
# We only copy keys/certs based on the CN name which is ud[0]
for ud in updatedDomains:
# We want to run ALL replaces and ONE update at the end
# in aggregated/combined/unified commands instead of running
# N copies and N updates if we were processing all cert updates
# individually.
replaceCert = " ".join(
[f"{configBase}/{getSubdir('cert')}/{ud}*" for ud in firstDomains])
replaceKey = " ".join(
[f"{configBase}/{getSubdir('key')}/{ud}*" for ud in firstDomains])
replaceDomainsCN = " ".join(firstDomains)
# Flatten the 'updatedDomains' list of lists so we can just join it all
replaceDomainsALL = " ".join(set(itertools.chain(*updatedDomains)))
# This loop basically flattens nested updatedDomains and annotates
# which ones are SAN domains versus the root CN itself
totalDomainsSANDescribed = []
updatedDomains = list(updatedDomains)
updatedDomains.sort(key=lambda x: sortByDomain(x[0]))
# Generate informative output during the final action reporting phase
for ud in updatedDomains:
if len(ud) > 1:
place = [ud[0]]
place.extend([f"{u} (SAN)" for u in ud[1:]])
place = ", ".join(place)
place = f"({place})"
place = ud[0]
updatedFormatted = ", ".join(totalDomainsSANDescribed)
log("Executing "
f"[{actions['actionName']}] for {updatedFormatted}",
# Do we have upload cert overrides?
if 'uploadCerts' in actions:
for upload in actions['uploadCerts']:
run(upload.replace('CERTS', replaceCert), shell=True)
# Do we have upload key overrides?
if 'uploadKeys' in actions:
for upload in actions['uploadKeys']:
run(upload.replace('KEYS', replaceKey), shell=True)
# Now with certs/keys replaced, run full service update:
if 'update' in actions:
for action in actions['update']:
action = action.replace('DOMAINS_CN', replaceDomainsCN)
action = action.replace('DOMAINS_ALL', replaceDomainsALL)
run(action, shell=True)
# 'combinedProcessingResult' is a map of:
# actionNames -> set of domains for action
# We use a set because with SAN domains, each SAN name has the full
# domain set for the entire cert, but we only care about each
# unique grouping.
combinedProcessingResult = collections.defaultdict(set)
# deduplicate actions across all domains so we only do one update
# action across all updated certs this round.
# print(updatedCerts)
# Do we have 'every' actions for post-processing?
hasGlobalEveryActionGroup = 'every' in domainActionNames
for updatedDomain, domainsOnCert in updatedCerts.items():
# Step 1: Lookup domain in map of DOMAIN->Actions
# Step 2: Get Action Name from map
# Step 3: Append domain to list in map of ActionName->[Domains]
# Step 4: Run each action on each aggregated domain list
# For SAN domains, we need to trigger SAN overrides too, but provide
# the key+cert starting with sniDomains[0] which probably isn't
# the SAN name itself...
# So, we need to map SAN actions back to actual cert names, which we
# accomplish by just using the entire domain list per cert and using
# the [0]th entry as the CN and the rest are alt names.
# print(updatedDomain, domainActions, domainActionNames)
# If this domain has an explicit override:
if updatedDomain in domainActions:
actions = domainActions[updatedDomain]
actionName = actions['actionName']
else: # else, no override, so use default action!
if hasGlobalEveryActionGroup:
# Now run deduplicated domain actions for uploads and service updates:
if combinedProcessingResult:
log("Copying keys and certs then reloading services...",
"action", update=True)
# print(combinedProcessingResult)
for sectionName, sectionDomains in combinedProcessingResult.items():
runUploadsAndUpdates(sectionDomains, domainActionNames[sectionName])
log("", update=True) # line break
def loadDomains():
# Format of 'domains' file is one or more domains per line.
# Each line becomes ONE certificate. If more than one domain
# is present, an SAN certificate will be generated.
# If the secondary domains on a line don't have a '.', they will
# be prepended to the first domain on the line.
# e.g. " www" will generate a certificate with
# domains: and
configuredDomains = []
with open(f"{configBase}/domains", 'r') as doms:
for line in doms:
# Skip commented out or blank lines
if line.startswith("#") or line.startswith("\n"):
# If multiple names are on one line, they all become
# one SAN certificate
domainsOnLine = line.split()
firstDomain = domainsOnLine[0]
# All rate limits detailed at:
if len(domainsOnLine) > 100:
f"Error! The domain limit is 100 per certificate, but you "
"configured {len(domainsOnLine)} domains:\n{domainsOnLine}")
# If only one domain, present as a string, _not_ a list,
# so the rest of our code knows not to populate SAN fields
if len(domainsOnLine) == 1:
domainsOnLine = firstDomain
# else, format domains where required
for i, domain in enumerate(domainsOnLine):
# you can use subdomains as shorthand by just giving their
# name and we take care of appending the first
# domain on the line to your subdomain
if '.' not in domain:
domainsOnLine[i] = f"{domain}.{firstDomain}"
return configuredDomains
if __name__ == "__main__":
# Rate limits described at:
# Testing / Staging:
# Production:
parser = argparse.ArgumentParser(
description="Matt's Let's Encrypt Automation")
# production-xor-staging/testing
group = parser.add_mutually_exclusive_group(required=True)
help="Use LE production endpoint. "
"Production rate limit is 5 duplicate certs per domain per week.")
help="""Use LE staging endpoint.
Keys and certs will have 'test' in filenames.
Don't waste your production rate limits during testing.
Staging rate limit is 30,000 cert requests per week and
30,000 duplicate cert issuance per week (per domain).""")
help="Only produce output when changes happen.")
help="Number of certificates to process in parallel")
parser.add_argument('--config', dest='config', default="conf/lematt.conf",
help="Path to your lematt.conf - "
"config files 'domains' and 'actions.conf' "
"must be in the same directory as lematt.conf")
args = parser.parse_args()
IS_CRON = args.isCron
IS_TEST = args.isTest
concurrency = args.concurrency
configBase = os.path.dirname(os.path.realpath(args.config))
conf = configparser.ConfigParser()
conf['DEFAULT'] = {'reauthorizeDays': 15,
'keyBitsRSA': '2048',
'alwaysGenerateNewKeys': 'no',
'generateNewCertsAfterDays': 0,
'curve': 'prime256v1'}
if not
print(f"Requested config path not found: {args.config}")
config = conf["config"]
# We treat these as globals throughout the code, so they must
# be initialized here outside of any functions:
reauthDays = float(config['reauthorizeDays'])
REAUTHORIZE_DAYS_IN_ADVANCE = timedelta(days=reauthDays)
CHALLENGE_DIR = config['challengeDropDir']
ACCOUNT_KEY = config['accountKey']
KEYBITS_RSA = config['keyBitsRSA']
CURVE = config['curve']
ALWAYS_NEW_KEYS = config.getboolean('alwaysGenerateNewKeys')
GENERATE_CERTS_DAYS = float(config['generateNewCertsAfterDays'])
if GENERATE_CERTS_DAYS: # <-- if !0
# Instead of days-before-expire, use days-since-issue math.
# Maximum rate should be 3.5 days-since-issue because:
# Fun Fact: LE gives 90 day certs, but you get 5 duplicates per week.
# Since we are issuing both RSA and EC certs, each issue eats
# 2 rate limits out of 5 in every 7 day sliding window.
# Remaining under rate limit of 5 per week means we can
# run a complete issue cycle twice a week, giving us a
# period for issuing of 7 days / 2 runs = 3.5 days/run
# Therefore, our 90 day certs should be renewed with:
# 90 days - 3.5 days = 86.5 days remaining,
# which python lets us express as math by:
# timedelta(days=90) - timedelta(days=3.5)
# (actually it's the same as timedelta(days=86.5), but the
# mathy way looks cleaner and can be adjusted easier)
REAUTHORIZE_DAYS_IN_ADVANCE = timedelta(days=90) - \
# Use old configparser .get() syntax because defaults are based on values
RSA_TAG = config.get("rsaTag", f"rsa{KEYBITS_RSA}")
CURVE_TAG = config.get("curveTag", f"{CURVE}")
# Endpoints taken from:
# See for updates:
# Updates:
# 2021-03-27: x3 expires
# 2019-07-08: LE will provide certificates from their own root
CROSSCHAIN_NAME_RSA = "lets-encrypt-x3-cross-signed.pem.txt"
# TODO: turn this into a map of CHAIN = {'rsa': CHAIN_RSA, 'ec': CHAIN_EC}
# LE plans a full ECDSA cert chain in Q3 2018
CHAIN_RSA = "{}/{}".format(configBase,
CROSSCHAIN_NAME_RSA).replace(".txt", "")
# LE actually returns a chained cert, so we don't have to manually apply
# the cross chain ourself, but the cross chain is useful for configuring
# stapling.
testing = ""
configuredDomains = loadDomains()
if not IS_CRON:
print(f"{testing}Welcome to LE Matt!")
print("Using domain list:")
for domain in configuredDomains:
if not os.path.isfile(ACCOUNT_KEY):
print(f"Account key doesn't exist: {ACCOUNT_KEY}")
print("Create your LE account key with: openssl genrsa 4096 > key.pem")
# Fetch intermediate cert so user can copy it elsewhere if needed
if not os.path.isfile(CHAIN_RSA):
run("wget -O{} {}{}".format(CHAIN_RSA,
# Create directories to store results (if they don't already exist)
for name in ["key", "cert", "csr"]:
# Parse actions.conf to load cert update actions (defaults and overrides)
domainActions, domainActionNames = loadDomainActions()
# Now process domains by:
# - requesting new certs from LE when cert doesn't exist or expires soon
# - generating rsa and ec keys if a key doesn't already exist
# - generating CSRs for each {key,domains} pair when CSRs don't exist
# - run per-domain prepare actions when configured
# - adding updated domains to results for post-update action triggering
# We now do massively parallel certificate updating where each Certificate
# for each domain gets processed with '--parallel' concurrency
# LE has per-second rate limits and we don't recover from those errors
# gracefully at the moment, so try to slow overzealous users down somewhat:
# ==================
# "The “new-reg”, “new-authz” and “new-cert” endpoints have an
# Overall Requests limit of 20 per second.
# The “/directory” endpoint and the “/acme” directory have an
# Overall Requests limit of 40 requests per second."
# ==================
if concurrency > 10:
concurrency = 10
with multiprocessing.Pool(processes=concurrency) as pool:
updatedCerts = pool.starmap(
generateKeysAndCertsAndRequestSignedCerts, itertools.product(
configuredDomains, [domainActions], [
"rsa", "ec"]))
# sanity check from starmap
assert isinstance(updatedCerts, list)
assert len(updatedCerts) and isinstance(updatedCerts[0], dict)
# pool.starmap() returns a list of dicts, but our final
# result expects one dict with all results,
# so merge the nested dicts into one big dict.
updatedCertsSingleDict = {}
for u in updatedCerts:
# sanity check
assert isinstance(updatedCertsSingleDict, dict)
# Now deduplicate updated certs to action mappings then
# copy keys, certs, and run configured update actions for updated certs
You can’t perform that action at this time.