[VOL-5263] - fix for openolt adpter crash issue

Change-Id: Ieeb22b562837b741a5ef902d0cf92e252bc5d1b4
Signed-off-by: Akash Soni <akash.soni@radisys.com>
diff --git a/VERSION b/VERSION
index b799a39..48e7fae 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-4.5.3-dev1
+4.5.3-dev2
diff --git a/internal/pkg/core/device_handler.go b/internal/pkg/core/device_handler.go
index f41ab4d..725acec 100755
--- a/internal/pkg/core/device_handler.go
+++ b/internal/pkg/core/device_handler.go
@@ -2513,13 +2513,6 @@
 
 	dh.StopAllFlowRoutines(ctx)
 
-	err := dh.cleanupDeviceResources(ctx)
-	if err != nil {
-		logger.Errorw(ctx, "could-not-remove-device-from-KV-store", log.Fields{"device-id": dh.device.Id, "err": err})
-	} else {
-		logger.Debugw(ctx, "successfully-removed-device-from-Resource-manager-KV-store", log.Fields{"device-id": dh.device.Id})
-	}
-
 	dh.lockDevice.RLock()
 	// Stop the Stats collector
 	if dh.isCollectorActive {
@@ -2534,6 +2527,14 @@
 		dh.stopIndications <- true
 	}
 	dh.lockDevice.RUnlock()
+
+	err := dh.cleanupDeviceResources(ctx)
+	if err != nil {
+		logger.Errorw(ctx, "could-not-remove-device-from-KV-store", log.Fields{"device-id": dh.device.Id, "err": err})
+	} else {
+		logger.Debugw(ctx, "successfully-removed-device-from-Resource-manager-KV-store", log.Fields{"device-id": dh.device.Id})
+	}
+
 	dh.removeOnuIndicationChannels(ctx)
 	//Reset the state
 	if dh.Client != nil {
diff --git a/internal/pkg/core/openolt.go b/internal/pkg/core/openolt.go
index c6d5563..ec47cd0 100644
--- a/internal/pkg/core/openolt.go
+++ b/internal/pkg/core/openolt.go
@@ -274,8 +274,29 @@
 		if err := handler.DeleteDevice(log.WithSpanFromContext(context.Background(), ctx), device); err != nil {
 			return nil, err
 		}
-		oo.deleteDeviceHandlerToMap(handler)
-		return &empty.Empty{}, nil
+		// Initialize a ticker with a 2-second interval to periodically check the states
+		ticker := time.NewTicker(2 * time.Second)
+		defer ticker.Stop()
+
+		// Set a maximum timeout duration of 30 seconds for the loop
+		timeout := time.After(30 * time.Second)
+
+		for {
+			select {
+			case <-ticker.C:
+				// Check if all processes have stopped
+				if !handler.isHeartbeatCheckActive && !handler.isCollectorActive && !handler.isReadIndicationRoutineActive {
+					logger.Debugf(ctx, "delete-device-handler")
+					oo.deleteDeviceHandlerToMap(handler)
+					return &empty.Empty{}, nil
+				}
+			case <-timeout:
+				// Timeout exceeded
+				logger.Warnw(ctx, "delete-device-handler timeout exceeded", log.Fields{"device-id": device.Id})
+				oo.deleteDeviceHandlerToMap(handler) // Clean up anyway
+				return &empty.Empty{}, nil
+			}
+		}
 	}
 	return nil, olterrors.NewErrNotFound("device-handler", log.Fields{"device-id": device.Id}, nil)
 }