Debian Codegraph @

mlat/client/net.py

raw symbols SCIP
1 # -*- mode: python; indent-tabs-mode: nil -*-
2
3 # Part of mlat-client - an ADS-B multilateration client.
4 # Copyright 2015, Oliver Jowett <[email protected]>
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18
19 """
20 Common networking bits, based on asyncore
21 """
22
23 import sys
24 import socket
25 import asyncore
26 from mlat.client.util import log, log_exc, monotonic_time
27
28 import random
29 random.seed()
30
31 __all__ = ('LoggingMixin', 'ReconnectingConnection')
32
33
34 class LoggingMixin:
35 """A mixin that redirects asyncore's logging to the client's
36 global logging."""
37
38 def log(self, message):
39 log('{0}', message)
40
41 def log_info(self, message, type='info'):
42 log('{0}: {1}', message, type)
43
44
45 class ReconnectingConnection(LoggingMixin, asyncore.dispatcher):
46 """
47 An asyncore connection that maintains a TCP connection to a particular
48 host/port, reconnecting on connection loss.
49 """
50
51 reconnect_interval = 10.0
52
53 def __init__(self, host, port):
54 asyncore.dispatcher.__init__(self)
55 self.host = host
56 self.port = port
57 # check port as well, if port doesn't match, could be direct MLAT
58 if self.host == 'feed.adsb.fi' and port == 31090:
59 self.adsbexchange = True
60 else:
61 self.adsbexchange = False
62 self.adsbexchangePortIndex = 0
63 self.adsbexchangeHostIndex = 0
64 self.adsbexchangePorts = [ 31090, 64590 ]
65 self.adsbexchangeHosts = [ 'feed1.adsb.fi', 'feed2.adsb.fi' ]
66 self.addrlist = []
67 self.state = 'disconnected'
68 self.reconnect_at = None
69 self.last_try = 0
70
71 def heartbeat(self, now):
72 if self.reconnect_at is None or self.reconnect_at > now:
73 return
74 if self.state == 'ready':
75 return
76 self.reconnect_at = None
77 self.reconnect()
78
79 def close(self, manual_close=False):
80 try:
81 asyncore.dispatcher.close(self)
82 except AttributeError:
83 # blarg, try to eat asyncore bugs
84 pass
85
86 if self.state != 'disconnected':
87 if not manual_close:
88 log('Lost connection to {host}:{port}', host=self.host, port=self.port)
89
90 self.state = 'disconnected'
91 self.reset_connection()
92 self.lost_connection()
93
94 if not manual_close:
95 self.schedule_reconnect()
96
97 def disconnect(self, reason):
98 if self.state != 'disconnected':
99 log('Disconnecting from {host}:{port}: {reason}', host=self.host, port=self.port, reason=reason)
100 self.close(True)
101
102 def writable(self):
103 return self.connecting
104
105 def schedule_reconnect(self):
106 if self.reconnect_at is None:
107 mono = monotonic_time()
108
109 if len(self.addrlist) > 0:
110 # we still have more addresses to try
111 # nb: asyncore breaks in odd ways if you try
112 # to reconnect immediately at this point
113 # (pending events for the old socket go to
114 # the new socket) so do it in 0.5s time
115 # so the caller can clean up the old
116 # socket and discard the events.
117 interval = 0.5
118 else:
119
120 interval = self.last_try + self.reconnect_interval - mono + 2 * random.random()
121
122 if interval < 4:
123 interval = 2 + 2 * random.random()
124
125 log('Reconnecting in {seconds:.1f} seconds'.format(seconds=interval))
126 self.reconnect_at = mono + interval
127
128 def refresh_address_list(self):
129 self.address
130
131 def reconnect(self):
132 if self.state != 'disconnected':
133 self.disconnect('About to reconnect')
134
135 self.last_try = monotonic_time()
136 try:
137 self.reset_connection()
138
139
140 if len(self.addrlist) == 0:
141 # ran out of addresses to try, resolve it again
142 if self.adsbexchange:
143 self.adsbexchangePortIndex = (self.adsbexchangePortIndex + 1) % len(self.adsbexchangePorts)
144 self.adsbexchangeHostIndex = (self.adsbexchangeHostIndex + 1) % len(self.adsbexchangeHosts)
145 self.host = self.adsbexchangeHosts[self.adsbexchangeHostIndex];
146 self.port = self.adsbexchangePorts[self.adsbexchangePortIndex];
147
148 self.addrlist = socket.getaddrinfo(host=self.host,
149 port=self.port,
150 family=socket.AF_UNSPEC,
151 type=socket.SOCK_STREAM,
152 proto=0,
153 flags=0)
154
155 # try the next available address
156 a_family, a_type, a_proto, a_canonname, a_sockaddr = self.addrlist[0]
157 del self.addrlist[0]
158
159 self.create_socket(a_family, a_type)
160 self.connect(a_sockaddr)
161 except socket.error as e:
162 log('Connection to {host}:{port} failed: {ex!s}', host=self.host, port=self.port, ex=e)
163 self.close()
164
165 def handle_connect(self):
166 self.state = 'connected'
167 self.addrlist = [] # connect was OK, re-resolve next time
168 self.start_connection()
169
170 def handle_read(self):
171 pass
172
173 def handle_write(self):
174 pass
175
176 def handle_close(self):
177 self.close()
178
179 def handle_error(self):
180 t, v, tb = sys.exc_info()
181 if isinstance(v, IOError):
182 log('Connection to {host}:{port} lost: {ex!s}',
183 host=self.host,
184 port=self.port,
185 ex=v)
186 else:
187 log_exc('Unexpected exception on connection to {host}:{port}',
188 host=self.host,
189 port=self.port)
190
191 self.handle_close()
192
193 def reset_connection(self):
194 pass
195
196 def start_connection(self):
197 pass
198
199 def lost_connection(self):
200 pass