eval '(exit $?0)' && eval 'exec perl -w -S $0 ${1+"$@"}'
                  && eval 'exec perl -w -S $0 $argv:q'
                  if 0;

########################################################################
########################################################################
use strict;

# Use the File::Basename package
use File::Basename;

# Use the Getopt package
use Getopt::Long;

# Use the File::Path package
use File::Path;

# Use the Pod::Usage package
use Pod::Usage;

# Use the Cwd package;
use Cwd qw(:DEFAULT chdir);

# Set parsing options
Getopt::Long::Configure(qw(no_ignore_case bundling require_order));

my %options = ( "log-files" => 0 );

GetOptions(\%options,
           "help|h|?",
           "man|m",
           "+quiet|q",
           "log-files|l",
           "no-log-files|n" => sub { $options{"log-files"} = 0 }
          ) or
  pod2usage(-exitval => 2);     # short usage (synopsis only)

# Medium usage (options explanation)
pod2usage(-verbose => 1) if exists $options{help};

# Full man page (requires working pod2man)
pod2usage(-verbose => 2) if exists $options{man};

my $test_timestamp = `date +'%Y%m%d'`;
chomp $test_timestamp;

if (not scalar @ARGV) {
  unshift @ARGV, 'local';
  $options{local} = 1;
}

print "gratia-site-diag version ", '$Revision: 2997 $', "\n";

foreach my $gk (@ARGV) {
  print "SITE: $gk\n";
  my ($osg_loc, $hostname);
  if ($options{local}) {
    $osg_loc = $ENV{OSG_LOCATION} || $ENV{VDT_LOCATION};
    $hostname = `hostname -f 2>/dev/null`;
    chomp $hostname;
  } else {
    my $printenv_output = `globus-job-run "$gk" /usr/bin/printenv 2>&1`;
    ($osg_loc) = ($printenv_output =~ m&^OSG_LOCATION=(.*)$&m);
    unless ($osg_loc) {
      print STDERR "  Output from command: \n$printenv_output";
    }
    $hostname = `globus-job-run "$gk" /bin/hostname 2>/dev/null`;
    chomp $hostname;
  }
  unless ($osg_loc) {
    print STDERR "  Unable to obtain OSG_LOCATION for $gk\n";
    next;
  }
  system("mkdir -p \"GratiaTests_${gk}_${test_timestamp}\"") == 0 or die "Unable to create test results directory";
  my $oldpwd = cwd();
  chdir("GratiaTests_${gk}_${test_timestamp}");
  print "  Directory output: listing.{out,err}\n";
  execute("/usr/bin/find \"$osg_loc/gratia\" \"$osg_loc/monitoring\" \"$osg_loc/globus/lib/perl/Globus/GRAM/JobManager\" -printf \"\%T\@\\t\" -ls > listing.out 2>listing.err", $gk);
  open(SITE_LISTING, "listing.out") or
    die "Unable to open listing.out for read.";
  my @interesting_files = ("$osg_loc/o..pacman..o/logs/commands",
                           "$osg_loc/vdt-install.log",
                           "$osg_loc/vdt/setup/configure_gratia",
                           "$osg_loc/osg-version");
  my %probe_log_file_info = ();
  my %file_map = ();
  my $tmpfiles_count = 0;
  while (<SITE_LISTING>) {
    chomp;
    my ($mtime_epoch, $index, $n_blocks, $perms, $dummy, $user, $group, $size, $month, $date, $time, $name) = split;
    $name or next;
    $perms =~ m&^d& and next;
    push @interesting_files, $name if $name =~ m&\Q$osg_loc\E/gratia/probe/[^/]+/ProbeConfig$&;
    push @interesting_files, $name if $name =~ m&\Q$osg_loc\E/gratia/probe/[^/]+/.*\.py$&;
    push @interesting_files, $name if $name =~ m&\Q$osg_loc\E/gratia/probe/[^/]+/urCollector\.conf$&;
    push @interesting_files, $name if $name =~ m&\Q$osg_loc\E/gratia/var/tmp/+[^/]+$&;
    push @interesting_files, $name if $name =~ m&\Q$osg_loc\E/monitoring/osg-vo-user-map\.txt$&;
    push @interesting_files, $name if $name =~ m&\Q$osg_loc\E/monitoring/osg-attributes\.conf$&;
    push @interesting_files, $name if $name =~ m&\Q$osg_loc\E/monitoring/osg-supported-vo-list\.txt$&;
    push @interesting_files, $name if $name =~ m&\Q$osg_loc\E/monitoring/osg-undefined-accounts\.txt$&;
    push @interesting_files, $name if $name =~ m&\Q$osg_loc\E/monitoring/osg-vo-user-map\.txt\.last_checked$&;
    if ($name =~ m&gratia/var/logs/.*\.log$&) {
      push @interesting_files, $name if ($name =~ m&gratia/var/logs/gratia-probe-.*\.log$&);
      $probe_log_file_info{$name} =
        { line => $_,
          mtime_epoch => $mtime_epoch,
          index => $index,
          n_blocks => $n_blocks,
          perms => $perms,
          user => $user,
          group => $group,
          size => $size,
          month => $month,
          date => $date,
          time => $time
        };
    } elsif ($options{"log-files"}) {
      # All log files
      push @interesting_files, $name if $name =~ m&gratia/var/logs/&;
    }
    push @interesting_files, $name if $name =~ m&Globus/GRAM/JobManager/.*\.pm$&;
    ++$tmpfiles_count if $name =~ m&gratia/var/tmp/gratiafiles/&g;
  }
  close SITE_LISTING;
  my @dated_log_list = reverse sort grep m&\d\d\d\d-\d\d-\d\d\.log$&, keys %probe_log_file_info;
  push @interesting_files, $dated_log_list[0] if scalar @dated_log_list;
  foreach my $file (@interesting_files) {
    my $local_file = $file;
    $local_file =~ s&^.*?\Q$osg_loc\E/&&;
    $local_file =~ s&/+&_&g;
    my $status = obtain($file, $local_file, $gk);
    if (not $options{quiet} or (($options{quiet} == 1) and ($status != 0))) {
      print "  > Obtaining file \"$file\" ... ", $status == 0?"OK":"FAILED", "\n";
    }
    if ($status == 0) {
      $file_map{$file} = $local_file;
    }
  }
  print "  Diagnostics ...\n";
  print "  > Found $tmpfiles_count unsent XML files in $osg_loc/gratia/var/tmp/gratiafiles\n";

  # Some attempts to identify common problems.
  # ProbeConfig checks
  my $file_ok;
  foreach my $remote_config_file (grep /(^.*ProbeConfig)$/, @interesting_files) {
    $file_ok = 1;
    my $local_config_file = $file_map{$remote_config_file};
    next unless $local_config_file;
    my ($probe_type) = ($remote_config_file =~ m&([^/]+)/ProbeConfig$&);
    my $log_file = "gratia_var_log_gratia-probe-$probe_type.log";
    if ($probe_type ne "metric") {
      print "  > Checking for existence and date of probe log file gratia-probe-$probe_type.log ... ";
      my ($remote_log_file) = (grep m&gratia/var/logs/gratia-probe-$probe_type\.log$&, keys %probe_log_file_info);
      if ($remote_log_file and $probe_log_file_info{$remote_log_file}) { # Log file exists
        if ((time - $probe_log_file_info{$remote_log_file}->{mtime_epoch}) > 86400) {
          print "\n    > WARNING: gratia-probe-$probe_type.log is more than 1 day old:\n",
            "      is probe service enabled with vdt-control --on?\n";
          $file_ok = 0;
        } else {
          print "OK\n";
        }
      } else {
        print "\n    > WARNING: gratia-probe-$probe_type.log does not exist:\n",
          "      is probe service enabled with vdt-control --on?\n";
        $file_ok = 0;
      }
    }
    $local_config_file =~ /common_ProbeConfig/ and next;
    print "  > Checking $local_config_file (verify INFO items manually):\n";
    unless (open(CONFIG_FILE, "$local_config_file")) {
      print "    > ERROR: Could not open local copy $local_config_file!\n";
      $file_ok = 0;
      next;
    }
    my $config = join("", <CONFIG_FILE>);
    $config =~ m&EnableProbe\s*=\s*"([^"]+)"&s and ($1 ne 1) and
      print "    > WARNING: EnableProbe set to \"$1\" instead of \"1\"\n" and $file_ok = 0;
    my ($meter_name, $site_dns) = ($config =~ m&MeterName\s*=\s*"((?:[^:]+:)?([^"]+))"&s);
    print "    > INFO: MeterName set to ", ($meter_name?$meter_name:"<UNSET>"), "\n";
    my ($site_name) = ($config =~ m&SiteName\s*=\s*"([^"]+)"&si);
    print "    > INFO: SiteName set to ", ($site_name?$site_name:"<UNSET>"), "\n";
    my ($soap_host) =  ($config =~ m&SOAPHost\s*=\s*"([^"]+)"&si);
    print "    > INFO: SOAPHost set to ", ($soap_host?$soap_host:"<UNSET>"), "\n";

    $site_dns or
      print "    > WARNING: MeterName set to \"$1\", which may not be correct.\n" and $file_ok = 0;
    $config =~ m&SiteName\s*=\s*"([^"]+)"&s and
      (($1 =~ /(?:generic|unknown)/i) or
       ($site_dns and ($1 eq $site_dns))) and
        print "    > WARNING: SiteName set to \"$1\", which may not be correct.\n" and $file_ok = 0;
    close CONFIG_FILE;
  }
  continue {
    if ($file_ok) {
      print "    > $remote_config_file OK\n";
    } else {
      my ($configure_gratia) = grep /configure_gratia$/, @interesting_files;
      if ($configure_gratia and $file_map{$configure_gratia}) {
        my ($probe_type) = ($remote_config_file =~ m&([^/]+)/ProbeConfig$&);
        $probe_type = '<my-probe-type>' unless $probe_type;
        my ($osg_version) = grep /osg-version$/, @interesting_files;
        my ($report_host_production, $report_host_itb) =
          ($hostname and $hostname =~ m&fnal\.gov$&)?
            ("gratia-fermi.fnal.gov:8880", "gratia-fermi-itb.fnal.gov:8881"):
            ("gratia.opensciencegrid.org:8880", "gratia.opensciencegrid.org:8881");
        my $is_itb;
        if ($osg_version and $file_map{$osg_version}) {
          if (system("grep -e '[IV]TB' \"$file_map{$osg_version}\" >/dev/null 2>&1") == 0) {
            $is_itb = 1;
          } elsif (system("grep -e '\"OSG' \"$file_map{$osg_version}\" >/dev/null 2>&1") == 0) {
            $is_itb = 0;
          }
        }
        if (defined $is_itb) {
          print "    > Please run the following commands: \n";
          print "      > $osg_loc/vdt/setup/configure_gratia --probe $probe_type --probe-cron --report-to ",
            $is_itb?$report_host_itb:$report_host_production, "\n";
        } else {
          print "    > If this is an ITB or VTB site, please run: \n";
          print "      > $osg_loc/vdt/setup/configure_gratia --probe $probe_type --probe-cron --report-to ",
            $report_host_itb, "\n";
          print "    > Otherwise, please run: \n";
          print "      > $osg_loc/vdt/setup/configure_gratia --probe $probe_type --probe-cron --report-to ",
            $report_host_production, "\n";
        }
        print <<EOF;
    > Check by re-running this diagnostics script and hand-correcting
      any remaining problems.
    > Obtain and run gratia-repair-tmpfiles (instructions and download at
      https://twiki.grid.iu.edu/twiki/bin/view/Accounting/TroubleShootingInstructions)
      to clear any backlogged XML files if they exist.
    > Finally, execute:
      > vdt-control --on gratia-$probe_type
EOF
      } else {
        print "    > $remote_config_file needs attention; and ",
          "configure_gratia script appears to be missing.\n";
      }
    }
  }
  my ($urcollector_conf) = grep /urCollector\.conf$/, @interesting_files;
  if ($urcollector_conf and $file_map{$urcollector_conf}) {
    print "  > Checking $urcollector_conf ...\n";
    open(URCOLLECTOR_CONF, $file_map{$urcollector_conf})
      or die "INTERNAL ERROR: missing downloaded file $file_map{$urcollector_conf}";
    my ($lrmsType, $pbsAcctLogDir, $lsfAcctLogDir);
    while (<URCOLLECTOR_CONF>) {
      m&^\s*lrmsType\s*=\s*"([^"]+)"& and $lrmsType = $1;
      m&^\s*pbsAcctLogDir\s*=\s*"([^"]+)"& and $pbsAcctLogDir = $1;
      m&^\s*lsfAcctLogDir\s*=\s*"([^"]+)"& and $lsfAcctLogDir = $1;
    }
    close URCOLLECTOR_CONF;
    if (not (defined $lrmsType and ($lrmsType eq "pbs" or $lrmsType eq "lsf"))) {
      print "    > lrmsType not correct: set to \"pbs\" or \"lsf\"\n";
    }
    if ($lrmsType eq "pbs") {
      if ($pbsAcctLogDir eq "/var/spool/pbs/server_priv/accounting/") {
        print "    > pbsAcctLogDir is set to default value";
      } else {
        print "    > pbsAcctLogDir is set to $pbsAcctLogDir";
      }
      print ": checking existence ... ";
      execute("/bin/ls -ld '$pbsAcctLogDir' > pbsAcctLogDir.txt 2>/dev/null", $gk);
      if ( -s "pbsAcctLogDir.txt") {
        print "OK\n";
      } else {
        my $checkdir = $pbsAcctLogDir;
        $checkdir =~ s/\/accounting\/?//;
        execute("/bin/ls -ld '$checkdir' > pbsAcctLogDir.txt 2>/dev/null", $gk);
        if ( -s "pbsAcctLogDir.txt") {
          print "PROBABLY OK ($pbsAcctLogDir inaccessible but $checkdir present)\n";
        } else {
          print "MISSING\n";
        }
      }
    } elsif ($lrmsType eq "lsf") {
      if ($lsfAcctLogDir eq "{path_lsf}/mnt/work/{cluster name}/logdir") {
        print "    > lsfAcctLogDir is set to default value: MUST FIX!\n";
      } else {
        print "    > lsfAcctLogDir is set to $lsfAcctLogDir: checking existence ... ";
        execute("/bin/ls -ld '$lsfAcctLogDir' > lsfAcctLogDir.txt 2>/dev/null", $gk);
        if ( -s "lsfAcctLogDir.txt") {
          print "OK\n";
        } else {
          print "MISSING\n";
        }
      }
    }
  }
  # sge_meter.py check
  my ($sge_meter_py) = grep /sge_meter\.py$/, @interesting_files;
  if ($sge_meter_py) {
    print "  > Checking $sge_meter_py ...\n";
    if (system ("grep -e 'requirePythonVersion' \"$file_map{$sge_meter_py}\" >/dev/null 2>&1") == 0) {
      print "    > WARNING: sge_meter.py is a known buggy version: please execute:\n";
      print "      > cd \$VDT_LOCATION\n";
      print "      > cp -p \"$sge_meter_py\" .\n";
      print "      > pacman -update Gratia-SGE-Probe\n";
      print "      > cp -p ProbeConfig \"$sge_meter_py\"\n";
    }
  }
  chdir($oldpwd);
}

1;

sub execute {
  my $command_string = shift;
  my $gk = shift;
  my $stream_command_option = shift || "";
  my $result;
  if ($options{local}) {
    $result = system("$command_string");
  } else {
    $result = system("globus-job-run \"$gk\" $stream_command_option $command_string");
  }
  return $result;
}

sub obtain {
  my ($file, $local_file, $gk) = @_;
  my $result;
  if ($options{local}) {
    $result = system("cp", "$file", "$ENV{PWD}/$local_file");
  } else {
#    $result = system("globus-url-copy", "gsiftp://$gk$file", "file://$ENV{PWD}/$local_file");
    $result = system("globus-job-run \"$gk\" /bin/cat \"$file\" > \"$local_file\" 2>/dev/null");
  }
  return $result;
}

__END__

=pod

=head1 NAME

gratia-site-diag - diagnose problems with probes on remote gatekeeper
using globus-job-run and globus-url-copy; or on local system.

=head1 SYNOPSIS

B<gratia-site-diag> B<-h>|B<--help>|B<-?>

B<gratia-site-diag> B<--man>|B<-m>

[The perl functionality required by the B<--man> option is broken in some
UPS KIT installations of perl.]

B<gratia-site-diag> [B<--[no-]log-files>|B<-l>|B<-n>|B<-q+>] I<gatekeeper DNS name>+

Options marked with B<+> are repeatable and cumulative.


=head1 DESCRIPTION

I<gratia-site-diag> is a simple script to obtain information useful for
diagnosing problems with Gratia probes at a remote site.

=head1 OPTIONS

=over 4

=item B<-h>

=item B<--help>

=item B<-?>


Short help.


=item B<-m>

=item B<--man>


Full man page information.


=item B<--log-files>

=item B<-l>

=item B<--no-log-files>

=item B<-n>


Select to receive or not receive files from the I<gratia/var/logs> directory (default is not).


=item B<-q+>


Quiet; multiple invocations may make the script progressively quieter.


=back

=head1 EXAMPLES

=over 4

=item C<gratia-site-diag -q>


Run on the local node; note C<VDT_LOCATION> or C<OSG_LOCATION> will need to be set first.


=item C<gratia-site-diag E<lt>my-remote-siteE<gt>>


Run tests on C<E<lt>my-remote-siteE<gt>>. Note that you will need to
have access to C<globus-url-copy> and C<globus-job-run>; and you should
already have obtained a valid grid or VOMS proxy.


=back


=head1 FILES

=over 4

=item I<GratiaTests_E<lt>site_addressE<gt>_E<lt>timestampE<gt>/>


Directory containing retrieved files from I<site_address>.

=back

=head1 SEE ALSO



=head1 AUTHOR

Chris Green <greenc@fnal.gov>.

=cut

### Local Variables:
### mode: cperl
### End:
