我正在研究在具有4G内存的Ubuntu机器上运行的Python应用程序的问题。该工具将用于审核服务器(我们更喜欢使用自己的工具)。它使用线程连接到许多服务器,并且许多TCP连接失败。但是,如果我在开始每个线程之间添加1秒的延迟,那么大多数连接都会成功。我使用这个简单的脚本来调查可能发生的事情:
#!/usr/bin/python
import sys
import socket
import threading
import time
class Scanner(threading.Thread):
def __init__(self, host, port):
threading.Thread.__init__(self)
self.host = host
self.port = port
self.status = ""
def run(self):
self.sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sk.settimeout(20)
try:
self.sk.connect((self.host, self.port))
except Exception, err:
self.status = str(err)
else:
self.status = "connected"
finally:
self.sk.close()
def get_hostnames_list(filename):
return open(filename).read().splitlines()
if (__name__ == "__main__"):
hostnames_file = sys.argv[1]
hosts_list = get_hostnames_list(hostnames_file)
threads = []
for host in hosts_list:
#time.sleep(1)
thread = Scanner(host, 443)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
print "Host: ", thread.host, " : ", thread.status
如果我在time.sleep(1)注释掉的情况下执行此操作,比方说,300个主机中的许多连接都会因超时错误而失败,而如果我将延迟时间设置为1秒,它们就不会超时。是否在另一台运行在功能更强大的机器上的Linux发行版上试用了应用程序并且没有那么多的连接错误?是由于内核限制吗?有没有什么可以让连接工作而不会延迟?
更新
我还尝试过一个限制池中可用线程数的程序。通过将其减少到20,我可以使所有连接工作,但它只检查大约1个主机每秒。所以无论我尝试什么(放入睡眠(1)或限制并发线程的数量),我似乎无法每秒检查多于1个主机。
更新
我刚刚发现 question ,这与我所看到的相似。
更新
我想知道用扭曲写这个可能会有帮助吗?任何人都可以展示我的例子看起来像使用twisted写的吗?
答案 0 :(得分:5)
您可以尝试gevent
:
from gevent.pool import Pool
from gevent import monkey; monkey.patch_all() # patches stdlib
import sys
import logging
from httplib import HTTPSConnection
from timeit import default_timer as timer
info = logging.getLogger().info
def connect(hostname):
info("connecting %s", hostname)
h = HTTPSConnection(hostname, timeout=2)
try: h.connect()
except IOError, e:
info("error %s reason: %s", hostname, e)
else:
info("done %s", hostname)
finally:
h.close()
def main():
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
info("getting hostname list")
hosts_file = sys.argv[1] if len(sys.argv) > 1 else "hosts.txt"
hosts_list = open(hosts_file).read().splitlines()
info("spawning jobs")
pool = Pool(20) # limit number of concurrent connections
start = timer()
for _ in pool.imap(connect, hosts_list):
pass
info("%d hosts took us %.2g seconds", len(hosts_list), timer() - start)
if __name__=="__main__":
main()
它每秒可以处理多个主机。
2011-01-31 11:08:29,052 getting hostname list
2011-01-31 11:08:29,052 spawning jobs
2011-01-31 11:08:29,053 connecting www.yahoo.com
2011-01-31 11:08:29,053 connecting www.abc.com
2011-01-31 11:08:29,053 connecting www.google.com
2011-01-31 11:08:29,053 connecting stackoverflow.com
2011-01-31 11:08:29,053 connecting facebook.com
2011-01-31 11:08:29,054 connecting youtube.com
2011-01-31 11:08:29,054 connecting live.com
2011-01-31 11:08:29,054 connecting baidu.com
2011-01-31 11:08:29,054 connecting wikipedia.org
2011-01-31 11:08:29,054 connecting blogspot.com
2011-01-31 11:08:29,054 connecting qq.com
2011-01-31 11:08:29,055 connecting twitter.com
2011-01-31 11:08:29,055 connecting msn.com
2011-01-31 11:08:29,055 connecting yahoo.co.jp
2011-01-31 11:08:29,055 connecting taobao.com
2011-01-31 11:08:29,055 connecting google.co.in
2011-01-31 11:08:29,056 connecting sina.com.cn
2011-01-31 11:08:29,056 connecting amazon.com
2011-01-31 11:08:29,056 connecting google.de
2011-01-31 11:08:29,056 connecting google.com.hk
2011-01-31 11:08:29,188 done www.google.com
2011-01-31 11:08:29,189 done google.com.hk
2011-01-31 11:08:29,224 error wikipedia.org reason: [Errno 111] Connection refused
2011-01-31 11:08:29,225 done google.co.in
2011-01-31 11:08:29,227 error msn.com reason: [Errno 111] Connection refused
2011-01-31 11:08:29,228 error live.com reason: [Errno 111] Connection refused
2011-01-31 11:08:29,250 done google.de
2011-01-31 11:08:29,262 done blogspot.com
2011-01-31 11:08:29,271 error www.abc.com reason: [Errno 111] Connection refused
2011-01-31 11:08:29,465 done amazon.com
2011-01-31 11:08:29,467 error sina.com.cn reason: [Errno 111] Connection refused
2011-01-31 11:08:29,496 done www.yahoo.com
2011-01-31 11:08:29,521 done stackoverflow.com
2011-01-31 11:08:29,606 done youtube.com
2011-01-31 11:08:29,939 done twitter.com
2011-01-31 11:08:33,056 error qq.com reason: timed out
2011-01-31 11:08:33,057 error taobao.com reason: timed out
2011-01-31 11:08:33,057 error yahoo.co.jp reason: timed out
2011-01-31 11:08:34,466 done facebook.com
2011-01-31 11:08:35,056 error baidu.com reason: timed out
2011-01-31 11:08:35,057 20 hosts took us 6 seconds
答案 1 :(得分:4)
我想知道用扭曲写这个可能会有帮助吗?任何人都可以展示我的例子看起来像使用twisted写的吗?
此变体比the code that uses gevent
快得多:
#!/usr/bin/env python
import sys
from timeit import default_timer as timer
from twisted.internet import defer, protocol, reactor, ssl, task
from twisted.python import log
info = log.msg
class NoopProtocol(protocol.Protocol):
def makeConnection(self, transport):
transport.loseConnection()
def connect(host, port, contextFactory=ssl.ClientContextFactory(), timeout=30):
info("connecting %s" % host)
cc = protocol.ClientCreator(reactor, NoopProtocol)
d = cc.connectSSL(host, port, contextFactory, timeout)
d.addCallbacks(lambda _: info("done %s" % host),
lambda f: info("error %s reason: %s" % (host, f.value)))
return d
def n_at_a_time(it, n):
"""Iterate over `it` concurently `n` items at a time.
`it` - an iterator creating Deferreds
`n` - number of concurrent iterations
return a deferred that fires on completion
"""
return defer.DeferredList([task.coiterate(it) for _ in xrange(n)])
def main():
try:
log.startLogging(sys.stderr, setStdout=False)
info("getting hostname list")
hosts_file = sys.argv[1] if len(sys.argv) > 1 else "hosts.txt"
hosts_list = open(hosts_file).read().splitlines()
info("spawning jobs")
start = timer()
jobs = (connect(host, 443, timeout=2) for host in hosts_list)
d = n_at_a_time(jobs, n=20) # limit number of simultaneous connections
d.addCallback(lambda _: info("%d hosts took us %.2g seconds" % (
len(hosts_list), timer() - start)))
d.addBoth(lambda _: (info("the end"), reactor.stop()))
except:
log.err()
reactor.stop()
if __name__=="__main__":
reactor.callWhenRunning(main)
reactor.run()
以下是使用t.i.d.inlineCallbacks
的变体。它需要Python 2.5或更高版本。它允许以同步(阻塞)方式编写异步代码:
#!/usr/bin/env python
import sys
from timeit import default_timer as timer
from twisted.internet import defer, protocol, reactor, ssl, task
from twisted.python import log
info = log.msg
class NoopProtocol(protocol.Protocol):
def makeConnection(self, transport):
transport.loseConnection()
@defer.inlineCallbacks
def connect(host, port, contextFactory=ssl.ClientContextFactory(), timeout=30):
info("connecting %s" % host)
cc = protocol.ClientCreator(reactor, NoopProtocol)
try:
yield cc.connectSSL(host, port, contextFactory, timeout)
except Exception, e:
info("error %s reason: %s" % (host, e))
else:
info("done %s" % host)
def n_at_a_time(it, n):
"""Iterate over `it` concurently `n` items at a time.
`it` - an iterator creating Deferreds
`n` - number of concurrent iterations
return a deferred that fires on completion
"""
return defer.DeferredList([task.coiterate(it) for _ in xrange(n)])
@defer.inlineCallbacks
def main():
try:
log.startLogging(sys.stderr, setStdout=False)
info("getting hostname list")
hosts_file = sys.argv[1] if len(sys.argv) > 1 else "hosts.txt"
hosts_list = open(hosts_file).read().splitlines()
info("spawning jobs")
start = timer()
jobs = (connect(host, 443, timeout=2) for host in hosts_list)
yield n_at_a_time(jobs, n=20) # limit number of simultaneous connections
info("%d hosts took us %.2g seconds" % (len(hosts_list), timer()-start))
info("the end")
except:
log.err()
finally:
reactor.stop()
if __name__=="__main__":
reactor.callWhenRunning(main)
reactor.run()
答案 2 :(得分:3)
真正的线程池怎么样?
#!/usr/bin/env python3
# http://code.activestate.com/recipes/577187-python-thread-pool/
from queue import Queue
from threading import Thread
class Worker(Thread):
def __init__(self, tasks):
Thread.__init__(self)
self.tasks = tasks
self.daemon = True
self.start()
def run(self):
while True:
func, args, kargs = self.tasks.get()
try: func(*args, **kargs)
except Exception as exception: print(exception)
self.tasks.task_done()
class ThreadPool:
def __init__(self, num_threads):
self.tasks = Queue(num_threads)
for _ in range(num_threads): Worker(self.tasks)
def add_task(self, func, *args, **kargs):
self.tasks.put((func, args, kargs))
def wait_completion(self):
self.tasks.join()
示例:
import threadpool
pool = threadpool.ThreadPool(20) # 20 threads
pool.add_task(print, "test")
pool.wait_completion()
它在python 3中,但不应该太难转换为2.x.如果这可以解决您的问题,我并不感到惊讶。
答案 3 :(得分:3)
Python 3.4为异步IO引入了新的provisional API - asyncio
module。
此方法类似于twisted
-based answer:
#!/usr/bin/env python3.4
import asyncio
import logging
from contextlib import closing
class NoopProtocol(asyncio.Protocol):
def connection_made(self, transport):
transport.close()
info = logging.getLogger().info
@asyncio.coroutine
def connect(loop, semaphor, host, port=443, ssl=True, timeout=15):
try:
with (yield from semaphor):
info("connecting %s" % host)
done, pending = yield from asyncio.wait(
[loop.create_connection(NoopProtocol, host, port, ssl=ssl)],
loop=loop, timeout=timeout)
if done:
next(iter(done)).result()
except Exception as e:
info("error %s reason: %s" % (host, e))
else:
if pending:
info("error %s reason: timeout" % (host,))
for ft in pending:
ft.cancel()
else:
info("done %s" % host)
@asyncio.coroutine
def main(loop):
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
limit, timeout, hosts = parse_cmdline()
# connect `limit` concurrent connections
sem = asyncio.BoundedSemaphore(limit)
coros = [connect(loop, sem, host, timeout=timeout) for host in hosts]
if coros:
yield from asyncio.wait(coros, loop=loop)
if __name__=="__main__":
with closing(asyncio.get_event_loop()) as loop:
loop.run_until_complete(main(loop))
除了twisted
变体之外,它还使用NoopProtocol
除了在成功连接时立即断开连接之外什么都不做。
使用信号量限制并发连接数。
代码为coroutine-based。
要了解我们可以从前百万Alexa列表中向前1000个主机建立多少个成功的ssl连接:
$ curl -O http://s3.amazonaws.com/alexa-static/top-1m.csv.zip
$ unzip *.zip
$ /usr/bin/time perl -nE'say $1 if /\d+,([^\s,]+)$/' top-1m.csv | head -1000 |\
python3.4 asyncio_ssl.py - --timeout 60 |& tee asyncio.log
结果是所有连接中只有不到一半成功。平均而言,它每秒检查约20台主机。许多网站在一分钟后超时。如果主机与服务器证书中的主机名不匹配,则连接也会失败。它包括example.com
与www.example.com
类比较。
答案 4 :(得分:0)
首先,尝试使用非阻塞套接字。 另一个原因是你正在消耗所有短暂的端口。 尝试删除限制。