Display ZooKeeper state for each server using the four-letter commands.

Use the following shell script to execute the four-letter command mntr that will output a list of variables that could be used for monitoring the health of the cluster. Then look for zk_server_state and zk_synced_followers variables.

#!/bin/bash
# Display ZooKeeper state for each provider server
#
# Usage:
#   zookeeper_check_state.sh zookeeper1.example.org zookeeper2.example.org zookeeper3.example.org
#

# zookeeper port
zookeeper_port=2181

# colors
color_error="\e[31m"
color_follower="\e[34m"
color_leader="\e[32m"
color_reset="\e[0m"

for server in "$@"; do
  monitoring_output="$(echo mntr | nc "$server" "$zookeeper_port" 2>/dev/null)"
  if [ "$?" -eq "0" ]; then
    server_state="$(echo -e "$monitoring_output" | awk '$1=="zk_server_state" {print $2}')"
    if [ "$server_state" = "leader" ]; then
     server_followers="$(echo -e "$monitoring_output" | awk '$1=="zk_synced_followers" {print $2}')"
     echo -e "${color_leader}Server ${server} is a ${server_state} with ${server_followers} followers${color_reset}";
    elif [ "$server_state" = "follower" ]; then
      echo -e "${color_follower}Server ${server} is a ${server_state}${color_reset}"
    fi
  else
    echo -e "${color_error}Server ${server} encountered an error${color_reset}"
  fi
done

Shell script output.

$ zookeeper_check_state.sh zookeeper1.example.org zookeeper2.example.org zookeeper3.example.org
Server zookeeper1.example.org is a follower
Server zookeeper2.example.org is a follower
Server zookeeper3.example.org is a leader with 2 followers