Clean L2GW CSIT, use same VMs as NetVirt
[releng/builder.git] / jjb / odl-openstack-cleanup-orphaned-nodes.sh
1 #!/bin/bash
2 # SPDX-License-Identifier: EPL-1.0
3 ##############################################################################
4 # Copyright (c) 2017 - 2018 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 # shellcheck source=/tmp/v/openstack/bin/activate disable=SC1091
14 source "/tmp/v/openstack/bin/activate"
15
16 minion_in_jenkins() {
17     # Usage: check_stack_in_jenkins STACK_NAME JENKINS_URL [JENKINS_URL...]
18     # Returns: 0 If stack is in Jenkins and 1 if stack is not in Jenkins.
19
20     MINION="${1}"
21
22     minions=()
23     for jenkins in "${@:2}"; do
24         JENKINS_URL="$jenkins/computer/api/json?tree=computer[displayName]"
25         resp=$(curl -s -w "\\n\\n%{http_code}" --globoff -H "Content-Type:application/json" "$JENKINS_URL")
26         json_data=$(echo "$resp" | head -n1)
27         #status=$(echo "$resp" | awk 'END {print $NF}')
28
29         # We purposely want to wordsplit here to combine the arrays
30         # shellcheck disable=SC2206,SC2207
31         minions=(${minions[@]} $(echo "$json_data" | \
32             jq -r '.computer[].displayName' | grep -v master)
33         )
34     done
35
36     if [[ "${minions[*]}" =~ $MINION ]]; then
37         return 0
38     fi
39
40     return 1
41 }
42
43 ##########################
44 ## FETCH ACTIVE MINIONS ##
45 ##########################
46 # Fetch server list before fetching active minions to minimize race condition
47 # where we might be trying to delete servers while jobs are trying to start
48
49 # We purposely need word splitting here to create the OS_SERVERS array.
50 # shellcheck disable=SC2207
51 OS_SERVERS=($(openstack server list -f value -c "Name" | grep -E 'prd|snd'))
52
53 #############################
54 ## DELETE ORPHANED SERVERS ##
55 #############################
56 # Search for servers that are not in use by either releng or sandbox silos and
57 # delete them.
58 for server in "${OS_SERVERS[@]}"; do
59     # JENKINS_URLS is provided by the Jenkins Job declaration and intentially
60     # needs to be globbed.
61     # shellcheck disable=SC2153,SC2086
62     if minion_in_jenkins "$server" $JENKINS_URLS; then
63         # No need to delete server if it is still attached to Jenkins
64         continue
65     else
66         echo "Deleting $server"
67         openstack server delete "$server"
68     fi
69 done