9 from utils import random_string, timestr, print_log
14 def __init__(self, config):
15 self.lock = threading.Lock()
20 print_log("Stopping Stratum")
29 class Processor(threading.Thread):
32 threading.Thread.__init__(self)
34 self.dispatcher = None
35 self.queue = queue.Queue()
37 def process(self, request):
40 def add_request(self, request):
41 self.queue.put(request)
43 def push_response(self, response):
44 #print "response", response
45 self.dispatcher.request_dispatcher.push_response(response)
48 while not self.shared.stopped():
49 request = self.queue.get(10000000000)
53 traceback.print_exc(file=sys.stdout)
55 print_log("processor terminating")
60 def __init__(self, config):
61 self.shared = Shared(config)
62 self.request_dispatcher = RequestDispatcher(self.shared)
63 self.request_dispatcher.start()
64 self.response_dispatcher = \
65 ResponseDispatcher(self.shared, self.request_dispatcher)
66 self.response_dispatcher.start()
68 def register(self, prefix, processor):
69 processor.dispatcher = self
70 processor.shared = self.shared
72 self.request_dispatcher.processors[prefix] = processor
75 class RequestDispatcher(threading.Thread):
77 def __init__(self, shared):
79 threading.Thread.__init__(self)
81 self.request_queue = queue.Queue()
82 self.response_queue = queue.Queue()
83 self.internal_ids = {}
85 self.lock = threading.Lock()
89 def push_response(self, item):
90 self.response_queue.put(item)
92 def pop_response(self):
93 return self.response_queue.get()
95 def push_request(self, session, item):
96 self.request_queue.put((session, item))
98 def pop_request(self):
99 return self.request_queue.get()
101 def get_session_by_address(self, address):
102 for x in self.sessions:
103 if x.address == address:
106 def get_session_id(self, internal_id):
108 return self.internal_ids.pop(internal_id)
110 def store_session_id(self, session, msgid):
112 self.internal_ids[self.internal_id] = session, msgid
114 self.internal_id += 1
118 if self.shared is None:
119 raise TypeError("self.shared not set in Processor")
120 while not self.shared.stopped():
121 session, request = self.pop_request()
123 self.do_dispatch(session, request)
125 traceback.print_exc(file=sys.stdout)
132 def do_dispatch(self, session, request):
133 """ dispatch request to the relevant processor """
135 method = request['method']
136 params = request.get('params', [])
137 suffix = method.split('.')[-1]
139 if session is not None:
140 is_new = session.protocol_version >= 0.5
141 if suffix == 'subscribe':
142 session.subscribe_to_service(method, params)
144 # store session and id locally
145 request['id'] = self.store_session_id(session, request['id'])
147 prefix = request['method'].split('.')[0]
149 p = self.processors[prefix]
151 print_log("error: no processor for", prefix)
154 p.add_request(request)
156 if method in ['server.version']:
157 session.version = params[0]
159 session.protocol_version = float(params[1])
163 #if session.protocol_version < 0.6:
164 # print_log("stopping session from old client", session.protocol_version)
167 def get_sessions(self):
172 def add_session(self, session):
174 self.sessions.append(session)
176 def collect_garbage(self):
177 # Deep copy entire sessions list and blank it
178 # This is done to minimize lock contention
180 sessions = self.sessions[:]
183 for session in sessions:
184 if not session.stopped():
185 # If session is still alive then re-add it back
186 # to our internal register
187 active_sessions.append(session)
190 self.sessions = active_sessions[:]
197 self._stopped = False
198 self.lock = threading.Lock()
199 self.subscriptions = []
202 self.version = 'unknown'
203 self.protocol_version = 0.
204 self.time = time.time()
205 threading.Timer(2, self.info).start()
207 # Debugging method. Doesn't need to be threadsafe.
209 for sub in self.subscriptions:
212 if method == 'blockchain.address.subscribe':
218 if self.subscriptions:
219 print_log("%4s" % self.name,
220 "%15s" % self.address,
222 "%3d" % len(self.subscriptions),
229 def subscribe_to_service(self, method, params):
230 subdesc = self.build_subdesc(method, params)
232 if subdesc is not None:
233 self.subscriptions.append(subdesc)
235 # subdesc = A subscription description
237 def build_subdesc(method, params):
238 if method == "blockchain.numblocks.subscribe":
240 elif method == "blockchain.headers.subscribe":
242 elif method in ["blockchain.address.subscribe"]:
246 return method, params[0]
250 def contains_subscription(self, subdesc):
252 return subdesc in self.subscriptions
255 class ResponseDispatcher(threading.Thread):
257 def __init__(self, shared, request_dispatcher):
259 self.request_dispatcher = request_dispatcher
260 threading.Thread.__init__(self)
264 while not self.shared.stopped():
268 response = self.request_dispatcher.pop_response()
269 #print "pop response", response
270 internal_id = response.get('id')
271 method = response.get('method')
272 params = response.get('params')
275 if internal_id is None: # and method is not None and params is not None:
276 found = self.notification(method, params, response)
277 if not found and method == 'blockchain.address.subscribe':
280 'method': method.replace('.subscribe', '.unsubscribe'),
281 'params': [self.shared.config.get('server', 'password')] + params,
284 self.request_dispatcher.push_request(None, request)
286 elif internal_id is not None:
287 self.send_response(internal_id, response)
289 print_log("no method", response)
291 def notification(self, method, params, response):
292 subdesc = Session.build_subdesc(method, params)
294 for session in self.request_dispatcher.sessions:
295 if session.stopped():
297 if session.contains_subscription(subdesc):
298 session.send_response(response)
300 # if not found: print_log("no subscriber for", subdesc)
303 def send_response(self, internal_id, response):
304 session, message_id = self.request_dispatcher.get_session_id(internal_id)
306 response['id'] = message_id
307 session.send_response(response)
309 # print_log("send_response: no session", message_id, internal_id, response )