1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
# mainloop/sockserv.py -- socket server state machines
#
# Copyright (C) 2012, 2014 Codethink Limited
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA..
import logging
from sm import StateMachine
from socketsrc import NewConnection, SocketError, ListeningSocketEventSource
class _Close(object):
pass
class ListenServer(StateMachine):
'''Listen for new connections on a port, send events for them.'''
def __init__(self, addr, port, machine, extra_args=None, port_file=''):
StateMachine.__init__(self, 'listening')
self._addr = addr
self._port = port
self._machine = machine
self._extra_args = extra_args or []
self._port_file = port_file
def setup(self):
src = ListeningSocketEventSource(self._addr, self._port)
if self._port_file:
host, port = src.sock.getsockname()
with open(self._port_file, 'w') as f:
f.write('%s\n' % port)
self.mainloop.add_event_source(src)
spec = [
# state, source, event_class, new_state, callback
('listening', src, NewConnection, 'listening', self.new_conn),
('listening', src, SocketError, None, self.report_error),
('listening', self, _Close, None, self._really_close),
]
self.add_transitions(spec)
self._src = src
def new_conn(self, event_source, event):
logging.debug(
'ListenServer: Creating new %s using %s and %s' %
(self._machine,
repr(event.connection),
repr(self._extra_args)))
m = self._machine(event.connection, *self._extra_args)
self.mainloop.add_state_machine(m)
def report_error(self, event_source, event):
logging.error(str(event))
def close(self):
self.mainloop.remove_event_source(self._src)
self.mainloop.queue_event(self, _Close())
def _really_close(self, event_source, event):
self._src.close()
|