Use TelnetClient to obtain Zookeeper Monitoring Data

Source: Internet
Author: User

Use TelnetClient to obtain Zookeeper Monitoring Data

To write a Java program that monitors Zookeeper, you can use either of the following methods:

(1) send commands through TelnetClient, detailed command reference: http://zookeeper.apache.org/doc/trunk/zookeeperAdmin.html# SC _zkCommands

(2) Through JMX, instructions please refer to: http://zookeeper.apache.org/doc/trunk/zookeeperJMX.html

This article uses a simple example to demonstrate how to use TelnetClient to send mntr commands to obtain the monitoring data of Zookeeper.

Write a Telnet tool class

Package com. eric. agent. utils;
Import org.apache.commons.net. telnet. TelnetClient;
Import java. io. IOException;
Import java. io. InputStream;
Import java. io. PrintStream;
/**
* Telnet operator, based on commons-net-2.2.jar
*
* @ Author aihua. sun
* @ Date 2015/4/9
* @ Since V1.0
*/
Public class TelnetTools {
Private String prompt = ">"; // end ID String. For Windows, yes>, for Linux #
Private char promptChar = '>'; // end identifier
Private TelnetClient telnet;
Private InputStream in; // input stream, receiving returned information
Private PrintStream out; // write commands to the server
/**
* @ Param termtype: VT100, VT52, VT220, VTNT, and ANSI
* @ Param prompt indicates the end of the result.
*/
Public TelnetTools (String termtype, String prompt ){
Telnet = new TelnetClient (termtype );
SetPrompt (prompt );
}
Public TelnetTools (String termtype ){
Telnet = new TelnetClient (termtype );
}
Public TelnetTools (){
Telnet = new TelnetClient ();
}
/**
* Log on to the target host
*
* @ Param ip
* @ Param port
*/
Public void login (String ip, int port ){
Try {
Telnet. connect (ip, port );
In = telnet. getInputStream ();
Out = new PrintStream (telnet. getOutputStream ());
} Catch (Exception e ){
Throw new RuntimeException (e );
}
}
/**
* Read the analysis results
*
* @ Param pattern returns the result when the string is matched.
* @ Return
*/
Public String readUntil (String pattern ){
StringBuffer sb = new StringBuffer ();
Try {
Char lastChar = (char)-1;
Boolean flag = pattern! = Null & pattern. length ()> 0;
If (flag)
LastChar = pattern. charAt (pattern. length ()-1 );
Char ch;
Int code =-1;
While (code = in. read ())! =-1 ){
Ch = (char) code;
Sb. append (ch );
// Return results when the end ID is matched
If (flag ){
If (ch = lastChar & sb. toString (). endsWith (pattern )){
Return sb. toString ();
}
} Else {
// If no end identifier is specified, the result is returned when the default end identifier is matched.
If (ch = promptChar)
Return sb. toString ();
}
// Return results when logon fails
If (sb. toString (). contains ("Login Failed ")){
Return sb. toString ();
}
}
} Catch (Exception e ){
E. printStackTrace ();
}
Return sb. toString ();
}
/**
* Send command
*
* @ Param value
*/
Public void write (String value ){
Try {
Out. println (value );
Out. flush ();
} Catch (Exception e ){
E. printStackTrace ();
}
}
/**
* Send the command and return the execution result.
*
* @ Param command
* @ Return
*/
Public String sendCommand (String command ){
Try {
Write (command );
Return readUntil (prompt );
} Catch (Exception e ){
E. printStackTrace ();
}
Return null;
}
/**
* Close the connection.
*/
Public void distinct (){
Try {
If (telnet! = Null &&! Telnet. isConnected ())
Telnet. disconnect ();
} Catch (IOException e ){
E. printStackTrace ();
}
}
Public void setPrompt (String prompt ){
If (prompt! = Null ){
This. prompt = prompt;
This. promptChar = prompt. charAt (prompt. length ()-1 );
}
}
}

Call class

Package com. tscloud. agent. flume. source. dataprovider;

/**
* Use HTTP as the source of HDFS Master monitoring information
* Details can refer to the http://zookeeper.apache.org/doc/r3.4.6/zookeeperAdmin.html# SC _zkCommands
* @ Author aihua. sun
* @ Date 2015/4/6
* @ Since V1.0
*/

Import com. eric. agent. flume. model. ZookeeperRoleInfo;
Import com. eric. agent. flume. source. base. IClusterServiceRoleDataProvider;
Import com. eric. agent. utils. AgentConstants;
Import com. eric. agent. utils. TelnetTools;
Import com. eric. common. utils. StringUtils;
Import org. slf4j. Logger;
Import org. slf4j. LoggerFactory;

Import java. io. UnsupportedEncodingException;
Import java. util .*;

Public class ZookeeperDataProvider {
Protected final Logger LOGGER = LoggerFactory. getLogger (getClass ());
Private static final String zk_avg_latency = "zk_avg_latency ";
Private static final String zk_max_latency = "zk_max_latency ";
Private static final String zk_min_latency = "zk_min_latency ";
Private static final String zk_packets_received = "zk_packets_received ";
Private static final String zk_packets_sent = "zk_packets_sent ";
Private static final String zk_server_state = "zk_server_state ";
Private static final String zk_znode_count = "zk_znode_count ";
Private static final String zk_followers = "zk_followers ";
Private static final String zk_open_file_descriptor_count = "zk_open_file_descriptor_count ";

Public String extractMonitorData (){
// TODO obtains the IP address and parameters by calling the API.
ZookeeperRoleInfo monitorDataPoint = new ZookeeperRoleInfo ();
String IP = "192.168.40.242 ";
Int port = 2181;
TelnetTools telnet = null;
Try {
Telnet = new TelnetTools ();
Telnet. login (IP, port );
String rs = telnet. sendCommand ("mntr ");
Map <String, String> telnetResultMap = parseTelnetResult (rs );
MonitorDataPoint. setZkAvgLatency (translateStrToLong (telnetResultMap. get (zk_avg_latency )));
MonitorDataPoint. setZkMaxLatency (translateStrToLong (telnetResultMap. get (zk_max_latency )));
MonitorDataPoint. setZkMinLatency (translateStrToLong (telnetResultMap. get (zk_min_latency )));
MonitorDataPoint. setZkPacketsReceived (translateStrToLong (telnetResultMap. get (zk_packets_received )));
MonitorDataPoint. setZkPacketsSent (translateStrToLong (telnetResultMap. get (zk_packets_sent )));
MonitorDataPoint. setZkServerState (telnetResultMap. get (zk_server_state ));
MonitorDataPoint. setZkZnodeCount (translateStrToLong (telnetResultMap. get (zk_znode_count )));
MonitorDataPoint. setZkFollowers (translateStrToLong (telnetResultMap. get (zk_followers )));
MonitorDataPoint. setZkOpenFileDescriptorCount (translateStrToLong (telnetResultMap. get (zk_open_file_descriptor_count )));
} Catch (Exception e ){
E. printStackTrace ();
} Finally {
Telnet. distinct ();
}

Return monitorDataPoint. toString ();
}

Private Long translateStrToLong (String value ){
If (org. apache. commons. lang. StringUtils. isAlphanumeric (value )){
Return Long. valueOf (value );
}
Return 0L;
}

Private Map <String, String> parseTelnetResult (String rs ){
// The output contains multiple lines with the following format:
// Key \ t value
String [] resultArray = rs. split ("\ n ");
Map <String, String> resultMap = new HashMap <String, String> ();
For (String recordLine: resultArray ){
String [] recordKeyValue = recordLine. split ("\ t ");
LOGGER. debug ("########### recordKeyValue. size:" + recordKeyValue. length + "recordKeyValue:" + Arrays. toString (recordKeyValue ));
If (recordKeyValue! = Null & recordKeyValue. length = 2 ){
ResultMap. put (recordKeyValue [0], recordKeyValue [1]);
}
}
Return resultMap;
}


Public static void main (String [] args ){
System. out. println (new ZookeeperDataProvider (). extractMonitorData ());
}

}

-------------------------------------- Split line --------------------------------------

Ubuntu 14.04 installs distributed storage Sheepdog + ZooKeeper

CentOS 6 installs sheepdog VM distributed storage

ZooKeeper cluster configuration

Use ZooKeeper to implement distributed shared locks

Distributed service framework ZooKeeper-manage data in a distributed environment

Build a ZooKeeper Cluster Environment

Test Environment configuration of ZooKeeper server cluster

ZooKeeper cluster Installation

This article permanently updates the link address:

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.