#!/bin/sh
#
# Copyright 2015-2020 The OpenZipkin Authors
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License
# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing permissions and limitations under
# the License.
#

# HEALTHCHECK for use in `docker ps` or `docker-compose ps`.
# It can also be used as a readiness probe in k8s

# Fail on unset variables, but don't quit on rc!=0, so we can log what happened
set -u +e

IP="$(hostname -i || echo '127.0.0.1')"

# kafka-topics.sh invokes a Java command which can overrun CPU quota, so we
# check the services at TCP layer instead.
ZK_HEALTH=$(echo ruok | nc ${IP} 2181)
ZK_RC=$?
if [ "$ZK_RC" == "0" ]; then
  if [ "$ZK_HEALTH" == "imok" ]; then
    nc -z ${IP} 9092 > /dev/null 2>&1
    KAFKA_RC=$?
    if [ "$KAFKA_RC" == "0" ]; then
      exit 0
    fi

    echo Kafka port check failed with code: $KAFKA_RC
    exit 1
  fi

  echo ZooKeeper not healthy: $ZK_HEALTH
  exit 1
fi

echo ZooKeeper port check failed with code: $ZK_RC
exit 1
