blob: 05ebb296bfb7958c6d384067c22a4e6f024672ce [file] [log] [blame]
Adrià Vilanova Martínezf19ea432024-01-23 20:20:52 +01001# Copyright 2023 The Chromium Authors
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4"""A handler run on Flask request teardown."""
5
6import logging
7import os
8
9from google.appengine.api import runtime
10from googleapiclient import discovery
11from googleapiclient import errors
12from oauth2client import client
13
14import settings
15
16_MAXIMUM_MEMORY_USAGE = 2000
17
18
19def Teardown(_exc):
20 if settings.local_mode:
21 return
22
23 # Stop the instance if it's using too much memory.
24 memory_usage = runtime.memory_usage().average10m
25 if memory_usage < _MAXIMUM_MEMORY_USAGE:
26 return
27
28 credentials = client.GoogleCredentials.get_application_default()
29 appengine = discovery.build('appengine', 'v1', credentials=credentials)
30 delete = appengine.apps().services().versions().instances().delete(
31 appsId=os.environ.get('GAE_APPLICATION').split('~')[-1],
32 servicesId=os.environ.get('GAE_SERVICE'),
33 versionsId=os.environ.get('GAE_VERSION'),
34 instancesId=os.environ.get('GAE_INSTANCE'))
35 try:
36 delete.execute()
37 except errors.HttpError as e:
38 if e.status_code != 404:
39 raise
40 else:
41 logging.critical('Deleted instance using %d MB of memory.' % memory_usage)