*New 12.1 series Release:
2019-11-08: XigmaNAS 12.1.0.4.7091 - released!

*New 11.3 series Release:
2019-10-19: XigmaNAS 11.3.0.4.7014 - released


We really need "Your" help on XigmaNAS https://translations.launchpad.net/xigmanas translations. Please help today!

Producing and hosting XigmaNAS costs money. Please consider donating for our project so that we can continue to offer you the best.
We need your support! eg: PAYPAL

shutdown/hibernate script when idle

XigmaNAS Scripts and shell tips
Forum rules
Set-Up GuideFAQsForum Rules
Post Reply
User avatar
siftu
Moderator
Moderator
Posts: 72
Joined: 17 Oct 2012 06:36
Status: Offline

shutdown/hibernate script when idle

#1

Post by siftu » 24 Jun 2013 04:48

I always had a problem of leaving my NAS up overnight or for a few days forgetting it was running. As my NAS is a bit of a power hog this can cost me quite a few $$ per month. I am sharing this script I created, which has been modified and added to over the years.

What does it do? It monitors the packets received and transmitted on the LAN interface of NAS4free and keeps a record of these number. Upon the next run it will compare the previous results with the current results and shutdown or power off the NAS if the required number of packets have not been transmitted/received. It will also ensure no scrub or resilver is in process and can optionally send an email telling you it shutdown with the statistics in the body.

Usage:
Run the following as a cron job

Code: Select all

Usage: nas_poweroff.sh <sleep packets> [-h -e]
The following flags are optional
    -e - send email when shutdown occurs
    -h - hibernate instead of shutdown (acpiconf -s3)
My setup is the following which is schedule to run every 30 mins. [System|Advanced|Cron]

Code: Select all

/mnt/zpool/scripts/nas_poweroff.sh 2000 -e 
You can grab the script here http://n4f.siftusystems.com/files/scrip ... oweroff.sh

or copy and paste the script below. Remember to chmod +x the script.

Let me know if you like it. Find bugs or improve it.

Code: Select all

#!/bin/bash
#
# Author: SIFTU
# Version: 1.3
#
# Usage: nas_powerdown <sleep_packets>
#
# This is scheduled in CRON.  Schedule it to run at regular intervals i.e. 15,30,60 mins 
# It compares the RX and TX packets from the previous run
# ago to detect if they significantly increased past the number of sleep packets.
# If they haven't, it will force the system to sleep.
#
# Notes: * Be sure to supply the sleep packets as an argument. if less packets than that has been recieved on the
#          interface since the last run the system will shutdown. A rough guide is 1200 packets per 5 mins
#        * optional arguments are -e for email and -h for hibernate
#        * The system will not shutdown if a ZFS scrub or a resilver is in progress

log="/tmp/idle.log"
stats_file="/tmp/nas_stats.log"
config="/cf/conf/config.xml"  # For embedded installs

## Find the LAN interface
ip=$(/usr/local/bin/xml sel -t -v "//interfaces/lan/ipaddr" $config)
interface=$(netstat -in|grep $ip|awk '{print $1}')

## Only works if smartd has a valid email set in SMART
email_to=$(/usr/local/bin/xml sel -t -v "//smartd/email/to" $config)
email_from=$(/usr/local/bin/xml sel -t -v "//email/from" $config)
subject="$(hostname -s) - Shutdown - $(date +%H:%M\ %Y-%m-%d)"

sleep_packets="$1"

process_args()
{
if [[ -z "$1" ]]; then
        echo "Usage: nas_poweroff.sh <sleep packets> [-h -e]"
        echo "The following flags are optional"
        echo "  -e - send email when shutdown occurs"
        echo "  -h - hibernate instead of shutdown (acpiconf -s3)"
        exit 1
fi
hibernate="n"; email="n"
for ARG in "$@"
      do
       case $ARG in
            "-e" ) email="y";;
            "-h" ) hibernate="y";;
       esac
done
}

process_args "$@"

# Extract the current values of RX/TX
rx=$(netstat -n -I $interface|grep $ip|awk {'print $5'})
tx=$(netstat -n -I $interface|grep $ip|awk {'print $8'})

#Write Date to log
echo "Current Values - $(date)" >> $log
echo -e "rx: $rx tx: $tx\n" >> $log

# Check if scrub is going
if [[ $(zpool status|grep "in progress") ]]; then
        scrub=1
    else
        scrub=0
fi

# Check if RX/TX Files Exist
if [[ -f $stats_file ]]; then
        read -r p_rx p_tx <<< $(cat $stats_file)
        echo "Previous Values" >> $log
        echo "p_rx: $p_rx t_rx: $p_tx" >> $log
        echo "$rx $tx" > $stats_file    ## Write packets to stats file

        # Calculate threshold limit 
        t_rx=$(($p_rx + $sleep_packets))
        t_tx=$(($p_tx + $sleep_packets))

        echo "Threshold Values" >> $log
        echo -e "t_rx: $t_rx t_tx: $t_tx\n" >> $log

        if [[ $rx -le $t_rx ]] || [[ $tx -le $t_tx ]]; then  ## If network packets have not changed that much
                echo " " >> $log
                rm $stats_file 
                if [[ $scrub -eq 0 ]]; then
                    if [[ $email == "y" ]]; then 
                        diff_rx=$((rx-p_rx))
                        diff_tx=$((tx-p_tx))
                        body="$(hostname -s) recieved $diff_rx and transmitted $diff_tx packets which is less than the threshold of $1 packets on the interface $interface. Shutting down"
                        printf "From:$email_from\nTo:$email_to\nSubject:$subject\n\n$body" | /usr/local/bin/msmtp --file=/var/etc/msmtp.conf -t
                        sleep 20 ## Give time for the email to be sent
                    fi
                    if [[ $hibernate == "y" ]]; then
                        acpiconf -s3            ## Go into S3.
                    else
                        shutdown -p now         ## Force shutdown
                    fi
                fi
        fi
#If RX/TX Files Doesn't Exist
else 
        echo "$rx $tx" > "$stats_file" ## Write packets to file
        touch "$log"
fi

exit 0
System specs: NAS4Free amd64-embedded on ASUSTeK. M5A78L-M LX PLUS - AMD Phenom(tm) II X3 720 Processor - 8GB ECC Ram, Storage: 2x ZFS mirrors with 4x Western Digital Green (WDC WD10EADS)
My NAS4Free related blog - http://n4f.siftusystems.com/

Indynamo
NewUser
NewUser
Posts: 1
Joined: 05 Nov 2013 00:25
Status: Offline

Re: shutdown/hibernate script when idle

#2

Post by Indynamo » 05 Nov 2013 00:29

Thanks for the script it was what i needed. Only a minor detail why couldn't you mention NO DHCP support?

User avatar
crest
Hardware & Software Guru
Hardware & Software Guru
Posts: 873
Joined: 02 Jul 2012 22:25
Location: Vienna, Austria - GMT+1
Status: Offline

Re: shutdown/hibernate script when idle

#3

Post by crest » 06 Jan 2014 10:34

Thanks for the script! It is very useful for me since I'm using Rapberry Pi now for video streaming and the PIs are switch on all the time. So my former used shutdown script which checked for online clients is no longer shuting down the NAS.

I've just one suggestion for your script. I changed the logic in this line

Code: Select all

  if [[ $rx -le $t_rx ]] || [[ $tx -le $t_tx ]]; then  ## If network packets have not changed that much
from "||" to "&&" because if you are streaming you get a lot of packets transmitted but less then the used threshold received and so the scripts closed down the NAS even it was streaming to my tv set.

With the "&&" the NAS now shuts down if both rx and tx are below the threshold.

But however, thanks again for great script!!!
NAS1: 11.2.0.4 - Omnius (Revision 6766) x64-embedded; MSI 760GM-P23; AMD Athlon(tm) II X2 250 7.58GiB RAM
NAS2: 11.2.0.4 - Omnius (Revision 6766) x64-embedded; MSI MS-7369; AMD Sempron(tm) LE-1250 8022MiB RAM
UPS: APC Back-UPS ES 550G
Extensions: OneButtonInstaller, Extended GUI, NextOwnCloud, BitTorrent Sync, Syncthing, Downloady, Midnight Commander, NCDU, MySQL, Rclone, Themes:

Ironcurtain
Starter
Starter
Posts: 16
Joined: 01 Sep 2012 14:43
Status: Offline

Re: shutdown/hibernate script when idle

#4

Post by Ironcurtain » 09 Feb 2014 11:48

Hi,

i'am using the embedded version of Nas4Free 9.2.0.1 - Shigawire. I created my zfs raid 1 pool and want to use this shutdown script. So i activated ssh and logged in as root with Putty.
I created a Folder in /mnt/pool_1/Skripte/
There i have downloaded the script:

Code: Select all

fetch http://n4f.siftusystems.com/files/scripts/nas_poweroff.sh
chmod +x ./nas_poweroff.sh
Now when i try to run the script with:

Code: Select all

./nas_poweroff.sh
I get this error:
Could not determine ip: dhcp or interface: or could not find the config file: /cf/conf/config.xml
Could someone help me?

Regards,

Ironcurtain

provels
experienced User
experienced User
Posts: 102
Joined: 05 Jan 2014 15:31
Location: Chicago, IL, USA
Status: Offline

Re: shutdown/hibernate script when idle

#5

Post by provels » 04 Mar 2014 00:58

I may be wrong, but be sure your LAN interface is set to static and not DHCP. DHCP seemed to break a couple things for me, including this script and minidlna viewer. Even though I had a reservation in DHCP (so I could use WOL from my pfSense box) the script would not run until I also changed the N4F to static. HTH/correct me if I'm wrong. Good luck.
Peder
XigmaNAS 11.3.0.4.7014 Embedded / MiniDLNA and CIFS/SMB only
HP ProLiant DL320 G3 / P4 660 3.6GHz HT / 4GB ECC / 2 x 3TB WD Red, ZFS Mirror / APC Back-UPS BR 800

ringwooddan
NewUser
NewUser
Posts: 10
Joined: 27 Jun 2014 17:12
Status: Offline

Re: shutdown/hibernate script when idle

#6

Post by ringwooddan » 03 Jan 2015 22:06

I realise this is an old thread, but I'm trying to get this script to work on my NAS4Free box and I cannot get the Cron job to successfully shutdown - it works fine when I use the run now button, just the cron job doesn't work. I've watched the time tick over the half hour or hour mark and the CPU spikes from 0% usage to 18% usage - so something is happening - just doesn't shut down. Any ideas? Thanks

ringwooddan
NewUser
NewUser
Posts: 10
Joined: 27 Jun 2014 17:12
Status: Offline

Re: shutdown/hibernate script when idle

#7

Post by ringwooddan » 03 Jan 2015 22:09

Actually, as I have tried this just now, the box reboots instead of shutting down when using the run now button. It doesn't do anything when running as the cron job.

KingB
Starter
Starter
Posts: 15
Joined: 11 Feb 2015 14:07
Status: Offline

Re: shutdown/hibernate script when idle

#8

Post by KingB » 12 Feb 2015 14:45

Yes, Scipt works only with static IP, DHCP brings error

anders.malm
Starter
Starter
Posts: 23
Joined: 01 Mar 2015 10:03
Status: Offline

Re: shutdown/hibernate script when idle

#9

Post by anders.malm » 01 Mar 2015 11:08

Hello i have successfully used this script with 9.2.0.1.972 but after upgrade to 9.3.0.2.1349 it doesn't work anymore. The script i activated, i receive an e-mail and Nas4Free is shut down but the computer doesn't suspend. After this the computer doesn´t respond on the magic package.
ASUS P10-S, Intel i3 CPU, 16 GB ECC ram, 250 GB M2 SSD, RootOnZFS

Gleneisenbach
Starter
Starter
Posts: 39
Joined: 04 Apr 2015 10:36
Location: Neu-Anspach
Status: Offline

Re: shutdown/hibernate script when idle

#10

Post by Gleneisenbach » 06 Apr 2015 09:30

Hi siftu,

I'm working on a similar script which is sheduled as Postinit instead cron.

I will use the following regualar expression instead parsing the XML-Config file: (attention it is SH not BSH)
`netstat -in | grep -E '[[:digit:]]{1,3}\.[1-9]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}'`
That will also work for DCHP as KingB complained already.
ASRock Q1900-ITX, be quiet! System Power S7 300 Watt bulk, Kingston 4GB DDR3L SO-DIMM 1600MHz, PC3-12800, 2 X Seagate ST3000VN000 NAS HDD 3TB, Cooler Master Elite 120 Advanced schwarz,Toshiba TransMemory mini Suruga 8GB schwarz
NAS4Free11.0.0.4 -(Sayyadina)

DirkS
NewUser
NewUser
Posts: 2
Joined: 08 Nov 2019 19:42
Status: Offline

Re: shutdown/hibernate script when idle

#11

Post by DirkS » 12 Feb 2020 17:03

Gleneisenbach wrote:
06 Apr 2015 09:30
Hi siftu,

I'm working on a similar script which is sheduled as Postinit instead cron.

I will use the following regualar expression instead parsing the XML-Config file: (attention it is SH not BSH)
`netstat -in | grep -E '[[:digit:]]{1,3}\.[1-9]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}'`
That will also work for DCHP as KingB complained already.

Hi Gleneisenbach,

can you share your modified script? And would it also work with 2 lan interfaces in different subnets?

Post Reply

Return to “Scripts and shell tips”