From ae66c60b50eaeadd74a584756adb68036ad5d79e Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Mon, 16 Nov 2026 06:06:59 -0500 Subject: [PATCH] Updater retries by itself when AWS throttles an update before it changes anything A throttled DescribeChangeSet during the deploy role check came back as "couldn't check", failed the update and told the admin to press Update again. Throttling now never counts as a refusal: every AWS client uses botocore's adaptive retry mode, each step before the change set runs is tried again with backoff and jitter, and the update (or the Update press) keeps waiting as "AWS is busy, retrying (attempt n)". Only after 10 minutes does it fail, in words that ask nothing of anyone, and it starts again by itself 30 minutes later unless an admin cancels it (DELETE /api/system/update). The model check stays pending, never refused, while AWS is busy. --- lambda/tests/test_updater_busy.py | 292 +++++++++++++++++++++ lambda/updater/handler.py | 348 ++++++++++++++++++++++++-- services/gateway/src/main.rs | 7 +- services/gateway/src/permissions.rs | 1 + services/gateway/src/routes/system.rs | 19 ++ 5 files changed, 641 insertions(+), 26 deletions(-) create mode 100644 lambda/tests/test_updater_busy.py diff --git a/lambda/tests/test_updater_busy.py b/lambda/tests/test_updater_busy.py new file mode 100644 index 000000000..ff15a4288 --- /dev/null +++ b/lambda/tests/test_updater_busy.py @@ -0,0 +1,292 @@ +"""AWS turning calls away (throttling) before an update changed anything: +the updater retries by itself, the update keeps waiting ("AWS is busy, +retrying (attempt n)"), and only after BUSY_LIMIT does it fail, with words +that never hand the retry to a person, and start again by itself later. + +Run: python3 -m unittest discover -s lambda/tests +""" + +import unittest +from datetime import timedelta + +from test_updater_native import ENV, NOW, FakeCfn, FakeDynamo, FakeIam, FakeLambda, u + +ROLE_ENV = dict(ENV, DEPLOY_ROLE_ARN="arn:aws:iam::1:role/coderhelm-prod-deploy") +ADMIN = "admin@example.com" + + +class ClientError(Exception): + """What botocore raises once its own retries are used up.""" + + def __init__(self, code="Throttling", op="DescribeChangeSet", http=400, message="Rate exceeded"): + self.response = {"Error": {"Code": code, "Message": message}, "ResponseMetadata": {"HTTPStatusCode": http}} + super().__init__(f"An error occurred ({code}) when calling the {op} operation (reached max retries: 5): {message}") + + +class TooManyRequestsException(Exception): + pass + + +class BusyCfn(FakeCfn): + """CloudFormation that throttles reading the change set's pages (the + checks before it runs) and creating change sets while told to.""" + + def __init__(self): + super().__init__() + self.busy_pages = False + self.busy_create = False + self.turned_away = 0 + + def describe_change_set(self, ChangeSetName, StackName=None, IncludePropertyValues=False, NextToken=None): + if self.busy_pages and IncludePropertyValues: + self.turned_away += 1 + raise ClientError() + return super().describe_change_set(ChangeSetName, StackName, IncludePropertyValues, NextToken) + + def create_change_set(self, **kw): + if self.busy_create: + self.turned_away += 1 + raise ClientError(op="CreateChangeSet") + return super().create_change_set(**kw) + + +class BusyIam(FakeIam): + """IAM throttling the deploy role's reads (the preflight) while told to.""" + + busy = True + + def get_role(self, RoleName): + if self.busy: + raise ClientError(op="GetRole") + return super().get_role(RoleName) + + +def no_press(text): + return "press update again" not in str(text).lower() + + +class Busy(unittest.TestCase): + def setUp(self): + self.store = u.Store(FakeDynamo(), "t") + self.cfn = BusyCfn() + u._clients["cloudformation"] = self.cfn + u._clients["lambda"] = FakeLambda() + self.sent = [] + self._notify, self._fetch, self._sleep = u.notify, u.fetch_template, u._sleep + u.notify = lambda *a, **k: self.sent.append(a) + u.fetch_template = lambda url, opener=None: __import__("test_updater_native").TEMPLATE + self.pauses = [] + u._sleep = self.pauses.append + self.store.put("MANIFEST#v1.1.0", {"verified": True, "manifest": None, "template_sha256": __import__("test_updater_native").SHA}) + self.store.put("MODEL_CHECK", {"version": "v1.1.0", "ok": True, "results": [], "checked_at": NOW.isoformat()}) + + def tearDown(self): + u.notify, u.fetch_template, u._sleep = self._notify, self._fetch, self._sleep + u._clients.pop("cloudformation", None) + u._clients.pop("lambda", None) + + def prepared(self, actor=ADMIN): + """An update whose change set exists and is ready to run.""" + e = u.begin(self.store, ROLE_ENV, NOW, "v1.1.0", actor, "update") + self.cfn.cs = {"Status": "CREATE_COMPLETE", "ExecutionStatus": "AVAILABLE"} + return e["id"] + + # ── telling throttling apart ───────────────────────────────────────── + + def test_throttling_is_told_apart_from_refusals(self): + for e in (ClientError(), ClientError("ThrottlingException"), ClientError("RequestLimitExceeded"), + ClientError("SlowDown", http=503), ClientError("Other", http=429), + TooManyRequestsException("Rate exceeded"), Exception("Rate exceeded")): + self.assertTrue(u.throttled(e), e) + wrapped = ValueError("couldn't prepare") + wrapped.__cause__ = ClientError() + self.assertTrue(u.throttled(wrapped)) + for e in (ClientError("AccessDenied", message="not authorized"), ClientError("LimitExceededException", message="Stack limit reached"), + Exception("ValidationError: throttled"), + ValueError("the stack is UPDATE_IN_PROGRESS")): + self.assertFalse(u.throttled(e), e) + + def test_one_call_retries_with_jittered_backoff_then_gives_up(self): + tries = [] + + def flaky(): + tries.append(1) + if len(tries) < 3: + raise ClientError() + return "ok" + self.assertEqual(u.busy_retry(flaky), "ok") + self.assertEqual(len(self.pauses), 2) + self.assertTrue(all(0 <= p <= u.BUSY_PAUSE_CAP for p in self.pauses)) + tries.clear() + with self.assertRaises(ClientError): + u.busy_retry(lambda: (_ for _ in ()).throw(ClientError())) + # Anything else is never retried. + tries.clear() + + def refused(): + tries.append(1) + raise ClientError("AccessDenied", message="not authorized") + with self.assertRaises(ClientError): + u.busy_retry(refused) + self.assertEqual(len(tries), 1) + + # ── the change set exists: its checks are throttled ────────────────── + + def test_a_throttled_check_waits_and_the_next_poll_starts_the_update(self): + hid = self.prepared(actor="auto") + self.cfn.busy_pages = True + r = u.native_poll(self.store, ROLE_ENV, NOW) + self.assertEqual(r["native"], "busy") + entry = self.store.get(hid) + self.assertEqual(entry["status"], "preparing") + self.assertEqual(entry["reason"], "AWS is busy, retrying (attempt 1)") + self.assertEqual(entry["busy"]["attempts"], 1) + self.assertEqual(self.cfn.deleted, []) + self.assertGreaterEqual(self.cfn.turned_away, u.BUSY_TRIES) + # Once more while still busy: attempt 2, still waiting, never failed. + r = u.native_poll(self.store, ROLE_ENV, NOW + timedelta(minutes=5)) + self.assertEqual(self.store.get(hid)["reason"], "AWS is busy, retrying (attempt 2)") + # AWS answers again: the checks pass and the update runs by itself. + self.cfn.busy_pages = False + r = u.native_poll(self.store, ROLE_ENV, NOW + timedelta(minutes=6)) + self.assertEqual(r["native"], "executing") + entry = self.store.get(hid) + self.assertEqual(entry["status"], "running") + self.assertNotIn("busy", entry) + self.assertEqual(entry["reason"], "") + self.assertEqual(entry["preflight"], []) # never a "couldn't check" refusal + + def test_a_throttled_preflight_is_never_a_refusal(self): + # What happened live: the deploy role's check read was throttled and + # came back as "couldn't check", which failed the update at once. + iam, u._clients["iam"] = u._clients["iam"], BusyIam() + try: + hid = self.prepared(actor="auto") + r = u.native_poll(self.store, ROLE_ENV, NOW) + self.assertEqual(r["native"], "busy") + self.assertEqual(self.store.get(hid)["status"], "preparing") + self.assertNotIn("preflight", self.store.get(hid)) + u._clients["iam"].busy = False + self.assertEqual(u.native_poll(self.store, ROLE_ENV, NOW + timedelta(minutes=5))["native"], "executing") + self.assertEqual(self.store.get(hid)["preflight"], []) + finally: + u._clients["iam"] = iam + + def test_still_throttled_after_the_bound_fails_in_plain_words_and_starts_again_by_itself(self): + hid = self.prepared() + self.cfn.busy_pages = True + u.native_poll(self.store, ROLE_ENV, NOW) + later = NOW + u.BUSY_LIMIT + timedelta(minutes=1) + r = u.native_poll(self.store, ROLE_ENV, later) + self.assertEqual(r["status"], "failed") + row = self.store.get(hid) + self.assertEqual(row["status"], "failed") + at = later + u.BUSY_RETRY_AFTER + self.assertIn("AWS was busy", row["summary"]) + self.assertIn("Nothing changed: your install stayed on v1.0.0.", row["summary"]) + self.assertEqual(row["fix"], f"Nothing to do: CoderHelm starts it again by itself at {at.strftime('%H:%M')} UTC.") + self.assertIn("Rate exceeded", row["technical"]) + for text in (row["reason"], row["summary"], row["fix"]): + self.assertTrue(no_press(text), text) + self.assertEqual(self.cfn.deleted, ["arn:cs/1"]) + # Never counted against the release, and the email asks nothing of anyone. + self.assertNotIn("v1.1.0", self.store.get("UPDATE_STATE").get("failed_versions") or []) + self.assertTrue(all(no_press(a) for sent in self.sent for a in sent)) + req = self.store.get("UPDATE_REQUEST") + self.assertEqual((req["status"], req["version"], req["actor"], req["failed_id"]), ("waiting", "v1.1.0", ADMIN, hid)) + self.assertEqual(req["retry_at"], at.isoformat()) + self.assertTrue(no_press(req["waiting_for"])) + # Not before its time... + self.cfn.busy_pages = False + u.follow_request(self.store, ROLE_ENV, later + timedelta(minutes=10)) + self.assertEqual(len(self.cfn.created), 1) + # ...then the scheduled poll starts it again, as the same admin's press. + u.handle({"action": "native_poll"}, ROLE_ENV, self.store, at + timedelta(minutes=1), fetch=lambda repo: []) + self.assertEqual(len(self.cfn.created), 2) + req = self.store.get("UPDATE_REQUEST") + self.assertEqual(req["status"], "started") + self.assertEqual(self.store.get(req["id"])["actor"], ADMIN) + + def test_cancel_stops_the_automatic_retry(self): + self.prepared() + self.cfn.busy_pages = True + u.native_poll(self.store, ROLE_ENV, NOW) + later = NOW + u.BUSY_LIMIT + timedelta(minutes=1) + u.native_poll(self.store, ROLE_ENV, later) + r = u.handle({"action": "cancel_request", "actor": ADMIN}, ROLE_ENV, self.store, later) + self.assertTrue(r["cancelled"]) + self.cfn.busy_pages = False + u.follow_request(self.store, ROLE_ENV, later + u.BUSY_RETRY_AFTER * 2) + self.assertEqual(len(self.cfn.created), 1) + self.assertEqual(self.store.get("UPDATE_REQUEST")["status"], "ended") + + # ── the change set can't be created: the start itself is throttled ─── + + def test_a_throttled_start_waits_and_starts_once_aws_answers(self): + self.cfn.busy_create = True + r = u.handle({"action": "update_now", "version": "v1.1.0", "actor": ADMIN}, ROLE_ENV, self.store, NOW, + fetch=lambda repo: [], probe=lambda env, p: {"results": []}) + self.assertEqual(r["state"], "checking") + self.assertEqual(r["request"]["status"], "waiting") + self.assertEqual(r["request"]["waiting_for"], "AWS is busy, retrying (attempt 1)") + self.assertEqual(r["request"]["busy"]["attempts"], 1) + self.assertEqual(self.store.history(), []) # nothing started, nothing failed + u.follow_request(self.store, ROLE_ENV, NOW + timedelta(minutes=5)) + self.assertEqual(self.store.get("UPDATE_REQUEST")["waiting_for"], "AWS is busy, retrying (attempt 2)") + self.cfn.busy_create = False + req = u.follow_request(self.store, ROLE_ENV, NOW + timedelta(minutes=6)) + self.assertEqual(req["status"], "started") + self.assertEqual(self.store.get(req["id"])["status"], "preparing") + + def test_a_start_throttled_past_the_bound_fails_and_starts_again_by_itself(self): + self.cfn.busy_create = True + u.handle({"action": "update_now", "version": "v1.1.0", "actor": ADMIN}, ROLE_ENV, self.store, NOW, + fetch=lambda repo: [], probe=lambda env, p: {"results": []}) + later = NOW + u.BUSY_LIMIT + timedelta(minutes=1) + req = u.follow_request(self.store, ROLE_ENV, later) + self.assertEqual(req["status"], "waiting") + row = self.store.get(req["failed_id"]) + self.assertEqual(row["status"], "failed") + self.assertTrue(row["summary"].startswith("The update couldn't start: AWS was busy")) + self.assertIn("starts it again by itself", row["fix"]) + self.assertTrue(no_press(row["reason"])) + self.cfn.busy_create = False + req = u.follow_request(self.store, ROLE_ENV, later + u.BUSY_RETRY_AFTER) + self.assertEqual(req["status"], "started") + + # ── the release check and status reads ────────────────────────────── + + def test_a_throttled_model_check_stays_pending_never_refused(self): + self.store.put("MANIFEST#v1.1.0", {"verified": True, "manifest": {"calls": ["sonnet"]}, "template_sha256": "x"}) + + def busy(env, payload): + raise TooManyRequestsException("Rate exceeded") + mc = u.model_check(self.store, ENV, NOW, "v1.1.0", u.RELEASE_REPO, busy) + self.assertTrue(mc["pending"]) + self.assertEqual(u.failures(mc), []) + self.assertIn("AWS is busy, retrying (attempt 1)", mc["note"]) + mc = u.model_check(self.store, ENV, NOW + timedelta(minutes=1), "v1.1.0", u.RELEASE_REPO, busy) + self.assertIn("attempt 2", mc["note"]) + mc = u.model_check(self.store, ENV, NOW + timedelta(minutes=2), "v1.1.0", u.RELEASE_REPO, + lambda env, p: {"results": [{"model": "sonnet", "status": "ok"}]}) + self.assertTrue(mc["ok"]) + self.assertNotIn("busy", mc) + + def test_the_status_route_answers_while_aws_is_busy(self): + hid = self.prepared() + self.cfn.busy_pages = True + r = u.handle({"action": "status"}, ROLE_ENV, self.store, NOW, fetch=lambda repo: []) + row = next(h for h in r["history"] if h["id"] == hid) + self.assertEqual((row["status"], row["reason"]), ("preparing", "AWS is busy, retrying (attempt 1)")) + + def test_no_throttling_message_hands_the_retry_to_a_person(self): + raw = "ClientError: An error occurred (Throttling) when calling the DescribeChangeSet operation: Rate exceeded" + for phase in (u.PREPARE, u.ROLLED_BACK): + for retry_at in (None, NOW): + d = u.explain_failure(raw, "v1.1.0", "v1.0.0", phase, retry_at=retry_at) + self.assertTrue(no_press(d["reason"]), (phase, retry_at, d["reason"])) + self.assertTrue(no_press(u.busy_note({"busy": {"attempts": 3}}))) + + +if __name__ == "__main__": + unittest.main() diff --git a/lambda/updater/handler.py b/lambda/updater/handler.py index 8deb82d63..523cd265b 100644 --- a/lambda/updater/handler.py +++ b/lambda/updater/handler.py @@ -374,16 +374,128 @@ def history(self, limit=20): # ── Outside calls (swapped in tests) ────────────────────────────────────── _clients = {} +# Each AWS call: botocore's adaptive retry mode (backoff with jitter, and it +# slows its own rate once AWS throttles), a few attempts per call. +AWS_ATTEMPTS = 4 def client(name, region=None): key = f"{name}@{region}" if region else name if key not in _clients: import boto3 - _clients[key] = boto3.client(name, region_name=region) if region else boto3.client(name) + kw = {"region_name": region} if region else {} + try: + from botocore.config import Config + kw["config"] = Config(retries={"max_attempts": AWS_ATTEMPTS, "mode": "adaptive"}) + except ImportError: # a stand-in boto3 (tests) has no botocore + pass + _clients[key] = boto3.client(name, **kw) return _clients[key] +# ── AWS turning calls away (throttling) ─────────────────────────────────── +# +# A throttled call says nothing about the release or the install: AWS was +# busy. Before anything changed (preparing the change set, reading it for the +# checks, the release and model checks) the updater retries by itself: a few +# times within the call (busy_retry, on top of botocore's own retries), then +# on each later poll or read of the page while the step stays waiting with +# "AWS is busy, retrying (attempt n)". Only after BUSY_LIMIT does the update +# fail, and then CoderHelm starts it again by itself after BUSY_RETRY_AFTER +# (an UPDATE_REQUEST with retry_at) unless an admin cancels it. + +BUSY_LIMIT = timedelta(minutes=10) +BUSY_RETRY_AFTER = timedelta(minutes=30) +BUSY_TRIES = 3 # tries of one step within a call +BUSY_CALL_BUDGET = 8 # seconds one call spends waiting between those tries +BUSY_PAUSE = 1.0 # the first pause (full jitter, doubling, at most BUSY_PAUSE_CAP) +BUSY_PAUSE_CAP = 4.0 +_THROTTLE_CODES = { + "Throttling", "ThrottlingException", "ThrottledException", "TooManyRequestsException", + "RequestLimitExceeded", "RequestThrottled", "RequestThrottledException", "SlowDown", + "ProvisionedThroughputExceededException", + "ServiceUnavailable", "ServiceUnavailableException", "EC2ThrottledException", +} +_THROTTLE_TEXT = re.compile(r"rate exceeded|too many requests|\((?:%s)\)|\b(?:%s)\b" % ( + "|".join(sorted(_THROTTLE_CODES)), "ThrottlingException|TooManyRequestsException|RequestLimitExceeded"), re.I) + + +def throttled(e): + """True when AWS turned the call away for being busy (throttling, a + request limit, 429 or 503), whatever wrapped it.""" + seen = set() + while e is not None and id(e) not in seen: + seen.add(id(e)) + resp = getattr(e, "response", None) + if isinstance(resp, dict): + code = (resp.get("Error") or {}).get("Code") or "" + http = (resp.get("ResponseMetadata") or {}).get("HTTPStatusCode") + if code in _THROTTLE_CODES or http in (429, 503): + return True + if type(e).__name__ in _THROTTLE_CODES or _THROTTLE_TEXT.search(str(e)): + return True + e = e.__cause__ or e.__context__ + return False + + +def busy_retry(fn, tries=BUSY_TRIES, budget=BUSY_CALL_BUDGET): + """fn(), tried again after a short pause (backoff with full jitter) when + AWS throttles it, within `budget` seconds and this invocation's time. + Anything else, and the last throttled try, raises as is.""" + import random + start = _clock() + for i in range(tries): + try: + return fn() + except Exception as e: # noqa: BLE001 + pause = random.uniform(0, min(BUSY_PAUSE_CAP, BUSY_PAUSE * 2 ** i)) + left = time_left() + if (not throttled(e) or i + 1 >= tries or _clock() - start + pause > budget + or (left is not None and left < pause + 5)): + raise + logger.warning(f"AWS is busy ({type(e).__name__}); trying again in {pause:.1f}s") + _sleep(pause) + + +def busy_mark(rec, now, why): + """Counts one more throttled try on `rec` (an update or a request, its + `busy`; `why`: what AWS said); True once AWS has turned it away for + BUSY_LIMIT or longer.""" + b = dict(rec.get("busy") or {}) + b.setdefault("since", now.isoformat()) + b["attempts"] = int(b.get("attempts") or 0) + 1 + b["last"] = str(why)[:300] + rec["busy"] = b + try: + return now - datetime.fromisoformat(b["since"]) >= BUSY_LIMIT + except ValueError: + return True + + +def busy_note(rec): + return f"AWS is busy, retrying (attempt {int((rec.get('busy') or {}).get('attempts') or 1)})" + + +def not_busy(rec): + """What AWS turned away went through: the count starts over.""" + if rec.pop("busy", None) is not None and str(rec.get("reason") or "").startswith("AWS is busy"): + rec["reason"] = "" + + +def busy_why(e): + return f"{type(e).__name__}: {str(e)[:250]}" + + +def retry_time(at): + if isinstance(at, str): + try: + at = datetime.fromisoformat(at) + except ValueError: + return "in a little while" + return "at " + at.strftime("%H:%M UTC") + + + def check_repo(repo): """Releases come only from CoderHelm's own repository.""" if repo != RELEASE_REPO: @@ -1471,6 +1583,15 @@ class ReleaseNotReady(ValueError): check hasn't verified it): a wait. Nothing is recorded in history.""" +class AwsBusy(ReleaseNotReady): + """AWS throttled a step before anything changed: a wait like the one + above, retried by itself (`cause`: what AWS said).""" + + def __init__(self, cause): + super().__init__("AWS is busy, retrying") + self.cause = cause + + class ModelsBlocked(ValueError): """Update now refused by the model check (the record goes with it).""" @@ -1520,8 +1641,9 @@ def start_verify(store, env, now, version): if recent and (v.get("claim") or build_state(v.get("build")) in (None, "IN_PROGRESS")): return False try: - build = start_check(env, version) + build = busy_retry(lambda: start_check(env, version)) except Exception as e: + # Throttled or not: the record stays pending and the next read starts it. logger.warning(f"Release check not started: {e}") return False state["verifying"] = {"version": version, "at": now.isoformat(), "build": build} @@ -1754,9 +1876,22 @@ def model_check(store, env, now, version, repo, probe=invoke_worker): required = set(manifest.get("calls") or []) | set(configured_models(env)) models = store.get("MODELS") or {} try: - answer = probe(env, {"targets": targets, "probe_team": models.get("probe_team")}) + answer = busy_retry(lambda: probe(env, {"targets": targets, "probe_team": models.get("probe_team")})) except Exception as e: # the worker didn't answer: unknown, not refused logger.warning(f"Model check not run: {e}") + old = store.get("MODEL_CHECK") or {} + if throttled(e): + # AWS was busy: pending (it holds the update, never refuses it), and + # every read of the page and every poll checks again by itself. + busy = {"busy": old["busy"]} if old.get("version") == version and old.get("busy") else {} + over = busy_mark(busy, now, busy_why(e)) + note = busy_note(busy) + " the model check" + ( + "; it keeps checking by itself" if over else "") + record = {"version": version, "checked_at": now.isoformat(), "ok": False, "pending": True, "results": [], + "started_at": busy["busy"]["since"], "busy": busy["busy"], "note": note, + "notified": bool(old.get("version") == version and old.get("notified"))} + store.put("MODEL_CHECK", record) + return record answer = {"results": [{"model": t["model"], "id": t["model"], "status": "fail", "code": "unreachable", "detail": "The model check couldn't run.", "fix": "Check again in a few minutes; if it keeps failing, see the worker's log.", @@ -1964,6 +2099,13 @@ def follow_request(store, env, now, probe=None, latest=None, record=None): return settle_request(store, req, now, "ended", "the requested version isn't a release") if parse_version(current) and compare(version, current) <= 0: return settle_request(store, req, now, "done", f"this install already runs {current}") + if req.get("retry_at") and not (latest and parse_version(latest) and compare(latest, version) > 0): + try: + later = now < datetime.fromisoformat(req["retry_at"]) + except ValueError: + later = False + if later: + return req # AWS was busy: it starts again by itself then if latest and parse_version(latest) and compare(latest, version) > 0: # A newer release came out while this one was checked: Update means the newest. req = record_request(store, now, latest, req.get("actor") or DIRECT_ACTOR, req.get("skip_check", False), @@ -1979,6 +2121,9 @@ def follow_request(store, env, now, probe=None, latest=None, record=None): if not (is_native(env) and unapplied(live)): return req # another update runs: this one waits for it mc = record if record and record.get("version") == version else (store.get("MODEL_CHECK") or {}) + if mc.get("version") == version and mc.get("pending") and mc.get("busy") and verified_manifest(store, version)[0]: + # AWS turned the model check away: checked again here, by itself. + mc = model_check(store, env, now, version, env.get("RELEASE_REPO", RELEASE_REPO), probe or invoke_worker) if mc.get("version") != version or mc.get("pending"): try: old = now - datetime.fromisoformat(req.get("requested_at") or "") > REQUEST_LIMIT @@ -1999,6 +2144,8 @@ def follow_request(store, env, now, probe=None, latest=None, record=None): try: started = begin(store, env, now, version, req.get("actor") or DIRECT_ACTOR, "update", note=note, consent=req.get("accept_permissions", False)) + except AwsBusy as e: + return busy_request(store, env, now, req, e) except ReleaseNotReady as e: req = dict(req, waiting_for=str(e)) store.put("UPDATE_REQUEST", req) @@ -2008,6 +2155,62 @@ def follow_request(store, env, now, probe=None, latest=None, record=None): return settle_request(store, req, now, "started", id=started.get("id")) +def busy_request(store, env, now, req, e): + """An Update press AWS turned away before the change set existed: it + keeps waiting ("AWS is busy, retrying (attempt n)") and every poll tries + again. Past BUSY_LIMIT the try is recorded as failed, and it starts + again by itself after BUSY_RETRY_AFTER unless an admin cancels it.""" + req = {k: v for k, v in req.items() if k != "retry_at"} + if not busy_mark(req, now, e.cause): + req["waiting_for"] = busy_note(req) + store.put("UPDATE_REQUEST", req) + return req + at = now + BUSY_RETRY_AFTER + current = env.get("CODERHELM_VERSION", "") + hid = f"UPDATE#{now.strftime('%Y-%m-%dT%H:%M:%SZ')}#{uuid.uuid4().hex[:8]}" + d = explain_failure(req["busy"]["last"], req.get("version"), current, PREPARE, retry_at=at) + store.put(hid, {"version": req.get("version"), "from_version": current, "actor": req.get("actor") or DIRECT_ACTOR, + "mode": "update", "status": "failed", "started_at": req["busy"]["since"], "finished_at": now.isoformat(), + "busy": req["busy"], "retry_at": at.isoformat(), **d}) + req.pop("busy", None) + req.update(retry_at=at.isoformat(), failed_id=hid, retries=int(req.get("retries") or 0) + 1, + waiting_for=f"AWS was busy, so CoderHelm starts it again by itself {retry_time(at)}") + store.put("UPDATE_REQUEST", req) + return req + + +def busy_retry_at(entry, now): + """When an update AWS kept turning away starts again by itself: an + update (an admin's press, or the window's), never a rollback or a switch.""" + return now + BUSY_RETRY_AFTER if entry.get("mode") == "update" and parse_version(entry.get("version") or "") else None + + +def busy_retry_later(store, now, entry, at, hid): + """Starts `entry`'s update again by itself at `at` (follow_request). The + window's own update is started again by the hourly check instead.""" + if entry.get("scheduled"): + return None + note = str(entry.get("note") or "") + req = record_request(store, now, entry["version"], entry.get("actor") or DIRECT_ACTOR, + skip_check=note.startswith("model check skipped"), + waiting_for=f"AWS was busy, so CoderHelm starts it again by itself {retry_time(at)}", + consent=consented(entry)) + req.update(retry_at=at.isoformat(), failed_id=hid) + store.put("UPDATE_REQUEST", req) + return req + + +def cancel_request(store, now, actor): + """An admin stops an Update press that waits (for the release check, or + to start again by itself after AWS was busy).""" + req = store.get("UPDATE_REQUEST") or {} + if req.get("status") != "waiting": + return {"cancelled": False, "request": None} + req = settle_request(store, {k: v for k, v in req.items() if k not in ("retry_at", "busy")}, now, "ended", + f"cancelled by {actor}", cancelled_by=actor) + return {"cancelled": True, "request": req} + + def request_view(req, now, current=""): """The Update press for the version route: while it waits, and for a day after it ended. Never once the install runs that version or a newer one: @@ -2023,7 +2226,11 @@ def request_view(req, now, current=""): return None except ValueError: return None - return {k: req.get(k) for k in ("version", "actor", "requested_at", "status", "waiting_for", "reason", "ended_at", "id", "replaces") if req.get(k) is not None} + view = {k: req.get(k) for k in ("version", "actor", "requested_at", "status", "waiting_for", "reason", "ended_at", "id", "replaces", + "retry_at", "failed_id") if req.get(k) is not None} + if req.get("busy") and req.get("status") == "waiting": + view["busy"] = {"attempts": int(req["busy"].get("attempts") or 1), "since": req["busy"].get("since")} + return view # ── The deploy window (hardened installs) ──────────────────────────────── @@ -3005,6 +3212,8 @@ def preflight(cfn, env, cs_id, stack, iam=None): try: access = deploy_role_access(env, iam) except Exception as e: # noqa: BLE001 + if throttled(e): + raise # AWS was busy: the check is made again, never counted as a refusal return [f"couldn't check: the deploy role's policies couldn't be read ({type(e).__name__}: {str(e)[:160]})"] account, partition = stack_account(stack), stack_partition(stack) region = env.get("AWS_REGION") or stack_region(stack) @@ -3033,6 +3242,8 @@ def walk(cid, part, stack_name): try: walk(cs_id, "parent", env["NATIVE_STACK"]) except Exception as e: # noqa: BLE001 + if throttled(e): + raise out.append(f"couldn't check: the change set couldn't be read in full ({type(e).__name__}: {str(e)[:160]})") return out @@ -3997,11 +4208,39 @@ def keep(e): store.put(hid, e) return True region = env.get("AWS_REGION") or "" + executed = bool(entry.get("executed_at")) + + def busy(e): + """AWS throttled a step before the change set ran: the update keeps + waiting and the next poll (or read of the page) tries again. Past + BUSY_LIMIT it fails, and starts again by itself (busy_retry_later).""" + if (store.get(hid, {}) or {}).get("status") != was: + return {"native": "moved on"} + if not busy_mark(entry, now, busy_why(e)): + entry["reason"] = busy_note(entry) + store.put(hid, entry) + logger.warning(f"{hid}: {entry['reason']} ({entry['busy']['last']})") + return {"native": "busy", "attempt": entry["busy"]["attempts"], "reason": entry["reason"]} + try: + cfn.delete_change_set(ChangeSetName=cs_id, StackName=env["NATIVE_STACK"]) + except Exception as d: # noqa: BLE001 + logger.warning(f"change set not deleted: {d}") + at = busy_retry_at(entry, now) + if at: + entry["retry_at"] = at.isoformat() + entry["reason"] = "" + store.put(hid, entry) + out = native_finish(store, env, now, hid, "failed", entry["busy"]["last"], PREPARE) + if at: + busy_retry_later(store, now, entry, at, hid) + return out try: - cs = cfn.describe_change_set(ChangeSetName=cs_id, StackName=env["NATIVE_STACK"]) + cs = busy_retry(lambda: cfn.describe_change_set(ChangeSetName=cs_id, StackName=env["NATIVE_STACK"])) except Exception as e: if "does not exist" in str(e) or "ChangeSetNotFound" in type(e).__name__: return native_finish(store, env, now, hid, "failed", "the proposed change set was deleted before it ran", PREPARE) + if throttled(e) and not executed: + return busy(e) raise summary = change_set_summary(cs, region, role=prepared_role(entry)) entry["change_set"] = summary @@ -4015,21 +4254,36 @@ def keep(e): keep(entry) return {"native": "preparing"} if execution == "AVAILABLE" and "checked" not in entry: - if not fetched_template_matches(cfn, env, cs_id, entry.get("template_canonical")): + def check(): + """What the change set does, read in full: AWS throttling any read + makes the whole check again, never a refusal.""" + matches = fetched_template_matches(cfn, env, cs_id, entry.get("template_canonical")) + if not matches: + return None + out = {"data_changes": data_changes(cfn, cs), "admin_changes": admin_changes(cs), + "permission_changes": permission_changes(cfn, cs_id, env["NATIVE_STACK"])} + if prepared_role(entry) or (prepared_role(entry) is None and entry.get("apply")): + stack = cfn.describe_stacks(StackName=env["NATIVE_STACK"])["Stacks"][0] + out["preflight"] = preflight(cfn, env, cs_id, stack) + return out + try: + found = busy_retry(check) + except Exception as e: + if throttled(e): + return busy(e) + raise + if found is None: try: cfn.delete_change_set(ChangeSetName=cs_id, StackName=env["NATIVE_STACK"]) except Exception as e: logger.warning(f"change set not deleted: {e}") return native_finish(store, env, now, hid, "failed", "the template CloudFormation fetched is not the verified one, so the change set was deleted", PREPARE) - entry["data_changes"] = data_changes(cfn, cs) - entry["admin_changes"] = admin_changes(cs) - entry["permission_changes"] = permission_changes(cfn, cs_id, env["NATIVE_STACK"]) - if prepared_role(entry) or (prepared_role(entry) is None and entry.get("apply")): - stack = cfn.describe_stacks(StackName=env["NATIVE_STACK"])["Stacks"][0] - entry["preflight"] = preflight(cfn, env, cs_id, stack) + entry.update(found) entry["checked"] = True summary["data_changes"] = entry["data_changes"] entry["change_set"] = summary + if not entry.get("apply"): + not_busy(entry) # nothing left to call AWS for until an admin applies it never = never_runs(entry) if execution == "AVAILABLE" and entry.get("checked") else "" if never and not entry.get("executed_at"): # It runs as the deploy role whoever executes it (the stack's service @@ -4067,8 +4321,14 @@ def keep(e): if entry.get("apply") and not hold and not entry.get("executed_at"): if (store.get(hid, {}) or {}).get("status") != was: return {"native": "moved on"} - cfn.execute_change_set(ChangeSetName=cs_id, StackName=env["NATIVE_STACK"]) + try: + busy_retry(lambda: cfn.execute_change_set(ChangeSetName=cs_id, StackName=env["NATIVE_STACK"])) + except Exception as e: + if throttled(e): + return busy(e) + raise entry.update({"executed_at": now.isoformat(), "status": "running"}) + not_busy(entry) if entry.get("permission_changes") and consented(entry): # What the press agreed to, as it turned out: kept with the update. c = entry["consent"] @@ -4910,8 +5170,9 @@ def _access_fix(access): else "An AWS admin applies the access stack update (Settings, System, Permissions has the link), then try again.") -def _cause(raw, access=None, phase=None): - """(what went wrong, the next step) for CloudFormation's text, or (None, None).""" +def _cause(raw, access=None, phase=None, retry_at=None): + """(what went wrong, the next step) for CloudFormation's text, or (None, None). + `retry_at`: when CoderHelm starts the update again by itself (AWS was busy).""" text = raw or "" low = text.lower() m = _NOT_ALLOWED.search(text) @@ -4924,8 +5185,15 @@ def _cause(raw, access=None, phase=None): if m or "accessdenied" in low or "access denied" in low: return ("CoderHelm's update role isn't allowed to do something this release needs", _NEXT_RELEASE + " If that one fails the same way, send the technical details to CoderHelm support.") - if "rate exceeded" in low or "throttl" in low or "too many requests" in low: - return ("AWS was busy and turned some calls away", "Press Update again in a few minutes.") + if "rate exceeded" in low or "throttl" in low or "too many requests" in low or throttled(Exception(text)): + # Never the release, and never a person's job to press again. + if phase == PREPARE: + what = f"AWS was busy and kept turning calls away for {int(BUSY_LIMIT.total_seconds() // 60)} minutes while CoderHelm retried" + if retry_at: + return (what, f"Nothing to do: CoderHelm starts it again by itself {retry_time(retry_at)}.") + return (what, "It wasn't the release or the install: try it again once AWS is less busy, in a few minutes.") + return ("AWS was busy and turned some calls away", + "It wasn't the release or the install: try it again once AWS is less busy, in a few minutes.") if "limitexceeded" in low or "limit exceeded" in low or "quota" in low: return ("your AWS account reached one of its limits", "Raise the limit the technical details name (AWS console, Service Quotas) or remove what you don't use, then press Update again.") @@ -4947,14 +5215,14 @@ def _cause(raw, access=None, phase=None): return (None, None) -def explain_failure(raw, version, from_version, phase, access=None): +def explain_failure(raw, version, from_version, phase, access=None, retry_at=None): """{summary, fix, technical, reason} for an update that didn't succeed. `access`: the access stack against the running release (access_stack_state), for a step that needs it first.""" raw = str(raw or "").strip() v = version or "the new release" was = from_version or "the release it ran before" - what, fix = _cause(raw, access, phase) + what, fix = _cause(raw, access, phase, retry_at) part = re.match(r"([A-Za-z][A-Za-z0-9]{0,63}): ", raw) broken = f"the {part.group(1)} part of the install could not be updated" if part else "a part of the install could not be updated" if phase == UNANSWERED: @@ -4995,7 +5263,7 @@ def native_finish(store, env, now, hid, status, reason, phase=None): access_needed(store, env, now, dict(entry, access=access), [denied]) except Exception as e: # noqa: BLE001 logger.warning(f"access card not marked: {e}") - event.update(explain_failure(reason, entry.get("version"), entry.get("from_version"), phase, access)) + event.update(explain_failure(reason, entry.get("version"), entry.get("from_version"), phase, access, entry.get("retry_at"))) elif (store.get(hid, {}) or {}).get("mode") == "options": # A change applied: whatever an earlier refusal needed is applied too. store.put("ACCESS_NEEDED", {}) @@ -5068,10 +5336,13 @@ def refused(e): if is_native(env): try: - entry.update(native_propose(store, env, version, mode, extra)) + entry.update(busy_retry(lambda: native_propose(store, env, version, mode, extra))) except ReleaseNotReady: raise except Exception as e: # noqa: BLE001 nothing changed: say so, never leave it running + if throttled(e): + # AWS was busy: a wait, never a refusal (busy_request). + raise AwsBusy(busy_why(e)) from e refused(e) entry["status"] = "preparing" store.put(hid, entry) @@ -5079,8 +5350,14 @@ def refused(e): else: store.put(hid, entry) try: - entry["build_id"] = start_build(env, version, actor, mode, hid, extra) if extra else start_build(env, version, actor, mode, hid) + entry["build_id"] = busy_retry(lambda: start_build(env, version, actor, mode, hid, extra) if extra + else start_build(env, version, actor, mode, hid)) except Exception as e: # noqa: BLE001 + if throttled(e): + # Nothing started: the press waits and is tried again (busy_request). + store.put(hid, dict(entry, status="not_started", finished_at=now.isoformat(), + reason="AWS was busy, so this try didn't start; CoderHelm tries again by itself")) + raise AwsBusy(busy_why(e)) from e refused(e) store.put(hid, entry) state.update({"running_since": now.isoformat(), "running_id": hid}) @@ -5249,6 +5526,12 @@ def releases(max_age, refresh=False): note = "model check skipped for " + ", ".join(f.get("model", "?") for f in failures(mc)) try: started = begin(store, env, now, version, actor, "update", note=note, consent=bool(event.get("accept_permissions"))) + except AwsBusy as e: + # AWS turned the start away: kept like a check, and tried again by itself. + req = record_request(store, now, version, actor, bool(event.get("skip_check")), waiting_for="AWS is busy, retrying", + consent=bool(event.get("accept_permissions"))) + req = busy_request(store, env, now, req, e) + return {"state": "checking", "version": version, "request": request_view(req, now, env.get("CODERHELM_VERSION", "")), "model_check": mc} except ReleaseNotReady as e: # Still publishing, or its template not verified yet: a wait, kept like a check. req = record_request(store, now, version, actor, bool(event.get("skip_check")), waiting_for=str(e), @@ -5364,6 +5647,9 @@ def releases(max_age, refresh=False): if action == "apply_update": return native_apply(store, env, now, event) + if action == "cancel_request": + return cancel_request(store, now, event.get("actor") or DIRECT_ACTOR) + if action == "set_options": return set_options(store, env, now, event) @@ -5395,7 +5681,8 @@ def releases(max_age, refresh=False): # about the release, so it never marks the version as failed. store.put("UPDATE_STATE", state) return domain_finished(store, env, now, entry, status) - if status != "succeeded" and version: + if status != "succeeded" and version and not entry.get("retry_at"): + # AWS being busy says nothing about the release: it isn't marked failed. failed = set(state.get("failed_versions") or []) failed.add(version) state["failed_versions"] = sorted(failed) @@ -5415,7 +5702,8 @@ def releases(max_age, refresh=False): "current": entry.get("from_version"), "checked_at": checked_at(now), "reason": entry.get("reason"), - "action": "Open the update's log under Settings, System, Update history, fix what it names, then press Update now.", + "action": (entry.get("fix") if entry.get("retry_at") else + "Open the update's log under Settings, System, Update history, fix what it names, then press Update now."), }, ) return {"status": status, "version": version} @@ -5438,6 +5726,11 @@ def releases(max_age, refresh=False): if not is_native(env): raise ValueError("native_poll: not a native install") out = native_poll(store, env, now, wait=True) + # An Update press waiting (AWS was busy, or its check) carries on every 5 minutes. + try: + follow_request(store, env, now, probe) + except Exception as e: # noqa: BLE001 the next poll tries again + logger.warning(f"waiting update not followed: {e}") # The release just installed: probed and watched, rolled back when it fails. w = watch_step(store, env, now, health) return dict(out, health_watch=w) if w else out @@ -5482,7 +5775,12 @@ def releases(max_age, refresh=False): d = {"action": "none", "version": d["version"], "reason": "a model this release calls was refused; checking again daily"} else: - begin(store, env, now, d["version"], "auto", "update", scheduled=True) + try: + begin(store, env, now, d["version"], "auto", "update", scheduled=True) + except AwsBusy as e: + # Nothing changed: the next hourly check in the window starts it again. + logger.warning(f"AWS is busy, the update starts at the next check: {e.cause}") + d = dict(d, action="none", reason="AWS is busy, retrying at the next check") remind_waiting(store, env, now, current) send_digest(store, env, now, settings, rel, current) logger.info(json.dumps(d)) diff --git a/services/gateway/src/main.rs b/services/gateway/src/main.rs index 3dd4e7fe2..d96dd438c 100644 --- a/services/gateway/src/main.rs +++ b/services/gateway/src/main.rs @@ -183,7 +183,12 @@ fn build_app(state: Arc) -> Router { "/system/uninstall-mode", put(routes::system::set_uninstall_mode), ) - .route("/system/update", post(routes::system::update_now)) + // DELETE: stop an Update press that waits (its release check, or + // starting again by itself after AWS was busy). + .route( + "/system/update", + post(routes::system::update_now).delete(routes::system::cancel_update), + ) // Apply the prepared update waiting for an admin (a native install). .route("/system/update/apply", post(routes::system::apply_update)) // What the install reads in its own account (Inspector, Health, diff --git a/services/gateway/src/permissions.rs b/services/gateway/src/permissions.rs index 15ab2afd1..313773860 100644 --- a/services/gateway/src/permissions.rs +++ b/services/gateway/src/permissions.rs @@ -838,6 +838,7 @@ pub const CAPABILITIES: &[Capability] = &[ "system::set_auto_update", "system::set_uninstall_mode", "system::update_now", + "system::cancel_update", "system::apply_update", "system::set_options", "system::check_update", diff --git a/services/gateway/src/routes/system.rs b/services/gateway/src/routes/system.rs index 8627639ee..e76dfa2fc 100644 --- a/services/gateway/src/routes/system.rs +++ b/services/gateway/src/routes/system.rs @@ -239,6 +239,25 @@ pub async fn update_now( answer(body) } +/// DELETE /api/system/update: stop the Update press that waits, for the +/// release check or to start again by itself after AWS turned the start +/// away (lambda/updater, cancel_request). Nothing that already started. +pub async fn cancel_update( + State(state): State>, + Extension(claims): Extension, +) -> Reply { + claims.require_role(3).map_err(status_only)?; + allowed(&claims).map_err(status_only)?; + warn!(email = %claims.email, "Waiting update cancelled"); + let body = call( + &state, + json!({ "action": "cancel_request", "actor": claims.email }), + ) + .await + .map_err(status_only)?; + answer(body) +} + /// What a request may send to apply a prepared update: the update's id and, /// when it would replace or remove data or change permissions, `confirm`: /// the token the version route lists with exactly those changes (the