blob: 7ba67a05707e4441e4d31b63242a2b340d5257be [file] [log] [blame]
Zack Williams704f70a2018-07-18 15:22:35 -07001#!/usr/bin/env bash
2
3# Copyright 2018-present Open Networking Foundation
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17# wait-for-jobs.sh
18# waits for all kubernetes jobs to complete before exiting
19# inspired by similar scripts in Kolla-Kubernetes and Openstack Helm
20
21set -e -u -o pipefail
22fail_wfj=0
23
24# Set these to configure maximum timeout, and interval for checks
25JOBS_TIMEOUT=${JOBS_TIMEOUT:-600}
26CHECK_INTERVAL=${CHECK_INTERVAL:-5}
27KUBECTL_ARGS=${KUBECTL_ARGS:-}
28
29# calculate timeout time
30START_TIME=$(date +%s)
31END_TIME=$((START_TIME + JOBS_TIMEOUT))
32
33echo "wait_for_jobs.sh - Waiting up to ${JOBS_TIMEOUT} seconds for all Kubernetes jobs to complete"
34echo "Number printed is number of currently active jobs"
35
36prev_job_count=0
37
38while true; do
39 NOW=$(date +%s)
40
41 # handle timeout without completion
42 if [ "$NOW" -gt "$END_TIME" ]
43 then
44 echo "Jobs didn't complete before timout of ${JOBS_TIMEOUT} seconds"
45 fail_wfj=1
46 break
47 fi
48
49 # get list of active jobs, and count of them
50 # jsonpath is picky about string vs comparison quoting, so have to have:
51 # shellcheck disable=SC2026
52 active_jobs=$(kubectl get jobs $KUBECTL_ARGS -o=jsonpath='{range .items[?(@.status.active=='1')]}{.metadata.name}{"\n"}{end}')
53 active_job_count=$(echo "${active_jobs}" | wc -l)
54
55 # if no jobs active, print runtime and break
56 if [ -z "$active_jobs" ]
57 then
58 runtime=$((NOW - START_TIME))
59 echo ""
60 echo "All jobs completed in $runtime seconds"
61 break
62 fi
63
64 # deal with changes in number of jobs
65 if [ "$active_job_count" -ne "$prev_job_count" ]
66 then
67 echo ""
68 echo "Number of active jobs changed - current jobs:"
69 echo "$active_jobs"
70 fi
71 prev_job_count=$active_job_count
72
73 # print number of remaining jobs every $CHECK_INTERVAL
74 echo -n "$active_job_count"
75 sleep "$CHECK_INTERVAL"
76done
77
78echo ""
79echo "Job Status - Name | Start Time | Completion Time"
80kubectl get jobs $KUBECTL_ARGS -o=jsonpath='{range .items[*]}{.metadata.name}{"\t| "}{.status.startTime}{" | "}{.status.completionTime}{"\n"}{end}'
81
82exit ${fail_wfj}