github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/build/bootstrap/autoshutdown.cron.sh (about)

     1  #!/usr/bin/env bash
     2  
     3  # This script is intended to be called periodical. If it doesn't detect remote
     4  # sessions in a given number of consecutive runs, a shutdown is initiated.
     5  #
     6  # To disable auto-shutdown: `sudo touch /.active`
     7  
     8  set -euxo pipefail
     9  
    10  if [ -z "${1-}" ]; then
    11    echo "Usage: $0 <num_periods> [shutdown command...]"
    12    exit 1
    13  fi
    14  
    15  MAX_COUNT="$1"
    16  shift
    17  
    18  if ! [ "$MAX_COUNT" -gt 0 -a "$MAX_COUNT" -lt 10000 ]; then
    19    echo "Invalid argument '$MAX_COUNT'"
    20    exit 1
    21  fi
    22  
    23  # We maintain the count of how many consecutive iterations of this script did
    24  # NOT detect a remote session. Once we exceed MAX_COUNT, we shut down.
    25  # We use /dev/shm which is not persistent over reboots.
    26  FILE=/dev/shm/autoshutdown-count
    27  COUNT=0
    28  
    29  
    30  if [ -f /.active ] || w -hs | grep pts | grep -vq "pts/[0-9]* *tmux" || pgrep unison; then
    31    # Auto-shutdown is disabled (via /.active) or there is a remote session.
    32    echo 0 > $FILE
    33    exit 0
    34  fi
    35  
    36  if [ -f $FILE ]; then
    37    COUNT=$(cat $FILE)
    38  fi
    39  
    40  COUNT=$((COUNT+1))
    41  
    42  if [ $COUNT -le $MAX_COUNT ]; then
    43    echo $COUNT > $FILE
    44    exit 0
    45  fi
    46  
    47  # Shut down.
    48  
    49  if [ -z "${1-}" ]; then
    50    /sbin/shutdown -h
    51  else
    52    # Run whatever command was passed on the command line.
    53    $@
    54  fi