Python使用multiprocessing.Manager共享网络套接字

时间:2010-12-17 04:11:36

标签: python sockets networking process share

我目前正在编写一个带有Request队列的nginx代理服务器模块,因此当nginx后面的服务器无法处理请求时,请求不会被删除(nginx被配置为负载均衡器)。

我正在使用

from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler

想法是在处理请求之前将请求放入队列中。我知道multiprocessing.Queue只支持简单对象,不能支持原始套接字,所以我尝试使用multiprocess.Manager来创建一个共享字典。 Manager也使用套接字进行连接,因此该方法也失败了。有没有办法在进程之间共享网络套接字? 以下是代码中存在问题的部分:

class ProxyServer(Threader, HTTPServer):

    def __init__(self, server_address, bind_and_activate=True):
        HTTPServer.__init__(self, server_address, ProxyHandler,
                bind_and_activate)

        self.manager = multiprocessing.Manager()

        self.conn_dict = self.manager.dict()
        self.ticket_queue = multiprocessing.Queue(maxsize= 10)
        self._processes = []
        self.add_worker(5)


    def process_request(self, request, client):
        stamp = time.time()
        print "We are processing"

        self.conn_dict[stamp] = (request, client) # the program crashes here


    #Exception happened during processing of request from ('172.28.192.34', 49294)
    #Traceback (most recent call last):
    #  File "/usr/lib64/python2.6/SocketServer.py", line 281, in _handle_request_noblock
    #    self.process_request(request, client_address)
    #  File "./nxproxy.py", line 157, in process_request
    #    self.conn_dict[stamp] = (request, client)
    #  File "<string>", line 2, in __setitem__
    #  File "/usr/lib64/python2.6/multiprocessing/managers.py", line 725, in _callmethod
    #    conn.send((self._id, methodname, args, kwds))
    #TypeError: expected string or Unicode object, NoneType found

        self.ticket_queue.put(stamp)


    def add_worker(self, number_of_workers):
        for worker in range(number_of_workers):
            print "Starting worker %d" % worker
            proc = multiprocessing.Process(target=self._worker, args = (self.conn_dict,))
            self._processes.append(proc)
            proc.start()

    def _worker(self, conn_dict):
        while 1:
            ticket = self.ticket_queue.get()

            print conn_dict
            a=0
            while a==0:
                try:
                    request, client = conn_dict[ticket]
                    a=1
                except Exception:
                    pass
            print "We are threading!"
            self.threader(request, client)

3 个答案:

答案 0 :(得分:7)

您可以使用multiprocessing.reduction在进程之间传输连接和套接字对象

示例代码

# Main process
from multiprocessing.reduction import reduce_handle
h = reduce_handle(client_socket.fileno())
pipe_to_worker.send(h)

# Worker process
from multiprocessing.reduction import rebuild_handle
h = pipe.recv()
fd = rebuild_handle(h)
client_socket = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM)
client_socket.send("hello from the worker process\r\n") 

答案 1 :(得分:0)

在进程之间看起来需要pass file descriptors(假设Unix在这里,没有关于Windows的线索)。我从来没有在Python中做过这个,但是这里是你可能要检查的python-passfd项目的链接。

答案 2 :(得分:0)

您可以查看此代码 - https://gist.github.com/sunilmallya/4662837 multiprocessing.reduction套接字服务器,父接收在接受连接后将连接传递给客户端