Fix orphaned nodes script
[releng/builder.git] / jjb / opendaylight-infra-cleanup-orphaned-nodes.sh
1 #!/bin/bash
2 # SPDX-License-Identifier: EPL-1.0
3 ##############################################################################
4 # Copyright (c) 2017 The Linux Foundation and others.
5 #
6 # All rights reserved. This program and the accompanying materials
7 # are made available under the terms of the Eclipse Public License v1.0
8 # which accompanies this distribution, and is available at
9 # http://www.eclipse.org/legal/epl-v10.html
10 ##############################################################################
11 echo "---> Cleanup orphaned servers"
12
13 virtualenv "/tmp/v/openstack"
14 # shellcheck source=/tmp/v/openstack/bin/activate disable=SC1091
15 source "/tmp/v/openstack/bin/activate"
16 pip install --upgrade pip
17 pip install --upgrade python-openstackclient python-heatclient
18 pip install --upgrade pipdeptree
19 pipdeptree
20
21 ##########################
22 ## FETCH ACTIVE MINIONS ##
23 ##########################
24 # Fetch server list before fetching active minions to minimize race condition
25 # where we might be trying to delete servers while jobs are trying to start
26 OS_SERVERS=($(openstack server list -f value -c "Name" | grep -E 'prd|snd'))
27
28 # Make sure we fetch active minions on both the releng and sandbox silos
29 ACTIVE_MINIONS=()
30 for silo in releng sandbox; do
31     JENKINS_URL="https://jenkins.opendaylight.org/$silo/computer/api/json?tree=computer[displayName]"
32     wget -nv -O "${silo}_builds.json" "$JENKINS_URL"
33     sleep 1  # Need to sleep for 1 second otherwise next line causes script to stall
34     ACTIVE_MINIONS=(${ACTIVE_MINIONS[@]} $( \
35         jq -r '.computer[].displayName' "${silo}_builds.json" | grep -v master))
36 done
37
38 #############################
39 ## DELETE ORPHANED SERVERS ##
40 #############################
41 # Search for servers that are not in use by either releng or sandbox silos and
42 # delete them.
43 for server in "${OS_SERVERS[@]}"; do
44     if [[ "${ACTIVE_MINIONS[*]}" =~ $server ]]; then
45         # No need to delete server if it is still attached to Jenkins
46         continue
47     else
48         echo "Deleting $server"
49         openstack server delete "$server"
50     fi
51 done