From c0d1bb1a5c988c3d0880060089ac39bdbf52f67a Mon Sep 17 00:00:00 2001
From: Kenichi Omichi <ken1ohmichi@gmail.com>
Date: Sat, 15 Jan 2022 00:50:15 -0800
Subject: [PATCH] Remove subnet from router on tf-elastx_cleanup (#8425)

The tf-elastx_cleanup test job was failed with error message:

Port xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx cannot be deleted
directly via the port API: has device owner network:router_interface.

That means necessary to remove a subnet from the router before
deleting the port.
This adds a method to removes a subnet from the router automatically.
---
 scripts/openstack-cleanup/main.py | 22 ++++++++++++++++++++--
 1 file changed, 20 insertions(+), 2 deletions(-)

diff --git a/scripts/openstack-cleanup/main.py b/scripts/openstack-cleanup/main.py
index 9bc24d3f3..511f06087 100755
--- a/scripts/openstack-cleanup/main.py
+++ b/scripts/openstack-cleanup/main.py
@@ -42,8 +42,26 @@ def main():
                conn.network.security_groups())
 
     print('Ports...')
-    map_if_old(conn.network.delete_port,
-               conn.network.ports())
+    try:
+        map_if_old(conn.network.delete_port,
+                   conn.network.ports())
+    except openstack.exceptions.ConflictException as ex:
+        # Need to find subnet-id which should be removed from a router
+        for sn in conn.network.subnets():
+            try:
+                fn_if_old(conn.network.delete_subnet, sn)
+            except openstack.exceptions.ConflictException:
+                for r in conn.network.routers():
+                    print("Deleting subnet %s from router %s", sn, r)
+                    try:
+                        conn.network.remove_interface_from_router(
+                            r, subnet_id=sn.id)
+                    except Exception as ex:
+                        print("Failed to delete subnet from router as %s", ex)
+
+        # After removing unnecessary subnet from router, retry to delete ports
+        map_if_old(conn.network.delete_port,
+                   conn.network.ports())
 
     print('Subnets...')
     map_if_old(conn.network.delete_subnet,
-- 
GitLab