hms_jobs_report.sh #2

  • //
  • p4-hms/
  • dev/
  • tools/
  • hms_jobs_report.sh
  • View
  • Commits
  • Open Download .zip Download (10 KB)
#!/bin/bash
#==============================================================================
# Copyright and license info is available in the LICENSE file included with
# the Helm Management System (HMS), and also available online:
# https://workshop.perforce.com/projects/perforce-software-hms/view/main/LICENSE
#------------------------------------------------------------------------------

#==============================================================================
# Declarations and Environment

# Allow override of P4U_HOME, which is set only when testing P4U scripts.
declare ThisScript="${0##*/}"
declare Version="1.3.1"
declare Log=
declare H="\n------------------------------------------------------------------------------"

declare ToolsDir="$PWD"
declare ReportStyle="OpenJobs"
declare ReportStyleTitle=
declare JobSearchQuery=
declare WorkshopUser="Unset"
declare JobStatusValues=
declare MaxTitleLength=70
declare -i ShowUserJobsOnly=0
declare -i SilentMode=0
declare -i JobCount=0
declare -i ErrorCount=0
declare -i Debug=0

#==============================================================================
# Local Functions

function msg () { echo -e "$*"; }
function errmsg () { msg "\nError: ${1:-Unknown Error}\n"; ErrorCount+=1; }
function dbg () { [[ "$Debug" -ne 0 ]] && msg "$*"; }

#------------------------------------------------------------------------------
# Function: terminate
function terminate
{
   # Disable signal trapping.
   trap - EXIT SIGINT SIGTERM

   dbg "$ThisScript: EXITCODE: $ErrorCount"

   # Stop logging.
   [[ "$Log" == off ]] || msg "\nLog is: $Log\n"

   # With the trap removed, exit.
   exit "$ErrorCount"
}

#------------------------------------------------------------------------------
# Function: usage (required function)
#
# Input:
# $1 - style, either -h (for short form) or -man (for man-page like format).
# The default is -h.
#
# $2 - error message (optional).  Specify this if usage() is called due to
# user error, in which case the given message displayed first, followed by the
# standard usage message (short or long depending on $1).  If displaying an
# errror, usually $1 should be -h so that the longer usage message doesn't
# obsure the error message.
#
# Sample Usage:
# usage
# usage -h
# usage -man
# usage -h "Incorrect command line usage."
#------------------------------------------------------------------------------
function usage
{
   declare style=${1:--h}
   declare errorMessage=${2:-Unset}

   if [[ $errorMessage != Unset ]]; then
      echo -e "\n\nUsage Error:\n\n$errorMessage\n\n"
   fi

   echo "USAGE for $ThisScript v$Version:

$ThisScript [-a|-o] [-me | -u <workshop_user>] [-st <status1>[,<status2>,...]] [-L <log>] [-si] [-v<n>] [-n] [-d|-D]

or

$ThisScript [-h|-man]
"
   if [[ $style == -man ]]; then
      echo -e "
DESCRIPTION:
	This script produces HMS jobs reports.

OPTIONS:
 -a	Show all HMS jobs regardless of the state.

 -o	Show only \"Open\" HMS jobs, which includes jobs in these states:
        * open
        * inprogress
        * blocked

	This skips jobs in these states:
	* closed
        * duplicate
        * fixed (optional status to use before closed).
	* punted
        * obsolete
	* suspended

	The '-o' behavior is the default.

 -me	Show only jobs for which the OwnedBy setting is the current user.
	Guessing logic is applied to map the current OS user to a Workshop account,
	e.g. ttyler -> tom_tyler, etc.  This works for some folks.

	See the guess_workshop_user() function in env.sh for details.

	Works with '-a' and '-o'.

 -u <workshop_user>
	Show only jobs for which the OwnedBy setting is the specified Workshop user
	account.

	Specify the special value 'none' to list unassigned jobs, i.e. those for
	which the OwnedBy field is not set.

	Works with '-a' and '-o'.

 -st <status1>[,<status2>,...]
	Specify a comma-delimited list of status values to include.

	The valid values can be seen by doing: p4 jobspec -o

 -v<n>	Set verbosity 1-5 (-v1 = quiet, -v5 = highest).

	The default is -v3.

	Specify -v4 to see the query used with the 'p4 jobs -e' command.

 -L <log>
	Specify the path to report log file, or the special value 'off' to disable
	logging.  By default, all output (stdout and stderr) goes to a file, then
	name of which is displayed when the script starts.

	NOTE: This script is self-logging.  That is, output displayed on the screen
	is simultaneously captured in the log file.  Do not run this script with
	redirection operators like '> log' or '2>&1', and do not use 'tee'.

-si	Operate silently.  All output (stdout and stderr) is redirected to the log
	only; no output appears on the terminal.  This cannot be used with
	'-L off'.
      
 -r	No-Op.  Prints commands instead of running them.

 -d     Set debugging verbosity.

 -D     Set extreme debugging verbosity using bash '-x' mode.

HELP OPTIONS:
 -h	Display short help message
 -man	Display man-style help message
 -V	Dispay version info for this script and its libraries.

EXAMPLES:
	Typical usage is with no arguments, to display open jobs:

	$ThisScript

	Show opened jobs assigned to me (based on the \$WORKSHOP_USER shell
	environment setting).

	$ThisScript -me

	Show only items listed as inprogress:

	$ThisScript -st inprogress

SEE ALSO:
"
   fi

   exit 1
}

#==============================================================================
# Command Line Processing

declare -i shiftArgs=0

set +u
while [[ $# -gt 0 ]]; do
   case $1 in
      (-a) ReportStyle="AllJobs";;
      (-o) ReportStyle="OpenJobs";;
      (-me) ShowUserJobsOnly=1; WorkshopUser="me";;
      (-u) ShowUserJobsOnly=1; WorkshopUser="$2"; shiftArgs=1;;
      (-st) JobStatusValues="$2"; shiftArgs=1;;
      (-h) usage -h;;
      (-man) usage -man;;
      (-L) Log="$2"; shiftArgs=1;;
      (-si) SilentMode=1;;
      (-n) export NO_OP=1;;
      (-d) Debug=1;; 
      (-D) Debug=1; set -x;; # Extreme debug; use bash 'set -x' mode.
      (*) usage -h "Unknown arg ($1).";;
   esac

   # Shift (modify $#) the appropriate number of times.
   shift; while [[ $shiftArgs -gt 0 ]]; do
      [[ $# -eq 0 ]] && usage -h "Incorrect number of arguments."
      shiftArgs=$shiftArgs-1
      shift
   done
done
set -u

#==============================================================================
# Command Line Verification

[[ $SilentMode -eq 1 && "$Log" == off ]] && \
   usage -h "Cannot use '-si' with '-L off'."

[[ -z "$Log" ]] && Log="${LOGS:-.}/jobs_report.${WORKSHOP_PROJECT_TAG}.$(date +'%Y%m%d-%H%M').txt"

[[ "$WorkshopUser" == "me" ]] && WorkshopUser="$(guess_workshop_user)"

#==============================================================================
# Main Program

trap terminate EXIT SIGINT SIGTERM

if [[ "$Log" != off ]]; then
   touch $Log || bail "Couldn't touch log file [$Log]."

   # Redirect stdout and stderr to a log file.
   if [[ $SilentMode -eq 0 ]]; then
      exec > >(tee "$Log")
      exec 2>&1
   else
      exec > "$Log"
      exec 2>&1
   fi
fi

msg "${H}\nStarted $ThisScript v$Version as $USER@${HOSTNAME%%.*}. on $(date)."

if [[ $ReportStyle == "OpenJobs" ]]; then
   ReportStyleTitle="Open Jobs"

   if [[ -n "$JobStatusValues" ]]; then
      # Query to show only HMS jobs in specific states.
      if [[ "$JobStatusValues" =~ /,/ ]];then
         # Query for a single job status
         JobSearchQuery="Project=$WORKSHOP_PROJECT Status=$JobStatusValues"
      else
         # Query for multiple job status values
         JobSearchQuery="Project=$WORKSHOP_PROJECT ("
         declare -i first=1
         for status in ${JobStatusValues/,/ }; do
            if [[ $first -eq 1 ]]; then
               first=0
               JobSearchQuery+="Status=$status"
            else
               JobSearchQuery+="|Status=$status"
            fi
         done
         JobSearchQuery+=")"
      fi
   else
      # Query to show only "Open" HMS jobs. See usage info for this script and
      # 'p4 jobspec -o' for details on all states.
      JobSearchQuery="Project=$WORKSHOP_PROJECT ^Status=closed ^Status=duplicate ^Status=fixed ^Status=obsolete ^Status=punted ^Status=suspended"
   fi
else
   ReportStyleTitle="Open Jobs"

   # Query to show all HMS jobs.
   JobSearchQuery="Project=$WORKSHOP_PROJECT"
fi

[[ "$ShowUserJobsOnly" -eq 1 ]] && ReportStyleTitle+=" owned by $WorkshopUser"

dbg "Job Search Query: $JobSearchQuery"

printf "HMS Jobs Report showing $ReportStyleTitle\n\n %-8s %-12s %-2s %-16s %-12s %-s\n" "Job" "Status" "Pr" "Owner" "Component" "Title"
printf " %-8s %-12s %-2s %-16s %-12s %-s\n" "--------" "------------" "--" "----------------" "------------" "----------------------------------------------------------------------"

for job in $(p4 -ztag -F %Job% jobs -e "$JobSearchQuery"); do
   jobData=$(p4 -ztag -F "%OwnedBy%:%Component%:%Status%:%Severity%" job -o $job)
   ownedBy="${jobData%%:*}"
   status="${jobData#*:}"
   status="${status#*:}"
   status="${status%:*}"
   component="${jobData#*:}"
   component="${component%%:*}"
   priority=${jobData##*:}

   # Skip jobs by users other than the current user of '-me' was specified.
   if [[ $ShowUserJobsOnly -eq 1 ]]; then
      if [[ "$WorkshopUser" == "none" ]]; then
         [[ -n "$ownedBy" ]] && continue
      else
         [[ "$ownedBy" != "$WorkshopUser" ]] && continue
      fi
   fi

   jobTitle=$(p4 -ztag -F %Description% job -o $job | head -1)
   jobTitle=$(echo $jobTitle | cut -c -$MaxTitleLength)
   printf " %-8s %-12s %-2s %-16s %-12s %-s\n" "$job" "$status" "$priority" "$ownedBy" "$component" "$jobTitle"
   JobCount+=1
done

msg "${H}\n$JobCount jobs reported in $(($SECONDS/3600)) hours $(($SECONDS%3600/60)) minutes $(($SECONDS%60)) seconds.\n"

# See the terminate() function, which is really where this script exits.
exit $ErrorCount
# Change User Description Committed
#2 33529 C. Thomas Tyler Cosmetic: normalize double-backslash \\n / \\t to single-backslash \n / \t

An older version of ShellCheck once recommended escaping backslash-n and
backslash-t as \\n / \\t in double-quoted strings; a later version reversed
that guidance since it was unnecessary. Both forms behave identically at
runtime, but the double-backslash form is visual clutter. Applied via
tools/sed_fixer.sh across the tree; no functional change.
#1 33516 C. Thomas Tyler Consistency pass: fix absolute URLs, p4ms->hms renames, script/doc typos and bugs

- Convert absolute workshop.perforce.com URLs to relative paths in dlp/ReadMe.md
- Fix case-mismatch link to HMS_Product_Roadmap.md in README.md
- Rename reset_p4ms.sh -> reset_hms.sh and p4broker_p4ms_test -> p4broker_hms_test
- Fix .sh-suffix bugs: bin/hms calling global_replica_status.sh (should be no ext),
  and matching SEE ALSO / doc references for sdp_sync and global_replica_status
- Add missing scripts (gtu, hrun, irun, global_replica_status) to gen_script_man_pages.sh
- Add stub scripts: nj_help.sh, broker_njob.pl, broker_mkproj.pl, broker_jr.pl
- Remove dangling absolute symlinks HostCM/p4 and HostCM/p4d (cruft)
- Rename test/b -> test/broker_ctl.sh for clarity
- Fix real bugs: broker_imply-u.pl broken regex match, gen_dlp_broker_cfg.sh and
  gen_nj_broker_cfg.sh copy-pasted Version-file existence check, garbled comment
  in broker_must_be_owner.pl, unclosed quote in tools/gsr.sh usage(), missing 'h'
  in HMS_SystemComponents.md broker command example (^ms$ -> ^hms$)
- Fix broken sed command and incomplete sentence in HMS_Install_Notes.md and
  SDP_and_HMS_Update_Process.md
- Fix broken markdown table in HMS_Product_Roadmap.md
- Fix unclosed parenthesis, missing verb, and FKA Swarm mislabel in
  HMSDeploymentPlanning.adoc
- Standardize //streams/main/... naming in HostCM/ReadMe.md
- Numerous typo fixes across README.md, HMS_SystemComponents.md,
  SDP_and_HMS_Update_Process.md, HMS_TightShipManagement.adoc,
  HMSDeploymentPlanning.adoc, HostCM/ReadMe.md, and various scripts

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>