#!/bin/sh
###################################
#
#  File: lrmsinfo-condor
# 
#  Author: David Rebatto
#  Email:  david.rebatto@mi.infn.it
#
# 30/05/2013: first release 
# 13/09/2016: use configuration file
#
###################################

# Read command line parameter
#
config_file=${1:-/etc/lrms/condor.conf}
if [[ ! -r $config_file ]]; then
  echo "$0: cannot read configuration file $config_file" >&2
  exit 1
fi

# Source the config file
#
. $config_file

condorstatus="${condor_path:-/usr/bin}/condor_status ${condor_host:+-pool $condor_host}"
condorq="${condor_path:-/usr/bin}/condor_q ${condor_host:+-pool $condor_host}"

# Build a reference classAd with MaxWallclockTime 
# values for all the queues
if [[ "$deployment" == "queue_to_schedd" ]]; then
  ## There is a schedd per queue (running on the central manager)
  ##  The queue information are stored as attributes of the schedd's classad
  maxwtime=$(
   echo -n "["
   $condorstatus -subsystem schedd \
     -format "'%s'=" Name \
     -format "%d;"   MaxWallclockTime
   echo "]"
  )
  # ClassAd function to extract the schedd name from the job id
  getqueue='regexps("^([^#]*)", GlobalJobId, "\1")'
elif [[ "$deployment" == "queue_to_jobattribute" ]]; then
  ## There is no relation between schedds and queues
  ##   The queue information are stored as variables in the configuration file
  maxwtime=$(
   echo -n "["
   for queuename in ${queues[@]}; do
     printf "'%s' = %d;" $queuename $(eval echo \$${queuename}_MaxWallClockTime)
   done
   echo "]"
  )
  getqueue="$queue_attribute"
else
  echo "$0: wrong or missing 'deployment' value in $config_file" >&2
  exit 1
fi
 
# Build the list of status strings
states='{"queued","queued","running","done","done","held","done"}'

# Retrieve information from the collector
$condorstatus -collector \
  -format "nactive\t\t%d\n" "HostsTotal-HostsOwner" \
  -format "nfree\t\t%d\n"   "HostsUnclaimed" \
  -format "now\t\t%d\n"     "CurrentTime"

# Retrieve the elapsed time between the last two
# negotiation cycles from negotiator
$condorstatus -negotiator \
  -format "schedCycle\t%d\n" "LastNegotiationCyclePeriod0"

# Retrieve the list of all the jobs
$condorq -global \
  -format "{" EMPTY \
  -format "'start': %d, "       "JobStartDate" \
  -format "'queue': '%s', "     "$getqueue" \
  -format "'state': '%s', "     "$states[eval(JobStatus)]" \
  -format "'cpucount': '%d', "  "OrigMaxHosts" \
  -format "'group': '%s', "     "Group =!= UNDEFINED ? Group : \"N/A\"" \
  -format "'user': '%s', "      "Owner" \
  -format "'maxwalltime': %d, " "$maxwtime[$getqueue]" \
  -format "'qtime': %d, "       "QDate" \
  -format "'jobid': '%s', "     "GlobalJobId" \
  -format "}\n" EMPTY 

