#! /bin/sh

# $Id: migration_common,v 1.1 2009/07/29 14:36:21 zalokar Exp $

# This file should not be used directly by the administrator.  It should
# only be sourced by migration_summary, duplication_summary and/or
# cloning_summary.  It provides variables and functions common to all three.

#Make sure to set a timeout.
timeout='--timeout 10 --retries 3'

#First obtain the directory to write the output.
html_dir=`enstore conf $timeout --show crons html_dir`
if [ ! -d "$html_dir" ]; then
    echo HTML directory $html_dir not found.
    exit 1
fi
#If the inventory directory does not exist, create it.
inventory_dir=$html_dir/tape_inventory
if [ ! -d "$inventory_dir" ]; then
    mkdir -p $inventory_dir
fi
#If the inventory directory does not exist, create it.
plots_dir=$html_dir/migration_summary
plots_link=$plots_dir/plot_enstore_system.html

#Second obtain the directory to put a link to.
url_dir=`enstore conf $timeout --show crons url_dir`

#Obtain the db port number.
DB_PORT=`enstore conf $timeout --show database dbport`
if [ -z "$DB_PORT" ]; then
    echo "dbport not found in configuration."
    exit 1
fi

#Obtain the db name.
DB_NAME=`enstore conf $timeout --show database dbname`
if [ -z "$DB_NAME" ]; then
    echo "dbname not found in configuration."
    exit 1
fi

#Obtain the db host.
DB_HOST=`enstore conf $timeout --show database dbhost`
if [ -z "$DB_HOST" ]; then
    echo "dbhost not found in configuration."
    exit 1
fi

#Obtain the db user/role.
DB_USER=`enstore conf $timeout --show database dbuser`   #dbuser_reader?
if [ -z "$DB_USER" ]; then
    echo "dbuser not found in configuration."
    exit 1
fi

#Get the temporary directory to use.
temp_dir=`enstore conf $timeout --show crons tmp_dir`
if [ ! -d "$temp_dir" ]; then
    temp_dir=/tmp
fi


summary()
{
## Note: This sql works as long as migrate.py/duplicate.py use the volume
## clerk set_system_migrated()/set_system_duplicated() function(s) to set
## the system_inhibit_1 value.  
psql -p $DB_PORT -h $DB_HOST -U $DB_USER $DB_NAME -c "
select /* It should be as simple as just using the media_type. However,
          LTO1 and LTO2 at FNAL are both set as 3480 do to limitations
          in the AML/2 when it was first put into use. */
       /*media_type,*/
       CASE WHEN media_type = '3480' and capacity_bytes = '107374182400'
            THEN 'LTO1'
            WHEN media_type = '3480' and capacity_bytes = '214748364800'
            THEN 'LTO2'
            WHEN media_type = '3480' and capacity_bytes < 100
            THEN NULL    --Cleaning tape; skip it.
            ELSE media_type
       END as media_type,
       count(distinct CASE WHEN system_inhibit_1 = 'migrating'
                           THEN label
                           ELSE NULL
                      END) AS migrating,
       count(distinct CASE WHEN system_inhibit_1 = 'migrated'
                           THEN label
                           ELSE NULL
                      END) AS migrated,
       count(distinct CASE WHEN system_inhibit_1 in ('migrating', 'migrated')
                           THEN label
                           ELSE NULL
                      END) AS migration_started,
       count(distinct CASE WHEN system_inhibit_1 = 'migrated'
                                /* Make sure that at least one destination
                                   has been scanned. */
                                and (select count(*)
                                     from migration_history
                                     where migration_history.src_vol_id = volume.id
                                       and migration_history.closed_time is not NULL
                                     limit 1) > 0
                                /* Reject if any destination volumes have
                                   not been scanned. */
                                and (select count(*)
                                     from migration_history
                                     where migration_history.src_vol_id = volume.id
                                       and migration_history.closed_time is NULL) = 0
                                and volume.sum_wr_access - volume.sum_wr_err > 0 --skip blank tapes
                                and library not like '%shelf%'
                           THEN label
                           ELSE NULL
                      END) AS migrated_closed_not_shelved,
       count(distinct CASE WHEN system_inhibit_1 = 'migrated'
                                /* Make sure that at least one destination
                                   has been scanned. */
                                and (select count(*)
                                     from migration_history
                                     where migration_history.src_vol_id = volume.id
                                       and migration_history.closed_time is not NULL
                                     limit 1) > 0
                                /* Reject if any destination volumes have
                                   not been scanned. */
                                and (select count(*)
                                     from migration_history
                                     where migration_history.src_vol_id = volume.id
                                       and migration_history.closed_time is NULL) = 0
                                and volume.sum_wr_access - volume.sum_wr_err > 0 --skip blank tapes
                                and library like '%shelf%'
                           THEN label
                           ELSE NULL
                      END) AS migrated_closed_shelved,
       count(distinct CASE WHEN system_inhibit_1 = 'duplicating'
                           THEN label
                           ELSE NULL
                      END) AS duplicating,
       count(distinct CASE WHEN system_inhibit_1 = 'duplicated'
                           THEN label
                           ELSE NULL
                      END) AS duplicated,
       count(distinct CASE WHEN system_inhibit_1 in ('duplicating', 'duplicated')
                           THEN label
                           ELSE NULL
                      END) AS duplication_started,
       count(distinct CASE WHEN system_inhibit_1 = 'duplicated'
                                /* Make sure that at least one destination
                                   has been scanned. */
                                and (select count(*)
                                     from migration_history
                                     where migration_history.src_vol_id = volume.id
                                       and migration_history.closed_time is not NULL
                                     limit 1) > 0
                                /* Reject if any destination volumes have
                                   not been scanned. */
                                and (select count(*)
                                     from migration_history
                                     where migration_history.src_vol_id = volume.id
                                       and migration_history.closed_time is NULL) = 0
                                and volume.sum_wr_access - volume.sum_wr_err > 0 --skip blank tapes
                                and library not like '%shelf%'
                      THEN label
                      ELSE NULL
                      END) AS duplicated_closed_not_shelved,
       count(distinct CASE WHEN system_inhibit_1 = 'duplicated'
                                /* Make sure that at least one destination
                                   has been scanned. */
                                and (select count(*)
                                     from migration_history
                                     where migration_history.src_vol_id = volume.id
                                       and migration_history.closed_time is not NULL
                                     limit 1) > 0
                                /* Reject if any destination volumes have
                                   not been scanned. */
                                and (select count(*)
                                     from migration_history
                                     where migration_history.src_vol_id = volume.id
                                       and migration_history.closed_time is NULL) = 0
                                and volume.sum_wr_access - volume.sum_wr_err > 0 --skip blank tapes
                                and library like '%shelf%'
                      THEN label
                      ELSE NULL
                      END) AS duplicated_closed_shelved,
       count(distinct CASE WHEN volume.sum_wr_access - volume.sum_wr_err > 0 /*skip blanks*/
                                and system_inhibit_1 not in ('migrated',
                                                             'duplicated',
                                                             'cloned',
                                                             'migrating',
                                                             'duplicating',
                                                             'cloning')
                                and library not like '%shelf%'
                           THEN label
                           ELSE NULL
                      END) AS remaining_to_start_migrating,
       count(distinct CASE WHEN volume.sum_wr_access - volume.sum_wr_err > 0 /*skip blanks*/
                                and system_inhibit_1 not in ('migrated',
                                                             'duplicated',
                                                             'cloned')
                                and library not like '%shelf%'
                           THEN label
                           ELSE NULL
                      END) AS remaining_to_finish_migrating,
       count(distinct CASE WHEN volume.sum_wr_access - volume.sum_wr_err > 0 /*skip blanks*/
                                and (system_inhibit_1 not in ('migrated',
                                                              'duplicated',
                                                              'cloned',
                                                              'cloning')
                                    or
                                      /* At least one needs to be NULL for
                                        this to still be remaing to complete */
                                     ((select count(*)
                                       from migration_history
                                       where src_vol_id = volume.id
                                         and closed_time is NULL) > 0
                                     or
                                      /* A scan has not yet been started. */
                                      (select count(*)
                                       from migration_history
                                       where migration_history.src_vol_id = volume.id) = 0
                                     )
                                    )
                                /* Skip cloning tapes for accurate numbers. */
                                and system_inhibit_1 not in ('cloned',
                                                             'cloning')
                                and library not like '%shelf%'
                           THEN label
                           ELSE NULL
                      END) AS remaining_to_scan_and_close,
       count(distinct CASE WHEN (volume.sum_wr_access = 0
                                 --Skip tapes where the first write failed.
                                 or (volume.wrapper = 'none' 
                                     and volume.sum_wr_access - volume.sum_wr_err = 0))
                            and library not like '%shelf%'
                           THEN label
                           ELSE NULL
                      END) as blank_volumes,
       count(distinct CASE WHEN library not like '%shelf%'
                             or system_inhibit_1 in ('migrated',
                                                     'migrating',
                                                     'duplicated',
                                                     'duplicating')
                           THEN label
                           ELSE NULL
                      END) as total,
       round(count(distinct CASE WHEN (select count(*)
                                 from migration_history
                                 where migration_history.src_vol_id = volume.id
                                       and migration_history.closed_time is not NULL) > 0
                                 THEN label
                                 ELSE NULL
                   END) / cast(count(distinct label) as DECIMAL(9,2)) * 100,2) as percentage_done
from volume
where (system_inhibit_0 != 'DELETED' 
       and label not like '%.deleted')
      and media_type != 'null'
      and capacity_bytes > 500  --Skip cleaning tapes.
group by media_type, capacity_bytes
order by media_type;
"
}




summary_skipped_bad_files()
{
psql -p $DB_PORT -h $DB_HOST -U $DB_USER $DB_NAME -c "
select /* It should be as simple as just using the media_type. However,
          LTO1 and LTO2 at FNAL are both set as 3480 do to limitations
          in the AML/2 when it was first put into use. */
       /*media_type,*/
       CASE WHEN media_type = '3480' and capacity_bytes = '107374182400'
            THEN 'LTO1'
            WHEN media_type = '3480' and capacity_bytes = '214748364800'
            THEN 'LTO2'
            WHEN media_type = '3480' and capacity_bytes < 100
            THEN NULL    --Cleaning tape; skip it.
            ELSE media_type
       END as media_type,
       system_inhibit_1 as migration_type,
       count(distinct src) as completed_volumes_with_skipped_bad_files
from volume
left join migration_history on migration_history.src_vol_id = volume.id
left join file on file.volume = volume.id
left join bad_file on bad_file.bfid = file.bfid
where (system_inhibit_1 = 'migrated' or system_inhibit_1 = 'duplicated')
      and volume.label not like '%.deleted'
      and library not like '%shelf%'
      and media_type != 'null'
      and bad_file.bfid is not NULL
      and capacity_bytes > 500  --Skip cleaning tapes.
group by media_type,capacity_bytes,system_inhibit_1;
"
}



migration_per_day()
{
    volumes_per_day migrating migrated
}
duplication_per_day()
{
    volumes_per_day duplicating duplicated
}
cloning_per_day()
{
    volumes_per_day cloning cloned
}

#volumes_per_day()
#
#First argument is the in progress migration related state.  This list is one
#   of migrating, duplicating or cloning.
#Second argument is the copleted migration related state.  This lst is one
#   of migrated, duplicated or cloned.
volumes_per_day()
{
# Note: This sql command is similar to the daily plots and daily Duplicated
# table in the src/migration_summary_plotter_module.py and
# sbin/duplication_summary scripts, respectively.  Be sure to modify them
# when you modify this sql statement.
psql -p $DB_PORT -h $DB_HOST -U $DB_USER $DB_NAME -c "
/*This outer select just sorts the merged s1, s2 and s3 'day' columns into
  a unified sorted order. */
select * from
(
/* This inner select combines three sub selects sorted by day and
   media type. */
select CASE WHEN s1.day is not null THEN s1.day
            WHEN s2.day is not null THEN s2.day
            WHEN s3.day is not null THEN s3.day
            ELSE NULL
       END as day,
       CASE WHEN s1.media_type is not null THEN s1.media_type
            WHEN s2.media_type is not null THEN s2.media_type
            WHEN S3.media_type is not null THEN s3.media_type
            ELSE NULL
       END as media_type,
       CASE WHEN s2.started is not NULL THEN s2.started
            ELSE 0
       END as started,
       CASE WHEN s1.completed is not NULL THEN s1.completed
            ELSE 0
       END as completed,
       CASE WHEN s3.closed is not NULL THEN s3.closed
            ELSE 0
       END as closed
from

/*Three sub selects get the count for each day and media for number of
  volumes started, migrated/duplicated and closed. */

/****  s1  ****/
(
select date(time) as day,
       /* It should be as simple as just using the media_type. However,
          LTO1 and LTO2 at FNAL are both set as 3480 do to limitations
          in the AML/2 when it was first put into use. */
       /*media_type,*/
       CASE WHEN media_type = '3480' and capacity_bytes = '107374182400'
            THEN 'LTO1'
            WHEN media_type = '3480' and capacity_bytes = '214748364800'
            THEN 'LTO2'
            WHEN media_type = '3480' and capacity_bytes < 100
            THEN NULL    --Cleaning tape; skip it.
            ELSE media_type
       END as media_type,
       count(distinct CASE WHEN system_inhibit_1 in ('$2')
                            THEN label
                            ELSE NULL
                      END) as completed

from volume,migration_history
where volume.id = migration_history.src_vol_id
      and volume.library not like '%shelf%'
      and volume.media_type != 'null'
      and volume.system_inhibit_1 in ('$2')
      /* This time sub-query is needed to limit test volumes migrated
         multiple times to be counted only once. */
      and time = (select max(time)
                  from migration_history m2
                  where m2.src_vol_id = volume.id)
      and capacity_bytes > 500  --Skip cleaning tapes.
group by day,media_type,capacity_bytes
order by day,media_type
) as s1
/****  s1  ****/

/****  s2  ****/
full join (
select date(state.time) as day,
       /* It should be as simple as just using the media_type. However,
          LTO1 and LTO2 at FNAL are both set as 3480 do to limitations
          in the AML/2 when it was first put into use. */
       /*media_type,*/
       CASE WHEN media_type = '3480' and capacity_bytes = '107374182400'
            THEN 'LTO1'
            WHEN media_type = '3480' and capacity_bytes = '214748364800'
            THEN 'LTO2'
            WHEN media_type = '3480' and capacity_bytes < 100
            THEN NULL    --Cleaning tape; skip it.
            ELSE media_type
       END as media_type,
       count(distinct volume.label) as started
from volume,migration_history,state
where volume.id = migration_history.src_vol_id
      and volume.id = state.volume
      and volume.library not like '%shelf%'
      and volume.media_type != 'null'
      and volume.system_inhibit_1 in ('$1', '$2')
      /* Hopefully, setting state.time like this will correctly handle
         all vintages of the migration process.  The migrating and duplicating
         stages were added September of 2008. */
      and state.time = (select min(s5.time) from (
                        select CASE WHEN s2.value in ('$1')
                                    THEN min(s2.time)
                                    WHEN s2.value in ('readonly')
                                         and time > current_timestamp - interval '30 days'
                                    THEN min(s2.time)
                                    WHEN s2.value in ('$2')
                                    THEN min(s2.time)
                                    ELSE NULL
                               END as time
                        from state s2
                        where s2.volume = volume.id
                              and s2.value in ('$1', '$2',
                                               'readonly')
                        group by s2.value, time
                        order by s2.value, time
                        ) as s5)
      and capacity_bytes > 500  --Skip cleaning tapes.
group by day, volume.media_type,capacity_bytes
order by day, volume.media_type
) as s2 on (s1.day, s1.media_type) = (s2.day, s2.media_type)
/****  s2  ****/

/****  s3  ****/
full join (
select date(closed_time) as day,
       /* It should be as simple as just using the media_type. However,
          LTO1 and LTO2 at FNAL are both set as 3480 do to limitations
          in the AML/2 when it was first put into use. */
       /*media_type,*/
       CASE WHEN media_type = '3480' and capacity_bytes = '107374182400'
            THEN 'LTO1'
            WHEN media_type = '3480' and capacity_bytes = '214748364800'
            THEN 'LTO2'
            WHEN media_type = '3480' and capacity_bytes < 100
            THEN NULL    --Cleaning tape; skip it.
            ELSE media_type
       END as media_type,
       count(distinct label) as closed
from volume,migration_history
where volume.id = migration_history.src_vol_id
      and volume.library not like '%shelf%'
      and volume.media_type != 'null'
      and volume.system_inhibit_1 in ('$2')
      /* This time sub-query is needed to limit test volumes migrated
         multiple times to be counted only once. */
      and closed_time = (select max(closed_time)
                         from migration_history m2
                         where m2.src_vol_id = volume.id)
      and capacity_bytes > 500  --Skip cleaning tapes.
group by day,media_type,capacity_bytes
order by day,media_type
) as s3 on (s2.day, s2.media_type) = (s3.day, s3.media_type)
/****  s3  ****/

group by s1.day,s2.day,s3.day,s1.media_type,s1.completed,s2.media_type,s2.started,s3.media_type,s3.closed
order by s1.day,s2.day,s3.day
) as inner_result order by day;
"
}




volumes_remaining()
{
#This first query is just to obtain the list of media types that have
# at least one tape already migrated or duplicated.
media_types=`psql -p $DB_PORT -h $DB_HOST -U $DB_USER $DB_NAME -c "
select /* It should be as simple as just using the media_type. However,
          LTO1 and LTO2 at FNAL are both set as 3480 do to limitations
          in the AML/2 when it was first put into use. */
       /* For this issue we need the raw media_types... */
       media_type
       /*CASE WHEN media_type = '3480' and capacity_bytes = '107374182400'
            THEN 'LTO1'
            WHEN media_type = '3480' and capacity_bytes = '214748364800'
            THEN 'LTO2'
            WHEN media_type = '3480' and capacity_bytes < 100
            THEN NULL    --Cleaning tape; skip it.
            ELSE media_type
       END as media_type*/
from volume v2
where (v2.system_inhibit_1 = 'migrated'
       or v2.system_inhibit_1 = 'duplicated')
      and v2.system_inhibit_0 != 'DELETED'
      and v2.library not like '%shelf%'
      and v2.media_type != 'null'
      and capacity_bytes > 500  --Skip cleaning tapes.
group by media_type,capacity_bytes
having count(v2.label) > 0;
" | sed '1,2d'`  #Remove the first to header lines.

#Now we use that to build a list of comma seperated media_types.  This uses
# an echo trick to put all the media_types on one line seperated by spaces.
#media_list=`echo $media_types | tr " " ","`
media_list=`echo $media_types | sed -e "s/^/\'/" -e "s/ /\',\'/g" -e "s/$/\'/"`


psql -p $DB_PORT -h $DB_HOST -U $DB_USER $DB_NAME -c "
select /* It should be as simple as just using the media_type. However,
          LTO1 and LTO2 at FNAL are both set as 3480 do to limitations
          in the AML/2 when it was first put into use. */
       /*media_type,*/
       CASE WHEN media_type = '3480' and capacity_bytes = '107374182400'
            THEN 'LTO1'
            WHEN media_type = '3480' and capacity_bytes = '214748364800'
            THEN 'LTO2'
            WHEN media_type = '3480' and capacity_bytes < 100
            THEN NULL    --Cleaning tape; skip it.
            ELSE media_type
       END as media_type,
       label,
       CASE WHEN system_inhibit_1 in ('migrated', 'duplicated', 'cloned',
                                      'migrating', 'duplicating', 'cloning')
            THEN system_inhibit_1
            ELSE NULL
       END as migration_state
from volume
left join migration_history mh on mh.src_vol_id = volume.id
where ((system_inhibit_1 not in ('migrated', 'duplicated', 'cloned'))
       or
       (mh.closed_time is NULL))
      and label not like '%.deleted'
      and library not like '%shelf%'
      and media_type != 'null'
      and media_type in (${media_list})
      and capacity_bytes > 500  --Skip cleaning tapes.
      and sum_wr_access > 0  --Skip most blank tapes.
      and wrapper != 'none' --Skip blank tapes recycled after write error.
group by media_type,capacity_bytes,label,system_inhibit_1
order by media_type,label;
"
}




migration_history()
{
    history migrated
}
duplication_history()
{
    history duplicated
}
cloning_history()
{
    history cloned
}

#history()
#
#First argument is the in completed migration related state.  This list is one
#   of migrated, duplicated or cloned.
history()
{
psql -p $DB_PORT -h $DB_HOST -U $DB_USER $DB_NAME -c " \
select migration_history.src as src_volume,
       /* It should be as simple as just using the media_type. However,
          LTO1 and LTO2 at FNAL are both set as 3480 do to limitations
          in the AML/2 when it was first put into use. */
       /*volume.media_type,*/
       CASE WHEN volume.media_type = '3480' and volume.capacity_bytes = '107374182400'
            THEN 'LTO1'
            WHEN volume.media_type = '3480' and volume.capacity_bytes = '214748364800'
            THEN 'LTO2'
            WHEN volume.media_type = '3480' and volume.capacity_bytes < 100
            THEN NULL    --Cleaning tape; skip it.
            ELSE volume.media_type
       END as src_type,
       migration_history.dst as dst_volume,
       /* It should be as simple as just using the media_type. However,
          LTO1 and LTO2 at FNAL are both set as 3480 do to limitations
          in the AML/2 when it was first put into use. */
       /*v2.media_type,*/
       CASE WHEN v2.media_type = '3480' and v2.capacity_bytes = '107374182400'
            THEN 'LTO1'
            WHEN v2.media_type = '3480' and v2.capacity_bytes = '214748364800'
            THEN 'LTO2'
            WHEN v2.media_type = '3480' and v2.capacity_bytes < 100
            THEN NULL    --Cleaning tape; skip it.
            ELSE v2.media_type
       END as dst_type,
       volume.system_inhibit_1 as migration,
       time as time_completed
from migration_history
left join volume on volume.id = migration_history.src_vol_id
left join volume as v2 on v2.id = migration_history.dst_vol_id
where volume.system_inhibit_1 = '$1'
order by time;
"
}
