【问题标题】:Logging request timeouts on Django + Gunicorn + Heroku在 Django + Gunicorn + Heroku 上记录请求超时
【发布时间】:2014-07-18 17:35:14
【问题描述】:

我们有一个运行 Gunicorn 的 Django 应用程序,该应用程序与部署在 Heroku 上的同步工作者一起运行。我们的请求响应时间显示了几个达到 30 秒(然后死掉)的请求,这是默认的 Gunicorn 超时。

记录这些请求并分析超时的最佳方法是什么? Gunicorn 似乎没有提供捕捉这些超时的钩子,至少不是很明显。

【问题讨论】:

  • 30 秒是 HEROKU 超时,您可能会看到 Heroku 终止连接时会发生什么,与任何 Gunicorn 超时不同。我认为 Gunicorn 有自己的超时系统;您是否尝试过将 Gunicorn 中的超时设置为低于 Heroku 的超时,并查看这是否会比 Heroku 杀死的更好地显示在日志/指标中?
  • @AndrewGorcester 这也是 gunicorn 默认值 docs.gunicorn.org/en/18.0/configure.html#timeout 虽然我同意将其设置为低于 30 秒可能是一个很好的测试。

标签: django heroku gunicorn


【解决方案1】:

一个相当粗略的方法是设置一个“看门狗”计时器,它会在 25 秒后中断进程。一旦您了解了哪些过程很慢,您就可以细化数据以了解发生了什么。

例子:

import signal

def timeout(_signum, _frame):
    print 'TIMEOUT'

signal.signal(signal.SIGALRM, timeout)
signal.alarm(1)                 # send SIGALRM in 1 second

print 'waiting'
signal.pause()
print 'done'

【讨论】:

  • 好主意,但我不确定将其注入 WSGI 循环是否容易。无论我选择什么解决方案,都必须能够在生产中可靠地工作,因为那是我偶尔会超时的地方。我将无法在开发环境中运行它。
【解决方案2】:

另一种方法是触发Thread,它会在经过一定时间后戳主代码。它有几个注意事项 - 请务必阅读 ActiveState 链接。

这是 Aaron Swartz 来自 ActiveState.com 的一个实现

import threading
class TimeoutError(Exception): pass

def timelimit(timeout):
    def internal(function):
        def internal2(*args, **kw):
            class Calculator(threading.Thread):
                def __init__(self):
                    threading.Thread.__init__(self)
                    self.result = None
                    self.error = None

                def run(self):
                    try:
                        self.result = function(*args, **kw)
                    except:
                        self.error = sys.exc_info()[0]

            c = Calculator()
            c.start()
            c.join(timeout)
            if c.isAlive():
                raise TimeoutError
            if c.error:
                raise c.error
            return c.result
        return internal2
    return internal

【讨论】:

    【解决方案3】:

    https://github.com/benoitc/gunicorn/pull/768/files 添加了一个worker_abort 信号,这是我在这种情况下使用的。

    【讨论】:

      猜你喜欢
      • 2019-10-29
      • 2021-12-19
      • 1970-01-01
      • 2020-06-20
      • 1970-01-01
      • 1970-01-01
      • 2021-12-07
      • 2021-09-29
      • 2011-11-27
      相关资源
      最近更新 更多