@@ -168,3 +168,36 @@ def __stop_instances(project_id, zone, instance_names, instances):
168168 instance = name ).execute ()
169169 print (f'Instance stopped successfully: { name } ' )
170170# [END functions_billing_limit]
171+
172+
173+ # [START functions_billing_limit_appengine]
174+ APP_NAME = os .getenv ('GCP_PROJECT' )
175+
176+
177+ def limit_use_appengine (data , context ):
178+ pubsub_data = base64 .b64decode (data ['data' ]).decode ('utf-8' )
179+ pubsub_json = json .loads (pubsub_data )
180+ cost_amount = pubsub_json ['costAmount' ]
181+ budget_amount = pubsub_json ['budgetAmount' ]
182+ if cost_amount <= budget_amount :
183+ print (f'No action necessary. (Current cost: { cost_amount } )' )
184+ return
185+
186+ appengine = discovery .build (
187+ 'appengine' ,
188+ 'v1' ,
189+ cache_discovery = False ,
190+ credentials = GoogleCredentials .get_application_default ()
191+ )
192+ apps = appengine .apps ()
193+
194+ # Get the target app's serving status
195+ target_app = apps .get (appsId = APP_NAME ).execute ()
196+ current_status = target_app ['servingStatus' ]
197+
198+ # Disable target app, if necessary
199+ if current_status == 'SERVING' :
200+ print (f'Attempting to disable app { APP_NAME } ...' )
201+ body = {'servingStatus' : 'USER_DISABLED' }
202+ apps .patch (appsId = APP_NAME , updateMask = 'serving_status' , body = body ).execute ()
203+ # [END functions_billing_limit_appengine]
0 commit comments