Smart Savings:Optimizing Cloud Costs Through Service Shutdown-Automatic Script to Stop and Start My DB System DBCS on OCI




Cloud providers offer a pay-as-you-go model, allowing businesses to scale resources up and down based on demand. While this elasticity is advantageous, it also necessitates careful management to prevent unnecessary expenditure. Many services run 24/7 by default, consuming resources even during periods of inactivity. Here's where the concept of "service shutdown" becomes a powerful strategy.

Implementing Service Shutdowns

1. Analyze Usage Patterns:
Identify usage patterns for various services to pinpoint periods of low demand. Utilize cloud monitoring tools to gain insights into when services are least active.

2. Set Up Automation:
Leverage automation tools and scripts to schedule service shutdowns during predefined time frames. Automation ensures consistency and reduces the chances of human error.

3. Monitor and Adjust:
Continuously monitor the impact of service shutdowns on costs and performance. Adjust schedules and strategies based on feedback and data analysis.

4. Consider Business Impact:
While optimizing costs is vital, it's essential to strike a balance between cost savings and maintaining critical services. Evaluate the potential impact of a service shutdown on business operations.

Please use as per your  needs and testing.
I am going to create an automatic script to stop by DBCS system to save cost during weekends or time when I don't need to use the service.


Pre-Requisites:



Current Cost of my DBCS when it run daily. As this is my demo system so the cost is still low but we will see when the system is down then how much it saves.




1)  I have mounted a shared bucket on my server. It will be used to keep files to be used to automatic shutdown.

[root@foadbserver shared]# df -h /shared
Filesystem      Size  Used Avail Use% Mounted on
s3fs            4.0G     0  4.0G   0% /shared


2)  Generate a ssh key for opc user on my centralized OCI CLI server.

[opc@ocicliserver .ssh]$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/opc/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/opc/.ssh/id_rsa.
Your public key has been saved in /home/opc/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:bBMfp8iLYRW0FGOvKGd1z2UsHcfh/dB6PGCbnK3M2fs opc@ocicliserver
The key's randomart image is:
+---[RSA 3072]----+
|       .B.    .oo|
|       o =   o.+o|
|        = + oo*.o|
|       * * *o+*+.|
|    . * S o o=.o+|
|     = + o  o +..|
|      . .    = . |
|                .|
|               .E|
+----[SHA256]-----+


3) Copy the public key from OCI CLi server to the DB server which I need to control from command line.

cat id_rsa.pub from OCI CLI server 

and 

Copy to authorised key on DB server
cd /home/opc/.ssh
ls -ltr authorized_keys

4) Now check the connectivity and it should connect without password.

[opc@ocicliserver ~]$ ssh opc@foadbserver
The authenticity of host 'foadbserver (10.0.2.14)' can't be established.
ECDSA key fingerprint is SHA256:2o7LzuJSgTIqwr9QMEuYbadM6buwj3+aWvcvarcSMN0.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added 'foadbserver,10.0.2.14' (ECDSA) to the list of known hosts.
Last login: Sat Aug 26 01:43:10 2023 from 49.36.13.24
[opc@foadbserver ~]$


5)  Below is script code what I use.


cat remote_manager.sh
#!/bin/bash
#set -x
# Remote DB Server Linux machine details
REMOTE_HOST="foadbserver"
REMOTE_USER="opc"

# Oracle database details
DB_SID="FOA12"

#Flag File to check status my shared Object storage bucket
flag_file=/shared/${DB_SID}_status.txt
#Cloud Compartment Name
COMPARTMENT_ID=ocid1.compartment.oc1..aaaaaaaampr6y6afm3oq6cz2fzu6jfvnllwpfvqioa5md2xc5taz5h34dpfa
#DBCS display name
ENV_NAME=TEST1219

# Operation selection
read -p "Enter 'start' or 'stop' to perform the operation: " OPERATION


OCID_DBSYSTEM=$(oci db system list  --compartment-id $COMPARTMENT_ID  --query "data [?\"display-name\" == '${ENV_NAME}'].id|join(',',@)"| tr -d '\"')

OCID_DB_NODE=$(oci db node list  --db-system-id $OCID_DBSYSTEM  --compartment-id $COMPARTMENT_ID --query "data[].id|join(',',@)"| tr -d '\"')

if [ "${OPERATION}" == "stop" ]; then
# Connect to the remote machine as "opc" user
ssh ${REMOTE_USER}@${REMOTE_HOST} << EOF
# Switch to the "oracle" user
sudo su - oracle << ORACLE_EOF
echo "Stopping the Oracle database..."
        sqlplus -S /nolog << SQL_EOF
        Connect /as sysdba
        shutdown immediate;
        exit;
SQL_EOF
if [ `ps -ef|grep pmon|grep -i ${DB_SID}|wc -l` -eq 0 ]
then
# Create a file to indicate the operation
touch ${flag_file}
echo "${OPERATION}" > ${flag_file}
fi
# Exit from oracle user
exit
ORACLE_EOF
# Exit from remote machine
exit
EOF
echo "Operation ${OPERATION} on database completed on `date`."

echo "Stopping the Oracle DB System..."

oci db node stop  --db-node-id $OCID_DB_NODE

elif [ "${OPERATION}" == "start" ]; then

echo "Starting the Oracle DB System..."

oci db node start  --db-node-id $OCID_DB_NODE

sleep 300

# Connect to the remote machine as "opc" user
ssh ${REMOTE_USER}@${REMOTE_HOST} << EOF
# Switch to the "oracle" user
sudo su - oracle << ORACLE_EOF
echo "Stopping the Oracle database..."
        sqlplus -S /nolog << SQL_EOF
        Connect /as sysdba
        Startup;
        exit;
SQL_EOF
if [ `ps -ef|grep pmon|grep -i ${DB_SID}|wc -l` -ne 0 ]
then
# Create a file to indicate the operation
touch ${flag_file}
echo "${OPERATION}" > ${flag_file}
fi
# Exit from oracle user
exit
ORACLE_EOF
# Exit from remote machine
exit
EOF
echo "Operation ${OPERATION} on database completed on `date`."
else
echo "Invalid operation. Please enter 'start' or 'stop'"
    exit 1;

fi




6) Once we stop the script check from DBCS console, it will display node as stopped.




7) We can schedule the script in cron when to stop and start the service.

You can always customize the script as per your needs and make it more generic . I have shared one of my script which I use.


8) Earlier my daily average cost was around $3.48 which is reduced to $0.74.








If you like please follow and comment