From 11d8f77a2323fa1d42bf9d196936742d3af2f9f4 Mon Sep 17 00:00:00 2001 From: Ryan Barrett Date: Tue, 18 Jun 2024 15:37:33 -0700 Subject: [PATCH] bring back checking CPU credit balance originally added in 353af359dd2253dc6884076b0adbbf8de0846cf3, accidentally removed in e6a09e4fb0a1812c1a94992888a815592539a5c9 --- app.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/app.py b/app.py index 3229783..25f7eae 100644 --- a/app.py +++ b/app.py @@ -18,6 +18,7 @@ from b2sdk.account_info.in_memory import InMemoryAccountInfo from b2sdk.api import B2Api from b2sdk.progress import AbstractProgressListener +import boto.ec2.cloudwatch import requests import webob import webob.exc @@ -85,6 +86,23 @@ def application(environ, start_response): 'Sorry, this content is not currently supported due to copyright.')( environ, start_response) + # check that our CPU credit balance isn't too low + try: + cloudwatch = boto.ec2.cloudwatch.connect_to_region('us-east-2') + for metric in cloudwatch.list_metrics(metric_name='CPUCreditBalance'): + if metric.name == 'CPUCreditBalance': + stats = metric.query(datetime.datetime.now() - datetime.timedelta(minutes=10), + datetime.datetime.now(), ['Average']) + if stats: + credit = stats[-1].get('Average') + if credit and credit <= 30: + msg = "Sorry, we're too busy right now. Please try again later!" + exc = webob.exc.HTTPServiceUnavailable(msg) + exc.html_template_obj = Template(HTML_HEADER + msg + HTML_FOOTER) + return exc(environ, start_response) + except: + logging.exception("Couldn't fetch CPU credit balance from CloudWatch!") + write_fn = start_response('200 OK', headers) def write(line): write_fn(line.encode())