#!/bin/bash # # Library for managing services # Functions ######################## # Read the provided pid file and returns a PID # Arguments: # $1 - Pid file # Returns: # PID ######################### get_pid_from_file() { local pid_file="${1:?pid file is missing}" if [[ -f "$pid_file" ]]; then if [[ -n "$(< "$pid_file")" ]] && [[ "$(< "$pid_file")" -gt 0 ]]; then echo "$(< "$pid_file")" fi fi } ######################## # Check if a provided PID corresponds to a running service # Arguments: # $1 - PID # Returns: # Boolean ######################### is_service_running() { local pid="${1:?pid is missing}" kill -0 "$pid" 2>/dev/null } ######################## # Stop a service by sending a termination signal to its pid # Arguments: # $1 - Pid file # Returns: # None ######################### stop_service_using_pid() { local pid_file="${1:?pid file is missing}" local pid pid="$(get_pid_from_file "$pid_file")" [[ -z "$pid" ]] || ! is_service_running "$pid" && return kill "$pid" local counter=10 while [[ "$counter" -ne 0 ]] && is_service_running "$pid"; do sleep 1 counter=$((counter - 1)) done } ######################## # Generate a monit configuration file for a given service # Arguments: # $1 - Service name # $2 - Pid file # $3 - Start command # $4 - Stop command # Returns: # None ######################### generate_monit_conf() { local -r service_name="${1:?service name is missing}" local -r pid_file="${2:?pid file is missing}" local -r start_command="${3:?start command is missing}" local -r stop_command="${4:?stop command is missing}" local -r monit_conf_dir="/etc/monit/conf.d" mkdir -p "$monit_conf_dir" cat >"${monit_conf_dir}/${service_name}.conf" <"${logrotate_conf_dir}/${service_name}" <