我们的应用程序使用了相当少的网络调用(它构建在第三方REST API之上),因此我们使用了大量异步操作来保持系统响应。 (使用Swirl保持理智,因为应用程序是在tornado.gen
出现之前编写的)。因此,当需要进行一些地理编码时,我们认为这将是微不足道的 - 抛出几个异步调用到另一个外部API,我们将是金色的。
不知何故,我们的异步代码神秘地挂起了Tornado - 该进程仍在运行,但它不会响应请求或向日志输出任何内容。更糟糕的是,当我们完全取消第三方服务器时,它仍然会挂起 - 它似乎在异步请求返回后锁定了一段任意时间。
这是一些复制问题的存根代码:
def async_geocode(lat, lon, callback, fields=('city', 'country')):
'''Translates lat and lon into human-readable geographic info'''
iol = IOLoop.instance()
iol.add_timeout(time.time() + 1, lambda: callback("(unknown)"))
这里的测试通常(但并非总是如此 - 它首先是生产方式)抓住它:
class UtilTest(tornado.testing.AsyncTestCase):
def get_new_ioloop(self):
'''Ensure that any test code uses the right IOLoop, since the code
it tests will use the singleton.'''
return tornado.ioloop.IOLoop.instance()
def test_async_geocode(self):
# Yahoo gives (-122.419644, 37.777125) for SF, so we expect it to
# reverse geocode to SF too...
async_geocode(lat=37.777, lon=-122.419, callback=self.stop,
fields=('city', 'country'))
result = self.wait(timeout=4)
self.assertEquals(result, u"San Francisco, United States")
# Now test if it's hanging (or has hung) the IOLoop on finding London
async_geocode(lat=51.506, lon=-0.127, callback=self.stop,
fields=('city',))
result = self.wait(timeout=5)
self.assertEquals(result, u"London")
# Test it fails gracefully
async_geocode(lat=0.00, lon=0.00, callback=self.stop,
fields=('city',))
result = self.wait(timeout=6)
self.assertEquals(result, u"(unknown)")
def test_async_geocode2(self):
async_geocode(lat=37.777, lon=-122.419, callback=self.stop,
fields=('city', 'state', 'country'))
result = self.wait(timeout=7)
self.assertEquals(result, u"San Francisco, California, United States")
async_geocode(lat=51.506325, lon=-0.127144, callback=self.stop,
fields=('city', 'state', 'country'))
result = self.wait(timeout=8)
self.io_loop.add_timeout(time.time() + 8, lambda: self.stop(True))
still_running = self.wait(timeout=9)
self.assert_(still_running)
请注意,第一个测试几乎总是通过,而第二个测试(及其对async_geocode
的调用)通常会失败。
编辑添加:请注意,我们对其他第三方API进行了大量类似的异步调用,这些调用工作正常。
(为了完整性,这里是async_geocode
及其助手类的完整实现(尽管上面的存根复制了问题)):
def async_geocode(lat, lon, callback, fields=('city', 'country')):
'''Use AsyncGeocoder to do the work.'''
geo = AsyncGeocoder(lat, lon, callback, fields)
geo.geocode()
class AsyncGeocoder(object):
'''
Reverse-geocode to as specific a level as possible
Calls Yahoo! PlaceFinder for reverse geocoding. Takes a lat, lon, and
callback function (to call with the result string when the request
completes), and optionally a sequence of fields to return, in decreasing
order of specificity (e.g. street, neighborhood, city, country)
NB: Does not do anything intelligent with the geocoded data -- just returns
the first result found.
'''
url = "http://where.yahooapis.com/geocode"
def __init__(self, lat, lon, callback, fields, ioloop=None):
self.lat, self.lon = lat, lon
self.callback = callback
self.fields = fields
self.io_loop = ioloop or IOLoop.instance()
self._client = AsyncHTTPClient(io_loop=self.io_loop)
def geocode(self):
params = urllib.urlencode({
'q': '{0}, {1}'.format(self.lat, self.lon),
'flags': 'J', 'gflags': 'R'
})
tgt_url = self.url + "?" + params
self._client.fetch(tgt_url, self.geocode_cb)
def geocode_cb(self, response):
geodata = json_decode(response.body)
try:
geodata = geodata['ResultSet']['Results'][0]
except IndexError:
# Response didn't contain anything
result_string = ""
else:
results = []
for f in self.fields:
val = geodata.get(f, None)
if val:
results.append(val)
result_string = ", ".join(results)
if result_string == '':
# This can happen if the response was empty _or_ if
# the requested fields weren't in it. Regardless,
# the user needs to see *something*
result_string = "(unknown)"
self.io_loop.add_callback(lambda: self.callback(result_string))
编辑:经过几天繁琐的调试和记录系统几天失败的情况后,事实证明,正如接受的答案指出的那样,我的测试失败了出于无关的原因。事实证明它挂起的原因与IOLoop无关,而是有问题的协同程序之一立即停止等待数据库锁定。
对于错误定位的问题感到抱歉,感谢大家的耐心等待。
答案 0 :(得分:3)
由于这一部分,您的第二次测试似乎失败了:
self.io_loop.add_timeout(time.time() + 8, lambda: self.stop(True))
still_running = self.wait(timeout=9)
self.assert_(still_running)
当您通过self.wait
向IOLoop添加超时时,根据我的判断,在调用self.stop
时不会清除该超时。 I.E.你的第一次超时是持续存在的,当你把IOLoop睡了8秒钟时,它会触发。
我怀疑这与你原来的问题有关。