Adrià Vilanova MartÃnez | f19ea43 | 2024-01-23 20:20:52 +0100 | [diff] [blame^] | 1 | # 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 | |
| 6 | import logging |
| 7 | import os |
| 8 | |
| 9 | from google.appengine.api import runtime |
| 10 | from googleapiclient import discovery |
| 11 | from googleapiclient import errors |
| 12 | from oauth2client import client |
| 13 | |
| 14 | import settings |
| 15 | |
| 16 | _MAXIMUM_MEMORY_USAGE = 2000 |
| 17 | |
| 18 | |
| 19 | def 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) |