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