10 return ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(N))
13 return time.strftime("[%d/%m/%Y-%H:%M:%S]")
16 print_lock = threading.Lock()
18 args = [str(item) for item in args]
20 sys.stderr.write(timestr() + " " + " ".join(args) + "\n")
28 self.lock = threading.Lock()
32 print_log( "Stopping Stratum" )
41 class Processor(threading.Thread):
44 threading.Thread.__init__(self)
46 self.dispatcher = None
47 self.queue = queue.Queue()
49 def process(self, request):
52 def add_request(self, request):
53 self.queue.put(request)
55 def push_response(self, response):
56 #print "response", response
57 self.dispatcher.request_dispatcher.push_response(response)
60 while not self.shared.stopped():
61 request = self.queue.get(10000000000)
65 traceback.print_exc(file=sys.stdout)
67 print_log( "processor terminating")
74 self.shared = Shared()
75 self.request_dispatcher = RequestDispatcher(self.shared)
76 self.request_dispatcher.start()
77 self.response_dispatcher = \
78 ResponseDispatcher(self.shared, self.request_dispatcher)
79 self.response_dispatcher.start()
81 def register(self, prefix, processor):
82 processor.dispatcher = self
83 processor.shared = self.shared
85 self.request_dispatcher.processors[prefix] = processor
89 class RequestDispatcher(threading.Thread):
91 def __init__(self, shared):
93 threading.Thread.__init__(self)
95 self.request_queue = queue.Queue()
96 self.response_queue = queue.Queue()
97 self.internal_ids = {}
99 self.lock = threading.Lock()
103 def push_response(self, item):
104 self.response_queue.put(item)
106 def pop_response(self):
107 return self.response_queue.get()
109 def push_request(self, session, item):
110 self.request_queue.put((session,item))
112 def pop_request(self):
113 return self.request_queue.get()
115 def get_session_by_address(self, address):
116 for x in self.sessions:
117 if x.address == address:
120 def get_session_id(self, internal_id):
122 return self.internal_ids.pop(internal_id)
124 def store_session_id(self, session, msgid):
126 self.internal_ids[self.internal_id] = session, msgid
128 self.internal_id += 1
132 if self.shared is None:
133 raise TypeError("self.shared not set in Processor")
134 while not self.shared.stopped():
135 session, request = self.pop_request()
137 self.do_dispatch(session, request)
139 traceback.print_exc(file=sys.stdout)
147 def do_dispatch(self, session, request):
148 """ dispatch request to the relevant processor """
150 method = request['method']
151 params = request.get('params',[])
152 suffix = method.split('.')[-1]
154 if session is not None:
155 is_new = session.protocol_version >= 0.5
156 if suffix == 'subscribe':
157 session.subscribe_to_service(method, params)
159 # store session and id locally
160 request['id'] = self.store_session_id(session, request['id'])
162 prefix = request['method'].split('.')[0]
164 p = self.processors[prefix]
166 print_log( "error: no processor for", prefix)
169 p.add_request(request)
171 if method in ['server.version']:
172 session.version = params[0]
174 session.protocol_version = float(params[1])
178 #if session.protocol_version < 0.6:
179 # print_log("stopping session from old client", session.protocol_version)
182 def get_sessions(self):
187 def add_session(self, session):
189 self.sessions.append(session)
191 def collect_garbage(self):
192 # Deep copy entire sessions list and blank it
193 # This is done to minimise lock contention
195 sessions = self.sessions[:]
197 for session in sessions:
198 if not session.stopped():
199 # If session is still alive then re-add it back
200 # to our internal register
201 self.add_session(session)
207 self._stopped = False
208 self.lock = threading.Lock()
209 self.subscriptions = []
212 self.version = 'unknown'
213 self.protocol_version = 0.
214 self.time = time.time()
215 threading.Timer(2, self.info).start()
217 # Debugging method. Doesn't need to be threadsafe.
219 for sub in self.subscriptions:
222 if method == 'blockchain.address.subscribe':
228 if self.subscriptions:
229 print_log( "%4s"%self.name, "%14s"%self.address, "%35s"%addr, "%3d"%len(self.subscriptions), self.version )
235 def subscribe_to_service(self, method, params):
236 subdesc = self.build_subdesc(method, params)
238 if subdesc is not None:
239 self.subscriptions.append(subdesc)
241 # subdesc = A subscription description
243 def build_subdesc(method, params):
244 if method == "blockchain.numblocks.subscribe":
246 elif method == "blockchain.headers.subscribe":
248 elif method in ["blockchain.address.subscribe"]:
252 return method, params[0]
256 def contains_subscription(self, subdesc):
258 return subdesc in self.subscriptions
261 class ResponseDispatcher(threading.Thread):
263 def __init__(self, shared, request_dispatcher):
265 self.request_dispatcher = request_dispatcher
266 threading.Thread.__init__(self)
270 while not self.shared.stopped():
274 response = self.request_dispatcher.pop_response()
275 #print "pop response", response
276 internal_id = response.get('id')
277 method = response.get('method')
278 params = response.get('params')
281 if internal_id is None: # and method is not None and params is not None:
282 found = self.notification(method, params, response)
283 if not found and method == 'blockchain.address.subscribe':
284 self.request_dispatcher.push_request(None,{'method':method.replace('.subscribe', '.unsubscribe'), 'params':params, 'id':None})
287 elif internal_id is not None:
288 self.send_response(internal_id, response)
290 print_log( "no method", response)
292 def notification(self, method, params, response):
293 subdesc = Session.build_subdesc(method, params)
295 for session in self.request_dispatcher.sessions:
296 if session.stopped():
298 if session.contains_subscription(subdesc):
299 session.send_response(response)
301 if not found: print "no subscriber for", subdesc
304 def send_response(self, internal_id, response):
305 session, message_id = self.request_dispatcher.get_session_id(internal_id)
307 response['id'] = message_id
308 session.send_response(response)
310 print_log( "send_response: no session", message_id, internal_id, response )