Line data Source code
1 : // Copyright (c) 2012-2021 Made to Order Software Corp. All Rights Reserved
2 : //
3 : // https://snapwebsites.org/project/eventdispatcher
4 : // contact@m2osw.com
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 2 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 along
17 : // with this program; if not, write to the Free Software Foundation, Inc.,
18 : // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 :
20 : /** \file
21 : * \brief Implementation of the permanent TCP connection.
22 : *
23 : * This class is an extension of the TCP client message connection used
24 : * to handle a TCP connection which supports messages and will automatically
25 : * try to reconnect if the connection drops.
26 : *
27 : * The class will also try to connect with the next address if more than one
28 : * is available.
29 : */
30 :
31 :
32 : // self
33 : //
34 : #include "eventdispatcher/tcp_client_permanent_message_connection.h"
35 :
36 : #include "eventdispatcher/communicator.h"
37 : #include "eventdispatcher/exception.h"
38 : #include "eventdispatcher/tcp_server_client_message_connection.h"
39 : #include "eventdispatcher/thread_done_signal.h"
40 :
41 :
42 : // snaplogger lib
43 : //
44 : #include <snaplogger/message.h>
45 :
46 :
47 : // snapdev lib
48 : //
49 : #include <snapdev/not_used.h>
50 :
51 :
52 : // cppthread lib
53 : //
54 : #include <cppthread/exception.h>
55 : #include <cppthread/guard.h>
56 : #include <cppthread/runner.h>
57 : #include <cppthread/thread.h>
58 :
59 :
60 : // C++ lib
61 : //
62 : #include <cstring>
63 :
64 :
65 : // C lib
66 : //
67 : #include <sys/socket.h>
68 :
69 :
70 : // last include
71 : //
72 : #include <snapdev/poison.h>
73 :
74 :
75 :
76 : namespace ed
77 : {
78 :
79 :
80 :
81 : namespace detail
82 : {
83 :
84 :
85 : /** \brief Internal implementation of the tcp_client_permanent_message_connection class.
86 : *
87 : * This class is used to handle a thread that will process a connection for
88 : * us. This allows us to connect in any amount of time required by the
89 : * Unix system to obtain the connection with the remote server.
90 : *
91 : * \todo
92 : * Having threads at the time we do a fork() is not safe. We may
93 : * want to reconsider offering this functionality here. Because at
94 : * this time we would have no control of when the thread is created
95 : * and thus a way to make sure that no such thread is running when
96 : * we call fork().
97 : */
98 : class tcp_client_permanent_message_connection_impl
99 : {
100 : public:
101 0 : class messenger
102 : : public tcp_server_client_message_connection
103 : {
104 : public:
105 : typedef std::shared_ptr<messenger> pointer_t;
106 :
107 0 : messenger(tcp_client_permanent_message_connection * parent, tcp_bio_client::pointer_t client)
108 0 : : tcp_server_client_message_connection(client)
109 0 : , f_parent(parent)
110 : {
111 0 : set_name("tcp_client_permanent_message_connection_impl::messenger");
112 0 : }
113 :
114 : messenger(messenger const & rhs) = delete;
115 : messenger & operator = (messenger const & rhs) = delete;
116 :
117 : // connection implementation
118 0 : virtual void process_empty_buffer()
119 : {
120 0 : tcp_server_client_message_connection::process_empty_buffer();
121 0 : f_parent->process_empty_buffer();
122 0 : }
123 :
124 : // connection implementation
125 0 : virtual void process_error()
126 : {
127 0 : tcp_server_client_message_connection::process_error();
128 0 : f_parent->process_error();
129 0 : }
130 :
131 : // connection implementation
132 0 : virtual void process_hup()
133 : {
134 0 : tcp_server_client_message_connection::process_hup();
135 0 : f_parent->process_hup();
136 0 : }
137 :
138 : // connection implementation
139 0 : virtual void process_invalid()
140 : {
141 0 : tcp_server_client_message_connection::process_invalid();
142 0 : f_parent->process_invalid();
143 0 : }
144 :
145 : // tcp_server_client_message_connection implementation
146 0 : virtual void process_message(message const & msg)
147 : {
148 : // We call the dispatcher from our parent since the child
149 : // (this messenger) is not given a dispatcher
150 : //
151 0 : message copy(msg);
152 0 : f_parent->dispatch_message(copy);
153 0 : }
154 :
155 : private:
156 : tcp_client_permanent_message_connection * f_parent = nullptr;
157 : };
158 :
159 0 : class thread_signal_handler
160 : : public thread_done_signal
161 : {
162 : public:
163 : typedef std::shared_ptr<thread_signal_handler> pointer_t;
164 :
165 0 : thread_signal_handler(tcp_client_permanent_message_connection_impl * parent_impl)
166 0 : : f_parent_impl(parent_impl)
167 : {
168 0 : set_name("tcp_client_permanent_message_connection_impl::thread_signal_handler");
169 0 : }
170 :
171 : thread_signal_handler(thread_signal_handler const & rhs) = delete;
172 : thread_signal_handler & operator = (thread_signal_handler const & rhs) = delete;
173 :
174 : /** \brief This signal was emitted.
175 : *
176 : * This function gets called whenever the thread is just about to
177 : * quit. Calling f_thread.is_running() may still return true when
178 : * you get in the 'thread_done()' callback. However, an
179 : * f_thread.stop() will return very quickly.
180 : */
181 0 : virtual void process_read()
182 : {
183 0 : thread_done_signal::process_read();
184 :
185 0 : f_parent_impl->thread_done();
186 0 : }
187 :
188 : private:
189 : tcp_client_permanent_message_connection_impl * f_parent_impl = nullptr;
190 : };
191 :
192 0 : class runner
193 : : public cppthread::runner
194 : {
195 : public:
196 0 : runner(
197 : tcp_client_permanent_message_connection_impl * parent_impl
198 : , std::string const & address
199 : , int port
200 : , tcp_bio_client::mode_t mode)
201 0 : : cppthread::runner("background tcp_client_permanent_message_connection for asynchronous connections")
202 : , f_parent_impl(parent_impl)
203 : , f_address(address)
204 : , f_port(port)
205 0 : , f_mode(mode)
206 : {
207 0 : }
208 :
209 : runner(runner const & rhs) = delete;
210 : runner & operator = (runner const & rhs) = delete;
211 :
212 :
213 : /** \brief This is the actual function run by the thread.
214 : *
215 : * This function calls the connect() function and then
216 : * tells the main thread we are done.
217 : */
218 0 : virtual void run()
219 : {
220 0 : connect();
221 :
222 : // tell the main thread that we are done
223 : //
224 0 : f_parent_impl->trigger_thread_done();
225 0 : }
226 :
227 :
228 : /** \brief This function attempts to connect.
229 : *
230 : * This function attempts a connection to the specified address
231 : * and port with the specified mode (i.e. plain or encrypted.)
232 : *
233 : * The function may take a long time to succeed connecting with
234 : * the server. The main thread will be awaken whenever this
235 : * thread dies.
236 : *
237 : * If an error occurs, then the f_socket variable member will
238 : * be set to -1. Otherwise it represents the socket that we
239 : * just connected with.
240 : */
241 0 : void connect()
242 : {
243 0 : char const * error_name(nullptr);
244 : try
245 : {
246 : // create a socket using the bio_client class,
247 : // but then just create a duplicate that we will
248 : // use in a server-client TCP object (because
249 : // we cannot directly create the right type of
250 : // object otherwise...)
251 : //
252 0 : f_tcp_connection = std::make_shared<tcp_bio_client>(f_address, f_port, f_mode);
253 0 : return;
254 : }
255 0 : catch(event_dispatcher_initialization_error const & e)
256 : {
257 0 : error_name = "event_dispatcher_initialization_error";
258 0 : f_last_error = e.what();
259 : }
260 0 : catch(event_dispatcher_runtime_error const & e)
261 : {
262 0 : error_name = "event_dispatcher_runtime_error";
263 0 : f_last_error = e.what();
264 : }
265 0 : catch(std::exception const & e)
266 : {
267 0 : error_name = "std::exception";
268 0 : f_last_error = e.what();
269 : }
270 0 : catch(...)
271 : {
272 0 : error_name = "... (any other exception)";
273 0 : f_last_error = "Unknown exception";
274 : }
275 0 : f_tcp_connection.reset();
276 :
277 : // connection failed... we will have to try again later
278 : //
279 : // WARNING: our logger is not multi-thread safe quiet yet
280 : //SNAP_LOG_ERROR
281 : // << "connection to "
282 : // << f_address
283 : // << ":"
284 : // << f_port
285 : // << " failed with: "
286 : // << f_last_error
287 : // << " ("
288 : // << error_name
289 : // << ")"
290 : // << SNAP_LOG_SEND;
291 : }
292 :
293 :
294 : /** \brief Retrieve the address to connect to.
295 : *
296 : * This function returns the address passed in on creation.
297 : *
298 : * \note
299 : * Since the variable is constant, it is likely to never change.
300 : * However, the c_str() function may change the buffer pointer.
301 : * Hence, to be 100% safe, you cannot call this function until
302 : * you make sure that the thread is fully stopped.
303 : */
304 0 : std::string const & get_address() const
305 : {
306 0 : return f_address;
307 : }
308 :
309 :
310 : /** \brief Retrieve the port to connect to.
311 : *
312 : * This function returns the port passed in on creation.
313 : *
314 : * \note
315 : * Since the variable is constant, it never gets changed
316 : * which means it is always safe to use it between
317 : * both threads.
318 : */
319 0 : int get_port() const
320 : {
321 0 : return f_port;
322 : }
323 :
324 :
325 : /** \brief Retrieve the client allocated and connected by the thread.
326 : *
327 : * This function returns the TCP connection object resulting from
328 : * connection attempts of the background thread.
329 : *
330 : * If the pointer is null, then you may get the corresponding
331 : * error message using the get_last_error() function.
332 : *
333 : * You can get the client TCP connection pointer once. After that
334 : * you always get a null pointer.
335 : *
336 : * \note
337 : * This function is guarded so the pointer and the object it
338 : * points to will be valid in another thread that retrieves it.
339 : *
340 : * \return The connection pointer.
341 : */
342 0 : tcp_bio_client::pointer_t release_client()
343 : {
344 0 : cppthread::guard g(f_mutex);
345 0 : tcp_bio_client::pointer_t tcp_connection;
346 0 : tcp_connection.swap(f_tcp_connection);
347 0 : return tcp_connection;
348 : }
349 :
350 :
351 : /** \brief Retrieve the last error message that happened.
352 : *
353 : * This function returns the last error message that was captured
354 : * when trying to connect to the socket. The message is the
355 : * e.what() message from the exception we captured.
356 : *
357 : * The message does not get cleared so the function can be called
358 : * any number of times. To know whether an error was generated
359 : * on the last attempt, make sure to first get the get_socket()
360 : * and if it returns -1, then this message is significant,
361 : * otherwise it is from a previous error.
362 : *
363 : * \warning
364 : * Remember that if the background thread was used the error will
365 : * NOT be available in the main thread until a full memory barrier
366 : * was executed. For that reason we make sure that the thread
367 : * was stopped when we detect an error.
368 : *
369 : * \return The last error message.
370 : */
371 0 : std::string const & get_last_error() const
372 : {
373 0 : return f_last_error;
374 : }
375 :
376 :
377 : /** \brief Close the connection.
378 : *
379 : * This function closes the connection. Since the f_tcp_connection
380 : * holds the socket to the remote server, we have get this function
381 : * called in order to completely disconnect.
382 : *
383 : * \note
384 : * This function does not clear the f_last_error parameter so it
385 : * can be read later.
386 : */
387 0 : void close()
388 : {
389 0 : f_tcp_connection.reset();
390 0 : }
391 :
392 :
393 : private:
394 : tcp_client_permanent_message_connection_impl * f_parent_impl = nullptr;
395 : std::string const f_address;
396 : int const f_port;
397 : tcp_bio_client::mode_t const f_mode;
398 : tcp_bio_client::pointer_t f_tcp_connection = tcp_bio_client::pointer_t();
399 : std::string f_last_error = std::string();
400 : };
401 :
402 :
403 : /** \brief Initialize a permanent message connection implementation object.
404 : *
405 : * This object manages the thread used to asynchronically connect to
406 : * the specified address and port.
407 : *
408 : * This class and its sub-classes may end up executing callbacks
409 : * of the tcp_client_permanent_message_connection object.
410 : * However, in all cases these are never run from the thread.
411 : *
412 : * \param[in] client A pointer to the owner of this
413 : * tcp_client_permanent_message_connection_impl object.
414 : * \param[in] address The address we are to connect to.
415 : * \param[in] port The port we are to connect to.
416 : * \param[in] mode The mode used to connect.
417 : */
418 0 : tcp_client_permanent_message_connection_impl(
419 : tcp_client_permanent_message_connection * parent
420 : , std::string const & address
421 : , int port
422 : , tcp_bio_client::mode_t mode)
423 0 : : f_parent(parent)
424 : , f_thread_runner(this, address, port, mode)
425 0 : , f_thread("background connection handler thread", &f_thread_runner)
426 : {
427 0 : }
428 :
429 :
430 : tcp_client_permanent_message_connection_impl(tcp_client_permanent_message_connection_impl const & rhs) = delete;
431 : tcp_client_permanent_message_connection_impl & operator = (tcp_client_permanent_message_connection_impl const & rhs) = delete;
432 :
433 : /** \brief Destroy the permanent message connection.
434 : *
435 : * This function makes sure that the messenger was lost.
436 : */
437 0 : ~tcp_client_permanent_message_connection_impl()
438 0 : {
439 : // to make sure we can lose the messenger, first we want to be sure
440 : // that we do not have a thread running
441 : //
442 : try
443 : {
444 0 : f_thread.stop();
445 : }
446 0 : catch(cppthread::cppthread_mutex_failed_error const &)
447 : {
448 : }
449 0 : catch(cppthread::cppthread_invalid_error const &)
450 : {
451 : }
452 :
453 : // in this case we may still have an instance of the f_thread_done
454 : // which linger around, we want it out
455 : //
456 : // Note: the call is safe even if the f_thread_done is null
457 : //
458 0 : communicator::instance()->remove_connection(f_thread_done);
459 :
460 : // although the f_messenger variable gets reset automatically in
461 : // the destructor, it would not get removed from the
462 : // communicator instance if we were not doing it explicitly
463 : //
464 0 : disconnect();
465 0 : }
466 :
467 :
468 : /** \brief Direct connect to the messenger.
469 : *
470 : * In this case we try to connect without the thread. This allows
471 : * us to avoid the thread problems, but we are blocked until the
472 : * OS decides to time out or the connection worked.
473 : */
474 0 : void connect()
475 : {
476 0 : if(f_done)
477 : {
478 0 : SNAP_LOG_ERROR
479 0 : << "Permanent connection marked done. Cannot attempt to reconnect."
480 : << SNAP_LOG_SEND;
481 0 : return;
482 : }
483 :
484 : // call the thread connect() function from the main thread
485 : //
486 0 : f_thread_runner.connect();
487 :
488 : // simulate receiving the thread_done() signal
489 : //
490 0 : thread_done();
491 : }
492 :
493 :
494 : /** \brief Check whether the permanent connection is currently connected.
495 : *
496 : * This function returns true if the messenger exists, which means that
497 : * the connection is up.
498 : *
499 : * \return true if the connection is up.
500 : */
501 0 : bool is_connected()
502 : {
503 0 : return f_messenger != nullptr;
504 : }
505 :
506 :
507 : /** \brief Try to start the thread runner.
508 : *
509 : * This function tries to start the thread runner in order to initiate
510 : * a connection in the background. If the thread could not be started,
511 : * then the function returns false.
512 : *
513 : * If the thread started, then the function returns true. This does
514 : * not mean that the connection was obtained. This is known once
515 : * the process_connected() function is called.
516 : *
517 : * \return true if the thread was successfully started.
518 : */
519 0 : bool background_connect()
520 : {
521 0 : if(f_done)
522 : {
523 0 : SNAP_LOG_ERROR
524 0 : << "Permanent connection marked done. Cannot attempt to reconnect."
525 : << SNAP_LOG_SEND;
526 0 : return false;
527 : }
528 :
529 0 : if(f_thread.is_running())
530 : {
531 0 : SNAP_LOG_ERROR
532 0 : << "A background connection attempt is already in progress. Further requests are ignored."
533 : << SNAP_LOG_SEND;
534 0 : return false;
535 : }
536 :
537 : // create the f_thread_done only when required
538 : //
539 0 : if(f_thread_done == nullptr)
540 : {
541 0 : f_thread_done = std::make_shared<thread_signal_handler>(this);
542 : }
543 :
544 0 : communicator::instance()->add_connection(f_thread_done);
545 :
546 0 : if(!f_thread.start())
547 : {
548 0 : SNAP_LOG_ERROR
549 0 : << "The thread used to run the background connection process did not start."
550 : << SNAP_LOG_SEND;
551 0 : return false;
552 : }
553 :
554 0 : return true;
555 : }
556 :
557 :
558 : /** \brief Tell the main thread that the background thread is done.
559 : *
560 : * This function is called by the thread so the thread_done()
561 : * function of the thread done object gets called. Only the
562 : * thread should call this function.
563 : *
564 : * As a result the thread_done() function of this class will be
565 : * called by the main thread.
566 : */
567 0 : void trigger_thread_done()
568 : {
569 0 : f_thread_done->thread_done();
570 0 : }
571 :
572 :
573 : /** \brief Signal that the background thread is done.
574 : *
575 : * This callback is called whenever the background thread sends
576 : * a signal to us. This is used to avoid calling end user functions
577 : * that would certainly cause a lot of problem if called from the
578 : * thread.
579 : *
580 : * The function calls the process_connection_failed() if the
581 : * connection did not happen.
582 : *
583 : * The function calls the process_connected() if the connection
584 : * did happen.
585 : *
586 : * \note
587 : * This is used only if the user requested that the connection
588 : * happen in the background (i.e. use_thread was set to true
589 : * in the tcp_client_permanent_message_connection object
590 : * constructor.)
591 : */
592 0 : void thread_done()
593 : {
594 : // if we used the thread we have to remove the signal used
595 : // to know that the thread was done
596 : //
597 0 : communicator::instance()->remove_connection(f_thread_done);
598 :
599 : // we will access the f_last_error member of the thread runner
600 : // which may not be available to the main thread yet, calling
601 : // stop forces a memory barrier so we are all good.
602 : //
603 : // calling stop() has no effect if we did not use the thread,
604 : // however, not calling stop() when we did use the thread
605 : // causes all sorts of other problems (especially, the thread
606 : // never gets joined)
607 : //
608 0 : f_thread.stop();
609 :
610 0 : tcp_bio_client::pointer_t client(f_thread_runner.release_client());
611 0 : if(f_done)
612 : {
613 : // already marked done, ignore the result and lose the
614 : // connection immediately
615 : //
616 : //f_thread_running.close(); -- not necessary, 'client' is the connection
617 0 : return;
618 : }
619 :
620 0 : if(client == nullptr)
621 : {
622 : // TODO: fix address in error message using a snap::addr so
623 : // as to handle IPv6 seamlessly.
624 : //
625 0 : SNAP_LOG_ERROR
626 0 : << "connection to "
627 0 : << f_thread_runner.get_address()
628 0 : << ":"
629 : << f_thread_runner.get_port()
630 : << " failed with: "
631 0 : << f_thread_runner.get_last_error()
632 : << SNAP_LOG_SEND;
633 :
634 : // signal that an error occurred
635 : //
636 0 : f_parent->process_connection_failed(f_thread_runner.get_last_error());
637 : }
638 : else
639 : {
640 0 : f_messenger = std::make_shared<messenger>(f_parent, client);
641 :
642 : // add the messenger to the communicator
643 : //
644 0 : communicator::instance()->add_connection(f_messenger);
645 :
646 : // if some messages were cached, process them immediately
647 : //
648 0 : while(!f_message_cache.empty())
649 : {
650 0 : f_messenger->send_message(f_message_cache[0]);
651 0 : f_message_cache.erase(f_message_cache.begin());
652 : }
653 :
654 : // let the client know we are now connected
655 : //
656 0 : f_parent->process_connected();
657 : }
658 : }
659 :
660 : /** \brief Send a message to the connection.
661 : *
662 : * This implementation function actually sends the message to the
663 : * connection, assuming that the connection exists. Otherwise, it
664 : * may cache the message (if cache is true.)
665 : *
666 : * Note that the message does not get cached if mark_done() was
667 : * called earlier since we are trying to close the whole connection.
668 : *
669 : * \param[in] message The message to send.
670 : * \param[in] cache Whether to cache the message if the connection is
671 : * currently down.
672 : *
673 : * \return true if the message was forwarded, false if the message
674 : * was ignored or cached.
675 : */
676 0 : bool send_message(message const & msg, bool cache)
677 : {
678 0 : if(f_messenger != nullptr)
679 : {
680 0 : return f_messenger->send_message(msg);
681 : }
682 :
683 0 : if(cache && !f_done)
684 : {
685 0 : f_message_cache.push_back(msg);
686 : }
687 :
688 0 : return false;
689 : }
690 :
691 :
692 : /** \brief Forget about the messenger connection.
693 : *
694 : * This function is used to fully disconnect from the messenger.
695 : *
696 : * If there is a messenger, this means:
697 : *
698 : * \li Removing the messenger from the communicator instance.
699 : * \li Closing the connection in the thread object.
700 : *
701 : * In most cases, it is called when an error occur, also it happens
702 : * that we call it explicitly through the disconnect() function
703 : * of the permanent connection class.
704 : *
705 : * \note
706 : * This is safe, even though it is called from the messenger itself
707 : * because it will not get deleted yet. This is because the run()
708 : * loop has a copy in its own temporary copy of the vector of
709 : * connections.
710 : */
711 0 : void disconnect()
712 : {
713 0 : if(f_messenger != nullptr)
714 : {
715 0 : communicator::instance()->remove_connection(f_messenger);
716 0 : f_messenger.reset();
717 :
718 : // just the messenger does not close the TCP connection because
719 : // we may have another in the thread runner
720 : //
721 0 : f_thread_runner.close();
722 : }
723 0 : }
724 :
725 :
726 : /** \brief Return the address and size of the remote computer.
727 : *
728 : * This function retrieve the socket address.
729 : *
730 : * \param[out] address The binary address of the remote computer.
731 : *
732 : * \return The size of the sockaddr structure, 0 if no address is available.
733 : */
734 0 : size_t get_client_address(sockaddr_storage & address) const
735 : {
736 0 : if(f_messenger != nullptr)
737 : {
738 0 : return f_messenger->get_client_address(address);
739 : }
740 0 : memset(&address, 0, sizeof(address));
741 0 : return 0;
742 : }
743 :
744 :
745 : /** \brief Return the address of the f_message object.
746 : *
747 : * This function returns the address of the message object.
748 : *
749 : * \return The address of the remote computer.
750 : */
751 0 : std::string get_client_addr() const
752 : {
753 0 : if(f_messenger != nullptr)
754 : {
755 0 : return f_messenger->get_client_addr();
756 : }
757 0 : return std::string();
758 : }
759 :
760 :
761 : /** \brief Mark the messenger as done.
762 : *
763 : * This function is used to mark the messenger as done. This means it
764 : * will get removed from the communicator instance as soon as it
765 : * is done with its current write buffer if there is one.
766 : *
767 : * You may also want to call the disconnection() function to actually
768 : * reset the pointer along the way.
769 : */
770 0 : void mark_done()
771 : {
772 0 : f_done = true;
773 :
774 : // once done we don't attempt to reconnect so we can as well
775 : // get rid of our existing cache immediately to save some
776 : // memory
777 : //
778 0 : f_message_cache.clear();
779 :
780 0 : if(f_messenger != nullptr)
781 : {
782 0 : f_messenger->mark_done();
783 : }
784 0 : }
785 :
786 :
787 : private:
788 : tcp_client_permanent_message_connection * f_parent = nullptr;
789 : thread_signal_handler::pointer_t f_thread_done = thread_signal_handler::pointer_t();
790 : runner f_thread_runner;
791 : cppthread::thread f_thread;
792 : messenger::pointer_t f_messenger = messenger::pointer_t();
793 : message::vector_t f_message_cache = message::vector_t();
794 : bool f_done = false;
795 : };
796 :
797 :
798 :
799 : }
800 : // namespace detail
801 :
802 :
803 :
804 : /** \brief Initializes this TCP client message connection.
805 : *
806 : * This implementation creates what we call a permanent connection.
807 : * Such a connection may fail once in a while. In such circumstances,
808 : * the class automatically requests for a reconnection (see various
809 : * parameters in the regard below.) However, this causes one issue:
810 : * by default, the connection just never ends. When you are about
811 : * ready to close the connection, you must call the mark_done()
812 : * function first. This will tell the various error functions to
813 : * drop this connection instead of restarting it after a small pause.
814 : *
815 : * This constructor makes sure to initialize the timer and saves
816 : * the address, port, mode, pause, and use_thread parameters.
817 : *
818 : * The timer is first set to trigger immediately. This means the TCP
819 : * connection will be attempted as soon as possible (the next time
820 : * the run() loop is entered, it will time out immediately.) You
821 : * are free to call set_timeout_date() with a date in the future if
822 : * you prefer that the connect be attempted a little later.
823 : *
824 : * The \p pause parameter is used if the connection is lost and this
825 : * timer is used again to attempt a new connection. It will be reused
826 : * as long as the connection fails (as a delay). It has to be at least
827 : * 10 microseconds, although really you should not use less than 1
828 : * second (1000000). You may set the pause parameter to 0 in which case
829 : * you are responsible to set the delay (by default there will be no
830 : * delay and thus the timer will never time out.)
831 : *
832 : * To start with a delay, instead of trying to connect immediately,
833 : * you may pass a negative pause parameter. So for example to get the
834 : * first attempt 5 seconds after you created this object, you use
835 : * -5000000LL as the pause parameter.
836 : *
837 : * The \p use_thread parameter determines whether the connection should
838 : * be attempted in a thread (asynchronously) or immediately (which means
839 : * the timeout callback may block for a while.) If the connection is to
840 : * a local server with an IP address specified as numbers (i.e. 127.0.0.1),
841 : * the thread is probably not required. For connections to a remote
842 : * computer, though, it certainly is important.
843 : *
844 : * \param[in] address The address to listen on. It may be set to "0.0.0.0".
845 : * \param[in] port The port to listen on.
846 : * \param[in] mode The mode to use to open the connection.
847 : * \param[in] pause The amount of time to wait before attempting a new
848 : * connection after a failure, in microseconds, or 0.
849 : * \param[in] use_thread Whether a thread is used to connect to the
850 : * server.
851 : */
852 0 : tcp_client_permanent_message_connection::tcp_client_permanent_message_connection(
853 : std::string const & address
854 : , int port
855 : , tcp_bio_client::mode_t mode
856 : , std::int64_t const pause
857 0 : , bool const use_thread)
858 : : timer(pause < 0 ? -pause : 0)
859 : , f_impl(std::make_shared<detail::tcp_client_permanent_message_connection_impl>(this, address, port, mode))
860 0 : , f_pause(llabs(pause))
861 0 : , f_use_thread(use_thread)
862 : {
863 0 : }
864 :
865 :
866 : /** \brief Destroy instance.
867 : *
868 : * This function cleans up everything in the permanent message object.
869 : */
870 0 : tcp_client_permanent_message_connection::~tcp_client_permanent_message_connection()
871 : {
872 : // Does nothing
873 0 : }
874 :
875 :
876 : /** \brief Attempt to send a message to this connection.
877 : *
878 : * If the connection is currently enabled, the message is sent immediately.
879 : * Otherwise, it may be cached if the \p cache parameter is set to true.
880 : * A cached message is forwarded as soon as a new successful connection
881 : * happens, which can be a problem if messages need to happen in a very
882 : * specific order (For example, after a reconnection to snapcommunicator
883 : * you first need to REGISTER or CONNECT...)
884 : *
885 : * \param[in] message The message to send to the connected server.
886 : * \param[in] cache Whether the message should be cached.
887 : *
888 : * \return true if the message was sent, false if it was not sent, although
889 : * if cache was true, it was cached
890 : */
891 0 : bool tcp_client_permanent_message_connection::send_message(message const & msg, bool cache)
892 : {
893 0 : return f_impl->send_message(msg, cache);
894 : }
895 :
896 :
897 : /** \brief Check whether the connection is up.
898 : *
899 : * This function returns true if the connection is considered to be up.
900 : * This means sending messages will work quickly instead of being
901 : * cached up until an actual TCP/IP connection gets established.
902 : *
903 : * Note that the connection may have hanged up since, and the system
904 : * may not have yet detected the fact (i.e. the connection is going
905 : * to receive the process_hup() call after the event in which you are
906 : * working.)
907 : *
908 : * \return true if connected
909 : */
910 0 : bool tcp_client_permanent_message_connection::is_connected() const
911 : {
912 0 : return f_impl->is_connected();
913 : }
914 :
915 :
916 : /** \brief Disconnect the messenger now.
917 : *
918 : * This function kills the current connection.
919 : *
920 : * There are a few cases where two daemons communicate between each others
921 : * and at some point one of them wants to exit and needs to disconnect. This
922 : * function can be used in that one situation assuming that you have an
923 : * acknowledgement from the other daemon.
924 : *
925 : * Say you have daemon A and B. B wants to quit and before doing so sends
926 : * a form of "I'm quitting" message to A. In that situation, B is not closing
927 : * the messenger connection, A is responsible for that (i.e. A acknowledges
928 : * receipt of the "I'm quitting" message from B by closing the connection.)
929 : *
930 : * B also wants to call the mark_done() function to make sure that it
931 : * does not reconnected a split second later and instead the permanent
932 : * connection gets removed from the communicator list of connections.
933 : */
934 0 : void tcp_client_permanent_message_connection::disconnect()
935 : {
936 0 : f_impl->disconnect();
937 0 : }
938 :
939 :
940 : /** \brief Overload so we do not have to use namespace everywhere.
941 : *
942 : * This function overloads the connection::mark_done() function so
943 : * we can call it without the need to use timer::mark_done()
944 : * everywhere.
945 : */
946 0 : void tcp_client_permanent_message_connection::mark_done()
947 : {
948 0 : timer::mark_done();
949 0 : }
950 :
951 :
952 : /** \brief Mark connection as done.
953 : *
954 : * This function allows you to mark the permanent connection and the
955 : * messenger as done.
956 : *
957 : * Note that calling this function with false is the same as calling the
958 : * base class mark_done() function.
959 : *
960 : * If the \p message parameter is set to true, we suggest you also call
961 : * the disconnect() function. That way the messenger will truly get
962 : * removed from everyone quickly.
963 : *
964 : * \param[in] messenger If true, also mark the messenger as done.
965 : */
966 0 : void tcp_client_permanent_message_connection::mark_done(bool messenger)
967 : {
968 0 : timer::mark_done();
969 0 : if(messenger)
970 : {
971 0 : f_impl->mark_done();
972 : }
973 0 : }
974 :
975 :
976 : /** \brief Retrieve a copy of the client's address.
977 : *
978 : * This function makes a copy of the address of this client connection
979 : * to the \p address parameter and returns the length.
980 : *
981 : * \param[in] address The reference to an address variable where the
982 : * address gets copied.
983 : *
984 : * \return Return the length of the address which may be smaller than
985 : * sizeof(struct sockaddr). If zero, then no address is defined.
986 : *
987 : * \sa get_addr()
988 : */
989 0 : size_t tcp_client_permanent_message_connection::get_client_address(sockaddr_storage & address) const
990 : {
991 0 : return f_impl->get_client_address(address);
992 : }
993 :
994 :
995 : /** \brief Retrieve the remote computer address as a string.
996 : *
997 : * This function returns the address of the remote computer as a string.
998 : * It will be a canonicalized IP address.
999 : *
1000 : * \return The canonicalized IP address.
1001 : */
1002 0 : std::string tcp_client_permanent_message_connection::get_client_addr() const
1003 : {
1004 0 : return f_impl->get_client_addr();
1005 : }
1006 :
1007 :
1008 : /** \brief Internal timeout callback implementation.
1009 : *
1010 : * This callback implements the guts of this class: it attempts to connect
1011 : * to the specified address and port, optionally after creating a thread
1012 : * so the attempt can happen asynchronously.
1013 : *
1014 : * When the connection fails, the timer is used to try again pause
1015 : * microseconds later (pause as specified in the constructor).
1016 : *
1017 : * When a connection succeeds, the timer is disabled until you detect
1018 : * an error while using the connection and re-enable the timer.
1019 : *
1020 : * \warning
1021 : * This function changes the timeout delay to the pause amount
1022 : * as defined with the constructor. If you want to change that
1023 : * amount, you can do so an any point after this function call
1024 : * using the set_timeout_delay() function. If the pause parameter
1025 : * was set to -1, then the timeout never gets changed.
1026 : * However, you should not use a permanent message timer as your
1027 : * own or you will interfere with the internal use of the timer.
1028 : */
1029 0 : void tcp_client_permanent_message_connection::process_timeout()
1030 : {
1031 : // got a spurious call when already marked done
1032 : //
1033 0 : if(is_done())
1034 : {
1035 0 : return;
1036 : }
1037 :
1038 : // change the timeout delay although we will not use it immediately
1039 : // if we start the thread or attempt an immediate connection, but
1040 : // that way the user can change it by calling set_timeout_delay()
1041 : // at any time after the first process_timeout() call
1042 : //
1043 0 : if(f_pause > 0)
1044 : {
1045 0 : set_timeout_delay(f_pause);
1046 0 : f_pause = 0;
1047 : }
1048 :
1049 0 : if(f_use_thread)
1050 : {
1051 : // in this case we create a thread, run it and know whether the
1052 : // connection succeeded only when the thread tells us it did
1053 : //
1054 : // TODO: the background_connect() may return false in two situations:
1055 : // 1) when the thread is already running and then the behavior
1056 : // we have below is INCORRECT
1057 : // 2) when the thread cannot be started (i.e. could not
1058 : // allocate the stack?) in which case the if() below
1059 : // is the correct behavior
1060 : //
1061 0 : if(f_impl->background_connect())
1062 : {
1063 : // we started the thread successfully, so block the timer
1064 : //
1065 0 : set_enable(false);
1066 : }
1067 : }
1068 : else
1069 : {
1070 : // the success is noted when we receive a call to
1071 : // process_connected(); there we do set_enable(false)
1072 : // so the timer stops
1073 : //
1074 0 : f_impl->connect();
1075 : }
1076 : }
1077 :
1078 :
1079 : /** \brief Process an error.
1080 : *
1081 : * When an error occurs, we restart the timer so we can attempt to reconnect
1082 : * to that server.
1083 : *
1084 : * If you overload this function, make sure to either call this
1085 : * implementation or enable the timer yourselves.
1086 : *
1087 : * \warning
1088 : * This function does not call the timer::process_error() function
1089 : * which means that this connection is not automatically removed from
1090 : * the communicator object on failures.
1091 : */
1092 0 : void tcp_client_permanent_message_connection::process_error()
1093 : {
1094 0 : if(is_done())
1095 : {
1096 0 : timer::process_error();
1097 : }
1098 : else
1099 : {
1100 0 : f_impl->disconnect();
1101 0 : set_enable(true);
1102 : }
1103 0 : }
1104 :
1105 :
1106 : /** \brief Process a hang up.
1107 : *
1108 : * When a hang up occurs, we restart the timer so we can attempt to reconnect
1109 : * to that server.
1110 : *
1111 : * If you overload this function, make sure to either call this
1112 : * implementation or enable the timer yourselves.
1113 : *
1114 : * \warning
1115 : * This function does not call the timer::process_hup() function
1116 : * which means that this connection is not automatically removed from
1117 : * the communicator object on failures.
1118 : */
1119 0 : void tcp_client_permanent_message_connection::process_hup()
1120 : {
1121 0 : if(is_done())
1122 : {
1123 0 : timer::process_hup();
1124 : }
1125 : else
1126 : {
1127 0 : f_impl->disconnect();
1128 0 : set_enable(true);
1129 : }
1130 0 : }
1131 :
1132 :
1133 : /** \brief Process an invalid signal.
1134 : *
1135 : * When an invalid signal occurs, we restart the timer so we can attempt
1136 : * to reconnect to that server.
1137 : *
1138 : * If you overload this function, make sure to either call this
1139 : * implementation or enable the timer yourselves.
1140 : *
1141 : * \warning
1142 : * This function does not call the timer::process_invalid() function
1143 : * which means that this connection is not automatically removed from
1144 : * the communicator object on failures.
1145 : */
1146 0 : void tcp_client_permanent_message_connection::process_invalid()
1147 : {
1148 0 : if(is_done())
1149 : {
1150 0 : timer::process_invalid();
1151 : }
1152 : else
1153 : {
1154 0 : f_impl->disconnect();
1155 0 : set_enable(true);
1156 : }
1157 0 : }
1158 :
1159 :
1160 : /** \brief Make sure that the messenger connection gets removed.
1161 : *
1162 : * This function makes sure that the messenger sub-connection also gets
1163 : * removed from the communicator. Otherwise it would lock the system
1164 : * since connections are saved in the communicator object as shared
1165 : * pointers.
1166 : */
1167 0 : void tcp_client_permanent_message_connection::connection_removed()
1168 : {
1169 0 : f_impl->disconnect();
1170 0 : }
1171 :
1172 :
1173 : /** \brief Process a connection failed callback.
1174 : *
1175 : * When a connection attempt fails, we restart the timer so we can
1176 : * attempt to reconnect to that server.
1177 : *
1178 : * If you overload this function, make sure to either call this
1179 : * implementation or enable the timer yourselves.
1180 : *
1181 : * \param[in] error_message The error message that triggered this callback.
1182 : */
1183 0 : void tcp_client_permanent_message_connection::process_connection_failed(std::string const & error_message)
1184 : {
1185 0 : snap::NOT_USED(error_message);
1186 0 : set_enable(true);
1187 0 : }
1188 :
1189 :
1190 : /** \brief The connection is ready.
1191 : *
1192 : * This callback gets called whenever the connection succeeded and is
1193 : * ready to be used.
1194 : *
1195 : * You should implement this virtual function if you have to initiate
1196 : * the communication. For example, the snapserver has to send a
1197 : * REGISTER to the snapcommunicator system and thus implements this
1198 : * function.
1199 : *
1200 : * The default implementation makes sure that the timer gets turned off
1201 : * so we do not try to reconnect every minute or so.
1202 : */
1203 0 : void tcp_client_permanent_message_connection::process_connected()
1204 : {
1205 0 : set_enable(false);
1206 0 : }
1207 :
1208 :
1209 :
1210 6 : } // namespace ed
1211 : // vim: ts=4 sw=4 et
|