Home > Mobile >  How to stop an App Engine instance programmatically
How to stop an App Engine instance programmatically

Time:09-28

I have an Google App Engine instance that is started every 15 minutes using a Cron job: it simply gets a https request every 15 minutes. The server then runs a number of cron jobs and needs to terminate. I have setup the server with a yaml file that starts with:

runtime: php81
service: crontask
instance_class: B4
basic_scaling:
  max_instances: 1
  idle_timeout: 2m

This works most of the time: the instance starts, the jobs run and then the instance terminates 2 minutes after completing the job. But sometimes (once every few weeks) the instance keeps on running for 24 hours (the maximum timeout from GAE), which breaks the cron job running at that moment.

Question: I want to programmatically terminate the server at the end if the job. So the server needs to send a termination signal to itself. Is this possible?

The CLI program gcloud allows you to shutdown an instance as documented in https://cloud.google.com/sdk/gcloud/reference/app/instances/delete and the parameters are all available as environment variables:

GAE_INSTANCE - instance id
GAE_VERSION  - version
GAE_SERVICE  - service name

So I am thinking it should be possible to call the same url called by gcloud to delete/shutdown the instance, but I haven't found the docs how to do this.

CodePudding user response:

I don't know whether you can do this because I've not done it.

However...

For any gcloud command, you can append --log-http to see which underlying REST calls are made by the command.

Alternatively, you can use APIs Explorer to find e.g. App Engine Admin API and then find instances.delete.

Google provides client libraries for all its services. So, depending your language, you can find either a Cloud Client Library or API Client Library for your language for this API. I encourage you to use the Google library rather than invoke the API directly.

CodePudding user response:

There is a work around for disabling a GAE App when you have reached your budget. That work around involves setting the servingStatus to USER_DISABLED. Maybe you can take a look at the code and see if you can repurpose it to accomplish what you want (e.g. find an attribute that will shut down the App instead of disabling it).

We published an article with the code here on our blog.

  • Related