7 from processor import Session, Dispatcher
8 from utils import print_log
11 class TcpSession(Session):
13 def __init__(self, connection, address, use_ssl, ssl_certfile, ssl_keyfile):
14 Session.__init__(self)
17 self._connection = ssl.wrap_socket(
20 certfile=ssl_certfile,
22 ssl_version=ssl.PROTOCOL_SSLv23)
24 self._connection = connection
26 self.address = address[0]
27 self.name = "TCP " if not use_ssl else "SSL "
31 raise Exception("Session was stopped")
33 return self._connection
36 self._connection.close()
37 #print "Terminating connection:", self.address
41 def send_response(self, response):
42 data = json.dumps(response) + "\n"
43 # Possible race condition here by having session
45 # I assume Python connections are thread safe interfaces
47 connection = self.connection()
49 l = connection.send(data)
55 class TcpClientRequestor(threading.Thread):
57 def __init__(self, dispatcher, session):
58 self.shared = dispatcher.shared
59 self.dispatcher = dispatcher
61 self.session = session
62 threading.Thread.__init__(self)
65 while not self.shared.stopped():
69 self.session.time = time.time()
86 return self.session.connection().recv(2048)
91 raw_buffer = self.message.find('\n')
95 raw_command = self.message[0:raw_buffer].strip()
96 self.message = self.message[raw_buffer + 1:]
97 if raw_command == 'quit':
102 command = json.loads(raw_command)
104 self.dispatcher.push_response({"error": "bad JSON", "request": raw_command})
108 # Try to load vital fields, and return an error if
110 message_id = command['id']
111 method = command['method']
113 # Return an error JSON in response.
114 self.dispatcher.push_response({"error": "syntax error", "request": raw_command})
116 self.dispatcher.push_request(self.session, command)
121 class TcpServer(threading.Thread):
123 def __init__(self, dispatcher, host, port, use_ssl, ssl_certfile, ssl_keyfile):
124 self.shared = dispatcher.shared
125 self.dispatcher = dispatcher.request_dispatcher
126 threading.Thread.__init__(self)
130 self.lock = threading.Lock()
131 self.use_ssl = use_ssl
132 self.ssl_keyfile = ssl_keyfile
133 self.ssl_certfile = ssl_certfile
137 print_log("TCP/SSL server started.")
139 print_log("TCP server started.")
140 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
141 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
142 sock.bind((self.host, self.port))
144 while not self.shared.stopped():
146 session = TcpSession(*sock.accept(), use_ssl=self.use_ssl, ssl_certfile=self.ssl_certfile, ssl_keyfile=self.ssl_keyfile)
147 except BaseException, e:
149 print_log("cannot start TCP session", error)
151 self.dispatcher.add_session(session)
152 self.dispatcher.collect_garbage()
153 client_req = TcpClientRequestor(self.dispatcher, session)