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]")
19 self.lock = threading.Lock()
23 print "Stopping Stratum"
32 class Processor(threading.Thread):
35 threading.Thread.__init__(self)
37 self.dispatcher = None
39 def process(self, request):
42 def push_response(self, response):
43 #print "response", response
44 self.dispatcher.request_dispatcher.push_response(response)
51 self.shared = Shared()
52 self.request_dispatcher = RequestDispatcher(self.shared)
53 self.request_dispatcher.start()
54 self.response_dispatcher = \
55 ResponseDispatcher(self.shared, self.request_dispatcher)
56 self.response_dispatcher.start()
58 def register(self, prefix, processor):
59 processor.dispatcher = self
60 processor.shared = self.shared
62 self.request_dispatcher.processors[prefix] = processor
66 class RequestDispatcher(threading.Thread):
68 def __init__(self, shared):
70 threading.Thread.__init__(self)
72 self.request_queue = queue.Queue()
73 self.response_queue = queue.Queue()
74 self.internal_ids = {}
76 self.lock = threading.Lock()
80 def push_response(self, item):
81 self.response_queue.put(item)
83 def pop_response(self):
84 return self.response_queue.get()
86 def push_request(self, session, item):
87 self.request_queue.put((session,item))
89 def pop_request(self):
90 return self.request_queue.get()
92 def get_session_by_address(self, address):
93 for x in self.sessions:
94 if x.address == address:
97 def get_session_id(self, internal_id):
99 return self.internal_ids.pop(internal_id)
101 def store_session_id(self, session, msgid):
103 self.internal_ids[self.internal_id] = session, msgid
105 self.internal_id += 1
109 if self.shared is None:
110 raise TypeError("self.shared not set in Processor")
111 while not self.shared.stopped():
112 session, request = self.pop_request()
113 self.process(session, request)
120 def process(self, session, request):
121 method = request['method']
122 params = request.get('params',[])
124 suffix = method.split('.')[-1]
125 if suffix == 'subscribe':
126 session.subscribe_to_service(method, params)
128 # store session and id locally
129 request['id'] = self.store_session_id(session, request['id'])
131 # dispatch request to the relevant module..
132 prefix = request['method'].split('.')[0]
134 p = self.processors[prefix]
136 print "error: no processor for", prefix
141 traceback.print_exc(file=sys.stdout)
143 if method in ['server.version']:
144 session.version = params[0]
147 def add_session(self, session):
149 self.sessions.append(session)
151 def collect_garbage(self):
152 # Deep copy entire sessions list and blank it
153 # This is done to minimise lock contention
155 sessions = self.sessions[:]
157 for session in sessions:
158 if not session.stopped():
159 # If session is still alive then re-add it back
160 # to our internal register
161 self.add_session(session)
167 self._stopped = False
168 self.lock = threading.Lock()
169 self.subscriptions = []
172 self.version = 'unknown'
173 threading.Timer(2, self.info).start()
175 # Debugging method. Doesn't need to be threadsafe.
177 for sub in self.subscriptions:
180 if method == 'blockchain.address.subscribe':
186 if self.subscriptions:
187 print timestr(), self.name, self.address, addr,\
188 len(self.subscriptions), self.version
194 def subscribe_to_service(self, method, params):
195 subdesc = self.build_subdesc(method, params)
197 if subdesc is not None:
198 self.subscriptions.append(subdesc)
200 # subdesc = A subscription description
202 def build_subdesc(method, params):
203 if method == "blockchain.numblocks.subscribe":
205 elif method == "blockchain.address.subscribe":
209 return method, params[0]
213 def contains_subscription(self, subdesc):
215 return subdesc in self.subscriptions
218 class ResponseDispatcher(threading.Thread):
220 def __init__(self, shared, processor):
222 self.processor = processor
223 threading.Thread.__init__(self)
227 while not self.shared.stopped():
231 response = self.processor.pop_response()
232 #print "pop response", response
233 internal_id = response.get('id')
234 method = response.get('method')
235 params = response.get('params')
238 if internal_id is None: # and method is not None and params is not None:
239 self.notification(method, params, response)
241 elif internal_id is not None: # and method is None and params is None:
242 self.send_response(internal_id, response)
244 print "no method", response
246 def notification(self, method, params, response):
247 subdesc = Session.build_subdesc(method, params)
248 for session in self.processor.sessions:
249 if session.stopped():
251 if session.contains_subscription(subdesc):
252 session.send_response(response)
254 def send_response(self, internal_id, response):
255 session, message_id = self.processor.get_session_id(internal_id)
257 response['id'] = message_id
258 session.send_response(response)
260 print "send_response: no session", message_id, internal_id, response