Start/Stop Compute Engine Instance from Cloud function

https://medium.com/google-cloud/start-stop-compute-engine-instance-from-cloud-function-bf9ae5199609

I design a web service that will running on Google Compute Engine to do some long-time data processing task. The data will be stored at Cloud Storage and service on Compute Engine will get the data from Cloud Storage. After processing, the service will save the handled data back to Cloud Storage. And also, the service is not frequency used.

If we start a instance of Compute Engine, it will start to consume our resource. For cost efficient purpose, I need to minimize the waste. So, I start to survey is there any way to start the compute engine only when we need it.

After digging from Google Cloud Platform documents, I found:Using the Node.js Client Libraries | Compute Engine Documentation | Google Cloud PlatformDeploying Docker Containers on Compute Enginecloud.google.com

This library allow us to access Compute Engine! I decide to change my system design to: When data upload to Cloud Storage, it trigger the Cloud Function. The Cloud Function send command to start Compute Engine to process the data. After processing, Compute Engine trigger a Cloud Function event to stop the Compute Engine itself. By this design, we can stop our VM to save money while it need not to be used. That is, only enable VM when it need!

For Cloud Function, I create two function:

Start Compute Engine:

var http = require('http');
var Compute = require('@google-cloud/compute');
var compute = Compute();
exports.startInstance = function startInstance(req, res) {
    var zone = compute.zone('us-west1-a');
    var vm = zone.vm('instance-1');
    vm.start(function(err, operation, apiResponse) {
    console.log('instance start successfully');
    });
res.status(200).send('Success start instance');
};

package.json:

{
    "name": "sample-http","dependencies": 
        {
            "@google-cloud/compute": "0.7.1"
        },
    "version": "0.0.1"
}

Stop Compute Engine:

var Compute = require('@google-cloud/compute');
var compute = Compute();
exports.stopInstance = function stopInstance(req, res) {
    var zone = compute.zone('instance zone here');
    var vm = zone.vm('instance name here');
    vm.stop(function(err, operation, apiResponse) {
        console.log('instance stop successfully');    
    });
res.status(200).send('Success stop instance');
};

Testing these functions and you will see your instance start/stop. This article is some try of my interesting. It may not be useful for a real system design, but it will save money for me!

For now, I did not finish the complete flow of the design, so maybe the design of my service will be changed again after understanding more about Google Cloud Platform. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *