Heartbeat communication layer Structure Analysis

Source: Internet
Author: User
Tags unix domain socket
Heartbeat communication layer structure analysis-Linux general technology-Linux programming and kernel information. The following is a detailed description. Original post:
Http://www.gd-linux.org/bbs/showthread.php? T = 4915

[CENTER] Heartbeat communication layer structure analysis [/CENTER]
Guangdong Linux Public Service Technical Support Center
Cai Qiang
Preface
Heartbeat is the name of the HA software released by the Linux-HA open-source project for key application environments. From 1999 to now, it has gone through multiple versions such as 1.2.x and 2.0.x, and is widely used in the world's open-source HA field, it is also supported by some mainstream Linux operating system vendors.
The implementation of the communication layer is undoubtedly the most basic underlying support for cluster software operation. This article analyzes the source code of Heartbeat and describes the basic structure and mechanism of the communication layer. The basic data structure and implementation process are provided.
All analyses are based on Heartbeat 2.0.4.
Related Source: http://www.linux-ha.org/download/heartbeat-2.0.4.tar.gz


Heartbeat communication structure Overview
There are two main types:
1. HBcomm PLUGIN (Process Communication between nodes)
The implementation is mainly in the Plugin of various media and loaded through the PILS dynamic Connection Library. For example, multicast, unicast, serial port, and other communication modes are supported. The PLUGIN module for communications between all nodes is placed under lib/plugins/hbcomm/path.
2. Unix Domain Socket (Process Communication in the node)
/Include/clplumbing/Ipc. h, IPC abstraction layer data structure definition
/Lib/clplumbing/ocf_ipc.c, underlying abstract Implementation of IPC
/Lib/clplumbing/ipcsocket. c, specific implementation of the unix domain socket of IPC

Intersection:
The two communication methods between nodes and the node are implemented in functions such as read_child () and write_child () of heartbeat. c, where messages are forwarded.
Heartbeat API
It is based on the Unix domain Implementation of the ipc abstraction layer and is used to meet the application layer communication requirements between the heartbeat and client submodules. :
Client_lib.c implements the Heartbeat API client.
Hb_api.c implements the heartbeat API server.


(400) {this. resized = true; this. width = 400; this. alt = 'click here to open new window';} "onmouseover =" if (this. resized) this. style. cursor = 'hand'; "onclick =" window. open ('HTTP: // www.gd-linux.org/liu_attach/4.11forum.jpg'); ">
: Heartbeat communication structure Overview
Describes the process in which a client sub-module sends messages to the same module of another node through the Heartbeat communication mechanism.
1. The client sub-module sends messages to the FIFO sub-process mongoo_child through the FIFO pipeline. Why is FIFO used for communication? Some processes cannot easily establish a Unix-domain IPC channel relationship with the master Heartbeat process, such as scripts executed and cluster management programs, cluster status query program.
2. After receiving a message from the FIFO pipeline through msgfromstream (), the fifo sub-process forwards the message to the Heartbeat master process through the IPC channel established in advance with Heartbeat.
3. If the main process determines that the message is sent to itself, it calls process_msg () for processing. Otherwise, send_to_all_media () is called and sent to the write_child sub-process through the wchan channel of each media.
4. The write_child sub-process receives a message from the master process through ipcmsgfromIPC () and calls the write function of hb_media in each media structure to send the message to other nodes in the cluster.
5. The read_child sub-processes on other nodes read messages through the read function of hb_media in each media structure, and send messages to the Heartbeat master process using the IPC channel established with the Heartbeat master process in advance.
6. After the Heartbeat master process receives a message through msgfromIPC (), it calls the process_clustermsg () function for processing. Specifically, HBDoMsgCallback is called for processing messages processed by the main process; otherwise, newstartha_monitor is used to send messages to each client sub-process.


Inter-node communication Plugin
The code is in the lib/plugins/hbcomm/directory.
Bcast. c/* broadcast */
Mcast. c/* multicast */
Ucast. c/* unicast */
Openais. c/* openais */
Serial. c/* serial port */
Ping. c/* icmp */
Ping_group.c/* ping a group of hosts */
Hbaping. c/* Optical Fiber bus adapter ping */

/* Each function in this structure corresponds to a specific function in the Plugin. */
Struct hb_media_fns {
Struct hb_media * (* new) (const char * token);/* Create media */
Int (* parse) (const char * options);/* read configuration file parameters */
Int (* open) (struct hb_media * mp);/* open */
Int (* close) (struct hb_media * mp);/* close */
Void * (* read) (struct hb_media * mp, int * len);/* read */
Int (* write) (struct hb_media * mp, void * msg, int len);/* write */
Int (* mtype) (char ** buffer);/* obtain media type */
Int (* descr) (char ** buffer);/* Get Media Description */
Int (* isping) (void);/* Whether to ping media */
};

Function calls of hb_media_fns:
New (): add_option function of config. c
Parse (): parse_config function of config. c
Open (): initialize_heartbeat function of heartbeat. c
Close (): initialize_heartbeat function of heartbeat. c
Read (): read_child function of heartbeat. c
Write (): write_child function of heartbeat. c
Mtype (): parse_config function of config. c
Descr (): parse_config function of config. c
Isping (): called in config. c and hb_api.c



Intra-node IPC Communication
IPC communication abstraction layer (include \ clplumbing \ ipc. h)
Overview of the data structure at the IPC abstraction layer:
(Note: indented is the element of the data structure)
IPC_AUTH/* security authentication data structure */
IPC_WAIT_CONNECTION/* Wait for the connection data structure */
IPC_WAIT_OPS/* Wait for the connection function set */
IPC_CHANNEL/* Data Structure of the Communication Pipeline */
IPC_OPS/* Communication Pipeline Function Set */
IPC_QUEUE/* information queue */
Ipc_bufpool/* receiving buffer pool, processed and converted to receiving queue */
IPC_MESSAGE/* IPC Communication Information Data Structure */
IPC_CHANNEL/* communication channel to which information belongs */
SOCKET_MSG_HEAD/* Information header data structure */


There are two main abstract data structures:
/* The server waits for the client connection */
Struct IPC_WAIT_CONNECTION {
Int ch_status;/* wait conn. status .*/
Void * ch_private;/* wait conn. private data .*/
IPC_WaitOps * ops;/* wait conn. function table .*/
};

/* Structure of the Active Communication Pipeline */
Struct IPC_CHANNEL {
Int ch_status;/* channel status */
Pid_t farside_pid;/* remote pid */
Void * ch_private;/* channel private data. (may contain conn. info .)*/
IPC_Ops * ops;/* channel function set */
Unsigned int msgpad;/* Number of Information prefix bytes */
Unsigned int bytes_remaining;/* Number of unsent bytes */
Gboolean should_send_block ;/**/

/* Private :*/
IPC_Queue * send_queue;/* Sending buffer */
IPC_Queue * recv_queue;/* Receive Buffer */

/* The receiving buffer pool, which is converted to the recv_queue of the receiving information queue after processing */
Struct ipc_bufpool * pool;/* buffer pool */

/* Send traffic control */
Int high_flow_mark;
Int low_flow_mark;
Void * high_flow_userdata;
Void * low_flow_userdata;
Flow_callback_t high_flow_callback;
Flow_callback_t low_flow_callback;

Int conntype;
Char failreason [MAXFAILREASON];
};


IPC abstraction layer communication
Server:
1. Call ipc_wait_conn_constructor () to establish a connection pipeline. If the connection is successful, IPC_WaitConnection is returned.
2. poll customer requests through poll/select. Use accept_connection to accept the connection and return IPC_Channel.

Client:
Call ipc_channel_constructor () to connect to the server and return IPC_Channel.


Implementation of UNIX Domain Socket in the IPC Abstraction Layer

Static struct IPC_OPS socket_ops = {
Destroy: socket_destroy_channel,/* delete a Communication Pipeline */
Initiate_connection: socket_initiate_connection,/* establish a connection from the client */
Verify_auth: socket_verify_auth,/* client authentication information */
Assert_auth: socket_assert_auth,/* assert_auth, (unused )*/
Send: socket_send,/* send information to the pipeline */
Recv: socket_recv,/* receive information from the pipeline */
Waitin: socket_waitin,/* Wait for the input information (and then read )*/
Waitout: socket_waitout,/* wait for the end of information output */
Is_message_pending: socket_is_message_pending,/* readable or hung up with information */
Is_sending_blocked: socket_is_output_pending,/* Whether the output is blocked */
Resume_io: socket_resume_io,/* restore all possible ipc operations */
Get_send_select_fd: socket_get_send_fd,/* Get and send fd */
Get_recv_select_fd: socket_get_recv_fd,/* Get the received fd */
Set_send_qlen: socket_set_send_qlen,/* set the maximum sending buffer length */
Set_recv_qlen: socket_set_recv_qlen,/* set the maximum length of the received buffer */
Set_high_flow_callback: socket_set_high_flow_callback,/* high-traffic callback function */
Set_low_flow_callback: socket_set_low_flow_callback,/* low-traffic callback function */
New_ipcmsg: socket_new_ipcmsg,/* returns a newly created IPC information */
Get_chan_status: socket_get_chan_status,/* return the MPs queue status */
Is_sendq_full: socket_is_sendq_full,/* Whether the sending buffer is full */
Is_recvq_full: socket_is_recvq_full,/* Whether the receiving buffer is full */
Get_conntype: socket_get_conntype,/* return the MPs queue type */
/* It Can Be IPC_SERVER, IPC_CLIENT, IPC_PEER */
};


Inter-node communication Plugin/intra-node communication Intersection
The main implementation code is in heartbeart. c.

Heartbeat communication media structure
Struct hb_media {
Void * pd;/* Custom Data Structure */
Const char * name;/* media name */
Char * type;/* media type */
Char * description;/* Media description */
Const struct hb_media_fns * vf;/* hbcomm media processing function set */
IPC_Channel * wchan [2];/* Unix domain write sub-process communication pipeline */
IPC_Channel * rchan [2];/* Unix domain read sub-process communication pipeline */
};


/* Heartbeat sending information cluster */
/* 1. send the message to the write_child sub-process */
Send_cluster_msg {/* send information to the cluster */
...
Process_outbound_packet {/* packet retransmission control */
Send_to_all_media {/* send to all media */
For (j = 0; j <nummedia; ++ j ){
IPC_Channel * wch = sysmedia [j]-> wchan [P_WRITEFD];
...
/* Write sub-processes sent to specific media */
Wrc = wch-> ops-> send (wch, outmsg );
}
}
}
}

/* 2. write_child write the sub-process to send messages to the cluster */
Write_child (){
IPC_Channel * ourchan = mp-> wchan [P_READFD];
For (;;){
/* Write_child receives heartbeat information through Unix Domain Socket */
IPC_Message * ipcmsg = ipcmsgfromIPC (ourchan);/* Call ops-> recv ()*/
...
/* Send to other nodes in the cluster */
If (mp-> vf-> write (mp, ipcmsg-> msg_body, ipcmsg-> msg_len )! = HA_ OK ){
......
}
}
}


/* Receive information from the cluster */
/* 1. Read the sub-process of read_child to receive messages from the cluster */
Read_child (){
IPC_Channel * ourchan = mp-> rchan [P_READFD];
For (;;){
/* Receive from hbcomm PLUGIN */
If (pkt = mp-> vf-> read (mp, & pktlen) = NULL ){
......
}
If (NULL! = Imsg ){
/* The read_child sub-process is sent to heartbeat through UNIX Domain Socket */
Rc = ourchan-> ops-> send (ourchan, imsg );
Rc2 = ourchan-> ops-> waitout (ourchan );
...
}
}
}

/* 2. heartbeat receives and processes information from the read_child sub-process */
S = G_main_add_IPC_Channel (PRI_READPKT
, Sysmedia [j]-> rchan [P_WRITEFD], FALSE
, Read_child_dispatch, sysmedia + j, NULL );
Read_child_dispatch (){
...
Msg = msgfromIPC (source, MSG_NEEDAUTH);/* Call ops-> recv () to read from read_child */
Process_clustermsg (msg, lnk);/* process read information */
}



Heartbeat API Server
Struct api_query_handler query_handler_list [] = {
{API_SIGNOFF, api_signoff},/* client Login */
{API_SETFILTER, api_setfilter},/* Set message filter */
{API_SETSIGNAL, api_setsignal},/* set the message arrival signal notification */
{API_NODELIST, api_nodelist},/* Get node list */
{API_NODESTATUS, api_nodestatus},/* query node status */
{API_NODETYPE, api_nodetype},/* query node type */
{API_IFSTATUS, api_ifstatus},/* query the heartbeat status */
{API_IFLIST, api_iflist},/* queries the heartbeat list */
{API_CLIENTSTATUS, api_clientstatus},/* query the status of the client module */
{API_NUMNODES, api_num_nodes},/* returns the number of common nodes in the cluster */
{API_GETPARM, api_get_parameter},/* return a specific parameter value */
{API_GETRESOURCES, api_get_resources},/* returns the resource status (compatible with versions earlier than 1.2.x )*/
{API_GETUUID, api_get_uuid},/* Get the node uuid value */
{API_GETNAME, api_get_nodename},/* Get node name */
{API_SET_SENDQLEN, api_set_sendqlen}/* set the length of the sending queue */
};


Heartbeat API client
Static struct llc_ops heartbeat_ops = {
Signon: hb_api_signon,/* register a new heartbeat client */
Signoff: hb_api_signoff,/* cancel a heartbeat client */
Delete: hb_api_delete,/* logout structure */
Set_msg_callback: set_msg_callback,/* sets a certain information type callback */
Set_nstatus_callback: set_nstatus_callback,/* sets the node status type callback */
Set_ifstatus_callback: set_ifstatus_callback,/* sets the heartbeat status type callback */
Set_cstatus_callback: set_cstatus_callback,/* sets the client status type callback */
Init_nodewalk: init_nodewalk,/* initialize node traversal */
Nextnode: nextnode,/* next node */
End_nodewalk: end_nodewalk,/* End Node traversal */
Node_status: get_nodestatus,/* current node status */
Node_type: get_nodetype,/* node type */
Init_ifwalk: init_ifwalk,/* initialize heartbeat traversal */
Nextif: nextif,/* next heartbeat interface */
End_ifwalk: end_ifwalk,/* end heartbeat traversal */
If_status: get_ifstatus,/* Current heartbeat status */
Client_status: get_clientstatus,/* current client status */
Get_uuid_by_name: get_uuid_by_name,/* obtain uuid by name */
Get_name_by_uuid: get_name_by_uuid,/* Get the name based on uuid */
Sendclustermsg: sendclustermsg,/* send messages to all cluster members */
Sendnodemsg: sendnodemsg,/* send a message to a specific node */
Sendnodemsg_byuuid: sendnodemsg_byuuid,/* send a message to a specific node (by uuid )*/
Send_ordered_clustermsg: send_ordered_clustermsg,/* Sending order cluster information */
Send_ordered_nodemsg: send_ordered_nodemsg,/* Sending sequence node information */
Inputfd: get_inputfd,/* return and Detection Information Arrival */
Ipcchan: get_ipcchan,/* returns IPC_Channel-type ipc channel */
Msgready: msgready,/* returns true if information is readable */
Setmsgsignal: hb_api_setsignal,/* setmsgsignal */
Rcvmsg: rcvmsg,/* Receives msg and submits it to callback for processing */
Readmsg: read_msg_w_callbacks,/* returns msg not registered with callback */
Setfmode: setfmode,/* setfmode */
Get_parameter: get_parameter,
Get_deadtime: get_deadtime,
Get_keepalive: get_keepalive,
Get_mynodeid: get_mynodeid,/* get the local node name */
Get_logfacility: get_logfacility,/* suggested logging facility */
Get_resources: get_resources,/* Get the current distribution of resources */
Chan_is_connected: chan_is_connected,
Set_sendq_len: set_sendq_len,/* set the sending cache length */
Set_send_block_mode: socket_set_send_block_mode,
Errmsg: APIError,
};
Note:
The Client-side API function set is much larger than the Server-side query and processing function set because some functions do not need to be obtained through Server-side query.

Original post:
Http://www.gd-linux.org/bbs/showthread.php? T = 4915
Related Article

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.