Fix: Use lf-activate-venv to install openstack dep
[releng/global-jjb.git] / shell / openstack-cleanup-orphaned-ports.sh
index fac8d20..e1f8436 100644 (file)
 # Scans OpenStack for orphaned ports
 echo "---> Orphaned ports"
 
+# shellcheck disable=SC1090
+source ~/lf-env.sh
+
 os_cloud="${OS_CLOUD:-vex}"
 
+# Check if openstack venv was previously created
+if [ -f "/tmp/.os_lf_venv" ]; then
+    os_lf_venv=$(cat "/tmp/.os_lf_venv")
+fi
+
+if [ -d "${os_lf_venv}" ] && [ -f "${os_lf_venv}/bin/openstack" ]; then
+    echo "Re-use existing venv: ${os_lf_venv}"
+    PATH=$os_lf_venv/bin:$PATH
+else
+    lf-activate-venv --python python3 \
+        python-heatclient \
+        python-openstackclient
+fi
+
 set -eux -o pipefail
 
-mapfile -t os_ports < <(openstack --os-cloud "$os_cloud" port list -f value -c ID -c status | egrep DOWN | awk '{print $1}')
+mapfile -t os_ports_ts < <(openstack --os-cloud "$os_cloud" port list \
+        -f value \
+        -c ID \
+        -c status \
+        -c created_at \
+        | grep -E DOWN \
+        | awk -F' ' '{print $1 " " $3}')
 
-if [ ${#os_ports[@]} -eq 0 ]; then
+if [ ${#os_ports_ts[@]} -eq 0 ]; then
     echo "No orphaned ports found."
 else
-    for port in "${os_ports[@]}"; do
-        echo "Removing orphaned port $port"
-        openstack --os-cloud "$os_cloud" port delete "$port"
+    cutoff=$(date -d "30 minutes ago"  +%s)
+    for port_ts in "${os_ports_ts[@]}"; do
+        created_at_isots="${port_ts#* }"
+        port_uuid="${port_ts% *}"
+        echo "checking port uuid: ${port_uuid} with TS: ${created_at_isots}"
+        created_at_uxts=$(date -d "${created_at_isots}" +"%s")
+        # Clean up ports where created_at > 30 minutes
+        if [[ "$created_at_uxts" -gt "$cutoff" ]]; then
+            echo "Removing orphaned port $port_uuid created_at ts > 30 minutes."
+            openstack --os-cloud "$os_cloud" port delete "$port_uuid"
+        fi
     done
 fi