#! /bin/sh

# $Id: pnfs_monitor,v 1.10 2008/04/21 19:53:07 zalokar Exp $

# Report on files in pnfs that have not yet been written to tape.  This script
# does handle volitile dcache files and zero length dcache files.

#Make sure to set a timeout.
timeout='--timeout 10 --retries 3'
file_fallback='--file-fallback' #Set this for SDE.

get_recent_pnfsids()
{
    db_name=$1
    fname=/tmp/recent_pnfids_${db_name}

    sql_txt="SELECT date,encode(pnfsid,'hex') as pnfsid from pnfs where date > CURRENT_TIMESTAMP - interval '49 hours' and date < CURRENT_TIMESTAMP - interval '24 hours';"

    psql -ae -o $fname $db_name -U enstore -c "$sql_txt" > /dev/null
    if [ $? -ne 0 ]; then
       echo "psql command failed" 1>&2
       exit 1
    fi
}


get_pnfs_dbs()
{
    pnfs_location=`egrep "^pnfs=" /usr/etc/pnfsSetup | cut -f 2 -d "="`
    if [ -z "$pnfs_location" ]; then
	echo "Unable to find pnfs installation." 1>&2
	exit 1
    fi
    mdb=$pnfs_location/tools/mdb
    if [ ! -f $mdb ]; then
	echo "Unable to find mdb command." 1>&2
	exit 1
    fi


    $mdb status | sed '1,2d' | awk '{print $2}' | egrep -v 'admin'
}

parse_id()
{
    pnfsid=$1

    #At this point the pnfsid looks like:
    #   0100000000000000b0a90000
    # when it should look like:
    #   00010000000000000000A9B0
    # These swaps re-order the bytes:
    #   01 00    00 00    00 00    00 00    b0 a9 00 00
    #     
    #   00 01    00 00    00 00    00 00    00 00 a9 b0
    # The first four groups are believed to swap the same way as the
    # database number (a.k.a. the first grouping of four bytes).
    #
    # Re-running this function on the swapped data, will result in the
    # original version of the pnfs id.

    #Insert spaces every two characters to aid in the swapping of
    # the chunks of pnfsid.
    pnfsid=`echo $pnfsid | sed 's/../& /g'`

    #Swap the db number.
    pnfsid=`echo $pnfsid | awk ' { temp=$2;$2=$1;$1=temp; print $0 } '`
    #Do more swaps.  #Is this entirely correct?
    pnfsid=`echo $pnfsid | awk ' { temp=$4;$4=$3;$3=temp; print $0 } '`
    pnfsid=`echo $pnfsid | awk ' { temp=$6;$6=$5;$5=temp; print $0 } '`
    pnfsid=`echo $pnfsid | awk ' { temp=$8;$8=$7;$7=temp; print $0 } '`
    #The last two sections are interweaved with each other.
    pnfsid=`echo $pnfsid | awk ' { temp=$9;$9=$12;$12=temp; print $0 } '`
    pnfsid=`echo $pnfsid | awk ' { temp=$10;$10=$11;$11=temp; print $0 } '`

    #Remove the spaces added for swapping.
    pnfsid=`echo $pnfsid | tr -d " "`

    echo $pnfsid
}

is_reg_file()
{
    dbname=$1
    pnfsid=$2

    #Get the showid path for the current pnfsid.
    fname_showid="/pnfs/fs/usr/$db_name/.(showid)(${pnfsid})"

    grep "Regular ( Inode )" $fname_showid > /dev/null 2>&1
    if [ $? -ne 0 ]; then
	#Not the type we are looking for.
	return 1
    fi
    
    return 0
}

get_l1_status()
{
    dbname=$1
    pnfsid=$2

    fname_l1="/pnfs/fs/usr/$db_name/.(access)(${pnfsid})(1)"
    L1=`cat "$fname_l1"`
    if [ `echo "$L1" | wc -c` -gt 1 ]; then
	echo y
	return 1
    else
	echo n
	return 0
    fi
}

get_l2_status()
{
    dbname=$1
    pnfsid=$2

    fname_l2="/pnfs/fs/usr/$db_name/.(access)(${pnfsid})(2)"
    L2=`cat "$fname_l2"`
    if [ `echo "$L2" | wc -l` -ge 2 ]; then
	echo y
	return 1
    else
	echo n
	return 0
    fi
}

get_l4_status()
{
    dbname=$1
    pnfsid=$2

    fname_l4="/pnfs/fs/usr/$db_name/.(access)(${pnfsid})(4)"
    L4=`cat "$fname_l4"`
    if [ `echo "$L4" | wc -l` -ge 8 ]; then
	echo y
	return 1
    else
	echo n
	return 0
    fi
}

get_hsm_status()
{
    dbname=$1
    pnfsid=$2

    fname_l2="/pnfs/fs/usr/$db_name/.(access)(${pnfsid})(2)"
    L2=`cat "$fname_l2"`
    if [ `echo "$L2" | wc -l` -ge 2 ]; then
	echo "$L2" | grep "h=yes" > /dev/null 2>&1 
	if [ $? -eq 0 ]; then
	    echo y
	    return 1
	fi
	echo n
	return 0
    else
	#If the layer is empty, assume that it should go to tape.
	echo y
	return 1
    fi
}

get_filesize()
{
    dbname=$1
    pnfsid=$2

    fname="/pnfs/fs/usr/$db_name/.(access)(${pnfsid})"
    size=`ls -l $fname | awk '{print $5}'`
    if [ $? -ne 0 ]; then
	echo -1
	return 1
    else
	#If the layer is empty, assume that it should go to tape.
	echo $size
	return 0
    fi
}

get_L2_filesize()
{
    dbname=$1
    pnfsid=$2

    fname="/pnfs/fs/usr/$db_name/.(access)(${pnfsid})"
    #size=`ls -l $fname | awk '{print $5}'`
    l2_fname="${fname}(2)"
    size=`cat $l2_fname | sed -n '2p' | sed 's/.*\(l=[0-9]*\).*/\1/' | cut -c 3- | tr -d ' \t\n'`
    if [ $? -ne 0 ]; then
	echo -1
	return 1
    else
	#If the layer is empty, assume that it should go to tape.
	echo $size
	return 0
    fi
}

get_filepath()
{
    which pathfinder > /dev/null 2>&1
    if [ $? -eq 0 ]; then
	path=`pathfinder $pnfsid`
	if [ $? -ne 0 ]; then
	    path=""
	else
	    #Success.  Now munge the data a little.
	    path=`echo "$path" | tail -n 1 | sed 's/root/pnfs/'`
	fi
    else
	path=""
    fi
    echo $path
}

#Uses $TEMP_OUTPUT_FILE and $TEMP_OUTPUT_FILE_2 to send the outputs to the
# correct locations.
check_pnfsids()
{
    TEMP_FILE=$1
    header_name=$2

    header_outputed=0 #Start with this false.  This will be set to 1 if
                      # a problem files is found (and the header is outputed).

    cat $TEMP_FILE |
    while read line; do
	if [ -z "$line" ]; then
	    #Skip empty lines.
	    continue
	fi

	#Seperate the time and pnfsid.  Remove leading and trailing whitespace.
	timestamp=`echo $line | cut -f 1 -d"|" | sed -e 's/^ //' -e 's/ $//'`
	pnfsid=`echo $line | cut -f 2 -d"|" | sed -e 's/^ //' -e 's/ $//'`

	if [ -z "$timestamp" -o -z "$pnfsid" ]; then
	    continue
	fi

	#Parse the pnfsid into the form we are used to.
	pnfsid=`parse_id $pnfsid`
	#echo "Working on pnfsid:" $pnfsid

	#Check if this is the correct type of file.
	is_reg_file $db_name $pnfsid
	if [ $? -ne 0 ]; then
	    #Not the type we are looking for.
	    continue
	fi

	#Get the status of the layers.
	L1_status=`get_l1_status $db_name $pnfsid`
	L4_status=`get_l4_status $db_name $pnfsid`

	#
	#Skip to next file if this file is already on tape.
	#
	if [ $L1_status = 'y' -a $L4_status = 'y' ]; then
	    #File is already on tape.
	    continue
	fi

	#Get the status of the layer 2.
	L2_status=`get_l2_status $db_name $pnfsid`
	#Get the likely status of the file going to tape or not.  'y'
	# if going to tape, 'n' if staying in disk cache.
	hsm_status=`get_hsm_status $db_name $pnfsid`

	#
	#Skip to next file if this file is not to be written to tape.
	#
	if [ $L2_status = 'y' -a ! $hsm_status = 'y' ]; then
	    #This is a file that is not going to be written to tape.
	    continue
	fi

	#Get the file size.
	filesize=`get_filesize $db_name $pnfsid`
	l2_filesize=`get_L2_filesize $db_name $pnfsid`

	#
	#Skip to next file if this file is likely not to be written to tape.
	#
	if [ $L2_status = 'y' -a -n "$l2_filesize" ]; then
	    if [ "$l2_filesize" -eq 0 ]; then
		#This is a file that may not be going to be written to tape.
		continue
	    fi
	fi

	#Get the file path.
	path=`get_filepath $db_name $pnfsid`
	
	#
	#Skip to next file if this file is a temporary nfs file.
	#
	if [ `basename "$path" | cut -c 1-4` = ".nfs" -a $filesize -eq 0 ]; then
	    continue
	fi

	if [ $header_outputed -eq 0 ]; then
            echo "$2 PNFS Database $db_name files:" >> $TEMP_OUTPUT_FILE
	    printf " %-26s | %24s | %6s | %6s | %6s | %s\n" timestamp pnfsid layer1 layer2 layer4 path >> $TEMP_OUTPUT_FILE
            header_outputed=1  #Don't output this again for this DB category.
	fi

	printf " %-26s | %24s | %6s | %6s | %6s | %s\n" "$timestamp" $pnfsid $L1_status $L2_status $L4_status $path >> $TEMP_OUTPUT_FILE

	#Echo a space (echo inserts one between the quotes and $line), to
	# the beginning to have the same file format as originally.  The
	# shell eats the leading space up.
	echo "" $line >> $TEMP_OUTPUT_FILE_2
	
    done

    if [ `wc -l $TEMP_OUTPUT_FILE_2 | awk '{print $1}'` -gt 1 ]; then
        #Add whitespace between databases.
        echo -e "\n\n" >> $TEMP_OUTPUT_FILE
    fi
}

############################################################################

if [ ! -d "/pnfs/fs/usr"  ]; then
    echo "Directory /pnfs/fs/usr was not found." 1>&2
    exit 1
fi

if [ `id -u` -ne 0 ]; then
    echo "Must be user root." 1>&2
    exit 1
fi

cd /pnfs/fs/usr #So, pathfinder works.
if [ $? -ne 0 ]; then
    echo "Failed to cd to /pnfs/fs/usr." 1>&2
    exit 1
fi

#Get the alias name if available.  Optional in config.
www_alias=`enstore conf $timeout $file_fallback --show crons www_alias`
if [ $? -ne 0 -o -z "$www_alias" ]; then
   www_alias=`hostname | cut -f 1 -d "."`
   #If the alias wasn't available, go with the hostname.
   if [ -z "$www_alias" ]; then
      www_alias=`hostanme | cut -f 1 -d "."`
   fi
fi

#Verify that we can find pnfs.
if [ ! -f /usr/etc/pnfsSetup ]; then
   echo "Unable to find /usr/etc/pnfsSetup file." 1>&2
   exit 1
fi
trash_location=`egrep "^trash=" /usr/etc/pnfsSetup | cut -f 2 -d "="`
if [ -z "$trash_location" ]; then
   echo "Unable to find pnfs installation." 1>&2
   exit 1
fi
#Make the pnfs_monitor directory, where the previous found errors are kept,
# a peer of trash.
REMEMBER_OUTPUT_DIR=`dirname $trash_location`/pnfs_monitor

#Specify where the temporary information should go.
mkdir -p $REMEMBER_OUTPUT_DIR
TEMP_OUTPUT_FILE=/tmp/${www_alias}_pnfs_monitor      #copied to web server
TEMP_OUTPUT_FILE_2=/tmp/pnfs_monitor_2  #copied to $REMEMBER_OUTPUT_DIR/
rm -f $TEMP_OUTPUT_FILE
#Make sure we know how up-to-date this is.
echo -e "Missing files in pnfs report:" `date` >> $TEMP_OUTPUT_FILE 2>&1
echo -e Brought to You by: `basename $0` "\n" >> $TEMP_OUTPUT_FILE 2>&1
TEMP_FILE_OLD=/tmp/pm_temp_old
TEMP_FILE_NEW=/tmp/pm_temp_new

#Obtain the directory to write the output.
html_dir=`enstore conf $timeout $file_fallback --show crons html_dir`
if [ $? -ne 0 -o -z "$html_dir" ]; then
    echo HTML directory $html_dir not found.
    exit 1
fi

#Obtain the node to copy the output to.
web_node=`enstore conf $timeout $file_fallback --show crons web_node`
if [ $? -ne 0 -o -z "$web_node" ]; then
    echo Web hostname $web_node not found.
    exit 1
fi

#
# Loop over the all of the pnfs databases (excluding admin).
#
db_list=`get_pnfs_dbs | sort`
for db_name in `echo $db_list`; do

    #Put the recent pnfsids in the /tmp/recent_pnfids_${db_name} file.
    get_recent_pnfsids $db_name
    #The output is in /tmp/recent_pnfids_${db_name}.  #Remove the 2 header
    # lines for this step, the row total line and any empty lines.
    cat /tmp/recent_pnfids_${db_name} | sed '1,2d' | grep -v " rows" | sed '/^$/d' > $TEMP_FILE_NEW
    new_count=`wc -l $TEMP_FILE_NEW | awk {'print $1}'`
    rm -f /tmp/recent_pnfids_${db_name} #Cleanup

    #Add any previously found files to the list to check.
    if [ -f $REMEMBER_OUTPUT_DIR/$db_name ]; then
	cat $REMEMBER_OUTPUT_DIR/$db_name | sed '/^$/d' > $TEMP_FILE_OLD
	old_count=`wc -l $TEMP_FILE_OLD | awk {'print $1}'`
    else
	rm -f $TEMP_FILE_OLD && touch $TEMP_FILE_OLD
	old_count=0
    fi

    #Send message to standard out.
    echo "Starting DB: $db_name with $new_count recent files to check."

    #
    # Output recent broken files.
    #
    if [ $new_count -gt 0 ]; then
	#Check the pnfsids. Appends (headers and) output to $TEMP_OUTPUT_FILE
        # and $TEMP_OUTPUT_FILE_2.
	check_pnfsids $TEMP_FILE_NEW "Recent"
    fi
    
    #Send message to standard out.
    echo "Starting DB: $db_name with $old_count previously known files."
    
    #
    # Output previously found broken files.
    #
    if [ $old_count -gt 0 ]; then
	#Check the pnfsids. Appends (headers and) output to $TEMP_OUTPUT_FILE
        # and $TEMP_OUTPUT_FILE_2.
	check_pnfsids $TEMP_FILE_OLD "Previously known"
    fi

    if [ -f $TEMP_OUTPUT_FILE_2 ]; then
	#Move the rolling record of what is not written to tape.
	mv $TEMP_OUTPUT_FILE_2 $REMEMBER_OUTPUT_DIR/${db_name}
    else
	#Clear the existing db info.
	rm -f $REMEMBER_OUTPUT_DIR/${db_name}
    fi
done

#Move the output file to its destination.
echo -e "\n" enrcp $TEMP_OUTPUT_FILE $web_node:$html_dir
enrcp $TEMP_OUTPUT_FILE $web_node:$html_dir
rc=$?

#Cleanup.
rm -f $TEMP_OUTPUT_FILE ${TEMP_FILE} $TEMP_OUTPUT_FILE_2

exit $rc
