equal
deleted
inserted
replaced
82 |
82 |
83 # $Id: keepalive.py,v 1.14 2006/04/04 21:00:32 mstenner Exp $ |
83 # $Id: keepalive.py,v 1.14 2006/04/04 21:00:32 mstenner Exp $ |
84 |
84 |
85 from __future__ import absolute_import, print_function |
85 from __future__ import absolute_import, print_function |
86 |
86 |
|
87 import collections |
87 import errno |
88 import errno |
88 import hashlib |
89 import hashlib |
89 import socket |
90 import socket |
90 import sys |
91 import sys |
91 import threading |
92 import threading |
112 The connection manager must be able to: |
113 The connection manager must be able to: |
113 * keep track of all existing |
114 * keep track of all existing |
114 """ |
115 """ |
115 def __init__(self): |
116 def __init__(self): |
116 self._lock = threading.Lock() |
117 self._lock = threading.Lock() |
117 self._hostmap = {} # map hosts to a list of connections |
118 self._hostmap = collections.defaultdict(list) # host -> [connection] |
118 self._connmap = {} # map connections to host |
119 self._connmap = {} # map connections to host |
119 self._readymap = {} # map connection to ready state |
120 self._readymap = {} # map connection to ready state |
120 |
121 |
121 def add(self, host, connection, ready): |
122 def add(self, host, connection, ready): |
122 self._lock.acquire() |
123 self._lock.acquire() |
123 try: |
124 try: |
124 if host not in self._hostmap: |
|
125 self._hostmap[host] = [] |
|
126 self._hostmap[host].append(connection) |
125 self._hostmap[host].append(connection) |
127 self._connmap[connection] = host |
126 self._connmap[connection] = host |
128 self._readymap[connection] = ready |
127 self._readymap[connection] = ready |
129 finally: |
128 finally: |
130 self._lock.release() |
129 self._lock.release() |
153 |
152 |
154 def get_ready_conn(self, host): |
153 def get_ready_conn(self, host): |
155 conn = None |
154 conn = None |
156 self._lock.acquire() |
155 self._lock.acquire() |
157 try: |
156 try: |
158 if host in self._hostmap: |
157 for c in self._hostmap[host]: |
159 for c in self._hostmap[host]: |
158 if self._readymap[c]: |
160 if self._readymap[c]: |
159 self._readymap[c] = 0 |
161 self._readymap[c] = 0 |
160 conn = c |
162 conn = c |
161 break |
163 break |
|
164 finally: |
162 finally: |
165 self._lock.release() |
163 self._lock.release() |
166 return conn |
164 return conn |
167 |
165 |
168 def get_all(self, host=None): |
166 def get_all(self, host=None): |
169 if host: |
167 if host: |
170 return list(self._hostmap.get(host, [])) |
168 return list(self._hostmap[host]) |
171 else: |
169 else: |
172 return dict(self._hostmap) |
170 return dict(self._hostmap) |
173 |
171 |
174 class KeepAliveHandler(object): |
172 class KeepAliveHandler(object): |
175 def __init__(self, timeout=None): |
173 def __init__(self, timeout=None): |