【问题标题】:gcp failure detector with cloud functions具有云功能的 gcp 故障检测器
【发布时间】:2020-08-04 19:11:57
【问题描述】:

我是谷歌云平台的初学者,我正在玩 iot-core、pub/sub 和 can 函数。我想为通过 pub/sub 向云端发送消息的设备制作一个简单的故障检测器。

为简单起见,我想直接将遥测数据用作心跳,但我很难将所有这些数据放在一起。

我草绘了这段代码,这是错误的,但我希望能帮助理解我想要做什么。 这个想法是捕获遥测消息并在每次有新消息时保存相应的 id。然后,每 10 分钟检查一次是否所有以前的存活者都还在。

/* devices on system */
var alive = [1,2];
/* heartbeats */ 
var received = []; 


/**
 * Triggered from a message on a Cloud Pub/Sub topic.
 *
 * @param {!Object} event Event payload.
 * @param {!Object} context Metadata for the event.
 */
exports.messagePubSub = (event, context) => {

  // extract device id from message
  const payload = Buffer.from(event.data, 'base64').toString();
  const info = JSON.parse(payload);
  const device = info.id;

  // heartbeat
  if (!received.includes(device){
    received.push(device);
    console.log('${device} is alive');
  }
};


/**
 * Triggered every 10 minutes
 */
exports.scheduledFunctionCrontab =
functions.pubsub.schedule('*/10 * * * *').onRun((context) => {
    const topicName = "..."
    
    // find dead devices
    var deads = [];
    for (i = 0; i < alive.length; i++) {
      if (!received.includes(alive[i])){
        deads.push(alive[i]);
        delete alive[i];
      }
    }

    // restore device
    for (i = 0; i < received.length; i++) {
      if (!alive.includes(received[i])){
        alive.push(received[i]);
      }
    }

    // build payload
    const messageObj = {
        data: {
            deads: deads
        }
    };
    const messageBuffer = Buffer.from(JSON.stringify(messageObj), 'utf8');
    console.log(messageObj);


    // publish failures
    try {
        await pubSubClient.topic(topicName).publisher().publish(messageBuffer);
        console.log("Message sent!")
    } catch (err) {
        console.error(err);
        return Promise.reject(err);
    }

    // reset 
    received = []
});

谢谢!

【问题讨论】:

    标签: google-cloud-platform google-cloud-functions


    【解决方案1】:

    当您考虑 GCP 上的无服务器时,请考虑无状态:您的实例可以随时删除,并且并非所有请求都会到达同一个 Cloud Functions 实例(Cloud Run 和 App Engine 也是如此)。

    这是一个常见错误,我们曾经将工作负载部署在持久性而非临时性 VM 上

    所以,您的问题是您不能依赖全局变量。首先,你有 2 个函数

    • 每 10 分钟安排一次
    • 接收 IoT 消息的人

    无论如何,它永远不会是同一个实例,因为它不是同一个服务(同一个 Cloud Functions)。那么,今天的结果应该是:所有设备都宕机了,对吧?

    要解决这个问题,您必须将数据保存在某个地方。

    • 将数据存储在数据库中。如果设备和消息的数量有限,Firestore 或 Datastore 是一个不错的选择:您有每天 30k 写入(50k 读取)的免费层级。如果您有大量的设备和消息,BigTable 将是推荐的解决方案。在中间,您可以在流式写入中使用 BigQuery。
    • 只需记录设备通信。

    使用日志,就像使用数据库一样,您只需查询哪些设备已发送消息并将其与您的设备列表进行比较,以检测哪些设备已死亡。

    【讨论】:

    • 谢谢,我试图避免数据集的开销,但我知道我的解决方案过于幼稚,不适合无服务器解决方案。我将部署 2 个单独的函数,将数组存储在等效的数据库表中,然后查找日志的使用情况。
    • 别担心,这是一个常见的错误!每个人都需要开始新的一天!如果需要,请随时回来!
    猜你喜欢
    • 2022-08-19
    • 1970-01-01
    • 2018-01-23
    • 2015-03-24
    • 1970-01-01
    • 2012-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多