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()
86 self.idlock = threading.Lock()
90 def push_response(self, item):
91 self.response_queue.put(item)
93 def pop_response(self):
94 return self.response_queue.get()
96 def push_request(self, session, item):
97 self.request_queue.put((session, item))
99 def pop_request(self):
100 return self.request_queue.get()
102 def get_session_by_address(self, address):
103 for x in self.sessions:
104 if x.address == address:
107 def get_session_id(self, internal_id):
109 return self.internal_ids.pop(internal_id)
111 def store_session_id(self, session, msgid):
113 self.internal_ids[self.internal_id] = session, msgid
115 self.internal_id += 1
119 if self.shared is None:
120 raise TypeError("self.shared not set in Processor")
121 while not self.shared.stopped():
122 session, request = self.pop_request()
124 self.do_dispatch(session, request)
126 traceback.print_exc(file=sys.stdout)
133 def do_dispatch(self, session, request):
134 """ dispatch request to the relevant processor """
136 method = request['method']
137 params = request.get('params', [])
138 suffix = method.split('.')[-1]
140 if session is not None:
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])
164 def get_sessions(self):
169 def add_session(self, session):
171 self.sessions.append(session)
173 def collect_garbage(self):
174 # Deep copy entire sessions list and blank it
175 # This is done to minimize lock contention
177 sessions = self.sessions[:]
182 for session in sessions:
183 if (now - session.time) > 1000:
186 for session in sessions:
187 if not session.stopped():
188 # If session is still alive then re-add it back
189 # to our internal register
190 active_sessions.append(session)
193 self.sessions = active_sessions[:]
200 self._stopped = False
201 self.lock = threading.Lock()
202 self.subscriptions = []
205 self.version = 'unknown'
206 self.protocol_version = 0.
207 self.time = time.time()
208 threading.Timer(2, self.info).start()
210 # Debugging method. Doesn't need to be threadsafe.
212 for sub in self.subscriptions:
215 if method == 'blockchain.address.subscribe':
221 if self.subscriptions:
222 print_log("%4s" % self.name,
223 "%15s" % self.address,
225 "%3d" % len(self.subscriptions),
232 def subscribe_to_service(self, method, params):
233 subdesc = self.build_subdesc(method, params)
235 if subdesc is not None:
236 self.subscriptions.append(subdesc)
238 # subdesc = A subscription description
240 def build_subdesc(method, params):
241 if method == "blockchain.numblocks.subscribe":
243 elif method == "blockchain.headers.subscribe":
245 elif method in ["blockchain.address.subscribe"]:
249 return method, params[0]
253 def contains_subscription(self, subdesc):
255 return subdesc in self.subscriptions
258 class ResponseDispatcher(threading.Thread):
260 def __init__(self, shared, request_dispatcher):
262 self.request_dispatcher = request_dispatcher
263 threading.Thread.__init__(self)
267 while not self.shared.stopped():
271 response = self.request_dispatcher.pop_response()
272 #print "pop response", response
273 internal_id = response.get('id')
274 method = response.get('method')
275 params = response.get('params')
278 if internal_id is None: # and method is not None and params is not None:
279 found = self.notification(method, params, response)
280 if not found and method == 'blockchain.address.subscribe':
283 'method': method.replace('.subscribe', '.unsubscribe'),
284 'params': [self.shared.config.get('server', 'password')] + params,
287 self.request_dispatcher.push_request(None, request)
289 elif internal_id is not None:
290 self.send_response(internal_id, response)
292 print_log("no method", response)
294 def notification(self, method, params, response):
295 subdesc = Session.build_subdesc(method, params)
297 for session in self.request_dispatcher.sessions:
298 if session.stopped():
300 if session.contains_subscription(subdesc):
301 session.send_response(response)
303 # if not found: print_log("no subscriber for", subdesc)
306 def send_response(self, internal_id, response):
307 session, message_id = self.request_dispatcher.get_session_id(internal_id)
309 response['id'] = message_id
310 session.send_response(response)
312 # print_log("send_response: no session", message_id, internal_id, response )