Scheduling GCE with Cloud Pub/Sub(Node.js 8)

2019-10-03

There’s something we have to automatically start and stop Compute Engine instances with scheduler. It is too waste of cost running development server that is not public service 24/7. There might be cases that are not necessary to keep running public service in all time.

It is used Cloud functions(Cloud Pub/Sub) and Cloud Scheduler in order to schedule GCE instances.
Scheduling compute instances with Cloud Scheduler

Basically, you can schedule instances in accordance to what is written the documents.

Cloud Scheduler & Cloud Pub/Sub with Nodejs8

It work fine in accordance to the above documents, but it’s only in “Node6". The document forces us use with Node6.

But the depreciation alert appear when we choice Node6.

Node.js 6 depreciation

Basically we should not deploy with node.js 6. so I deployed the script that start or stop instances with node.js 8.

However, The script was not working well with node.js8. The following error message was logged.

	TypeError: First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object. 
	at Function.Buffer.from (buffer.js:183:11) at exports.startInstancePubSub (/srv/index.js:20:25) at /worker/worker.js:825:24 at  at process._tickDomainCallback (internal/process/next_tick.js:229:7)

In spite of according to the official reference, It appear the error with nodejs8. I found “pubsubMessage.data" undefind.

	const pubsubMessage = event.data;
    const payload = _validatePayload(
      // pubsubMessage.data が undefind!
      JSON.parse(Buffer.from(pubsubMessage.data, 'base64').toString())
    );

I don’t know why does’t work, but it is going to work well, if the following.

	const pubsubMessage = event.data;
    const payload = _validatePayload(
      JSON.parse(Buffer.from(pubsubMessage, 'base64').toString())
    );

Although, the following error message was still logged.

	TypeError: callback is not a function at compute.zone.vm.stop.then.then.catch.err
	 (/srv/index.js:39:9) at  at process._tickDomainCallback (internal/process/next_tick.js:229:7)

An error occurs in finaly callback after starting or stopping instances.
The solution is the following.
Scheduling GCE with Cloud Pub/Sub(Node.js 8)(2)