【发布时间】:2020-03-15 10:56:41
【问题描述】:
我正在尝试在 Google Cloud 上为我的 VM 实例创建启动/停止计划。我正在关注这个由 Google 创建的tutorial,但是当我到达 (可选)验证功能工作 部分并尝试测试 stopInstancePubSub 功能并通过 {"data":"eyJ6b25lIjoidXMtd2VzdDEtYiIsICJsYWJlbCI6ImVudj1kZXYifQo="} JSON 对象我收到以下错误:
2019-06-09 17:23:54.225 EDT
stopInstancePubSub
ipmdukx38xpw
TypeError: callback is not a function at exports.stopInstancePubSub (/srv/index.js:55:5) at /worker/worker.js:825:24 at <anonymous> at process._tickDomainCallback (internal/process/next_tick.js:229:7)
不确定我在这里做错了什么,我是否缺少另一个要传递给函数的参数?
*编辑:使用的代码取自谷歌教程:
const Buffer = require('safe-buffer').Buffer;
const Compute = require('@google-cloud/compute');
const compute = new Compute();
/**
* Stops a Compute Engine instance.
*
* Expects a PubSub message with JSON-formatted event data containing the
* following attributes:
* zone - the GCP zone the instances are located in.
* instance - the name of a single instance.
* label - the label of instances to start.
*
* Exactly one of instance or label must be specified.
*
* @param {!object} event Cloud Function PubSub message event.
* @param {!object} callback Cloud Function PubSub callback indicating completion.
*/
exports.stopInstancePubSub = (event, callback) => {
try {
const pubsubMessage = event.data;
const payload = _validatePayload(
JSON.parse(Buffer.from(pubsubMessage.data, 'base64').toString())
);
const options = {filter: `labels.${payload.label}`};
compute.getVMs(options).then(vms => {
vms[0].forEach(instance => {
if (payload.zone === instance.zone.id) {
compute
.zone(payload.zone)
.vm(instance.name)
.stop()
.then(data => {
// Operation pending.
const operation = data[0];
return operation.promise();
})
.then(() => {
// Operation complete. Instance successfully stopped.
const message = 'Successfully stopped instance ' + instance.name;
console.log(message);
callback(null, message);
})
.catch(err => {
console.log(err);
callback(err);
});
}
});
});
} catch (err) {
console.log(err);
callback(err);
}
};
/**
* Validates that a request payload contains the expected fields.
*
* @param {!object} payload the request payload to validate.
* @return {!object} the payload object.
*/
function _validatePayload(payload) {
if (!payload.zone) {
throw new Error(`Attribute 'zone' missing from payload`);
} else if (!payload.label) {
throw new Error(`Attribute 'label' missing from payload`);
}
return payload;
}
【问题讨论】:
-
请提供代码以供审核。
-
你的 JSON 没问题。您需要发布代码。
-
请看编辑,代码与上面链接的教程相同。 @约翰汉利
-
在调试中,您有一条错误消息。现在将该错误消息映射到问题中的文件和行。这将帮助我们找出问题所在。注意:做出假设是许多错误的根源。因此,在发布问题时,我们不会假设任何事情。我们需要所有的细节。
标签: node.js google-cloud-platform google-cloud-pubsub google-cloud-scheduler