How to make hard drive standby (spin down) on a timer?How can I mount a UFS drive in linux?How to make setting of kern.ipc.somaxconn persistent?ZFS on FreeBSD: recovery from data corruptionWeb site kills hard disk I/O, how to prevent?How to rebuild gmirror from bad hard driveHow to make proxy on nginx?FreeNAS not detecting hard driveCan the Dell PowerEdge T320 boot from a USB stick in hard drive emulation mode?IBM M1115 and LSI 9211-8i IT modeHow to get FreeNAS to spin down disks?

Should an arbiter claim draw at a K+R vs K+R endgame?

PhD - Well known professor or well known school?

Does an ice chest packed full of frozen food need ice?

Déjà vu, again?

What to do when surprise and a high initiative roll conflict with the narrative?

Why did the Tesseract "burn" a hole through Red Skull's plane but not Nick Fury's desk?

How can electric fields be used to detect cracks in metals?

1980s live-action movie where individually-coloured nations on clouds fight

Are there any instruments that don't produce overtones?

How to construct an hbox with negative height?

How can I get an unreasonable manager to approve time off?

bash script: "*.jpg" expansion not working as expected inside $(...), for picking a random file

Thread Pool C++ Implementation

Passing multiple files through stdin (over ssh)

Using "subway" as name for London Underground?

When conversion from Integer to Single may lose precision

How to tell your grandparent to not come to fetch you with their car?

Character descriptions

Why doesn't Adrian Toomes give up Spider-Man's identity?

What language is software running on the ISS written in?

An average heaven where everyone has sexless golden bodies and is bored

What can I, as a user, do about offensive reviews in App Store?

Motivation - or how can I get myself to do the work I know I need to?

Soft question: Examples where lack of mathematical rigour cause security breaches?



How to make hard drive standby (spin down) on a timer?


How can I mount a UFS drive in linux?How to make setting of kern.ipc.somaxconn persistent?ZFS on FreeBSD: recovery from data corruptionWeb site kills hard disk I/O, how to prevent?How to rebuild gmirror from bad hard driveHow to make proxy on nginx?FreeNAS not detecting hard driveCan the Dell PowerEdge T320 boot from a USB stick in hard drive emulation mode?IBM M1115 and LSI 9211-8i IT modeHow to get FreeNAS to spin down disks?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I'd like to have my hard drives spin down when idle for, let's say 20 minutes. Any number of minutes is fine, as this NAS is rarely used.



What I've tried and didn't work:



  • ataidle -S 20 /dev/ada0 simply spins down the drive immediately and the timer has no effect. Once drives are spun back up due to an access they stay spinning.


  • camcontrol standby /dev/ada0 -t 1200 same behavior as ataidle.


  • FreeNAS UI's Storage -> Disks -> Adv. Power Manager setting simply calls camcontrol and similarly the timer has no effect. If a power setting that allows standby is selected (such as 127) then drives spin down nearly immediately (potentially after 8 seconds), and get constantly spun up and down if there are any accesses.


How can I get the normal expected "stand by if not used in a while" behavior?



Using FreeBSD 11.2-STABLE via FreeNAS 11.2. Drives are 4x Samsung 2TB 2.5" .T2000LM003`



# smartctl -P show /dev/ada0
smartctl 6.6 2017-11-05 r4594 [FreeBSD 11.2-STABLE amd64] (local build)
Copyright (C) 2002-17, Bruce Allen, Christian Franke, www.smartmontools.org

Drive found in smartmontools Database. Drive identity strings:
MODEL: ST2000LM003 HN-M201RAD
FIRMWARE: 2BC10007
match smartmontools Drive Database entry:
MODEL REGEXP: ST(1500|2000)LM0(03|04|06|07|10) HN-M[0-9]*RAD
FIRMWARE REGEXP: .*
MODEL FAMILY: Seagate Samsung SpinPoint M9T
ATTRIBUTE OPTIONS: None preset; no -v options are required.









share|improve this question
























  • Are you sure they don't already spin down when idle? Have you verified you have absolutely nothing reading/writing to the drives? IE, you need to make sure you don't have any logs writing things, any cron processes that might read or write. Any daemons touch the drives/etc.

    – Zoredache
    May 21 at 23:53











  • If I don't explicitly access the drives then they stay spun down. The first ls wakes them up, then afterwards they stay spun up.

    – Adam
    May 22 at 1:20

















1















I'd like to have my hard drives spin down when idle for, let's say 20 minutes. Any number of minutes is fine, as this NAS is rarely used.



What I've tried and didn't work:



  • ataidle -S 20 /dev/ada0 simply spins down the drive immediately and the timer has no effect. Once drives are spun back up due to an access they stay spinning.


  • camcontrol standby /dev/ada0 -t 1200 same behavior as ataidle.


  • FreeNAS UI's Storage -> Disks -> Adv. Power Manager setting simply calls camcontrol and similarly the timer has no effect. If a power setting that allows standby is selected (such as 127) then drives spin down nearly immediately (potentially after 8 seconds), and get constantly spun up and down if there are any accesses.


How can I get the normal expected "stand by if not used in a while" behavior?



Using FreeBSD 11.2-STABLE via FreeNAS 11.2. Drives are 4x Samsung 2TB 2.5" .T2000LM003`



# smartctl -P show /dev/ada0
smartctl 6.6 2017-11-05 r4594 [FreeBSD 11.2-STABLE amd64] (local build)
Copyright (C) 2002-17, Bruce Allen, Christian Franke, www.smartmontools.org

Drive found in smartmontools Database. Drive identity strings:
MODEL: ST2000LM003 HN-M201RAD
FIRMWARE: 2BC10007
match smartmontools Drive Database entry:
MODEL REGEXP: ST(1500|2000)LM0(03|04|06|07|10) HN-M[0-9]*RAD
FIRMWARE REGEXP: .*
MODEL FAMILY: Seagate Samsung SpinPoint M9T
ATTRIBUTE OPTIONS: None preset; no -v options are required.









share|improve this question
























  • Are you sure they don't already spin down when idle? Have you verified you have absolutely nothing reading/writing to the drives? IE, you need to make sure you don't have any logs writing things, any cron processes that might read or write. Any daemons touch the drives/etc.

    – Zoredache
    May 21 at 23:53











  • If I don't explicitly access the drives then they stay spun down. The first ls wakes them up, then afterwards they stay spun up.

    – Adam
    May 22 at 1:20













1












1








1








I'd like to have my hard drives spin down when idle for, let's say 20 minutes. Any number of minutes is fine, as this NAS is rarely used.



What I've tried and didn't work:



  • ataidle -S 20 /dev/ada0 simply spins down the drive immediately and the timer has no effect. Once drives are spun back up due to an access they stay spinning.


  • camcontrol standby /dev/ada0 -t 1200 same behavior as ataidle.


  • FreeNAS UI's Storage -> Disks -> Adv. Power Manager setting simply calls camcontrol and similarly the timer has no effect. If a power setting that allows standby is selected (such as 127) then drives spin down nearly immediately (potentially after 8 seconds), and get constantly spun up and down if there are any accesses.


How can I get the normal expected "stand by if not used in a while" behavior?



Using FreeBSD 11.2-STABLE via FreeNAS 11.2. Drives are 4x Samsung 2TB 2.5" .T2000LM003`



# smartctl -P show /dev/ada0
smartctl 6.6 2017-11-05 r4594 [FreeBSD 11.2-STABLE amd64] (local build)
Copyright (C) 2002-17, Bruce Allen, Christian Franke, www.smartmontools.org

Drive found in smartmontools Database. Drive identity strings:
MODEL: ST2000LM003 HN-M201RAD
FIRMWARE: 2BC10007
match smartmontools Drive Database entry:
MODEL REGEXP: ST(1500|2000)LM0(03|04|06|07|10) HN-M[0-9]*RAD
FIRMWARE REGEXP: .*
MODEL FAMILY: Seagate Samsung SpinPoint M9T
ATTRIBUTE OPTIONS: None preset; no -v options are required.









share|improve this question
















I'd like to have my hard drives spin down when idle for, let's say 20 minutes. Any number of minutes is fine, as this NAS is rarely used.



What I've tried and didn't work:



  • ataidle -S 20 /dev/ada0 simply spins down the drive immediately and the timer has no effect. Once drives are spun back up due to an access they stay spinning.


  • camcontrol standby /dev/ada0 -t 1200 same behavior as ataidle.


  • FreeNAS UI's Storage -> Disks -> Adv. Power Manager setting simply calls camcontrol and similarly the timer has no effect. If a power setting that allows standby is selected (such as 127) then drives spin down nearly immediately (potentially after 8 seconds), and get constantly spun up and down if there are any accesses.


How can I get the normal expected "stand by if not used in a while" behavior?



Using FreeBSD 11.2-STABLE via FreeNAS 11.2. Drives are 4x Samsung 2TB 2.5" .T2000LM003`



# smartctl -P show /dev/ada0
smartctl 6.6 2017-11-05 r4594 [FreeBSD 11.2-STABLE amd64] (local build)
Copyright (C) 2002-17, Bruce Allen, Christian Franke, www.smartmontools.org

Drive found in smartmontools Database. Drive identity strings:
MODEL: ST2000LM003 HN-M201RAD
FIRMWARE: 2BC10007
match smartmontools Drive Database entry:
MODEL REGEXP: ST(1500|2000)LM0(03|04|06|07|10) HN-M[0-9]*RAD
FIRMWARE REGEXP: .*
MODEL FAMILY: Seagate Samsung SpinPoint M9T
ATTRIBUTE OPTIONS: None preset; no -v options are required.






freebsd freenas






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited May 29 at 4:01







Adam

















asked May 21 at 23:01









AdamAdam

1655




1655












  • Are you sure they don't already spin down when idle? Have you verified you have absolutely nothing reading/writing to the drives? IE, you need to make sure you don't have any logs writing things, any cron processes that might read or write. Any daemons touch the drives/etc.

    – Zoredache
    May 21 at 23:53











  • If I don't explicitly access the drives then they stay spun down. The first ls wakes them up, then afterwards they stay spun up.

    – Adam
    May 22 at 1:20

















  • Are you sure they don't already spin down when idle? Have you verified you have absolutely nothing reading/writing to the drives? IE, you need to make sure you don't have any logs writing things, any cron processes that might read or write. Any daemons touch the drives/etc.

    – Zoredache
    May 21 at 23:53











  • If I don't explicitly access the drives then they stay spun down. The first ls wakes them up, then afterwards they stay spun up.

    – Adam
    May 22 at 1:20
















Are you sure they don't already spin down when idle? Have you verified you have absolutely nothing reading/writing to the drives? IE, you need to make sure you don't have any logs writing things, any cron processes that might read or write. Any daemons touch the drives/etc.

– Zoredache
May 21 at 23:53





Are you sure they don't already spin down when idle? Have you verified you have absolutely nothing reading/writing to the drives? IE, you need to make sure you don't have any logs writing things, any cron processes that might read or write. Any daemons touch the drives/etc.

– Zoredache
May 21 at 23:53













If I don't explicitly access the drives then they stay spun down. The first ls wakes them up, then afterwards they stay spun up.

– Adam
May 22 at 1:20





If I don't explicitly access the drives then they stay spun down. The first ls wakes them up, then afterwards they stay spun up.

– Adam
May 22 at 1:20










2 Answers
2






active

oldest

votes


















1














I ended up doing this very manually. Write a script that checks for drive activity, spins down drives if there is none, then schedule this script as a cron job.



I settled on an approach that uses iostat to monitor drives for a set period of time, in my case 600 seconds (10 minutes). If iostat reports no usage, call ataidle -s /dev/ada[0123] to suspend the drives. I setup a cron job to call this script every 15 minutes: */15 * * * * spindown_if_idle.sh 600



spindown_if_idle.sh:



#!/bin/bash

# argument is the number of seconds to test for drive use, default to 5
if [ -z "$1" ]; then
SECONDS=5
else
SECONDS="$1"
fi

function list_ada_drives
# emit a list of hard drives, i.e. ada0 ada1 ada2 ...
iostat -x

function spindown
# for every hard drive use ataidle to place it in standby
for ADA in $(list_ada_drives); do
ataidle -s /dev/$ADA
done


function are_drives_used
# argument is number of seconds to test over

# run iostat for the specified number of seconds and ask to report any usage
# -z means to omit any drives that are idle
# iostat will print two reports, the first since boot and the second during the interval
# The first tail and grep strip off the first useless report. The second tail strips off the header
# The final grep strips off drives we're not interested in
iostat -x -z -d $SECONDS 2

if are_drives_used $SECONDS ; then
echo "Drives are being used"
else
echo "Drives are idle, going to standby"
spindown
fi


collectd metrics



I tried avoiding that 10-minute block by querying historic usage as recorded by collectd. I used rrdtool fetch to query the metrics stored in /var/db/collectd/rrd/localhost/disk-ada0, but those have a lag of several minutes. Relying on them would mean that the script might standby drives that are actively used if they had been idle recently.



Testing if drives are spun up



The following script will report if each drive is idle or spinning. Useful for testing.



is_spinning.sh:



#!/bin/sh

camcontrol devlist | grep ada | awk -F( 'print $2' | awk -F",|\\)" 'print $2' |while read LINE
do
CM=$(camcontrol cmd $LINE -a "E5 00 00 00 00 00 00 00 00 00 00 00" -r - | awk 'print $10')
if [ "$CM" = "FF" ] ; then
echo "$LINE: SPINNING"
elif [ "$CM" = "00" ] ; then
echo "$LINE: IDLE"
else
echo "$LINE: UNKNOWN"
fi
done


Based on this forum post.






share|improve this answer
































    1














    Thanks for this idea. I had been struggling with this problem for a few days. As I am not used to write bash scripts I rewrote it in python3. Maybe somebody finds it useful:



    import subprocess
    import time

    drives_to_check = ['ada3', 'ada4', 'ada5']
    no_sleep_hours = ['00', '01']
    seconds = 600

    if time.strftime("%H") in no_sleep_hours:
    exit()

    o = subprocess.check_output(f'/usr/sbin/iostat -x -z -d seconds 2', shell=True)

    for drive in drives_to_check:
    if drive not in o.decode().split('extended')[-1]:
    p = subprocess.check_output(f'/sbin/camcontrol cmd drive -a "E5 00 00 00 00 00 00 00 00 00 00 00" -r -', shell=True)
    if p.decode()[27:29] != '00':
    q = subprocess.check_output(f'/usr/local/sbin/ataidle -s /dev/drive', shell=True)


    My small add-ons were: you can add hours to no_sleep_hours when you don't want the script to run. And you have to add the drives you want to check to "drives_to_check" so you can exclude drives that should not do a spindown.
    Maybe you would have to adjust the paths for iostat and ataidle, these are the paths used in FreeNAS. You can find your paths with: which adaidle or which iostat.
    You can add it to cron with
    */15 * * * * /usr/local/bin/python3 /path/to/the/folder/check_disk_usage_and_spindown.py






    share|improve this answer








    New contributor



    pelipro is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.



















    • nice script! It sure is easier to parse output in Python than it is in Bash. I'd suggest adding some comments to your script, though, both for yourself and for others trying to learn from you. Your script largely does the same thing as mine, but there are some important differences. In some ways yours is better, but a few strategic comments can point out what your script does so someone who hasn't been knee deep in these commands can notice and modify the script to their system and/or needs.

      – Adam
      1 hour ago











    Your Answer








    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "2"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fserverfault.com%2fquestions%2f968303%2fhow-to-make-hard-drive-standby-spin-down-on-a-timer%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    I ended up doing this very manually. Write a script that checks for drive activity, spins down drives if there is none, then schedule this script as a cron job.



    I settled on an approach that uses iostat to monitor drives for a set period of time, in my case 600 seconds (10 minutes). If iostat reports no usage, call ataidle -s /dev/ada[0123] to suspend the drives. I setup a cron job to call this script every 15 minutes: */15 * * * * spindown_if_idle.sh 600



    spindown_if_idle.sh:



    #!/bin/bash

    # argument is the number of seconds to test for drive use, default to 5
    if [ -z "$1" ]; then
    SECONDS=5
    else
    SECONDS="$1"
    fi

    function list_ada_drives
    # emit a list of hard drives, i.e. ada0 ada1 ada2 ...
    iostat -x

    function spindown
    # for every hard drive use ataidle to place it in standby
    for ADA in $(list_ada_drives); do
    ataidle -s /dev/$ADA
    done


    function are_drives_used
    # argument is number of seconds to test over

    # run iostat for the specified number of seconds and ask to report any usage
    # -z means to omit any drives that are idle
    # iostat will print two reports, the first since boot and the second during the interval
    # The first tail and grep strip off the first useless report. The second tail strips off the header
    # The final grep strips off drives we're not interested in
    iostat -x -z -d $SECONDS 2

    if are_drives_used $SECONDS ; then
    echo "Drives are being used"
    else
    echo "Drives are idle, going to standby"
    spindown
    fi


    collectd metrics



    I tried avoiding that 10-minute block by querying historic usage as recorded by collectd. I used rrdtool fetch to query the metrics stored in /var/db/collectd/rrd/localhost/disk-ada0, but those have a lag of several minutes. Relying on them would mean that the script might standby drives that are actively used if they had been idle recently.



    Testing if drives are spun up



    The following script will report if each drive is idle or spinning. Useful for testing.



    is_spinning.sh:



    #!/bin/sh

    camcontrol devlist | grep ada | awk -F( 'print $2' | awk -F",|\\)" 'print $2' |while read LINE
    do
    CM=$(camcontrol cmd $LINE -a "E5 00 00 00 00 00 00 00 00 00 00 00" -r - | awk 'print $10')
    if [ "$CM" = "FF" ] ; then
    echo "$LINE: SPINNING"
    elif [ "$CM" = "00" ] ; then
    echo "$LINE: IDLE"
    else
    echo "$LINE: UNKNOWN"
    fi
    done


    Based on this forum post.






    share|improve this answer





























      1














      I ended up doing this very manually. Write a script that checks for drive activity, spins down drives if there is none, then schedule this script as a cron job.



      I settled on an approach that uses iostat to monitor drives for a set period of time, in my case 600 seconds (10 minutes). If iostat reports no usage, call ataidle -s /dev/ada[0123] to suspend the drives. I setup a cron job to call this script every 15 minutes: */15 * * * * spindown_if_idle.sh 600



      spindown_if_idle.sh:



      #!/bin/bash

      # argument is the number of seconds to test for drive use, default to 5
      if [ -z "$1" ]; then
      SECONDS=5
      else
      SECONDS="$1"
      fi

      function list_ada_drives
      # emit a list of hard drives, i.e. ada0 ada1 ada2 ...
      iostat -x

      function spindown
      # for every hard drive use ataidle to place it in standby
      for ADA in $(list_ada_drives); do
      ataidle -s /dev/$ADA
      done


      function are_drives_used
      # argument is number of seconds to test over

      # run iostat for the specified number of seconds and ask to report any usage
      # -z means to omit any drives that are idle
      # iostat will print two reports, the first since boot and the second during the interval
      # The first tail and grep strip off the first useless report. The second tail strips off the header
      # The final grep strips off drives we're not interested in
      iostat -x -z -d $SECONDS 2

      if are_drives_used $SECONDS ; then
      echo "Drives are being used"
      else
      echo "Drives are idle, going to standby"
      spindown
      fi


      collectd metrics



      I tried avoiding that 10-minute block by querying historic usage as recorded by collectd. I used rrdtool fetch to query the metrics stored in /var/db/collectd/rrd/localhost/disk-ada0, but those have a lag of several minutes. Relying on them would mean that the script might standby drives that are actively used if they had been idle recently.



      Testing if drives are spun up



      The following script will report if each drive is idle or spinning. Useful for testing.



      is_spinning.sh:



      #!/bin/sh

      camcontrol devlist | grep ada | awk -F( 'print $2' | awk -F",|\\)" 'print $2' |while read LINE
      do
      CM=$(camcontrol cmd $LINE -a "E5 00 00 00 00 00 00 00 00 00 00 00" -r - | awk 'print $10')
      if [ "$CM" = "FF" ] ; then
      echo "$LINE: SPINNING"
      elif [ "$CM" = "00" ] ; then
      echo "$LINE: IDLE"
      else
      echo "$LINE: UNKNOWN"
      fi
      done


      Based on this forum post.






      share|improve this answer



























        1












        1








        1







        I ended up doing this very manually. Write a script that checks for drive activity, spins down drives if there is none, then schedule this script as a cron job.



        I settled on an approach that uses iostat to monitor drives for a set period of time, in my case 600 seconds (10 minutes). If iostat reports no usage, call ataidle -s /dev/ada[0123] to suspend the drives. I setup a cron job to call this script every 15 minutes: */15 * * * * spindown_if_idle.sh 600



        spindown_if_idle.sh:



        #!/bin/bash

        # argument is the number of seconds to test for drive use, default to 5
        if [ -z "$1" ]; then
        SECONDS=5
        else
        SECONDS="$1"
        fi

        function list_ada_drives
        # emit a list of hard drives, i.e. ada0 ada1 ada2 ...
        iostat -x

        function spindown
        # for every hard drive use ataidle to place it in standby
        for ADA in $(list_ada_drives); do
        ataidle -s /dev/$ADA
        done


        function are_drives_used
        # argument is number of seconds to test over

        # run iostat for the specified number of seconds and ask to report any usage
        # -z means to omit any drives that are idle
        # iostat will print two reports, the first since boot and the second during the interval
        # The first tail and grep strip off the first useless report. The second tail strips off the header
        # The final grep strips off drives we're not interested in
        iostat -x -z -d $SECONDS 2

        if are_drives_used $SECONDS ; then
        echo "Drives are being used"
        else
        echo "Drives are idle, going to standby"
        spindown
        fi


        collectd metrics



        I tried avoiding that 10-minute block by querying historic usage as recorded by collectd. I used rrdtool fetch to query the metrics stored in /var/db/collectd/rrd/localhost/disk-ada0, but those have a lag of several minutes. Relying on them would mean that the script might standby drives that are actively used if they had been idle recently.



        Testing if drives are spun up



        The following script will report if each drive is idle or spinning. Useful for testing.



        is_spinning.sh:



        #!/bin/sh

        camcontrol devlist | grep ada | awk -F( 'print $2' | awk -F",|\\)" 'print $2' |while read LINE
        do
        CM=$(camcontrol cmd $LINE -a "E5 00 00 00 00 00 00 00 00 00 00 00" -r - | awk 'print $10')
        if [ "$CM" = "FF" ] ; then
        echo "$LINE: SPINNING"
        elif [ "$CM" = "00" ] ; then
        echo "$LINE: IDLE"
        else
        echo "$LINE: UNKNOWN"
        fi
        done


        Based on this forum post.






        share|improve this answer















        I ended up doing this very manually. Write a script that checks for drive activity, spins down drives if there is none, then schedule this script as a cron job.



        I settled on an approach that uses iostat to monitor drives for a set period of time, in my case 600 seconds (10 minutes). If iostat reports no usage, call ataidle -s /dev/ada[0123] to suspend the drives. I setup a cron job to call this script every 15 minutes: */15 * * * * spindown_if_idle.sh 600



        spindown_if_idle.sh:



        #!/bin/bash

        # argument is the number of seconds to test for drive use, default to 5
        if [ -z "$1" ]; then
        SECONDS=5
        else
        SECONDS="$1"
        fi

        function list_ada_drives
        # emit a list of hard drives, i.e. ada0 ada1 ada2 ...
        iostat -x

        function spindown
        # for every hard drive use ataidle to place it in standby
        for ADA in $(list_ada_drives); do
        ataidle -s /dev/$ADA
        done


        function are_drives_used
        # argument is number of seconds to test over

        # run iostat for the specified number of seconds and ask to report any usage
        # -z means to omit any drives that are idle
        # iostat will print two reports, the first since boot and the second during the interval
        # The first tail and grep strip off the first useless report. The second tail strips off the header
        # The final grep strips off drives we're not interested in
        iostat -x -z -d $SECONDS 2

        if are_drives_used $SECONDS ; then
        echo "Drives are being used"
        else
        echo "Drives are idle, going to standby"
        spindown
        fi


        collectd metrics



        I tried avoiding that 10-minute block by querying historic usage as recorded by collectd. I used rrdtool fetch to query the metrics stored in /var/db/collectd/rrd/localhost/disk-ada0, but those have a lag of several minutes. Relying on them would mean that the script might standby drives that are actively used if they had been idle recently.



        Testing if drives are spun up



        The following script will report if each drive is idle or spinning. Useful for testing.



        is_spinning.sh:



        #!/bin/sh

        camcontrol devlist | grep ada | awk -F( 'print $2' | awk -F",|\\)" 'print $2' |while read LINE
        do
        CM=$(camcontrol cmd $LINE -a "E5 00 00 00 00 00 00 00 00 00 00 00" -r - | awk 'print $10')
        if [ "$CM" = "FF" ] ; then
        echo "$LINE: SPINNING"
        elif [ "$CM" = "00" ] ; then
        echo "$LINE: IDLE"
        else
        echo "$LINE: UNKNOWN"
        fi
        done


        Based on this forum post.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited May 29 at 4:09

























        answered May 29 at 4:01









        AdamAdam

        1655




        1655























            1














            Thanks for this idea. I had been struggling with this problem for a few days. As I am not used to write bash scripts I rewrote it in python3. Maybe somebody finds it useful:



            import subprocess
            import time

            drives_to_check = ['ada3', 'ada4', 'ada5']
            no_sleep_hours = ['00', '01']
            seconds = 600

            if time.strftime("%H") in no_sleep_hours:
            exit()

            o = subprocess.check_output(f'/usr/sbin/iostat -x -z -d seconds 2', shell=True)

            for drive in drives_to_check:
            if drive not in o.decode().split('extended')[-1]:
            p = subprocess.check_output(f'/sbin/camcontrol cmd drive -a "E5 00 00 00 00 00 00 00 00 00 00 00" -r -', shell=True)
            if p.decode()[27:29] != '00':
            q = subprocess.check_output(f'/usr/local/sbin/ataidle -s /dev/drive', shell=True)


            My small add-ons were: you can add hours to no_sleep_hours when you don't want the script to run. And you have to add the drives you want to check to "drives_to_check" so you can exclude drives that should not do a spindown.
            Maybe you would have to adjust the paths for iostat and ataidle, these are the paths used in FreeNAS. You can find your paths with: which adaidle or which iostat.
            You can add it to cron with
            */15 * * * * /usr/local/bin/python3 /path/to/the/folder/check_disk_usage_and_spindown.py






            share|improve this answer








            New contributor



            pelipro is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.



















            • nice script! It sure is easier to parse output in Python than it is in Bash. I'd suggest adding some comments to your script, though, both for yourself and for others trying to learn from you. Your script largely does the same thing as mine, but there are some important differences. In some ways yours is better, but a few strategic comments can point out what your script does so someone who hasn't been knee deep in these commands can notice and modify the script to their system and/or needs.

              – Adam
              1 hour ago















            1














            Thanks for this idea. I had been struggling with this problem for a few days. As I am not used to write bash scripts I rewrote it in python3. Maybe somebody finds it useful:



            import subprocess
            import time

            drives_to_check = ['ada3', 'ada4', 'ada5']
            no_sleep_hours = ['00', '01']
            seconds = 600

            if time.strftime("%H") in no_sleep_hours:
            exit()

            o = subprocess.check_output(f'/usr/sbin/iostat -x -z -d seconds 2', shell=True)

            for drive in drives_to_check:
            if drive not in o.decode().split('extended')[-1]:
            p = subprocess.check_output(f'/sbin/camcontrol cmd drive -a "E5 00 00 00 00 00 00 00 00 00 00 00" -r -', shell=True)
            if p.decode()[27:29] != '00':
            q = subprocess.check_output(f'/usr/local/sbin/ataidle -s /dev/drive', shell=True)


            My small add-ons were: you can add hours to no_sleep_hours when you don't want the script to run. And you have to add the drives you want to check to "drives_to_check" so you can exclude drives that should not do a spindown.
            Maybe you would have to adjust the paths for iostat and ataidle, these are the paths used in FreeNAS. You can find your paths with: which adaidle or which iostat.
            You can add it to cron with
            */15 * * * * /usr/local/bin/python3 /path/to/the/folder/check_disk_usage_and_spindown.py






            share|improve this answer








            New contributor



            pelipro is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.



















            • nice script! It sure is easier to parse output in Python than it is in Bash. I'd suggest adding some comments to your script, though, both for yourself and for others trying to learn from you. Your script largely does the same thing as mine, but there are some important differences. In some ways yours is better, but a few strategic comments can point out what your script does so someone who hasn't been knee deep in these commands can notice and modify the script to their system and/or needs.

              – Adam
              1 hour ago













            1












            1








            1







            Thanks for this idea. I had been struggling with this problem for a few days. As I am not used to write bash scripts I rewrote it in python3. Maybe somebody finds it useful:



            import subprocess
            import time

            drives_to_check = ['ada3', 'ada4', 'ada5']
            no_sleep_hours = ['00', '01']
            seconds = 600

            if time.strftime("%H") in no_sleep_hours:
            exit()

            o = subprocess.check_output(f'/usr/sbin/iostat -x -z -d seconds 2', shell=True)

            for drive in drives_to_check:
            if drive not in o.decode().split('extended')[-1]:
            p = subprocess.check_output(f'/sbin/camcontrol cmd drive -a "E5 00 00 00 00 00 00 00 00 00 00 00" -r -', shell=True)
            if p.decode()[27:29] != '00':
            q = subprocess.check_output(f'/usr/local/sbin/ataidle -s /dev/drive', shell=True)


            My small add-ons were: you can add hours to no_sleep_hours when you don't want the script to run. And you have to add the drives you want to check to "drives_to_check" so you can exclude drives that should not do a spindown.
            Maybe you would have to adjust the paths for iostat and ataidle, these are the paths used in FreeNAS. You can find your paths with: which adaidle or which iostat.
            You can add it to cron with
            */15 * * * * /usr/local/bin/python3 /path/to/the/folder/check_disk_usage_and_spindown.py






            share|improve this answer








            New contributor



            pelipro is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.









            Thanks for this idea. I had been struggling with this problem for a few days. As I am not used to write bash scripts I rewrote it in python3. Maybe somebody finds it useful:



            import subprocess
            import time

            drives_to_check = ['ada3', 'ada4', 'ada5']
            no_sleep_hours = ['00', '01']
            seconds = 600

            if time.strftime("%H") in no_sleep_hours:
            exit()

            o = subprocess.check_output(f'/usr/sbin/iostat -x -z -d seconds 2', shell=True)

            for drive in drives_to_check:
            if drive not in o.decode().split('extended')[-1]:
            p = subprocess.check_output(f'/sbin/camcontrol cmd drive -a "E5 00 00 00 00 00 00 00 00 00 00 00" -r -', shell=True)
            if p.decode()[27:29] != '00':
            q = subprocess.check_output(f'/usr/local/sbin/ataidle -s /dev/drive', shell=True)


            My small add-ons were: you can add hours to no_sleep_hours when you don't want the script to run. And you have to add the drives you want to check to "drives_to_check" so you can exclude drives that should not do a spindown.
            Maybe you would have to adjust the paths for iostat and ataidle, these are the paths used in FreeNAS. You can find your paths with: which adaidle or which iostat.
            You can add it to cron with
            */15 * * * * /usr/local/bin/python3 /path/to/the/folder/check_disk_usage_and_spindown.py







            share|improve this answer








            New contributor



            pelipro is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.








            share|improve this answer



            share|improve this answer






            New contributor



            pelipro is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.








            answered 5 hours ago









            pelipropelipro

            111




            111




            New contributor



            pelipro is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.




            New contributor




            pelipro is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.














            • nice script! It sure is easier to parse output in Python than it is in Bash. I'd suggest adding some comments to your script, though, both for yourself and for others trying to learn from you. Your script largely does the same thing as mine, but there are some important differences. In some ways yours is better, but a few strategic comments can point out what your script does so someone who hasn't been knee deep in these commands can notice and modify the script to their system and/or needs.

              – Adam
              1 hour ago

















            • nice script! It sure is easier to parse output in Python than it is in Bash. I'd suggest adding some comments to your script, though, both for yourself and for others trying to learn from you. Your script largely does the same thing as mine, but there are some important differences. In some ways yours is better, but a few strategic comments can point out what your script does so someone who hasn't been knee deep in these commands can notice and modify the script to their system and/or needs.

              – Adam
              1 hour ago
















            nice script! It sure is easier to parse output in Python than it is in Bash. I'd suggest adding some comments to your script, though, both for yourself and for others trying to learn from you. Your script largely does the same thing as mine, but there are some important differences. In some ways yours is better, but a few strategic comments can point out what your script does so someone who hasn't been knee deep in these commands can notice and modify the script to their system and/or needs.

            – Adam
            1 hour ago





            nice script! It sure is easier to parse output in Python than it is in Bash. I'd suggest adding some comments to your script, though, both for yourself and for others trying to learn from you. Your script largely does the same thing as mine, but there are some important differences. In some ways yours is better, but a few strategic comments can point out what your script does so someone who hasn't been knee deep in these commands can notice and modify the script to their system and/or needs.

            – Adam
            1 hour ago

















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Server Fault!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fserverfault.com%2fquestions%2f968303%2fhow-to-make-hard-drive-standby-spin-down-on-a-timer%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Club Baloncesto Breogán Índice Historia | Pavillón | Nome | O Breogán na cultura popular | Xogadores | Adestradores | Presidentes | Palmarés | Historial | Líderes | Notas | Véxase tamén | Menú de navegacióncbbreogan.galCadroGuía oficial da ACB 2009-10, páxina 201Guía oficial ACB 1992, páxina 183. Editorial DB.É de 6.500 espectadores sentados axeitándose á última normativa"Estudiantes Junior, entre as mellores canteiras"o orixinalHemeroteca El Mundo Deportivo, 16 setembro de 1970, páxina 12Historia do BreogánAlfredo Pérez, o último canoneiroHistoria C.B. BreogánHemeroteca de El Mundo DeportivoJimmy Wright, norteamericano do Breogán deixará Lugo por ameazas de morteResultados de Breogán en 1986-87Resultados de Breogán en 1990-91Ficha de Velimir Perasović en acb.comResultados de Breogán en 1994-95Breogán arrasa al Barça. "El Mundo Deportivo", 27 de setembro de 1999, páxina 58CB Breogán - FC BarcelonaA FEB invita a participar nunha nova Liga EuropeaCharlie Bell na prensa estatalMáximos anotadores 2005Tempada 2005-06 : Tódolos Xogadores da Xornada""Non quero pensar nunha man negra, mais pregúntome que está a pasar""o orixinalRaúl López, orgulloso dos xogadores, presume da boa saúde económica do BreogánJulio González confirma que cesa como presidente del BreogánHomenaxe a Lisardo GómezA tempada do rexurdimento celesteEntrevista a Lisardo GómezEl COB dinamita el Pazo para forzar el quinto (69-73)Cafés Candelas, patrocinador del CB Breogán"Suso Lázare, novo presidente do Breogán"o orixinalCafés Candelas Breogán firma el mayor triunfo de la historiaEl Breogán realizará 17 homenajes por su cincuenta aniversario"O Breogán honra ao seu fundador e primeiro presidente"o orixinalMiguel Giao recibiu a homenaxe do PazoHomenaxe aos primeiros gladiadores celestesO home que nos amosa como ver o Breo co corazónTita Franco será homenaxeada polos #50anosdeBreoJulio Vila recibirá unha homenaxe in memoriam polos #50anosdeBreo"O Breogán homenaxeará aos seus aboados máis veteráns"Pechada ovación a «Capi» Sanmartín e Ricardo «Corazón de González»Homenaxe por décadas de informaciónPaco García volve ao Pazo con motivo do 50 aniversario"Resultados y clasificaciones""O Cafés Candelas Breogán, campión da Copa Princesa""O Cafés Candelas Breogán, equipo ACB"C.B. Breogán"Proxecto social"o orixinal"Centros asociados"o orixinalFicha en imdb.comMario Camus trata la recuperación del amor en 'La vieja música', su última película"Páxina web oficial""Club Baloncesto Breogán""C. B. Breogán S.A.D."eehttp://www.fegaba.com

            Vilaño, A Laracha Índice Patrimonio | Lugares e parroquias | Véxase tamén | Menú de navegación43°14′52″N 8°36′03″O / 43.24775, -8.60070

            Cegueira Índice Epidemioloxía | Deficiencia visual | Tipos de cegueira | Principais causas de cegueira | Tratamento | Técnicas de adaptación e axudas | Vida dos cegos | Primeiros auxilios | Crenzas respecto das persoas cegas | Crenzas das persoas cegas | O neno deficiente visual | Aspectos psicolóxicos da cegueira | Notas | Véxase tamén | Menú de navegación54.054.154.436928256blindnessDicionario da Real Academia GalegaPortal das Palabras"International Standards: Visual Standards — Aspects and Ranges of Vision Loss with Emphasis on Population Surveys.""Visual impairment and blindness""Presentan un plan para previr a cegueira"o orixinalACCDV Associació Catalana de Cecs i Disminuïts Visuals - PMFTrachoma"Effect of gene therapy on visual function in Leber's congenital amaurosis"1844137110.1056/NEJMoa0802268Cans guía - os mellores amigos dos cegosArquivadoEscola de cans guía para cegos en Mortágua, PortugalArquivado"Tecnología para ciegos y deficientes visuales. Recopilación de recursos gratuitos en la Red""Colorino""‘COL.diesis’, escuchar los sonidos del color""COL.diesis: Transforming Colour into Melody and Implementing the Result in a Colour Sensor Device"o orixinal"Sistema de desarrollo de sinestesia color-sonido para invidentes utilizando un protocolo de audio""Enseñanza táctil - geometría y color. Juegos didácticos para niños ciegos y videntes""Sistema Constanz"L'ocupació laboral dels cecs a l'Estat espanyol està pràcticament equiparada a la de les persones amb visió, entrevista amb Pedro ZuritaONCE (Organización Nacional de Cegos de España)Prevención da cegueiraDescrición de deficiencias visuais (Disc@pnet)Braillín, un boneco atractivo para calquera neno, con ou sen discapacidade, que permite familiarizarse co sistema de escritura e lectura brailleAxudas Técnicas36838ID00897494007150-90057129528256DOID:1432HP:0000618D001766C10.597.751.941.162C97109C0155020