#! /bin/sh

# $Id$

# 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.

# To inject files into the cache that have been missed:
# 1) Copy and past the parse_id() function from this file into a terminal.
# 2) source /usr/etc/pnfsSetup
# 3) Run using the correct *.missing_file or *.missing_layer_* file:
#    for item in `cut -f 1 -d " " dzero_forward.error2.error.missing_file`; do
#       timestamp=`stat $item | grep "Modify:" | cut -f 2-3 -d " "`;
#       echo -n "" $timestamp "| ";
#       parse_id `enstore pnfs --id $item`;
#    done | tee /tmp/missing_files
# 4) cp /tmp/missing_files ``dirname $trash`/pnfs_monitor/missing_files
# 5) Re-run the pnfs_monitor or wait until its regularly scheduled time.
#
# An example for a single file insertion by would look like:
#    $ parse_id 0002000000000000022CF258
#    020000000000000058F22C02
#    $ echo " 2007-10-10 10:36:37.000000000 | 020000000000000058F22C02" >> xyz

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

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

    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 $db_user -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=" $PNFS_CONFIG_FILE | 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 $NF}' | sed 's:.*/::' | 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})"
fname_showid="/pnfs/fs/usr/.(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)"
fname_l1="/pnfs/fs/usr/.(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)"
    fname_l2="/pnfs/fs/usr/.(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)"
    fname_l4="/pnfs/fs/usr/.(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)"
    fname_l2="/pnfs/fs/usr/.(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})"
    fname="/pnfs/fs/usr/.(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})"
    fname="/pnfs/fs/usr/.(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
}

#Return the path of the supplied pnfsid.
get_filepath()
{
    db_name=$1
    pnfsid=$2

    #Loop over
    count=1
    while [ $count -lt 3 ]; do
        pathfinder_path=$pnfs/tools/pathfinder
        if [ -x $pathfinder_path ]; then
            path=`$pathfinder_path $pnfsid`
            if [ $? -ne 0 ]; then
                path=""
            else
                #Success.  Now munge the data a little.
                path=`echo "$path" | tail -n 1 | sed 's/root/pnfs/'`

		#Verify that path is valid.  Two conditions seem to be
		# possible:
		# 1) pathfinder drops a directory from the path it returns.
                # 2) pathfinder reports "File not found" when it really
                #    does exist.
                #In either case, wait a moment and try again.
		if [ -z "$path" -o ! -f "$path" ]; then
		    sleep 3  #How long is best?
		    echo "Retrying $pnfsid" > /dev/tty
                    continue
                fi
		break
            fi
	else
            path=""
            break
        fi
        count=$((count+1))
    done
    #If we still haven't gotten a valid path, prepend it with question marks.
    if [ -z "$path" -o \( -n "$path" -a ! -f "$path" \) ]; then
	path="??? $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).

    #Clear the temporary file.
    rm -f $TEMP_OUTPUT_FILE_2
    touch $TEMP_OUTPUT_FILE_2

    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/ $//'`
	#Kick it to upper case so enstore pnfs commands will recognized it
	# as a pnfsid.
	pnfsid=`echo $pnfsid | tr '[a-z]' '[A-Z]'`

	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`
	if [ -z "$filesize" ]; then
	    filesize=-1
	fi
	l2_filesize=`get_L2_filesize $db_name $pnfsid`
	if [ -z "$l2_filesize" ]; then
	    l2_filesize=-1
	fi

	#
	#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.
	#
	#Extract the first four characters of the basename.
	file_ending=`basename "$path" | cut -c 1-4`
	if [ "$file_ending" = ".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

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

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

# This section allows for a user to pass a filename to this script, and
# have this script output to standard out the information necessary for
# that file in the pnfs_monitor cache file format.

format_cache()
{
timestamp=`stat $1 | grep Modify | cut -f 2-3 -d " " | cut -c 1-25`
pnfsid=`enstore pnfs --id $1`
pnfsid=`parse_id $pnfsid`
echo "" $timestamp "|" $pnfsid
}

if [ -n "$1" ]; then
    for item in $*; do
        format_cache $item
    done
    exit 0
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 [ ! -r $PNFS_CONFIG_FILE ]; then
   echo "Unable to find $PNFS_CONFIG_FILE file." 1>&2
   exit 1
fi
source $PNFS_CONFIG_FILE
if [ $? -ne 0 ]; then
   echo "Failed to source $PNFS_CONFIG_FILE." 1>&2
   exit 1
fi
trash_location=`egrep "^trash=" $PNFS_CONFIG_FILE | 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

#Grab the postres username from the pnfs configurationn file.
db_user=`egrep -o "user=[a-zA-Z0-9]*" "$PNFS_CONFIG_FILE" | cut -f 2 -d "="`
if [ -z "$db_user" ]; then
   db_user=`postgres`
fi

#
# Loop over the all of the pnfs databases.
#
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.
    # For quicker debugging of just already known files, use touch instead
    # of get_recent_pnfsids.
    get_recent_pnfsids $db_name $db_user
    ###  For debugging only. ### touch /tmp/recent_pnfids_${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

    #The following are useful for debugging a specific storage group.
    #if [ $db_name != 'test' ]; then
    #    continue
    #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
