2 # SPDX-License-Identifier: EPL-1.0
3 ##############################################################################
4 # Copyright (c) 2017, 2018 The Linux Foundation and others.
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 # Scans OpenStack for orphaned servers
12 echo "---> Orphaned servers"
14 os_cloud="${OS_CLOUD:-vex}"
15 jenkins_urls="${JENKINS_URLS:-}"
18 # Usage: minion_in_jenkins STACK_NAME JENKINS_URL [JENKINS_URL...]
19 # Returns: 0 If stack is in Jenkins and 1 if stack is not in Jenkins.
24 for jenkins in "${@:2}"; do
25 JENKINS_URL="$jenkins/computer/api/json?tree=computer[displayName]"
26 resp=$(curl -s -w "\\n\\n%{http_code}" --globoff -H "Content-Type:application/json" "$JENKINS_URL")
27 json_data=$(echo "$resp" | head -n1)
28 status=$(echo "$resp" | awk 'END {print $NF}')
30 if [ "$status" != 200 ]; then
31 >&2 echo "ERROR: Failed to fetch data from $JENKINS_URL with status code $status"
36 # We purposely want to wordsplit here to combine the arrays
37 # shellcheck disable=SC2206,SC2207
38 minions=(${minions[@]} $(echo "$json_data" | \
39 jq -r '.computer[].displayName' | grep -v master)
43 if [[ "${minions[*]}" =~ $MINION ]]; then
50 # shellcheck disable=SC1090
53 lf-activate-venv --python python3 "lftools[openstack]" \
57 python-openstackclient \
61 ##########################
62 ## FETCH ACTIVE MINIONS ##
63 ##########################
64 # Fetch server list before fetching active minions to minimize race condition
65 # where we might be trying to delete servers while jobs are trying to start
67 mapfile -t OS_SERVERS < <(openstack --os-cloud "$os_cloud" server list -f value -c "Name" | grep -E 'prd|snd')
69 echo "-----> Active servers"
70 for server in "${OS_SERVERS[@]}"; do
75 #############################
76 ## DELETE ORPHANED SERVERS ##
77 #############################
78 echo "-----> Delete orphaned servers"
80 # Search for servers not in use by any active Jenkins systems and remove them.
81 for server in "${OS_SERVERS[@]}"; do
82 # jenkins_urls intentially needs globbing to be passed a separate params.
83 # needs to be globbed.
84 # shellcheck disable=SC2153,SC2086
85 if minion_in_jenkins "$server" $jenkins_urls; then
86 # No need to delete server if it is still attached to Jenkins
89 echo "Deleting orphaned server: $server"
90 lftools openstack --os-cloud "$os_cloud" \
91 server remove --minutes 15 "$server"