#!/usr/bin/perl -w
######################################################################
#
# $Id: webjob-jqd-freeze-queue,v 1.13 2012/01/07 08:01:19 mavrik Exp $
#
######################################################################
#
# Copyright 2007-2012 The WebJob Project, All Rights Reserved.
#
######################################################################
#
# Purpose: Freeze or thaw the specified job queues.
#
######################################################################

use FindBin qw($Bin $RealBin); use lib ("$Bin/../lib/perl5/site_perl", "$RealBin/../lib/perl5/site_perl", "/usr/local/webjob/lib/perl5/site_perl", "/opt/local/webjob/lib/perl5/site_perl");

use strict;
use File::Basename;
use Getopt::Std;
use WebJob::JqdRoutines 1.024;
use WebJob::KvpRoutines 1.029;
use WebJob::Properties 1.035;

BEGIN
{
  ####################################################################
  #
  # The Properties hash is essentially private. Those parts of the
  # program that wish to access or modify the data in this hash need
  # to call GetProperties() to obtain a reference.
  #
  ####################################################################

  my (%hProperties);

  ####################################################################
  #
  # Initialize regex variables.
  #
  ####################################################################

  $hProperties{'CommonRegexes'} = PropertiesGetGlobalRegexes();

  ####################################################################
  #
  # Define helper routines.
  #
  ####################################################################

  sub GetProperties
  {
    return \%hProperties;
  }
}

######################################################################
#
# Main Routine
#
######################################################################

  ####################################################################
  #
  # Punch in and go to work.
  #
  ####################################################################

  my ($phProperties);

  $phProperties = GetProperties();

  $$phProperties{'Program'} = basename(__FILE__);

  ####################################################################
  #
  # Get Options.
  #
  ####################################################################

  my (%hOptions);

  if (!getopts('d:e:G:i:t', \%hOptions))
  {
    Usage($$phProperties{'Program'});
  }

  ####################################################################
  #
  # A job queue directory, '-d', is optional.
  #
  ####################################################################

  $$phProperties{'JobQueueDirectory'} = (exists($hOptions{'d'})) ? $hOptions{'d'} : "/var/webjob/spool/jqd";

  ####################################################################
  #
  # A comma delimited list of excludes, '-e', is optional.
  #
  ####################################################################

  $$phProperties{'ExcludeList'} = (exists($hOptions{'e'})) ? $hOptions{'e'} : "";

  ####################################################################
  #
  # A group file, '-G', is optional.
  #
  ####################################################################

  $$phProperties{'GroupsFile'} = (exists($hOptions{'G'})) ? $hOptions{'G'} : "/var/webjob/config/jqd/groups";

  ####################################################################
  #
  # A comma delimited list of includes, '-i', is required.
  #
  ####################################################################

  my (@aIncludes);

  $$phProperties{'IncludeList'} = (exists($hOptions{'i'})) ? $hOptions{'i'} : "";

  if ($$phProperties{'IncludeList'} eq "")
  {
    Usage($$phProperties{'Program'});
  }

  ####################################################################
  #
  # The thaw flag, '-t', is optional.
  #
  ####################################################################

  $$phProperties{'Thaw'} = (exists($hOptions{'t'})) ? 1 : 0;

  ####################################################################
  #
  # If any arguments remain, it's an error.
  #
  ####################################################################

  if (scalar(@ARGV) > 0)
  {
    Usage($$phProperties{'Program'});
  }

  ####################################################################
  #
  # Make sure the job queue directory exists.
  #
  ####################################################################

  if (!-d $$phProperties{'JobQueueDirectory'})
  {
    print STDERR "$$phProperties{'Program'}: Error='Base directory ($$phProperties{'JobQueueDirectory'}) does not exist.'\n";
    exit(2);
  }

  ####################################################################
  #
  # Create forward/reverse queue maps.
  #
  ####################################################################

  my (%hForwardQueueMap, %hQueueMapArgs, %hReverseQueueMap);

  %hQueueMapArgs =
  (
    'ForwardQueueMap'   => \%hForwardQueueMap,
    'JobQueueDirectory' => $$phProperties{'JobQueueDirectory'},
    'KeyRegex'          => "(?:" . $$phProperties{'CommonRegexes'}{'ClientId'} . "|" . $$phProperties{'CommonRegexes'}{'ClientSuppliedFilename'} . ")",
    'ReverseQueueMap'   => \%hReverseQueueMap,
    'SharedLock'        => 1,
    'ValueRegex'        => "\\d+",
  );
  if (!JqdSetupQueueMaps(\%hQueueMapArgs))
  {
    print STDERR "$$phProperties{'Program'}: Error='$hQueueMapArgs{'Error'}'\n";
    exit(2);
  }

  ####################################################################
  #
  # Create group queue map, and conditionally fill it with groups.
  #
  ####################################################################

  my (%hGroupMap);

  %hGroupMap = ();

  if (-f $$phProperties{'GroupsFile'})
  {
    my $sKeyRegex = $$phProperties{'CommonRegexes'}{'Group'};
    my $sUnitRegex = "(?:" . $$phProperties{'CommonRegexes'}{'GroupToken'} . "|" . $$phProperties{'CommonRegexes'}{'ClientId'} . ")";
    my $sValueRegex = "(?:|$sUnitRegex(?:,$sUnitRegex)*)"; # Empty groups are allowed.
    my %hLArgs =
    (
      'File'           => $$phProperties{'GroupsFile'},
      'Properties'     => \%hGroupMap,
      'Template'       => { $sKeyRegex => $sValueRegex, },
      'VerifyValues'   => 1,
    );
    if (!KvpGetKvps(\%hLArgs))
    {
      print STDERR "$$phProperties{'Program'}: Error='$hLArgs{'Error'}'\n";
      exit(2);
    }
  }

  ####################################################################
  #
  # Resolve the include and exclude lists.
  #
  ####################################################################

  my (%hExcludes, %hIncludes, %hResolverArgs);

  %hResolverArgs =
  (
    'ForwardMap'     => \%hForwardQueueMap,
    'GroupMap'       => \%hGroupMap,
    'QueueMap'       => \%hIncludes,
    'QueueList'      => $$phProperties{'IncludeList'},
    'RecursionStack' => [],
  );
  if (!JqdResolveQueueList(\%hResolverArgs))
  {
    print STDERR "$$phProperties{'Program'}: IncludeList='$$phProperties{'IncludeList'}' Error='$hResolverArgs{'Error'}'\n";
    exit(2);
  }

  %hResolverArgs =
  (
    'ForwardMap'     => \%hForwardQueueMap,
    'GroupMap'       => \%hGroupMap,
    'QueueMap'       => \%hExcludes,
    'QueueList'      => $$phProperties{'ExcludeList'},
    'RecursionStack' => [],
  );
  if (!JqdResolveQueueList(\%hResolverArgs))
  {
    print STDERR "$$phProperties{'Program'}: ExcludeList='$$phProperties{'ExcludeList'}' Error='$hResolverArgs{'Error'}'\n";
    exit(2);
  }

  ####################################################################
  #
  # Bash the excludes against the includes, and remove the overlap.
  #
  ####################################################################

  foreach my $sExclude (sort(keys(%hExcludes)))
  {
    if (exists($hIncludes{$sExclude}))
    {
      delete($hIncludes{$sExclude});
    }
  }

  ####################################################################
  #
  # Make sure all queues exist.
  #
  ####################################################################

  my (@aMissingQueues);

  foreach my $sQueue (sort(keys(%hIncludes)))
  {
    my $sQueueDirectory = $$phProperties{'JobQueueDirectory'} . "/" . $sQueue;
    if (!-d $sQueueDirectory)
    {
      push(@aMissingQueues, $sQueue);
    }
  }

  if (scalar(@aMissingQueues) > 0)
  {
    print STDERR "$$phProperties{'Program'}: Error='One or more queues (" . join(",", @aMissingQueues) . ") do not exist. No queues can be manipulated until this is fixed.'\n";
    exit(2);
  }

  ####################################################################
  #
  # Do some work.
  #
  ####################################################################

  my (@aResults);

  foreach my $sQueue (sort(keys(%hIncludes)))
  {
    ##################################################################
    #
    # Freeze or thaw the specified queue.
    #
    ##################################################################

    my (%hLArgs, $sJqdQueueDirectory, $sStatus);

    $sJqdQueueDirectory = $$phProperties{'JobQueueDirectory'} . "/" . $sQueue;

    %hLArgs =
    (
      'Directory' => $sJqdQueueDirectory,
    );
    $sStatus = ($$phProperties{'Thaw'}) ? JqdThawQueue(\%hLArgs) : JqdFreezeQueue(\%hLArgs);
    if (!defined($sStatus))
    {
      print STDERR "$$phProperties{'Program'}: Queue='$sQueue' Error='$hLArgs{'Error'}'\n";
      push(@aResults, "fail|$hLArgs{'CurrentState'}|$sQueue");
    }
    else
    {
      push(@aResults, "$sStatus|$hLArgs{'CurrentState'}|$sQueue");
    }
  }

  ####################################################################
  #
  # Report the results.
  #
  ####################################################################

  foreach my $sResult (@aResults)
  {
    print $sResult, "\n";
  }

  ####################################################################
  #
  # Shutdown and go home.
  #
  ####################################################################

  1;


######################################################################
#
# Usage
#
######################################################################

sub Usage
{
  my ($sProgram) = @_;
  print STDERR "\n";
  print STDERR "Usage: $sProgram [-t] [-d jqd-dir] [-e queue[,queue[...]]] [-G group-file] -i queue[,queue[...]]\n";
  print STDERR "\n";
  exit(1);
}


=pod

=head1 NAME

webjob-jqd-freeze-queue - Freeze or thaw the specified job queues.

=head1 SYNOPSIS

B<webjob-jqd-freeze-queue> B<[-t]> B<[-d jqd-dir]> B<[-e queue[,queue[...]]]> B<[-G group-file]> B<-i queue[,queue[...]]>

=head1 DESCRIPTION

This utility freezes or thaws the specified job queues.

=head1 OPTIONS

=over 4

=item B<-d jqd-dir>

Specifies the base directory where queues live.  This directory must
exist.  The default value is /var/webjob/spool/jqd.

=item B<-e queue[,queue[...]]>

Specifies one or more queues or queue groups that are to be excluded
from the job assignment.  Note that group names must be prefixed with
'%'.  For example, a group called 'test' must be specified as '%test'.

=item B<-G group-file>

Specifies an alternate group file.  The default group file is
/var/webjob/config/jqd/groups.

=item B<-i queue[,queue[...]]>

Specifies one or more queues or queue groups that are to be included
in the job assignment.  Note that group names must be prefixed with
'%'.  For example, a group called 'test' must be specified as '%test'.

=item B<-t>

Causes the script to thaw (rather than freeze) the specified queues.

=back

=head1 AUTHOR

Klayton Monroe

=head1 SEE ALSO

webjob-jqd-create-queue(1), webjob-jqd-delete-queue(1)

=head1 LICENSE

All documentation and code are distributed under same terms and
conditions as B<WebJob>.

=cut
