e1f84360c9d4266b764a4d59511db760528bb6a1
[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 os_cloud="${OS_CLOUD:-vex}"
18
19 # Check if openstack venv was previously created
20 if [ -f "/tmp/.os_lf_venv" ]; then
21     os_lf_venv=$(cat "/tmp/.os_lf_venv")
22 fi
23
24 if [ -d "${os_lf_venv}" ] && [ -f "${os_lf_venv}/bin/openstack" ]; then
25     echo "Re-use existing venv: ${os_lf_venv}"
26     PATH=$os_lf_venv/bin:$PATH
27 else
28     lf-activate-venv --python python3 \
29         python-heatclient \
30         python-openstackclient
31 fi
32
33 set -eux -o pipefail
34
35 mapfile -t os_ports_ts < <(openstack --os-cloud "$os_cloud" port list \
36         -f value \
37         -c ID \
38         -c status \
39         -c created_at \
40         | grep -E DOWN \
41         | awk -F' ' '{print $1 " " $3}')
42
43 if [ ${#os_ports_ts[@]} -eq 0 ]; then
44     echo "No orphaned ports found."
45 else
46     cutoff=$(date -d "30 minutes ago"  +%s)
47     for port_ts in "${os_ports_ts[@]}"; do
48         created_at_isots="${port_ts#* }"
49         port_uuid="${port_ts% *}"
50         echo "checking port uuid: ${port_uuid} with TS: ${created_at_isots}"
51         created_at_uxts=$(date -d "${created_at_isots}" +"%s")
52         # Clean up ports where created_at > 30 minutes
53         if [[ "$created_at_uxts" -gt "$cutoff" ]]; then
54             echo "Removing orphaned port $port_uuid created_at ts > 30 minutes."
55             openstack --os-cloud "$os_cloud" port delete "$port_uuid"
56         fi
57     done
58 fi