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