source: trunk/FACT++/src/Connection.cc@ 20011

Last change on this file since 20011 was 20005, checked in by tbretz, 4 years ago
The API in boost 1.70 changed.
File size: 13.1 KB
Line 
1// **************************************************************************
2/** @class Connection
3
4@brief Maintains an ansynchronous TCP/IP client connection
5
6@todo
7 Unify with ConnectionUSB
8
9*/
10// **************************************************************************
11#include "Connection.h"
12
13using namespace std;
14
15namespace ba = boost::asio;
16namespace bs = boost::system;
17namespace dummy = ba::placeholders;
18
19using ba::ip::tcp;
20
21 // -------- Abbreviations for starting async tasks ---------
22
23int Connection::Write(const Time &t, const string &txt, int qos)
24{
25 if (fLog)
26 return fLog->Write(t, txt, qos);
27
28 return MessageImp::Write(t, txt, qos);
29}
30
31void Connection::AsyncRead(const ba::mutable_buffers_1 buffers, int type)
32{
33 ba::async_read(*this, buffers,
34 boost::bind(&Connection::HandleReceivedData, this,
35 dummy::error, dummy::bytes_transferred, type));
36}
37
38void Connection::AsyncWrite(const ba::const_buffers_1 &buffers)
39{
40 ba::async_write(*this, buffers,
41 boost::bind(&Connection::HandleSentData, this,
42 dummy::error, dummy::bytes_transferred));
43}
44
45/*
46void Connection::AsyncWait(ba::deadline_timer &timer, int millisec,
47 void (Connection::*handler)(const bs::error_code&))
48{
49 // - The boost::asio::basic_deadline_timer::expires_from_now()
50 // function cancels any pending asynchronous waits, and returns
51 // the number of asynchronous waits that were cancelled. If it
52 // returns 0 then you were too late and the wait handler has
53 // already been executed, or will soon be executed. If it
54 // returns 1 then the wait handler was successfully cancelled.
55 // - If a wait handler is cancelled, the bs::error_code passed to
56 // it contains the value bs::error::operation_aborted.
57 timer.expires_from_now(boost::posix_time::milliseconds(millisec));
58
59 timer.async_wait(boost::bind(handler, this, dummy::error));
60}
61*/
62
63void Connection::AsyncConnect(tcp::resolver::iterator iterator)
64{
65 tcp::endpoint endpoint = *iterator;
66
67 // AsyncConnect + Deadline
68 async_connect(endpoint,
69 boost::bind(&Connection::ConnectIter,
70 this, iterator, ba::placeholders::error));
71
72 // We will get a "Connection timeout anyway"
73 //AsyncWait(fConnectTimeout, 5, &Connection::HandleConnectTimeout);
74}
75
76void Connection::AsyncConnect()
77{
78 // AsyncConnect + Deadline
79 async_connect(fEndpoint,
80 boost::bind(&Connection::ConnectAddr,
81 this, fEndpoint, ba::placeholders::error));
82
83 // We will get a "Connection timeout anyway"
84 //AsyncWait(fConnectTimeout, 5, &Connection::HandleConnectTimeout);
85}
86
87// ------------------------ close --------------------------
88// close from another thread
89void Connection::CloseImp(bool restart)
90{
91 if (IsConnected() && fVerbose)
92 {
93 ostringstream str;
94 str << "Connection closed to " << URL() << ".";
95 Info(str);
96 }
97
98 // Stop any pending connection attempt
99 fConnectionTimer.cancel();
100
101 // Close possible open connections
102 close();
103
104 // Reset the connection status
105 fQueueSize = 0;
106 fConnectionStatus = kDisconnected;
107
108 // Stop deadline counters
109 fInTimeout.cancel();
110 fOutTimeout.cancel();
111
112 if (!restart || IsConnecting())
113 return;
114
115 // We need some timeout before reconnecting!
116 // And we have to check if we are alreayd trying to connect
117 // We shoudl wait until all operations in progress were canceled
118
119 // Start trying to reconnect
120 fMsgConnect = "";
121 fErrConnect = "";
122 StartConnect();
123}
124
125void Connection::PostClose(bool restart)
126{
127 get_io_service().post(boost::bind(&Connection::CloseImp, this, restart));
128}
129
130// ------------------------ write --------------------------
131void Connection::HandleWriteTimeout(const bs::error_code &error)
132{
133 if (error==ba::error::basic_errors::operation_aborted)
134 return;
135
136 // 125: Operation canceled (bs::error_code(125, bs::system_category))
137 if (error)
138 {
139 ostringstream str;
140 str << "Write timeout of " << URL() << ": " << error.message() << " (" << error << ")";// << endl;
141 Error(str);
142
143 CloseImp();
144 return;
145 }
146
147 if (!is_open())
148 {
149 // For example: Here we could schedule a new accept if we
150 // would not want to allow two connections at the same time.
151 return;
152 }
153
154 // Check whether the deadline has passed. We compare the deadline
155 // against the current time since a new asynchronous operation
156 // may have moved the deadline before this actor had a chance
157 // to run.
158 if (fOutTimeout.expires_at() > ba::deadline_timer::traits_type::now())
159 return;
160
161 Error("fOutTimeout has expired, writing data to "+URL());
162
163 CloseImp();
164}
165
166void Connection::HandleSentData(const bs::error_code& error, size_t n)
167{
168 if (error==ba::error::basic_errors::operation_aborted)
169 return;
170
171 if (error && error != ba::error::not_connected)
172 {
173 ostringstream str;
174 str << "Writing to " << URL() << ": " << error.message() << " (" << error << ")";// << endl;
175 Error(str);
176
177 CloseImp();
178 return;
179 }
180
181 if (error == ba::error::not_connected)
182 {
183 ostringstream msg;
184 msg << n << " bytes could not be sent to " << URL() << " due to missing connection.";
185 Warn(msg);
186
187 return;
188 }
189
190 if (--fQueueSize==0)
191 fOutTimeout.cancel();
192
193 if (fDebugTx)
194 {
195 ostringstream msg;
196 msg << n << " bytes successfully sent to " << URL();
197 Debug(msg);
198 }
199}
200
201void Connection::PostMessage(const void *ptr, size_t sz)
202{
203 // This function can be called from a different thread...
204 if (!is_open())
205 return;
206
207 // ... this is why we have to increase fQueueSize first
208 fQueueSize++;
209
210 // ... and shift the deadline timer
211 // This is not ideal, because if we are continously
212 // filling the buffer, it will never timeout
213 AsyncWait(fOutTimeout, 5000, &Connection::HandleWriteTimeout);
214
215 // Now we can schedule the buffer to be sent
216 AsyncWrite(ba::const_buffers_1(ptr, sz));
217
218 // If a socket is closed, all pending asynchronous
219 // operation will be aborted.
220}
221
222void Connection::PostMessage(const string &cmd, size_t max)
223{
224 if (max==size_t(-1))
225 max = cmd.length()+1;
226
227 PostMessage(cmd.c_str(), min(cmd.length()+1, max));
228}
229
230void Connection::HandleConnectionTimer(const bs::error_code &error)
231{
232 if (error==ba::error::basic_errors::operation_aborted)
233 return;
234
235 if (error)
236 {
237 ostringstream str;
238 str << "Connetion timer of " << URL() << ": " << error.message() << " (" << error << ")";// << endl;
239 Error(str);
240 }
241
242 if (is_open())
243 {
244 // For example: Here we could schedule a new accept if we
245 // would not want to allow two connections at the same time.
246 return;
247 }
248
249 // Check whether the deadline has passed. We compare the deadline
250 // against the current time since a new asynchronous operation
251 // may have moved the deadline before this actor had a chance
252 // to run.
253 if (fConnectionTimer.expires_at() < ba::deadline_timer::traits_type::now())
254 StartConnect();
255}
256
257bool Connection::ConnectImp(const tcp::endpoint &endpoint, const bs::error_code& error)
258{
259 const string host = endpoint.port()==0 ? "" :
260 endpoint.address().to_string()+':'+to_string((long long unsigned int)endpoint.port());
261
262 // Connection established
263 if (!error)
264 {
265 set_option(socket_base::keep_alive(true));
266
267 const int optval = 30;
268
269#if BOOST_VERSION <107000
270 // First keep alive after 30s
271 setsockopt(native(), SOL_TCP, TCP_KEEPIDLE, &optval, sizeof(optval));
272 // New keep alive after 30s
273 setsockopt(native(), SOL_TCP, TCP_KEEPINTVL, &optval, sizeof(optval));
274#else
275 // First keep alive after 30s
276 setsockopt(native_handle(), SOL_TCP, TCP_KEEPIDLE, &optval, sizeof(optval));
277 // New keep alive after 30s
278 setsockopt(native_handle(), SOL_TCP, TCP_KEEPINTVL, &optval, sizeof(optval));
279#endif
280
281 if (fVerbose)
282 Info("Connection established to "+host+"...");
283
284 fQueueSize = 0;
285 fConnectionStatus = kConnected;
286
287 ConnectionEstablished();
288 return true;
289 }
290
291 // If returning from run will lead to deletion of this
292 // instance, close() is not needed (maybe implicitly called).
293 // If run is called again, close() is needed here. Otherwise:
294 // Software caused connection abort when we try to resolve
295 // the endpoint again.
296 CloseImp(false);
297
298 ostringstream msg;
299 if (!host.empty())
300 msg << "Connecting to " << host << ": " << error.message() << " (" << error << ")";
301
302 if (fErrConnect!=msg.str())
303 {
304 if (error!=ba::error::basic_errors::connection_refused)
305 fMsgConnect = "";
306 fErrConnect = msg.str();
307 Warn(fErrConnect);
308 }
309
310 if (error==ba::error::basic_errors::operation_aborted)
311 return true;
312
313 fConnectionStatus = kConnecting;
314
315 return false;
316/*
317 // Go on with the next
318 if (++iterator != tcp::resolver::iterator())
319 {
320 AsyncConnect(iterator);
321 return;
322 }
323*/
324 // No more entries to try, if we would not put anything else
325 // into the queue anymore it would now return (run() would return)
326
327 // Since we don't want to block the main loop, we wait using an
328 // asnychronous timer
329
330 // FIXME: Should we move this before AsyncConnect() ?
331// AsyncWait(fConnectionTimer, 250, &Connection::HandleConnectionTimer);
332}
333
334void Connection::ConnectIter(tcp::resolver::iterator iterator, const bs::error_code& error)
335{
336 if (ConnectImp(*iterator, error))
337 return;
338
339 // Go on with the next
340 if (++iterator != tcp::resolver::iterator())
341 {
342 AsyncConnect(iterator);
343 return;
344 }
345
346 // No more entries to try, if we would not put anything else
347 // into the queue anymore it would now return (run() would return)
348 AsyncWait(fConnectionTimer, 250, &Connection::HandleConnectionTimer);
349}
350
351void Connection::ConnectAddr(const tcp::endpoint &endpoint, const bs::error_code& error)
352{
353 if (ConnectImp(endpoint, error))
354 return;
355
356 AsyncWait(fConnectionTimer, 250, &Connection::HandleConnectionTimer);
357}
358
359// FIXME: Async connect should get address and port as an argument
360void Connection::StartConnect()
361{
362 fConnectionStatus = kConnecting;
363
364 if (fEndpoint!=tcp::endpoint())
365 {
366 ostringstream msg;
367 msg << "Trying to connect to " << fEndpoint << "...";
368 if (fMsgConnect!=msg.str())
369 {
370 fMsgConnect = msg.str();
371 Info(msg);
372 }
373
374 AsyncConnect();
375 return;
376 }
377
378 const bool valid = !fAddress.empty() || !fPort.empty();
379
380 boost::system::error_code ec;
381
382 ostringstream msg;
383 if (!valid)
384 msg << "No target address... connection attempt postponed.";
385 else
386 {
387 tcp::resolver resolver(get_io_service());
388
389 tcp::resolver::query query(fAddress, fPort);
390 tcp::resolver::iterator iterator = resolver.resolve(query, ec);
391
392 msg << "Trying to connect to " << URL() << "...";
393
394 // Start connection attempts (will also reset deadline counter)
395 if (!ec)
396 AsyncConnect(iterator);
397 else
398 msg << " " << ec.message() << " (" << ec << ")";
399 }
400
401 // Only output message if it has changed
402 if (fMsgConnect!=msg.str())
403 {
404 fMsgConnect = msg.str();
405 if (ec)
406 Error(msg);
407 if (!ec && fVerbose)
408 Info(msg);
409 }
410
411 if (!valid || ec)
412 AsyncWait(fConnectionTimer, 250, &Connection::HandleConnectionTimer);
413}
414
415void Connection::SetEndpoint(const string &addr, int port)
416{
417 if (fConnectionStatus>=1)
418 Warn("Connection or connection attempt in progress. New endpoint only valid for next connection.");
419
420 fAddress = addr;
421 fPort = to_string((long long)port);
422}
423
424void Connection::SetEndpoint(const string &addr, const string &port)
425{
426 if (fConnectionStatus>=1 && URL()!=":")
427 Warn("Connection or connection attempt in progress. New endpoint only valid for next connection.");
428
429 fAddress = addr;
430 fPort = port;
431}
432
433void Connection::SetEndpoint(const string &addr)
434{
435 const size_t p0 = addr.find_first_of(':');
436 const size_t p1 = addr.find_last_of(':');
437
438 if (p0==string::npos || p0!=p1)
439 {
440 Error("Connection::SetEndpoint - Wrong format of argument '"+addr+"' ('host:port' expected)");
441 return;
442 }
443
444 SetEndpoint(addr.substr(0, p0), addr.substr(p0+1));
445}
446
447void Connection::SetEndpoint(const tcp::endpoint &ep)
448{
449 const ba::ip::address addr = ep.address();
450
451 const ba::ip::address use =
452 addr.is_v6() && addr.to_v6().is_loopback() ?
453 ba::ip::address(ba::ip::address_v4::loopback()) :
454 addr;
455
456 SetEndpoint(use.to_string(), ep.port());
457
458 fEndpoint = tcp::endpoint(use, ep.port());
459}
460
461
462Connection::Connection(ba::io_service& ioservice, ostream &out) :
463MessageImp(out), tcp::socket(ioservice),
464fLog(0), fVerbose(true), fDebugTx(false),
465fInTimeout(ioservice), fOutTimeout(ioservice), fConnectionTimer(ioservice),
466fQueueSize(0), fConnectionStatus(kDisconnected)
467{
468}
Note: See TracBrowser for help on using the repository browser.