尝试推送 Azure AppInsights 指标时进程挂起

Process hangs while trying to push Azure AppInsights metric

我正在使用 Application Insights Python API 每 30 秒为我的应用程序发布一个自定义指标。 这可以正常工作一段时间(最多几天),但随后我的 Python 脚本在尝试将数据刷新到 Azure 时挂起。

Python 代码本身相当简单,就是这个无限循环:

while True:
    count = get_connection_count()
    if count is not None:
        tc.track_metric("ConnectionCount", count, type=DataPointType.measurement, count=1)
        tc.flush()
    time.sleep(10)

堆栈跟踪(下方)显示进程卡在 tc.flush(),等待服务器的响应。

如果我查看该进程的 TCP 连接,我可以看到该进程仍然有到 Azure 的开放 TCP 连接;它只是没有得到任何答复。 有没有人遇到过类似的问题?什么会导致 Azure AppInsights 像这样停止响应?

或者,是否可以为 tc.flush 调用定义超时,这样我至少可以从无响应的端点恢复?

这是我能够提取的堆栈跟踪:

  File "/var/lib/app-monitor/connectionMonitor.py", line 52, in <module>
        tc.flush()
  File "/usr/local/lib/python2.7/dist-packages/applicationinsights/TelemetryClient.py", line 55, in flush
        self._channel.flush()
  File "/usr/local/lib/python2.7/dist-packages/applicationinsights/channel/TelemetryChannel.py", line 71, in flush
        self._queue.flush()
  File "/usr/local/lib/python2.7/dist-packages/applicationinsights/channel/SynchronousQueue.py", line 39, in flush
        local_sender.send(data)
  File "/usr/local/lib/python2.7/dist-packages/applicationinsights/channel/SenderBase.py", line 118, in send
        response = HTTPClient.urlopen(request)
  File "/usr/lib/python2.7/urllib2.py", line 127, in urlopen
        return _opener.open(url, data, timeout)
  File "/usr/lib/python2.7/urllib2.py", line 404, in open
        response = self._open(req, data)
  File "/usr/lib/python2.7/urllib2.py", line 422, in _open
        '_open', req)
  File "/usr/lib/python2.7/urllib2.py", line 382, in _call_chain
        result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 1222, in https_open
        return self.do_open(httplib.HTTPSConnection, req)
  File "/usr/lib/python2.7/urllib2.py", line 1187, in do_open
        r = h.getresponse(buffering=True)
  File "/usr/lib/python2.7/httplib.py", line 1089, in getresponse
        response.begin()
  File "/usr/lib/python2.7/httplib.py", line 444, in begin
        version, status, reason = self._read_status()
  File "/usr/lib/python2.7/httplib.py", line 400, in _read_status
        line = self.fp.readline(_MAXLINE + 1)
  File "/usr/lib/python2.7/socket.py", line 476, in readline
        data = self._sock.recv(self._rbufsize)
  File "/usr/lib/python2.7/ssl.py", line 341, in recv
        return self.read(buflen)
  File "/usr/lib/python2.7/ssl.py", line 260, in read
        return self._sslobj.read(len)

根据我的经验,可能有两个原因会导致此问题。

  1. 您的应用程序超出了对指标和事件数量的一些限制,请参考官方 document 并通过 Wireshark 或 Fiddler 在 [=26= 上捕获响应状态代码] 检查它。这种情况有一些错误代码,包括 402(需要付款)、429(请求太多)、503(服务不可用)等。

  2. 您始终可以在 http://aka.ms/aistatus 获取 Application Insights 有关该服务的运行状况和状态的信息,以检查该问题是否是由某些计划维护或问题解决操作引起的。

希望对您有所帮助。

经过内部讨论后,有一个解决方法,但不是真正的解决方法: 确保套接字具有某种默认超时值以防止它们永远挂起:

import socket
socket.setdefaulttimeout(30)

请注意,这适用于来自脚本的任何+所有 http 调用,因此它不一定理想,但确实可以防止事情长时间挂起。