#!/bin/bash
################################################################################
# Copyright (c) 2013-2019 VMware, Inc. All rights reserved.
################################################################################
# Drop OS caches on Linux.  This script can only be run by an OS user who has
# permissions to perform all the operations listed below.

# Make sure that all environment variables are present
source /etc/profile

if [ -z $VMWARE_POSTGRES_BASE ]; then
   echo "VMWARE_POSTGRES_BASE is not set."
   echo "Check your installation."
   exit 1
fi
SANITY_FILE=$VMWARE_POSTGRES_BASE/scripts/vpostgres_sanity_checks
if [ -f $SANITY_FILE ]; then
   source $SANITY_FILE
else
   echo "Sanity check file for environment variables of VMware Postgres"
   echo "is not available. Check your installation."
   exit 1
fi

# Show utility help
show_help()
{
   ERROR_NUM=$1
   echo "Usage: `pg_drop_os_caches`"
   exit $ERROR_NUM
}

# Wrapper to log given message to stderr, which is something that
# can be digested by vMon when running this script as part of the
# pre-start command of service vmware-vpostgres.
log_stderr()
{
   >&2 echo ${1}
}

# Per linux documentation, synchronizing dirty object is required to drop as
# many objects as possible:
# https://www.kernel.org/doc/Documentation/sysctl/vm.txt
#
# This is a non-destructive operation and will not free any dirty objects.
# To increase the number of objects freed by this operation, the user may run
# "sync" prior to writing to /proc/sys/vm/drop_caches.  This will minimize the
# number of dirty objects on the system and create more candidates to be
# dropped.
sync
ERR_NUM=$?
if [ $ERR_NUM != 0 ]; then
	log_stderr "Failed to synchronize caches writes to permanent storage."
	exit $ERR_NUM
fi

sysctl vm.drop_caches=1
ERR_NUM=$?
if [ $ERR_NUM != 0 ]; then
	log_stderr "Failed to drop clean caches."
	exit $ERR_NUM
fi

exit 0

