Skip to content

Instantly share code, notes, and snippets.

@michimani
Created May 23, 2018 01:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save michimani/8e89359baf94078ba2cbbc373b853edd to your computer and use it in GitHub Desktop.
Save michimani/8e89359baf94078ba2cbbc373b853edd to your computer and use it in GitHub Desktop.
Put linux process status to Amazon CloudWatch.
###################################################################################
# check process aliving (count process number)
# return integer 1 (process is running) or 0 (process is dead) or 9 (some error)
###################################################################################
function is_process_alive() {
count=`ps awux | grep -v grep | grep -v "$0" | grep -w "$1" | wc -l`
if [[ $count =~ ^[0-9]+$ ]]; then
if [ $count != 0 ]; then
echo 1
else
echo 0
fi
else
echo 9
fi
}
## instance config
readonly INSTANCE_ID=`curl -s http://169.254.169.254/latest/meta-data/instance-id`
readonly REGION='ap-northeast-1'
## config
readonly NAMESPACE='CustomMetrics'
readonly UNIT='Count'
if [ $# -ne 1 ]; then
echo '[ERROR] invalid paramter'
exit 1;
fi
process_name=$1
if [ $process_name = '' ]; then
echo '[ERROR] process name is required'
exit 1;
fi
metrics_name="process/$process_name"
## process count
value=`is_process_alive $@`
if [ $value -ne 1 ] && [ $value -ne 0 ]; then
echo '[ERROR] failed to count process number'
exit 1;
fi
## put data to CloudWatch
aws cloudwatch put-metric-data --metric-name $metrics_name --namespace $NAMESPACE --value $value --region $REGION --unit $UNIT --dimensions "InstanceId=$INSTANCE_ID,ProcessName=$process_name"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment