2 # SPDX-License-Identifier: EPL-1.0
3 ##############################################################################
4 # Copyright (c) 2017, 2022 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 COE clusters
12 echo "---> Orphaned k8s clusters"
14 os_cloud="${OS_CLOUD:-vex}"
15 jenkins_urls="${JENKINS_URLS:-}"
17 cluster_in_jenkins() {
18 # Usage: cluster_in_jenkins CLUSTER_NAME JENKINS_URL [JENKINS_URL...]
19 # Returns: 0 If CLUSTER_NAME is in Jenkins and 1 if CLUSTER_NAME is not
25 for jenkins in "${@:2}"; do
26 PARAMS="tree=computer[executors[currentExecutable[url]],"
27 PARAMS=$PARAMS"oneOffExecutors[currentExecutable[url]]]"
28 PARAMS=$PARAMS"&xpath=//url&wrapper=builds"
29 JENKINS_URL="$jenkins/computer/api/json?$PARAMS"
30 resp=$(curl -s -w "\\n\\n%{http_code}" --globoff -H "Content-Type:application/json" "$JENKINS_URL")
31 json_data=$(echo "$resp" | head -n1)
32 status=$(echo "$resp" | awk 'END {print $NF}')
34 if [ "$status" != 200 ]; then
35 >&2 echo "ERROR: Failed to fetch data from $JENKINS_URL with status code $status"
40 if [[ "${jenkins}" == *"jenkins."*".org" ]] || [[ "${jenkins}" == *"jenkins."*".io" ]]; then
43 silo=$(echo "$jenkins" | sed 's/\/*$//' | awk -F'/' '{print $NF}')
46 # We purposely want to wordsplit here to combine the arrays
47 # shellcheck disable=SC2206,SC2207
48 builds=(${builds[@]} $(echo "$json_data" | \
49 jq -r '.computer[].executors[].currentExecutable.url' \
50 | grep -v null | awk -F'/' '{print ENVIRON["silo"] "-" $6 "-" $7}')
54 if [[ "${builds[*]}" =~ $CLUSTER_NAME ]]; then
61 #########################
62 ## FETCH ACTIVE BUILDS ##
63 #########################
64 # Fetch coe cluster list before fetching active stacks.
65 mapfile -t OS_COE_CLUSTERS < <(openstack --os-cloud "$os_cloud" coe cluster list \
66 -f value -c "uuid" -c "name" -c "status" -c "health_status" \
69 ##########################
70 ## DELETE UNUSED STACKS ##
71 ##########################
72 echo "-----> Delete orphaned cluster"
74 # Search for COE clusters not in use by any active Jenkins systems and remove them.
75 for CLUSTER_NAME in "${OS_COE_CLUSTERS[@]}"; do
76 # jenkins_urls intentially needs globbing to be passed a separate params.
77 # shellcheck disable=SC2153,SC2086
78 if cluster_in_jenkins "$CLUSTER_NAME" $jenkins_urls; then
79 # No need to delete stacks if there exists an active build for them
82 echo "Deleting orphaned k8s cluster: $CLUSTER_NAME"
83 openstack --os-cloud "$os_cloud" coe cluster delete "$CLUSTER_NAME"