长时间运行的 App Engine 脚本“退出终止信号”

Dan*_*ams 3 google-app-engine timeout node.js express google-cloud-platform

我正在尝试通过应用引擎运行几个长时间运行的脚本。我是初学者,这是我使用 App Engine 和 express 的第一个项目。

我正在使用 express 处理 Node 中的请求。

当我(或 cron 作业)向我的任何端点发送请求时,脚本似乎运行良好,直到大约 5-10 分钟后的随机点,我得到以下日志:

  1. 项目收到“/_ah/stop”请求
  2. “退出终止信号”消息
  3. “启动程序失败:用户应用程序失败,退出代码为 -1(有关更多详细信息,请参阅 stdout/stderr 日志):信号:已终止”

我无法弄清楚为什么会发生这种情况。

我的 app.yaml:

runtime: nodejs10
instance_class: B2
basic_scaling:
  max_instances: 25
  idle_timeout: 12m
Run Code Online (Sandbox Code Playgroud)

请求处理程序代码:

app.get("/longRunningFunctionOne", async (req, res) => {
    await longRunningFunctionOne();
    res.send("DONE");
});

app.get("/longRunningFunctionTwo", async (req, res) => {
    await longRunningFunctionTwo();
    res.send("DONE");
});

app.get("/_ah/start", async (req, res) => {
    res.sendStatus(200);
});
Run Code Online (Sandbox Code Playgroud)

在本地运行时绝对没有问题。知道我在做什么来获得过早的 /_ah/stop 请求吗?因为我使用的是基本缩放,所以我不会超时。谷歌将其描述为:

“HTTP 请求和任务队列任务为 24 小时。如果您的应用程序未在此时间限制内返回请求,App Engine 将中断请求处理程序并发出错误以供您的代码处理。”

有任何想法吗?也许与我如何处理 /_ah/start 这只是在黑暗中的一个镜头有关?

Dan*_*ams 5

我发现,因为我向应用程序发送了非常少的请求,所以我在脚本完成之前遇到了实例空闲超时/

因此,即使任务仍在应用程序上运行,因为它在过去约 15 分钟内没有收到 http 请求,它也会发送 /_ah/stop 请求并关闭实例。

为了在脚本运行时保持实例处于活动状态,我创建了一个函数,该函数每分钟向应用程序发送一个请求以保持运行状态,而不是达到空闲超时。

我称它为 Beegees“保持活力”功能:

const appUrl = "https://myurl.appspot.com/";

app.get("/script1", async (req, res) => {
    res.send("running script 1");
    stayAlive(script1);
});

app.get("/script2", async (req, res) => {
    res.send("running script 2");
    stayAlive(script2);
});

app.get("/", async (req, res) => {
    res.send(" ");
});

app.listen(process.env.PORT || 4000, () => {
  console.log(`Listening on port ${process.env.PORT || 4000}`);
});

const stayAlive = async (mainAsyncFunc) => {
  const intervalId = setInterval(sendAppRequest, 60000);
  await mainAsyncFunc();
  clearInterval(intervalId);
};

const sendAppRequest = () => {
  console.log("Stayin alive");
  axios.get(appUrl);
};
Run Code Online (Sandbox Code Playgroud)

看起来有点奇怪,但它有效。如果您知道更好的方法,请告诉我。