#!/bin/sh

# $Id: choose_ran_file,v 1.54 2009/11/23 22:55:40 zalokar Exp $

#
# Script to return a random file name(s) for tapes in the current inventory.
#  Optionaly, attempt to copy the files from tape using encp (see
#  copy_ran_file).
#

set -u

if [ "${1:-}" = "-x" ] ; then set -xv; shift; fi

if [ "${1:-}" = "-V" ] ; then verbose=1; shift; else verbose=0; fi

if [ "${1:-}" = "-C" ] ; then copyit=1; shift; else copyit=0; fi

if [ "${1:-}" = "-F" ] ; then force_try=1; shift; else force_try=0; fi

#  $1 should be the number of tapes to list/copy.
COUNT=${1:-1}
#  $2 should be one of: "onlylast" or "alsolast" or "onlyfirst" or "alsofirst" 
#                       or "onlyfirstlast" or "alsofirstlast" or "onlyran"
WHICH_FILE=${2:-"onlyran"}

if [ "$ENSTORE_CONFIG_HOST"x == x ]; then
   source /usr/local/etc/setups.sh
   if [ -f $HOME/enstore ]; then
      setup -r `cd $HOME/enstore;pwd` enstore
   else
      setup enstore
   fi
fi

#Verify that all of the pnfs mount points in /etc/fstab are mounted before
# continueing.  If /etc/fstab is missing a new mount point, this check
# will still miss it.
check_pnfs_mounts
if [ $? -gt 0 ]; then
   exit 9
fi

here=`pwd`
override_ro="" #Used to audit the state of the write protect tab.
tmp_dir=/tmp

#Make sure to set a timeout.
timeout="--retries 3 --timeout 30"

#Obtain a list of test libraries to ignore.  (ttl = Test Library List)
## Get the information from the configuration.

tll_raw=`enstore conf $timeout --print crons test_library_list 2> /dev/null`
###   If there is no test_library_list then this will be an error.
###   Comment this check out for now.
##if [ $? -ne 0 ]; then
##    echo "Failed to obtain test library list from configuration." 1>&2
##    exit 1
##fi
##
#Remove the line header contents (before the :), remove any empty lines,
# stick single quotes on either side of each item, replace all newlines
# with commas and lastly remove the last comma.
if [ -z "$tll_raw" ]; then
    tll=""
else
    tll=`echo "$tll_raw" | cut -f 2 -d ":" | egrep -v ^$ | sed -e "s/$/'/" -e "s/^/'/" | tr "\n" "," | sed "s/,$//"`
fi
if [ -z "$tll" ]; then
    skip_library_sql=""
else
    if [ $verbose -eq 1 ]; then
	echo "Skipping libraries:" "$tll"
    fi
    skip_library_sql="and library not in ($tll)"
fi

#Make sure the library exists.  Get the list of configured libraries,
# grab just the first part out the output, remove everything after the period
# leaving just the short library name, stick single quotes on either size
# of each item, replace all newlines with commas and lastly remove the last
# comma.
#vll = Valid Library List
vll_raw=`enstore conf $timeout --list-library`
if [ $? -gt 0 ]; then
   echo "Unable to obtain the list of configured libraries." 2>&1
   exit 1
fi
vll=`echo "$vll_raw" | sed '1d' | awk '{print $1}' | tr "." " " | awk '{print $1}' | sed -e "s/$/'/" -e "s/^/'/" | tr "\n" "," | sed "s/,$//"`


#Get the list of suitable tapes for testing.
###8-16-2007: The 'or' of the system_inhibit_1 values to readonly and full
###           should have a third condition.  If the last_access time is
###           older than three months, allow the tape for consideration.
enstore info $timeout --query \
"select label,library,media_type,wrapper,write_protected
from volume where 
    label not like '%.deleted' and 
    label not like 'CLN%' and 
    label not like '%:%' and
    system_inhibit_0 = 'none' and
    ( system_inhibit_1 = 'readonly' or system_inhibit_1 = 'full' or
      last_access < CURRENT_TIMESTAMP - interval '3 months' ) and
    user_inhibit_0 = 'none' and
    extract('epoch' from last_access) <> -1 and
    media_type <> 'null' and
    library in ($vll) and   --Only consider configured libraries.
    library not like '%shelf%' $skip_library_sql and
    system_inhibit_1 not in ('migrated', 'migrating', 'duplicated',
                             'duplicating', 'cloned', 'cloning')
order by label;" \
    | sed '1,2d' > $tmp_dir/V_D

N=`wc /$tmp_dir/V_D| awk '{print $1}'`

if [ $verbose -eq 1 ]; then
    echo "Found $N suitable tapes."
    cat /$tmp_dir/V_D
fi
   
if [ $N -eq 0 ]; then
   rm /$tmp_dir/V_D
   exit 1
fi

done=$COUNT
loops=0
RC=0

while [ $done -gt 0 ]; do

  cd $here
  loops=`expr $loops + 1`
  if [ $loops -ge 1000 ]; then echo "TOO MANY LOOPS = $loops, EXIT"; 
    rm -f $tmp_dir/V_D;
    exit 1; 
  fi

  # choose a random volume from the list
  ran=`python -c "import random;print random.randint(1,"$N")"`
  tape=`head -n $ran /$tmp_dir/V_D|tail -n 1| awk '{print $1}'`

  # Get up to date information on the tape to make sure we have a chance 
  # to read a file.
  if [ $verbose -eq 1 ]; then
    echo `date` enstore info $timeout --vol $tape
  fi
  tinfo=`enstore info $timeout --vol $tape`
  if [ $? -ne 0 ]; then
    echo "Unable to obtain $tape information." 1>&2
    exit 1
  fi  
  if [ $verbose -eq 1 ]; then
    echo "$tinfo"
  fi
  #Skip the tape if is is marked deleted, not allowed by an administrator
  # or noaccess by the system.
  if [ `echo $tinfo | egrep -c 'DELETED|NOTALLOWED|NOACCESS'` -ne 0 ]; then
    echo REJECTED $tape is DELETED/NOTALLOWED/NOACCESS
    continue
  fi
  #We need to tell encp to tell the mover to load the tape for read-write
  # mode (full or readonly; migrated too???).  This is so that we can audit 
  # the state of the write_protect tab.
  if [ `echo $tinfo | egrep -c "full|readonly|migrated"` -ne 0 ]; then
     override_ro="--override-ro-mount"
  #   echo "override $override"
  fi
  #If the library is not available, pick another one.  Start by pulling
  # out the library name from the volume record.
  library=`echo "$tinfo" | grep library | awk '{print $2}' | tr -d "',"`
  if [ $library = "none" ]; then
    #Skip blank volumes.
    continue
  fi
  #Get the current state of the library.
  raw_lm_status=`enstore library --status $library`
  if [ $? -ne 0 ]; then
    echo "Unable to obtain $library library manager status." 1>&2
    continue
  fi
  lm_status=`echo $raw_lm_status | tr ":" " " | awk '{print $3}' | tr -d "',"`
  #If the state is broken, locked, pause, ignore, noread or moverlock skip it.
  # The expected value is "unlocked", however, allow "nowrite".
  if [ $lm_status != "unlocked" -a $lm_status != "nowrite" ]; then
    echo "Library $library in $lm_status state for volume $tape." 1>&2
    continue
  fi

  #Get a list of all files on the tape.
  enstore info $timeout --list $tape > $tmp_dir/$tape.raw
  if [ $? -ne 0 ]; then
    echo "Unable to obtain $tape content information." 1>&2
    exit 1
  fi
  cat $tmp_dir/$tape.raw | sed '1,2d' > $tmp_dir/$tape
  rm $tmp_dir/$tape.raw

  # make sure this volume is still on the readable list.
  if [ `egrep -c 'DELETED|NOACCESS|NOTALLOWED' /$tmp_dir/$tape` -ne 0 ]; then 
	echo `date` REJECTED $tape is DELETED/NOACCESS/NOTALLOED
	rm -f $tmp_dir/$tape
	continue
  fi

  # get list of known bad file bfid's.
  enstore file --show-bad | grep $tape | cut -f 2 -d " " > $tmp_dir/bad_list
  #Turn this into an egrep compatible filter string.  (be sure to remember
  # to remove the first " | " from the string.
  bad_filter=`for item in $(cat $tmp_dir/bad_list); do echo -n " |" $item; done | cut -c 2-`
  rm $tmp_dir/bad_list

  # Get rid of volume information - we already processed that and don't 
  # need it anymore. Get rid of all files the user already deleted. 
  # We don't want to read these files.  If there aren't any files left, 
  # start over with a new tape.  Ignore hidden files and sort the filelist 
  # according to location on the tape.  Also, skip known bad files.
  if [ -n "$bad_filter" ]; then
    grep /pnfs $tmp_dir/$tape | egrep -v 'deleted|  yes /' | grep active | egrep -v "$bad_filter" | grep -v '\/\.' | sort -k4 > $tmp_dir/${tape}_
  else
      grep /pnfs $tmp_dir/$tape | egrep -v 'deleted|  yes /' | grep active | grep -v '\/\.' | sort -k4 > $tmp_dir/${tape}_
  fi
  rm -f $tmp_dir/$tape
  NF=`wc $tmp_dir/${tape}_| awk '{print $1}'`
  if [ $NF -gt 0 ]; then 
    if [ $verbose -eq 1 ]; then echo `date`: $NF SUITABLE FILES on $tape; fi
  else
    if [ $verbose -eq 1 ]; then echo `date`: NO SUITABLE FILES on $tape; fi
    rm -f $tmp_dir/${tape}_
    continue
  fi

  # Choose a random file and  1st and last non-deleted files on the 
  # random volume
  ran=`python -c "import random;print random.randint(1,"$NF")"`
  file_r=`head -n $ran $tmp_dir/${tape}_ | tail -n 1 | awk '{print $NF,$1,$3,$4,$2}'`
  file_f=`head -n 1 $tmp_dir/${tape}_ | awk '{print $NF,$1,$3,$4,$2}'`
  file_l=`tail -n 1 $tmp_dir/${tape}_ | awk '{print $NF,$1,$3,$4,$2}'`
  rm -f $tmp_dir/${tape}_

  #We are going to need these...
  ran_bfid=`echo $file_r | awk '{print $5}'`
  first_bfid=`echo $file_f | awk '{print $5}'`
  last_bfid=`echo $file_l |awk '{print $5}'`
   
  #...and these...
  raw_ran_pnfsid=`enstore info $timeout --bfid $ran_bfid`
  if [ $? -ne 0 ]; then
    echo "Unable to get file information for $ran_bfid" 1>&2
    exit 1
  fi
  ran_pnfsid=`echo "$raw_ran_pnfsid" | grep pnfsid | cut -c 13-36`
  raw_first_pnfsid=`enstore info $timeout --bfid $first_bfid`
  if [ $? -ne 0 ]; then
    echo "Unable to get file information for $first_bfid" 1>&2
    exit 1
  fi
  first_pnfsid=`echo "$raw_first_pnfsid" | grep pnfsid | cut -c 13-36`
  raw_last_pnfsid=`enstore info $timeout --bfid $last_bfid`
  if [ $? -ne 0 ]; then
    echo "Unable to get file information for $last_bfid" 1>&2
    exit 1
  fi
  last_pnfsid=`echo "$raw_last_pnfsid" | grep pnfsid | cut -c 13-36`

  #...with help from this function...
  check_files()
  {
     #This function takes the second argument through the last argument and
     # finds the file whos bfid matches that of the first argument.  When
     # the match is found, 0 (success) is returned and the matching
     # filename is echo-ed to stdout.
     file_bfid=$1; shift
     file_list=$*

     for filename in `echo "$file_list"`; do
        pnfs_bfid=`enstore pnfs --bfid $filename`
	if [ "$pnfs_bfid" = "$file_bfid" ]; then
	   echo $filename
	   return 0
	fi
    done
    return 1
  }

  #...to get these.
  ran_file=`enstore pnfs --path $ran_pnfsid 2> /dev/null`
  ran_file=`check_files $ran_bfid "$ran_file"`
  rc_r=$?
  first_file=`enstore pnfs --path $first_pnfsid 2> /dev/null`
  first_file=`check_files $first_bfid "$first_file"`
  rc_f=$?
  last_file=`enstore pnfs --path $last_pnfsid 2> /dev/null`
  last_file=`check_files $last_bfid "$last_file"`
  rc_l=$?

  if [ $rc_r -ne 0 -o $rc_f -ne 0 -o $rc_l -ne 0 ]; then
    #One likely reason that this step would fail, is that we have a pnfsid
    # that exists in two different PNFSes.  (i.e. stkensrv1 and cmspnfs1)
    #Another is that we don't have sufficient permissions to access the
    # file in PNFS.
    if [ $verbose -eq 1 ]; then
       echo "Failed finding suitable files."
    fi
    #These are useful for debugging.
    #  echo $rc_r $ran_bfid $ran_pnfsid $ran_file 
    #  echo $rc_f $first_bfid $first_pnfsid $first_file
    #  echo $rc_l $last_bfid $last_pnfsid $last_file
    continue
  fi

  # Make a list of what the user wants.  Valid values are:
  #  "onlylast" or "alsolast" or "onlyfirst" or "alsofirst" 
  #  or "onlyfirstlast" or "alsofirstlast" or "onlyran"
  case $WHICH_FILE in
    onlyran)       thefiles=$ran_file; thebfids=$ran_bfid;;
    onlyfirst)     thefiles=$first_file; thebfids=$first_bfid;;
    onlylast)      thefiles=$last_file; thebfids=$last_bfid;;
    onlyfirstlast) thefiles="$first_file $last_file"; thebfids="$first_bfid $last_bfid";;
    alsofirst)     thefiles="$ran_file $first_file"; thebfids="$ran_bfid $first_bfid";;
    alsolast)      thefiles="$ran_file $last_file"; thebfids="$ran_bfid $last_bfid";;
    alsofirstlast) thefiles="$ran_file $first_file $last_file"; thebfids="$ran_bfid $first_bfid $last_bfid";;
    *)             thefiles=$ran_file; thebfids=$ran_bfid;;
  esac

  # ok, just tell the user the name of the file and do another if needed
  # or copy the file to /dev/null if user requested this
  if [ $copyit -eq 0 ]; then
    echo $thefiles
  else
    echo
    echo Random volume = $tape 
    echo Random file = $file_r
    echo First  file = $file_f
    echo Last   file = $file_l
    echo 

    #Obtain the library that this tape belongs too.
    raw_library=`enstore info $timeout --vol $tape`
    if [ $? -ne 0 ]; then
        echo "Unable to obtain information about $tape." 1>&1
        exit 1
    fi
    library=`echo "$raw_library" | grep library | cut -d' ' -f3`
    library=`echo $library | tr ",'" "  " | sed "s/ //g"`

    #Verify that there is a library manager for this library.
    raw_is_lib_known=`enstore conf $timeout --list-library-manager`
    if [ $? -ne 0 ]; then
        echo "Unable to obtain the list of libraries." 1>&2
        exit 1
    fi
    is_lib_known=`echo "$raw_is_lib_known" | grep $library | wc -l`
    if [ "$is_lib_known" -eq 0 ]; then
        echo "Unable to find ${library}.library_manager." 1>&2
	echo
        #Update the return value and the number of volumes done count.
        RC=`expr $RC + 1`
        done=`expr $done - 1`
        continue
    fi

    #List the number of active volumes.  This will give more meaningful
    # output for the administrators.
    cmd="enstore lib $timeout --vols $library"
    echo $cmd
    vols_at_movers=`eval $cmd`
    if [ $? -ne 0 ]; then
	echo "Unable to determine busy drives for ${library}.library_manager." 1>&2
	echo
        continue
    fi
    
    echo "$vols_at_movers"
    #If the system is busy, don't start encp.
    busy_movers=`echo "$vols_at_movers" | wc -l`
    #Subract the title line of output.
    busy_movers=`expr $busy_movers - 1`

    #Determine the number of total drives for this library.
    cmd2="enstore mov $timeout --list"
    echo $cmd2
    raw_configured_movers=`eval $cmd2`
    if [ $? -ne 0 ]; then
        echo "Unable to obtain the list of movers for library ${library}." 1>&2
        exit 1
    fi
    configured_movers=`echo "$raw_configured_movers" | grep ${library}.library_manager`
    #Now count the number of lines. (Ignore empty lines.)
    total_movers=`echo "$configured_movers" | egrep -v "^$" | wc -l`

    down_movers=0
    #Obtain the list of down movers.  Remove headers and empty lines.
    raw_servers_down=`enstore sched $timeout --show`
    if [ $? -ne 0 ]; then
        echo "Unable to obtain schedule information." 2>&1
	exit 1
    fi
    servers_down=`echoe "$raw_servers_down" | egrep -v " Enstore | -----|^$"`
    #Pull out just the server names.
    echo "$servers_down" | awk '{print $1}' > /tmp/copy_ran_file_servers_down
    #Loop over the configured movers looking for a match to a down mover.
    for mover_line in "$configured_movers"; do
	mover_name=`echo $mover_line | awk '{print $1'}`
        if [ -z "$mover_name" ]; then
            continue
        fi
	grep $mover_name /tmp/copy_ran_file_servers_down > /dev/null
	if [ $? -eq 0 ]; then
            #If the grep returns success (0), increase the down movers
            # count by one.
            down_movers=`expr $down_movers + 1`
        fi
    done
    #Determine the number of drives available right now.
    online_movers=`expr $total_movers - $down_movers`

    #There needs to be at least one mover up for this library.
    if [ $online_movers -le 0 ]; then
	echo "Unable to find available movers for ${library}.library_manager." 1>&2
	echo
	continue
    fi

    #This test should compare this number to the number of drives in the
    # library.  I don't know of a good way from bash to get the number of
    # drives in a library, so for now using the value 6.  If -F was specified
    # on the command line (force_try = 1), we will force choose_ran_file to 
    # skip this test and force it to run the encp(s).
    mover_threshold=`expr $online_movers - 1` #Leave one idle.
    if [ $busy_movers -gt $mover_threshold -a $force_try -eq 0 ]; then
        echo
	#Report the number of drives that are busy and those that exist.
	echo "Busy Drives: $busy_movers  Total Drives: $total_movers  Down Drives: $down_movers  Online Drives: $online_movers"
	echo
	echo "Aborting early from high mover usage."
	echo
	#5 seems like a good number. Its greater than 3 indicating 3 failures.
	# It is not -1, -2, 0, 10 or 7 which have special meaning in the plots.
	#9-10-2002: Edited to return 0 instead of 5.  Emails were being 
	# generated that make this the simpliest solution.
	exit 0
    fi

    #for f in $thefiles; do
    #  cmd="encp --verbose 10 --bypass-filesystem-max-filesize-check --max-resubmit 7 --delayed-dismount 1 $override_ro $f /dev/null"
    #  echo $cmd
    #  eval $cmd
    #  rc=$?
    #  RC=`expr $RC + $rc`
    #done
    for b in $thebfids; do
      cmd="encp --verbose 10 --bypass-filesystem-max-filesize-check --max-resubmit 7 --delayed-dismount 1 $override_ro --get-bfid $b /dev/null"
      echo $cmd
      eval $cmd
      rc=$?
      RC=`expr $RC + $rc`
    done
  fi
  done=`expr $done - 1`
done

rm -f $tmp_dir/V_D
cd $here

if [ $verbose -eq 1 -a $copyit -eq 1 ]; then
  echo "The combined exit code for all encps executed is $RC."
elif [ $verbose -eq 1 ]; then
  echo "The exit code is $RC."
fi
exit $RC
