Connection establishment and reconnection mechanism in ZeroMQ (java)

Source: Internet
Author: User

In the previous article, Dealer is the simplest Socket type in ZeroMQ .. However, I think this specific Socket type analysis can be left in the future, or it will not be too late to analyze when it will be used in the future ....

However, as a message communication framework, the most important thing is the reliability of communication, and the most important thing is the reconnection mechanism after the connection is disconnected...

Before looking at the specific reconnection mechanism, let's take a look at how ZeroMQ actively establishes a remote connection. Let's take a look at the connect method defined in SocketBase:

// Establish a connection with the remote address public boolean connect (String addr _) {if (ctx_terminated) {throw new ZError. ctxTerminatedException ();} // Process pending commands, if any. boolean brc = process_commands (0, false); if (! Brc) return false; // Parse addr _ string. URI uri; try {uri = new URI (addr _); // construct URI object} catch (URISyntaxException e) {throw new IllegalArgumentException (e);} String protocol = uri. getScheme (); // obtain the protocol type String address = uri. getAuthority (); String path = uri. getPath (); if (address = null) address = path; check_protocol (protocol); // check whether the protocol type is qualified if (protocol. equals (inproc) {// if the communication is in the process, // DO: inproc connect is specific with respect to creating pipes // as there's no 'reconnection' functionality implemented. once that // is in place we shoshould follow generic pipe creation algorithm. // Find the peer endpoint. ctx. endpoint peer = find_endpoint (addr _); if (peer. socket = null) return false; // The total HWM for an inproc connection shocould be the sum of // the binder's HWM and the connect Or's HWM. int sndhwm = 0; if (options. sndhwm! = 0 & peer. options. rcvhwm! = 0) sndhwm = options. sndhwm + peer. options. rcvhwm; int rcvhwm = 0; if (options. rcvhwm! = 0 & peer. options. sndhwm! = 0) rcvhwm = options. rcvhwm + peer. options. sndhwm; // Create a bi-directional pipe to connect the peers. ZObject [] parents = {this, peer. socket}; Pipe [] pipes = {null, null}; int [] hwms = {sndhwm, rcvhwm}; boolean [] delays = {options. delay_on_disconnect, options. delay_on_close}; Pipe. pipepair (parents, pipes, hwms, delays); // Attach local end of the pipe to this socket object. attach_pipe (pipes [0]); // If required, send the identity of the peer to the local socket. if (peer. options. recv_identity) {Msg id = new Msg (options. identity_size); id. put (options. identity, 0, options. identity_size); id. set_flags (Msg. identity); boolean written = pipes [0]. write (id); assert (written); pipes [0]. flush ();} // If required, send the identity of the local socket to the peer. if (options. recv_iden Tity) {Msg id = new Msg (peer. options. identity_size); id. put (peer. options. identity, 0, peer. options. identity_size); id. set_flags (Msg. identity); boolean written = pipes [1]. write (id); assert (written); pipes [1]. flush ();} // Attach remote end of the pipe to the peer socket. note that peer's // seqnum was incremented in find_endpoint function. we don't need it // increased here. send_bind (pe Er. socket, pipes [1], false); // Save last endpoint URI options. last_endpoint = addr _; // remember inproc connections for disconnect inprocs. put (addr _, pipes [0]); return true;} // select a comparison IO thread to deploy the session IOThread io_thread = choose_io_thread (options. affinity); if (io_thread = null) {throw new IllegalStateException (Empty IO Thread);} // create address object Address paddr = new Address (protocol, Ddress); if (protocol. equals (tcp) {// if it is tcp, paddr. resolved (new TcpAddress (); paddr. resolved (). resolve (address, options. ipv4only! = 0? True: false);} else if (protocol. equals (ipc) {// inter-process communication paddr. resolved (new IpcAddress (); paddr. resolved (). resolve (address, true);} // Create session. // create a session. The first parameter is the IO thread that the current session will be attached to. The second parameter indicates that you need to establish a connection with SessionBase session = SessionBase. create (io_thread, true, this, options, paddr); assert (session! = Null); // PGM does not support subpipeline forwarding; ask for all data to be // sent to this pipe. boolean icanhasall = false; if (protocol. equals (pgm) | protocol. equals (epgm) icanhasall = true; // creates a pipe Association to connect the session to the current socket if (options. delay_attach_on_connect! = 1 | icanhasall) {// Create a bi-directional pipe. ZObject [] parents = {this, session}; Pipe [] pipes = {null, null}; int [] hwms = {options. sndhwm, options. rcvhwm}; boolean [] delays = {options. delay_on_disconnect, options. delay_on_close}; Pipe. pipepair (parents, pipes, hwms, delays); // Attach local end of the pipe to the socket object. // associate the first pipe with the current socket attach_pipe (pipes [0], icanhasall); // Attach remote end of the pipe to the session object later on. // associate another pipe with the session so that the session and socket can communicate with the session through pipe. attach_pipe (pipes [1]);} // Save last endpoint URI options. last_endpoint = paddr. toString (); add_endpoint (addr _, session); // associate this session with this address and return true ;}

 

Here we will focus on the establishment of TCP connections. After all, TCP is used in a distributed environment. Through the previous article, we know that a Socket may correspond to multiple connections, each connection corresponds to a StreamEngine object, and each StreamEngine object is associated with a Session object for interaction with the upper-layer Socket, here we can see that the most important thing to do in the code is to create Session objects and Pipe objects .... Next, call the add_endpoint method to deploy this session. Next, let's take a look at this method:

// Here, the address and session are managed. In fact, all the connection established addresses and the relative session private void add_endpoint (String addr _, Own endpoint _) are recorded _) {// Activate the session. make it a child of this socket. launch_child (endpoint _); // deploy this endpoint. Here we mainly want to add this endpoint to the I/O thread endpoints. put (addr _, endpoint _);}

 

This is actually used as not a session object. For this session object, the process_plug method will be executed. Let's take a look at the definition of this method:

// Execute the plug command. If you need to connect, start to connect protected void process_plug () {io_object.set_handler (this); // set the handler of the io object, used to respond to io events if (connect) {// if You Need To actively establish a connection with a remote connection, start the connection start_connecting (false); // start the connection, false indicates not waiting }}

 

First, the Event Callback and connect attribute of the current io object will be set during session creation. If the connection is automatically created, it will be true, if it is the connection received by listener, it will be false. Let's take a look at the definition of this method:

// If it is connect, you need to call this method to establish the connection private void start_connecting (boolean wait _) {assert (connect ); // Choose I/O thread to run connecter in. given that we are already // running in an I/O thread, there must be at least one available. IOThread io_thread = choose_io_thread (options. affinity); // select an io thread for deploying the tcpconneassert (io_thread! = Null); // Create the connecter object. if (addr. protocol (). equals (tcp) {TcpConnecter connecter = new TcpConnecter (io_thread, this, options, addr, wait _); // alloc_assert (connecter); launch_child (connecter ); // deploy the TCPconnector return;} if (addr. protocol (). equals (ipc) {IpcConnecter connecter = new IpcConnecter (io_thread, this, options, addr, wait _); // alloc_assert (connecter); launch_child (connecter); return ;} assert (false );}

 

 

A parameter is input here, which will be used when the TCPConnector is built to indicate whether the establishment of the connection is delayed .. Here, when the connection is established, it is false, indicating no delay. When the connection is valued, we will find that delayed connections will be used in the reconnection...

We can also see that the establishment of a specific connection is actually delegated to the TCPConnector object. It is actually a tool class...

Specifically, how the connection is established is not listed in detail. Let's take a rough look at the process:

(1) create a socketchannel object and set it to non-blocking. Then, call the connect method to establish a connection to the remote address.

(2) register the socketchannel to the poller of the IO thread and set the connect event.

(3) what to do for the callback of the connect event is to cancel the registration of the socketchannel on the poeller object, and then create a new streamengine object to wrap the socketchannel, then, associate the streamEngine object with the session object ..

 

Here, let's take a look at what the connect Event Callback method has done:

// Connection established Event Callback may also be connection timeout public void connect_event () {boolean err = false; SocketChannel fd = null; try {fd = connect (); // obtain the channel} catch (ConnectException e) {err = true;} catch (SocketException e) {err = true;} catch (SocketTimeoutException e) with established connections) {err = true;} catch (IOException e) {throw new ZError. IOException (e);} io_object.rm_fd (handle); // you can remove the current IOObject from poller. It also indicates that the TCPConnector becomes invalid, and handle_valid = false; if (err) {// Handle the error condition by attempt to reconnect. close (); add_reconnect_timer (); // try to establish a new connection return;} handle = null; try {Utils. tune_tcp_socket (fd); Utils. tune_tcp_keepalives (fd, options. tcp_keepalive, options. tcp_keepalive_cnt, options. tcp_keepalive_idle, options. tcp_keepalive_intvl);} catch (SocketException e) {throw new RuntimeException (e);} // Create the engine object for this connection. // create a streamEngine object and re-encapsulate the channel StreamEngine engine = null that establishes the connection; try {engine = new StreamEngine (fd, options, endpoint);} catch (ZError. instantiationException e) {socket. event_connect_delayed (endpoint,-1); return;} // Attach the engine to the corresponding session object. send_attach (session, engine); // bind the engine to the session, and then bind the current streamEngine to the IO thread, that is, register the // Shut the connecter down on the poller. terminate (); // close the current connector socket. event_connected (endpoint, fd); // The upper-layer socket notifies the message created by the connection}

 

 

The specific code is straightforward. Here we can also see that the connection establishment timeout will also try to reconnect...

 

Now, it is clear how to establish a connection .. Next, let's take a look at how reconnect will be performed after the connection is disconnected. First, let's take a look at what operations will be performed after the connection is disconnected,

First of all, you must know how to determine whether the connection of the underlying channel has been disconnected. How can you determine it? Well, you should know that if the connection has been disconnected, then read will return-1 on the channel. Well, we will know where to start reading the code. Well, let's look at the in_event method of streamEngine, what will it do after read returns-1:

// The callback method public void in_event () {if (handshaking) if (! Handshake () return; assert (decoder! = Null); boolean disconnection = false; // If there's no data to process in the buffer... if (insize = 0) {// if there is no data in inbuf, you need to process it // Retrieve the buffer and read as much data as possible. // Note that buffer can be arbitrarily large. however, we assume // the underlying TCP layer has fixed buffer size and thus the // number of bytes read will be always limited. inbuf = decoder. get_buffer (); // get the buf from the decoder to write the read data, because the size of the TCP receiving buffer of the underlying socket is set to insize = read (inbuf ); // write the sent data to buf and record the size of inbuf. flip (); // read data from the buf. // Check whether the peer has closed the connection. if (insize =-1) {// if it is-1, it indicates that the underlying socket connection has a problem insize = 0; disconnection = true; // set flag} // Push the data to the decoder. int processed = decoder. process_buffer (inbuf, insize); // parse the read data if (processed =-1) {disconnection = true ;} else {// Stop polling for input if we got stuck. if (processed <insize) // if the processed data has not read much, cancel the registration io_object.reset_pollin (handle); // Adjust the buffer. insize-= processed; // the size of the data that has not been processed} // Flush all messages the decoder may have produced. session. flush (); // send the data parsed by the decoder to the session // An input error has occurred. if the last decoded message // has already been accepted, we terminate the engine immediately. // Otherwise, we stop waiting for socket events and postpone // the termination until after the message is accepted. if (disconnection) {// indicates that the connection has been disconnected, you need to handle if (decoder. stalled () {io_object.rm_fd (handle); io_enabled = false;} else {error ();}}}

 

Well, here we can see that if-1 is returned, the disconnection flag is set and the error method is called to report an error, then let's take a look at what this error method has done:

// If an error is reported, disable the current connection private void error () {assert (session! = Null); socket. event_disconnected (endpoint, handle); // it can be understood as the socket and session of the Upper-layer notification. detach (); // This is mainly used for session cleaning and pipe of the socket, and then tries to reconnect unplug (); // cancel the registration of destroy () on poller (); // close underlying channel and close current}

In fact, if the underlying link is disconnected, the current channel will be invalid, and the current streamEngine object will be invalid. The only thing to do is to destroy the current object, then we need to cancel the registration on poller, and then notify the upper-layer socket that the current connection address has been disconnected... Of course, we also need to tell the session object to perform some processing, and the session processing includes reconnection. Let's take a look at what he has done:
// Equivalent to removing the public void detach () associated with the underlying Engine {// Engine is dead. let's forget about it. engine = null; // This is equivalent to releasing the current engine object // Remove any half-done messages from the pipes. clean_pipes (); // clear the msg that has not been accepted // Send the event to the derived class. detached (); // cancel pipe and then reconnect // Just in case there's only a delimiter in the pipe. if (pipe! = Null) pipe. check_read ();}

The reconnection code is not visible here. Next, let's continue to look at the detached method:
Private void detached () {// Transient session self-destructs after peer disconnects. if (! Connect) {// If the connection is not established, terminate the connection directly. Otherwise, try terminate (); return;} // For delayed connect situations, terminate the pipe // and reestablish later on if (pipe! = Null & options. delay_attach_on_connect = 1 & addr. protocol ()! = Pgm & addr. protocol ()! = Epgm) {pipe. hiccup (); pipe. terminate (false); terminating_pipes.add (pipe); pipe = null;} reset (); // reset flag bit // The attempt to perform a reconnection here if (options. reconnect_ivl! =-1) {start_connecting (true); // retry the connection. Some latency is required here.} // For subscriber sockets we hiccup the inbound pipe, which will cause // the socket object to resend all the subscriptions. if (pipe! = Null & (options. type = ZMQ. ZMQ_SUB | options. type = ZMQ. ZMQ_XSUB) pipe. hiccup ();}

 

Here we can see that the start_conneting method is called, but the parameter passed in here is true. The specific execution process is similar to the connection established above, but the connection is delayed here...

That is, it will set the timing on the IO thread, and the connection will be established only after the timeout... In this way, reconnection is performed within a certain frequency...

The specific timing will not be detailed. It's quite simple...

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.