#!/bin/bash

# @file process-stability
#
# Copyright (C) Metaswitch Networks 2017
# If license terms are provided to you in a COPYING file in the root directory
# of the source code repository by which you are accessing this code, then
# the license outlined in that COPYING file applies to your use.
# Otherwise no rights are granted except for those provided to you by
# Metaswitch Networks in a separate written agreement.

# Used for monitoring the stability of a process.

method=$1
process_name=$2
grace_period=$3
abort_flag_name="$process_name-aborting-flag"

usage="Usage: check-stability {check|reset|aborted} <process name> <grace period (s)>"

[ $# = 3 ] || { echo $usage >&2 ; exit 2; }

# Returns 1 if the process has not been running for at least the grace period,
# or the abort flag is set (and has not timed out). Returns 2 if there is no
# process matching the value in the pidfile. Returns 0 otherwise.
check_stability() {
  pidfile=/var/run/$process_name/$process_name.pid

  # It's expected that there might not be a pidfile
  pid=$( cat $pidfile 2>/dev/null)

  # Determine the uptime
  uptime=$( ps -p $pid -o etimes= 2>/dev/null) || { echo "No process matching value from pidfile: $pid " >&2 ; return 1 ; }

  if ! /usr/share/clearwater/bin/cw-flag read $abort_flag_name; then
    echo "process is unstable as it is currently aborting" >&2
    exit 1
  elif [ "$uptime" -lt "$grace_period" ]; then
    uptime_no_whitespace=$( echo -e $uptime | tr -d '[:space:]')
    echo "process is unstable as it has not been up for long enough ($uptime_no_whitespace s < $grace_period s)" >&2
    return 1
  else
    return 0
  fi
}

# Clears the abort flag - should be called when (re)starting the process.
reset_stability() {
  /usr/share/clearwater/bin/cw-flag clear $abort_flag_name
}

aborted_stability() {
  /usr/share/clearwater/bin/cw-flag set $abort_flag_name
}

case "$method" in

  check)
    check_stability
    exit $?
    ;;

  reset)
    reset_stability
    ;;

  aborted)
    aborted_stability
    ;;

  *)
    echo $usage
    ;;

esac
