HOWTO: Recommend downloading, update index stats, point to step 10 in step 7
[electrum-server.git] / processor.py
1 import json
2 import Queue as queue
3 import socket
4 import threading
5 import time
6 import traceback
7 import sys
8
9 from utils import random_string, timestr, print_log
10
11
12 class Shared:
13
14     def __init__(self, config):
15         self.lock = threading.Lock()
16         self._stopped = False
17         self.config = config
18
19     def stop(self):
20         print_log("Stopping Stratum")
21         with self.lock:
22             self._stopped = True
23
24     def stopped(self):
25         with self.lock:
26             return self._stopped
27
28
29 class Processor(threading.Thread):
30
31     def __init__(self):
32         threading.Thread.__init__(self)
33         self.daemon = True
34         self.dispatcher = None
35         self.queue = queue.Queue()
36
37     def process(self, request):
38         pass
39
40     def add_request(self, request):
41         self.queue.put(request)
42
43     def push_response(self, response):
44         #print "response", response
45         self.dispatcher.request_dispatcher.push_response(response)
46
47     def run(self):
48         while not self.shared.stopped():
49             request = self.queue.get(10000000000)
50             try:
51                 self.process(request)
52             except:
53                 traceback.print_exc(file=sys.stdout)
54
55         print_log("processor terminating")
56
57
58 class Dispatcher:
59
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()
67
68     def register(self, prefix, processor):
69         processor.dispatcher = self
70         processor.shared = self.shared
71         processor.start()
72         self.request_dispatcher.processors[prefix] = processor
73
74
75 class RequestDispatcher(threading.Thread):
76
77     def __init__(self, shared):
78         self.shared = shared
79         threading.Thread.__init__(self)
80         self.daemon = True
81         self.request_queue = queue.Queue()
82         self.response_queue = queue.Queue()
83         self.internal_ids = {}
84         self.internal_id = 1
85         self.lock = threading.Lock()
86         self.idlock = threading.Lock()
87         self.sessions = []
88         self.processors = {}
89
90     def push_response(self, item):
91         self.response_queue.put(item)
92
93     def pop_response(self):
94         return self.response_queue.get()
95
96     def push_request(self, session, item):
97         self.request_queue.put((session, item))
98
99     def pop_request(self):
100         return self.request_queue.get()
101
102     def get_session_by_address(self, address):
103         for x in self.sessions:
104             if x.address == address:
105                 return x
106
107     def get_session_id(self, internal_id):
108         with self.idlock:
109             return self.internal_ids.pop(internal_id)
110
111     def store_session_id(self, session, msgid):
112         with self.idlock:
113             self.internal_ids[self.internal_id] = session, msgid
114             r = self.internal_id
115             self.internal_id += 1
116             return r
117
118     def run(self):
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()
123             try:
124                 self.do_dispatch(session, request)
125             except:
126                 traceback.print_exc(file=sys.stdout)
127
128         self.stop()
129
130     def stop(self):
131         pass
132
133     def do_dispatch(self, session, request):
134         """ dispatch request to the relevant processor """
135
136         method = request['method']
137         params = request.get('params', [])
138         suffix = method.split('.')[-1]
139
140         if session is not None:
141             if suffix == 'subscribe':
142                 session.subscribe_to_service(method, params)
143
144         # store session and id locally
145         request['id'] = self.store_session_id(session, request['id'])
146
147         prefix = request['method'].split('.')[0]
148         try:
149             p = self.processors[prefix]
150         except:
151             print_log("error: no processor for", prefix)
152             return
153
154         p.add_request(request)
155
156         if method in ['server.version']:
157             session.version = params[0]
158             try:
159                 session.protocol_version = float(params[1])
160             except:
161                 pass
162
163
164     def get_sessions(self):
165         with self.lock:
166             r = self.sessions[:]
167         return r
168
169     def add_session(self, session):
170         with self.lock:
171             self.sessions.append(session)
172
173     def collect_garbage(self):
174         # Deep copy entire sessions list and blank it
175         # This is done to minimize lock contention
176         with self.lock:
177             sessions = self.sessions[:]
178
179         active_sessions = []
180         now = time.time()
181         for session in sessions:
182             if not session.stopped() and (now - session.time) < 1000:
183                 # If session is still alive then re-add it back
184                 # to our internal register
185                 active_sessions.append(session)
186
187         with self.lock:
188             self.sessions = active_sessions[:]
189
190
191
192 class Session:
193
194     def __init__(self):
195         self._stopped = False
196         self.lock = threading.Lock()
197         self.subscriptions = []
198         self.address = ''
199         self.name = ''
200         self.version = 'unknown'
201         self.protocol_version = 0.
202         self.time = time.time()
203         threading.Timer(2, self.info).start()
204
205     # Debugging method. Doesn't need to be threadsafe.
206     def info(self):
207         for sub in self.subscriptions:
208             #print sub
209             method = sub[0]
210             if method == 'blockchain.address.subscribe':
211                 addr = sub[1]
212                 break
213         else:
214             addr = None
215
216         if self.subscriptions:
217             print_log("%4s" % self.name,
218                       "%15s" % self.address,
219                       "%35s" % addr,
220                       "%3d" % len(self.subscriptions),
221                       self.version)
222
223     def stopped(self):
224         with self.lock:
225             return self._stopped
226
227     def subscribe_to_service(self, method, params):
228         subdesc = self.build_subdesc(method, params)
229         with self.lock:
230             if subdesc is not None:
231                 self.subscriptions.append(subdesc)
232
233     # subdesc = A subscription description
234     @staticmethod
235     def build_subdesc(method, params):
236         if method == "blockchain.numblocks.subscribe":
237             return method,
238         elif method == "blockchain.headers.subscribe":
239             return method,
240         elif method in ["blockchain.address.subscribe"]:
241             if not params:
242                 return None
243             else:
244                 return method, params[0]
245         else:
246             return None
247
248     def contains_subscription(self, subdesc):
249         with self.lock:
250             return subdesc in self.subscriptions
251
252
253 class ResponseDispatcher(threading.Thread):
254
255     def __init__(self, shared, request_dispatcher):
256         self.shared = shared
257         self.request_dispatcher = request_dispatcher
258         threading.Thread.__init__(self)
259         self.daemon = True
260
261     def run(self):
262         while not self.shared.stopped():
263             self.update()
264
265     def update(self):
266         response = self.request_dispatcher.pop_response()
267         #print "pop response", response
268         internal_id = response.get('id')
269         method = response.get('method')
270         params = response.get('params')
271
272         # A notification
273         if internal_id is None:  # and method is not None and params is not None:
274             found = self.notification(method, params, response)
275             if not found and method == 'blockchain.address.subscribe':
276                 request = {
277                     'id': None,
278                     'method': method.replace('.subscribe', '.unsubscribe'),
279                     'params': [self.shared.config.get('server', 'password')] + params,
280                 }
281
282                 self.request_dispatcher.push_request(None, request)
283         # A response
284         elif internal_id is not None:
285             self.send_response(internal_id, response)
286         else:
287             print_log("no method", response)
288
289     def notification(self, method, params, response):
290         subdesc = Session.build_subdesc(method, params)
291         found = False
292         for session in self.request_dispatcher.sessions:
293             if session.stopped():
294                 continue
295             if session.contains_subscription(subdesc):
296                 session.send_response(response)
297                 found = True
298         # if not found: print_log("no subscriber for", subdesc)
299         return found
300
301     def send_response(self, internal_id, response):
302         session, message_id = self.request_dispatcher.get_session_id(internal_id)
303         if session:
304             response['id'] = message_id
305             session.send_response(response)
306         #else:
307         #    print_log("send_response: no session", message_id, internal_id, response )