1#!/usr/bin/env bash
2# Copyright 2023 gRPC authors.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#     http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16set -eo pipefail
17
18SCRIPT_DIR="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
19readonly SCRIPT_DIR
20readonly XDS_K8S_DRIVER_DIR="${SCRIPT_DIR}/.."
21
22cd "${XDS_K8S_DRIVER_DIR}"
23
24NO_SECURE="yes"
25DATE_TO=$(date -Iseconds)
26
27while [[ $# -gt 0 ]]; do
28  case $1 in
29    --secure) NO_SECURE=""; shift ;;
30    --date_to=*) DATE_TO="${1#*=}T00:00:00Z"; shift ;;
31    *) echo "Unknown argument $1"; exit 1 ;;
32  esac
33done
34
35jq_selector=$(cat <<- 'EOM'
36  .items[].metadata |
37  select(
38    (.name | test("-(client|server)-")) and
39    (.creationTimestamp < $date_to)
40  ) | .name
41EOM
42)
43
44mapfile -t namespaces < <(\
45  kubectl get namespaces --sort-by='{.metadata.creationTimestamp}'\
46                         --selector='owner=xds-k8s-interop-test'\
47                          -o json\
48  | jq --arg date_to "${DATE_TO}" -r "${jq_selector}"
49)
50
51if [[ -z "${namespaces[*]}"  ]]; then
52    echo "All clean."
53    exit 0
54fi
55
56echo "Found namespaces:"
57namespaces_joined=$(IFS=,; printf '%s' "${namespaces[*]}")
58kubectl get namespaces --sort-by='{.metadata.creationTimestamp}' \
59                       --selector="name in (${namespaces_joined})"
60
61# Suffixes
62mapfile -t suffixes < <(\
63  printf '%s\n' "${namespaces[@]}" | sed -E 's/^.+-(server|client)-//'
64)
65echo
66echo "Found suffixes: ${suffixes[*]}"
67echo "Count: ${#namespaces[@]}"
68
69echo "Run plan:"
70for suffix in "${suffixes[@]}"; do
71  echo ./bin/cleanup.sh ${NO_SECURE:+"--nosecure"} "--resource_suffix=${suffix}"
72done
73
74read -r -n 1 -p "Continue? (y/N) " answer
75if [[ "$answer" != "${answer#[Yy]}" ]] ;then
76  echo
77  echo "Starting the cleanup."
78else
79  echo
80  echo "Exit"
81  exit 0
82fi
83
84failed=0
85for suffix in "${suffixes[@]}"; do
86  echo "-------------------- Cleaning suffix ${suffix} --------------------"
87  set -x
88  ./bin/cleanup.sh ${NO_SECURE:+"--nosecure"} "--resource_suffix=${suffix}" || (( ++failed ))
89  set +x
90  echo "-------------------- Finished cleaning ${suffix} --------------------"
91done
92echo "Failed runs: ${failed}"
93if (( failed > 0 )); then
94  exit 1
95fi
96