Fix: set correct exit status when parsing openstack port objects
[releng/global-jjb.git] / shell / openstack-cleanup-orphaned-ports.sh
1 #!/bin/bash -l
2 # SPDX-License-Identifier: EPL-1.0
3 ##############################################################################
4 # Copyright (c) 2019 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 # Scans OpenStack for orphaned ports
12 echo "---> Orphaned ports"
13
14 # shellcheck disable=SC1090
15 source ~/lf-env.sh
16
17 lf-activate-venv --python python3 "lftools[openstack]" \
18         python-openstackclient
19
20 os_cloud="${OS_CLOUD:-vex}"
21
22 set -eu -o pipefail
23
24 tmpfile=$(mktemp --suffix -openstack-ports.txt)
25 cores=$(nproc --all)
26 threads=$((3*cores))
27
28 # Set age for deletion/removal
29 age="30 minutes ago"
30 cutoff=$(date -d "$age" +%s)
31
32 _cleanup()
33 {
34     uuid=$1
35     created_at=$(openstack --os-cloud "$os_cloud" port show -f value -c created_at "$uuid")
36     if [ "$created_at" == "None" ]; then
37         echo "No value for port creation time; skipping: $uuid"
38     else
39         created_at_uxts=$(date -d "$created_at" +"%s")
40
41         # For debugging only; this outout usually disabled
42         # echo "Port: ${uuid} created at ${created_at} / ${created_at_uxts}"
43
44         # Validate timing values are numeric
45         if [[ "$created_at_uxts" -eq "$created_at_uxts" ]]; then
46             # Clean up ports where created_at > 30 minutes
47             if [[ "$created_at_uxts" -lt "$cutoff" ]]; then
48                 echo "Removing orphaned port $uuid created > $age"
49                 openstack --os-cloud "$os_cloud" port delete "$uuid"
50             fi
51         else
52             echo "Date variable failed numeric test; deletion not possible"
53         fi
54     fi
55 }
56
57 # Output the initial list of port UUIDs to a temporary file
58 openstack --os-cloud "$os_cloud" port list -f value -c ID -c status \
59     | { grep -e DOWN || true; } | { awk '{print $1}' || true; } > "$tmpfile"
60
61 # Count the number to process
62 total=$(wc -l "$tmpfile" | awk '{print $1}')
63 echo "Ports to process: $total; age limit: $cutoff"
64 echo "Using $threads parallel processes..."
65
66 # Export variables and send to parallel for processing
67 export -f _cleanup
68 export os_cloud cutoff age
69 parallel --progress --retries 3 -j "$threads" _cleanup < "$tmpfile"
70
71 rm "$tmpfile"