Prefix $silo to the list of active builds
[releng/builder.git] / jjb / opendaylight-infra-cleanup-stale-stacks.sh
1 #!/bin/bash
2 virtualenv "$WORKSPACE/.venv"
3 # shellcheck disable=SC1090
4 source "$WORKSPACE/.venv/bin/activate"
5 pip install --upgrade pip
6 pip install --upgrade python-openstackclient python-heatclient
7 pip freeze
8
9 #########################
10 ## FETCH ACTIVE BUILDS ##
11 #########################
12 # Fetch stack list before fetching active builds to minimize race condition
13 # where we might be try to delete stacks while jobs are trying to start
14 OS_STACKS=($(openstack stack list \
15             -f json -c "Stack Name" -c "Stack Status" \
16             --property "stack_status=CREATE_COMPLETE" \
17             --property "stack_status=DELETE_FAILED" \
18             --property "stack_status=CREATE_FAILED" \
19             | jq -r '.[] | ."Stack Name"'))
20
21 # Make sure we fetch active builds on both the releng and sandbox silos
22 ACTIVE_BUILDS=()
23 for silo in releng sandbox; do
24     JENKINS_URL="https://jenkins.opendaylight.org/$silo//computer/api/json?tree=computer[executors[currentExecutable[url]],oneOffExecutors[currentExecutable[url]]]&xpath=//url&wrapper=builds"
25     wget --no-verbose -O "${silo}_builds.json" "$JENKINS_URL"
26     sleep 1  # Need to sleep for 1 second otherwise next line causes script to stall
27     ACTIVE_BUILDS=(${ACTIVE_BUILDS[@]} $( \
28         jq -r '.computer[].executors[].currentExecutable.url' "${silo}_builds.json" \
29         | grep -v null | awk -F'/' '{print $4 "-" $6 "-" $7}'))
30 done
31
32 ##########################
33 ## DELETE UNUSED STACKS ##
34 ##########################
35 # Search for stacks taht are not in use by either releng or sandbox silos and
36 # delete them.
37 for stack in "${OS_STACKS[@]}"; do
38     if [[ "${ACTIVE_BUILDS[@]}" =~ $stack ]]; then
39         # No need to delete stacks if there exists an active build for them
40         continue
41     else
42         echo "Deleting orphaned stack: $stack"
43         openstack stack delete --yes "$stack"
44     fi
45 done