[VOL-5489] Delete device closed channel crash fix

Change-Id: Ie898d1baa9eda9ad3190f63e92a81c8ff62739d1
Signed-off-by: Abhay Kumar <abhay.kumar@radisys.com>
diff --git a/VERSION b/VERSION
index c78c496..83da99b 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-4.6.2
+4.6.3
diff --git a/internal/pkg/core/device_handler.go b/internal/pkg/core/device_handler.go
index c85be74..30bcbf9 100755
--- a/internal/pkg/core/device_handler.go
+++ b/internal/pkg/core/device_handler.go
@@ -282,7 +282,13 @@
 }
 
 // CloseKVClient closes open KV clients
+// This method is thread-safe and can be called concurrently
 func (dh *DeviceHandler) CloseKVClient(ctx context.Context) {
+	// Acquire read lock to safely iterate over resourceMgr and flowMgr slices
+	// Use RLock since we're only reading the slices, not modifying them
+	dh.lockDevice.RLock()
+	defer dh.lockDevice.RUnlock()
+
 	if dh.resourceMgr != nil {
 		for _, rscMgr := range dh.resourceMgr {
 			if rscMgr != nil {
@@ -2583,6 +2589,11 @@
 	   other pon resources like alloc_id and gemport_id
 	*/
 
+	if dh.getDeviceDeletionInProgressFlag() {
+		logger.Errorw(ctx, "cannot complete operation as device deletion is in progress", log.Fields{"device-id": dh.device.Id})
+		return olterrors.NewErrAdapter(fmt.Errorf("cannot complete operation as device deletion is in progress").Error(), log.Fields{"device-id": dh.device.Id}, nil)
+	}
+
 	dh.setDeviceDeletionInProgressFlag(true)
 	dh.StopAllFlowRoutines(ctx)
 
@@ -2651,7 +2662,7 @@
 
 func (dh *DeviceHandler) cleanupDeviceResources(ctx context.Context) error {
 	var errs []error
-	if dh.resourceMgr != nil {
+	if dh.resourceMgr != nil && dh.totalPonPorts > 0 {
 		var ponPort uint32
 		for ponPort = 0; ponPort < dh.totalPonPorts; ponPort++ {
 			onuGemData := dh.resourceMgr[ponPort].GetOnuGemInfoList(ctx)
@@ -2680,6 +2691,7 @@
 		errs = append(errs, err)
 	}
 
+	logger.Debugw(ctx, "lockDevice for KVStore close client", log.Fields{"deviceID": dh.device.Id})
 	dh.CloseKVClient(ctx)
 
 	// Take one final sweep at cleaning up KV store for the OLT device