[VOL-3476] Introduce concurrency handling for MIB template generation
plus minor refactorings

Change-Id: I994d8b0a34eab80368656ff998abda56d1eebb1b
diff --git a/internal/pkg/onuadaptercore/device_handler.go b/internal/pkg/onuadaptercore/device_handler.go
index 49bdaaa..32039ab 100644
--- a/internal/pkg/onuadaptercore/device_handler.go
+++ b/internal/pkg/onuadaptercore/device_handler.go
@@ -1134,10 +1134,7 @@
 		   we omit that here first (declaration unclear) -> todo at Adapter specialization ...*/
 		/* also no 'clock' argument - usage open ...*/
 		/* and no alarm_db yet (oo.alarm_db)  */
-		deviceEntry = newOnuDeviceEntry(ctx, dh.deviceID, dh.pOpenOnuAc.KVStoreHost,
-			dh.pOpenOnuAc.KVStorePort, dh.pOpenOnuAc.KVStoreType,
-			dh, dh.coreProxy, dh.AdapterProxy,
-			dh.pOpenOnuAc.pSupportedFsms) //nil as FSM pointer would yield deviceEntry internal defaults ...
+		deviceEntry = newOnuDeviceEntry(ctx, dh)
 		onuTechProfProc := newOnuUniTechProf(ctx, dh)
 		//error treatment possible //TODO!!!
 		dh.setOnuDeviceEntry(deviceEntry, onuTechProfProc)
diff --git a/internal/pkg/onuadaptercore/mib_sync.go b/internal/pkg/onuadaptercore/mib_sync.go
index bbc3be5..90dd7bb 100644
--- a/internal/pkg/onuadaptercore/mib_sync.go
+++ b/internal/pkg/onuadaptercore/mib_sync.go
@@ -65,92 +65,92 @@
 
 var fsmMsg TestMessageType
 
-func (onuDeviceEntry *OnuDeviceEntry) enterStartingState(e *fsm.Event) {
-	logger.Debugw("MibSync FSM", log.Fields{"Start processing MibSync-msgs in State": e.FSM.Current(), "device-id": onuDeviceEntry.deviceID})
-	onuDeviceEntry.pOnuDB = newOnuDeviceDB(context.TODO(), onuDeviceEntry)
-	go onuDeviceEntry.processMibSyncMessages()
+func (oo *OnuDeviceEntry) enterStartingState(e *fsm.Event) {
+	logger.Debugw("MibSync FSM", log.Fields{"Start processing MibSync-msgs in State": e.FSM.Current(), "device-id": oo.deviceID})
+	oo.pOnuDB = newOnuDeviceDB(context.TODO(), oo)
+	go oo.processMibSyncMessages()
 }
 
-func (onuDeviceEntry *OnuDeviceEntry) enterResettingMibState(e *fsm.Event) {
-	logger.Debugw("MibSync FSM", log.Fields{"Start MibTemplate processing in State": e.FSM.Current(), "device-id": onuDeviceEntry.deviceID})
+func (oo *OnuDeviceEntry) enterResettingMibState(e *fsm.Event) {
+	logger.Debugw("MibSync FSM", log.Fields{"Start MibTemplate processing in State": e.FSM.Current(), "device-id": oo.deviceID})
 
-	logger.Debugw("MibSync FSM", log.Fields{"send mibReset in State": e.FSM.Current(), "device-id": onuDeviceEntry.deviceID})
-	_ = onuDeviceEntry.PDevOmciCC.sendMibReset(context.TODO(), ConstDefaultOmciTimeout, true)
+	logger.Debugw("MibSync FSM", log.Fields{"send mibReset in State": e.FSM.Current(), "device-id": oo.deviceID})
+	_ = oo.PDevOmciCC.sendMibReset(context.TODO(), ConstDefaultOmciTimeout, true)
 
 	//TODO: needs to handle timeouts
 }
 
-func (onuDeviceEntry *OnuDeviceEntry) enterGettingVendorAndSerialState(e *fsm.Event) {
-	logger.Debugw("MibSync FSM", log.Fields{"Start getting VendorId and SerialNumber in State": e.FSM.Current(), "device-id": onuDeviceEntry.deviceID})
+func (oo *OnuDeviceEntry) enterGettingVendorAndSerialState(e *fsm.Event) {
+	logger.Debugw("MibSync FSM", log.Fields{"Start getting VendorId and SerialNumber in State": e.FSM.Current(), "device-id": oo.deviceID})
 	requestedAttributes := me.AttributeValueMap{"VendorId": "", "SerialNumber": 0}
-	meInstance := onuDeviceEntry.PDevOmciCC.sendGetMe(context.TODO(), me.OnuGClassID, onugMeID, requestedAttributes, ConstDefaultOmciTimeout, true)
+	meInstance := oo.PDevOmciCC.sendGetMe(context.TODO(), me.OnuGClassID, onugMeID, requestedAttributes, ConstDefaultOmciTimeout, true)
 	//accept also nil as (error) return value for writing to LastTx
 	//  - this avoids misinterpretation of new received OMCI messages
-	onuDeviceEntry.PDevOmciCC.pLastTxMeInstance = meInstance
+	oo.PDevOmciCC.pLastTxMeInstance = meInstance
 }
 
-func (onuDeviceEntry *OnuDeviceEntry) enterGettingEquipmentIDState(e *fsm.Event) {
-	logger.Debugw("MibSync FSM", log.Fields{"Start getting EquipmentId in State": e.FSM.Current(), "device-id": onuDeviceEntry.deviceID})
+func (oo *OnuDeviceEntry) enterGettingEquipmentIDState(e *fsm.Event) {
+	logger.Debugw("MibSync FSM", log.Fields{"Start getting EquipmentId in State": e.FSM.Current(), "device-id": oo.deviceID})
 	requestedAttributes := me.AttributeValueMap{"EquipmentId": ""}
-	meInstance := onuDeviceEntry.PDevOmciCC.sendGetMe(context.TODO(), me.Onu2GClassID, onu2gMeID, requestedAttributes, ConstDefaultOmciTimeout, true)
+	meInstance := oo.PDevOmciCC.sendGetMe(context.TODO(), me.Onu2GClassID, onu2gMeID, requestedAttributes, ConstDefaultOmciTimeout, true)
 	//accept also nil as (error) return value for writing to LastTx
 	//  - this avoids misinterpretation of new received OMCI messages
-	onuDeviceEntry.PDevOmciCC.pLastTxMeInstance = meInstance
+	oo.PDevOmciCC.pLastTxMeInstance = meInstance
 }
 
-func (onuDeviceEntry *OnuDeviceEntry) enterGettingFirstSwVersionState(e *fsm.Event) {
-	logger.Debugw("MibSync FSM", log.Fields{"Start getting IsActive and Version of first SW-image in State": e.FSM.Current(), "device-id": onuDeviceEntry.deviceID})
+func (oo *OnuDeviceEntry) enterGettingFirstSwVersionState(e *fsm.Event) {
+	logger.Debugw("MibSync FSM", log.Fields{"Start getting IsActive and Version of first SW-image in State": e.FSM.Current(), "device-id": oo.deviceID})
 	requestedAttributes := me.AttributeValueMap{"IsActive": 0, "Version": ""}
-	meInstance := onuDeviceEntry.PDevOmciCC.sendGetMe(context.TODO(), me.SoftwareImageClassID, firstSwImageMeID, requestedAttributes, ConstDefaultOmciTimeout, true)
+	meInstance := oo.PDevOmciCC.sendGetMe(context.TODO(), me.SoftwareImageClassID, firstSwImageMeID, requestedAttributes, ConstDefaultOmciTimeout, true)
 	//accept also nil as (error) return value for writing to LastTx
 	//  - this avoids misinterpretation of new received OMCI messages
-	onuDeviceEntry.PDevOmciCC.pLastTxMeInstance = meInstance
+	oo.PDevOmciCC.pLastTxMeInstance = meInstance
 }
 
-func (onuDeviceEntry *OnuDeviceEntry) enterGettingSecondSwVersionState(e *fsm.Event) {
-	logger.Debugw("MibSync FSM", log.Fields{"Start getting IsActive and Version of second SW-image in State": e.FSM.Current(), "device-id": onuDeviceEntry.deviceID})
+func (oo *OnuDeviceEntry) enterGettingSecondSwVersionState(e *fsm.Event) {
+	logger.Debugw("MibSync FSM", log.Fields{"Start getting IsActive and Version of second SW-image in State": e.FSM.Current(), "device-id": oo.deviceID})
 	requestedAttributes := me.AttributeValueMap{"IsActive": 0, "Version": ""}
-	meInstance := onuDeviceEntry.PDevOmciCC.sendGetMe(context.TODO(), me.SoftwareImageClassID, secondSwImageMeID, requestedAttributes, ConstDefaultOmciTimeout, true)
+	meInstance := oo.PDevOmciCC.sendGetMe(context.TODO(), me.SoftwareImageClassID, secondSwImageMeID, requestedAttributes, ConstDefaultOmciTimeout, true)
 	//accept also nil as (error) return value for writing to LastTx
 	//  - this avoids misinterpretation of new received OMCI messages
-	onuDeviceEntry.PDevOmciCC.pLastTxMeInstance = meInstance
+	oo.PDevOmciCC.pLastTxMeInstance = meInstance
 }
 
-func (onuDeviceEntry *OnuDeviceEntry) enterGettingMacAddressState(e *fsm.Event) {
-	logger.Debugw("MibSync FSM", log.Fields{"Start getting MacAddress in State": e.FSM.Current(), "device-id": onuDeviceEntry.deviceID})
+func (oo *OnuDeviceEntry) enterGettingMacAddressState(e *fsm.Event) {
+	logger.Debugw("MibSync FSM", log.Fields{"Start getting MacAddress in State": e.FSM.Current(), "device-id": oo.deviceID})
 	requestedAttributes := me.AttributeValueMap{"MacAddress": ""}
-	meInstance := onuDeviceEntry.PDevOmciCC.sendGetMe(context.TODO(), me.IpHostConfigDataClassID, ipHostConfigDataMeID, requestedAttributes, ConstDefaultOmciTimeout, true)
+	meInstance := oo.PDevOmciCC.sendGetMe(context.TODO(), me.IpHostConfigDataClassID, ipHostConfigDataMeID, requestedAttributes, ConstDefaultOmciTimeout, true)
 	//accept also nil as (error) return value for writing to LastTx
 	//  - this avoids misinterpretation of new received OMCI messages
-	onuDeviceEntry.PDevOmciCC.pLastTxMeInstance = meInstance
+	oo.PDevOmciCC.pLastTxMeInstance = meInstance
 }
 
-func (onuDeviceEntry *OnuDeviceEntry) enterGettingMibTemplate(e *fsm.Event) {
+func (oo *OnuDeviceEntry) enterGettingMibTemplate(e *fsm.Event) {
 
 	for i := firstSwImageMeID; i <= secondSwImageMeID; i++ {
-		if onuDeviceEntry.swImages[i].isActive > 0 {
-			onuDeviceEntry.activeSwVersion = onuDeviceEntry.swImages[i].version
+		if oo.swImages[i].isActive > 0 {
+			oo.activeSwVersion = oo.swImages[i].version
 		}
 	}
 
 	meStoredFromTemplate := false
-	path := fmt.Sprintf(cSuffixMibTemplateKvStore, onuDeviceEntry.vendorID, onuDeviceEntry.equipmentID, onuDeviceEntry.activeSwVersion)
-	logger.Debugw("MibSync FSM - MibTemplate - etcd search string", log.Fields{"path": path})
-	Value, err := onuDeviceEntry.mibTemplateKVStore.Get(context.TODO(), path)
+	oo.mibTemplatePath = fmt.Sprintf(cSuffixMibTemplateKvStore, oo.vendorID, oo.equipmentID, oo.activeSwVersion)
+	logger.Debugw("MibSync FSM - MibTemplate - etcd search string", log.Fields{"path": oo.mibTemplatePath})
+	Value, err := oo.mibTemplateKVStore.Get(context.TODO(), oo.mibTemplatePath)
 	if err == nil {
 		if Value != nil {
 			logger.Debugf("MibSync FSM - MibTemplate read: Key: %s, Value: %s  %s", Value.Key, Value.Value)
 
 			// swap out tokens with specific data
 			mibTmpString, _ := kvstore.ToString(Value.Value)
-			mibTmpString2 := strings.Replace(mibTmpString, "%SERIAL_NUMBER%", onuDeviceEntry.serialNumber, -1)
-			mibTmpString = strings.Replace(mibTmpString2, "%MAC_ADDRESS%", onuDeviceEntry.macAddress, -1)
+			mibTmpString2 := strings.Replace(mibTmpString, "%SERIAL_NUMBER%", oo.serialNumber, -1)
+			mibTmpString = strings.Replace(mibTmpString2, "%MAC_ADDRESS%", oo.macAddress, -1)
 			mibTmpBytes := []byte(mibTmpString)
 			logger.Debugf("MibSync FSM - MibTemplate tokens swapped out: %s", mibTmpBytes)
 
 			var fistLevelMap map[string]interface{}
 			if err = json.Unmarshal(mibTmpBytes, &fistLevelMap); err != nil {
-				logger.Errorw("MibSync FSM - Failed to unmarshal template", log.Fields{"error": err, "device-id": onuDeviceEntry.deviceID})
+				logger.Errorw("MibSync FSM - Failed to unmarshal template", log.Fields{"error": err, "device-id": oo.deviceID})
 			} else {
 				for fistLevelKey, firstLevelValue := range fistLevelMap {
 					logger.Debugw("MibSync FSM - fistLevelKey", log.Fields{"fistLevelKey": fistLevelKey})
@@ -171,7 +171,7 @@
 											logger.Debugw("MibSync FSM - thirdLevelKey refers to attributes", log.Fields{"thirdLevelKey": thirdLevelKey})
 											attributesMap := thirdLevelValue.(map[string]interface{})
 											logger.Debugw("MibSync FSM - attributesMap", log.Fields{"attributesMap": attributesMap})
-											onuDeviceEntry.pOnuDB.PutMe(meClassID, meEntityID, attributesMap)
+											oo.pOnuDB.PutMe(meClassID, meEntityID, attributesMap)
 											meStoredFromTemplate = true
 										}
 									}
@@ -182,15 +182,15 @@
 				}
 			}
 		} else {
-			logger.Debugw("No MIB template found", log.Fields{"path": path, "device-id": onuDeviceEntry.deviceID})
+			logger.Debugw("No MIB template found", log.Fields{"path": oo.mibTemplatePath, "device-id": oo.deviceID})
 		}
 	} else {
 		logger.Errorf("Get from kvstore operation failed for path",
-			log.Fields{"path": path, "device-id": onuDeviceEntry.deviceID})
+			log.Fields{"path": oo.mibTemplatePath, "device-id": oo.deviceID})
 	}
 	if meStoredFromTemplate {
 		logger.Debug("MibSync FSM - valid MEs stored from template")
-		onuDeviceEntry.pOnuDB.logMeDb()
+		oo.pOnuDB.logMeDb()
 		fsmMsg = LoadMibTemplateOk
 	} else {
 		logger.Debug("MibSync FSM - no valid MEs stored from template - perform MIB-upload!")
@@ -203,87 +203,87 @@
 			TestMessageVal: fsmMsg,
 		},
 	}
-	onuDeviceEntry.pMibUploadFsm.commChan <- mibSyncMsg
+	oo.pMibUploadFsm.commChan <- mibSyncMsg
 }
 
-func (onuDeviceEntry *OnuDeviceEntry) enterUploadingState(e *fsm.Event) {
-	logger.Debugw("MibSync FSM", log.Fields{"send MibUpload in State": e.FSM.Current(), "device-id": onuDeviceEntry.deviceID})
-	_ = onuDeviceEntry.PDevOmciCC.sendMibUpload(context.TODO(), ConstDefaultOmciTimeout, true)
+func (oo *OnuDeviceEntry) enterUploadingState(e *fsm.Event) {
+	logger.Debugw("MibSync FSM", log.Fields{"send MibUpload in State": e.FSM.Current(), "device-id": oo.deviceID})
+	_ = oo.PDevOmciCC.sendMibUpload(context.TODO(), ConstDefaultOmciTimeout, true)
 }
 
-func (onuDeviceEntry *OnuDeviceEntry) enterInSyncState(e *fsm.Event) {
-	logger.Debugw("MibSync FSM", log.Fields{"send notification to core in State": e.FSM.Current(), "device-id": onuDeviceEntry.deviceID})
-	onuDeviceEntry.transferSystemEvent(MibDatabaseSync)
+func (oo *OnuDeviceEntry) enterInSyncState(e *fsm.Event) {
+	logger.Debugw("MibSync FSM", log.Fields{"send notification to core in State": e.FSM.Current(), "device-id": oo.deviceID})
+	oo.transferSystemEvent(MibDatabaseSync)
 }
 
-func (onuDeviceEntry *OnuDeviceEntry) enterExaminingMdsState(e *fsm.Event) {
-	logger.Debugw("MibSync FSM", log.Fields{"Start GetMds processing in State": e.FSM.Current(), "device-id": onuDeviceEntry.deviceID})
+func (oo *OnuDeviceEntry) enterExaminingMdsState(e *fsm.Event) {
+	logger.Debugw("MibSync FSM", log.Fields{"Start GetMds processing in State": e.FSM.Current(), "device-id": oo.deviceID})
 	logger.Debug("function not implemented yet")
 }
 
-func (onuDeviceEntry *OnuDeviceEntry) enterResynchronizingState(e *fsm.Event) {
-	logger.Debugw("MibSync FSM", log.Fields{"Start MibResync processing in State": e.FSM.Current(), "device-id": onuDeviceEntry.deviceID})
+func (oo *OnuDeviceEntry) enterResynchronizingState(e *fsm.Event) {
+	logger.Debugw("MibSync FSM", log.Fields{"Start MibResync processing in State": e.FSM.Current(), "device-id": oo.deviceID})
 	logger.Debug("function not implemented yet")
 }
 
-func (onuDeviceEntry *OnuDeviceEntry) enterAuditingState(e *fsm.Event) {
-	logger.Debugw("MibSync FSM", log.Fields{"Start MibResync processing in State": e.FSM.Current(), "device-id": onuDeviceEntry.deviceID})
+func (oo *OnuDeviceEntry) enterAuditingState(e *fsm.Event) {
+	logger.Debugw("MibSync FSM", log.Fields{"Start MibResync processing in State": e.FSM.Current(), "device-id": oo.deviceID})
 	logger.Debug("function not implemented yet")
 }
 
-func (onuDeviceEntry *OnuDeviceEntry) enterOutOfSyncState(e *fsm.Event) {
-	logger.Debugw("MibSync FSM", log.Fields{"Start  MibReconcile processing in State": e.FSM.Current(), "device-id": onuDeviceEntry.deviceID})
+func (oo *OnuDeviceEntry) enterOutOfSyncState(e *fsm.Event) {
+	logger.Debugw("MibSync FSM", log.Fields{"Start  MibReconcile processing in State": e.FSM.Current(), "device-id": oo.deviceID})
 	logger.Debug("function not implemented yet")
 }
 
-func (onuDeviceEntry *OnuDeviceEntry) processMibSyncMessages( /*ctx context.Context*/ ) {
-	logger.Debugw("MibSync Msg", log.Fields{"Start routine to process OMCI-messages for device-id": onuDeviceEntry.deviceID})
+func (oo *OnuDeviceEntry) processMibSyncMessages( /*ctx context.Context*/ ) {
+	logger.Debugw("MibSync Msg", log.Fields{"Start routine to process OMCI-messages for device-id": oo.deviceID})
 loop:
 	for {
 		// case <-ctx.Done():
 		// 	logger.Info("MibSync Msg", log.Fields{"Message handling canceled via context for device-id": onuDeviceEntry.deviceID})
 		// 	break loop
-		message, ok := <-onuDeviceEntry.pMibUploadFsm.commChan
+		message, ok := <-oo.pMibUploadFsm.commChan
 		if !ok {
-			logger.Info("MibSync Msg", log.Fields{"Message couldn't be read from channel for device-id": onuDeviceEntry.deviceID})
+			logger.Info("MibSync Msg", log.Fields{"Message couldn't be read from channel for device-id": oo.deviceID})
 			break loop
 		}
-		logger.Debugw("MibSync Msg", log.Fields{"Received message on ONU MibSyncChan for device-id": onuDeviceEntry.deviceID})
+		logger.Debugw("MibSync Msg", log.Fields{"Received message on ONU MibSyncChan for device-id": oo.deviceID})
 
 		switch message.Type {
 		case TestMsg:
 			msg, _ := message.Data.(TestMessage)
-			onuDeviceEntry.handleTestMsg(msg)
+			oo.handleTestMsg(msg)
 		case OMCI:
 			msg, _ := message.Data.(OmciMessage)
-			onuDeviceEntry.handleOmciMessage(msg)
+			oo.handleOmciMessage(msg)
 		default:
-			logger.Warn("MibSync Msg", log.Fields{"Unknown message type received for device-id": onuDeviceEntry.deviceID, "message.Type": message.Type})
+			logger.Warn("MibSync Msg", log.Fields{"Unknown message type received for device-id": oo.deviceID, "message.Type": message.Type})
 		}
 	}
-	logger.Info("MibSync Msg", log.Fields{"Stopped handling of MibSyncChan for device-id": onuDeviceEntry.deviceID})
+	logger.Info("MibSync Msg", log.Fields{"Stopped handling of MibSyncChan for device-id": oo.deviceID})
 	// TODO: only this action?
-	_ = onuDeviceEntry.pMibUploadFsm.pFsm.Event(ulEvStop)
+	_ = oo.pMibUploadFsm.pFsm.Event(ulEvStop)
 }
 
-func (onuDeviceEntry *OnuDeviceEntry) handleTestMsg(msg TestMessage) {
+func (oo *OnuDeviceEntry) handleTestMsg(msg TestMessage) {
 
-	logger.Debugw("MibSync Msg", log.Fields{"TestMessage received for device-id": onuDeviceEntry.deviceID, "msg.TestMessageVal": msg.TestMessageVal})
+	logger.Debugw("MibSync Msg", log.Fields{"TestMessage received for device-id": oo.deviceID, "msg.TestMessageVal": msg.TestMessageVal})
 
 	switch msg.TestMessageVal {
 	case LoadMibTemplateFailed:
-		_ = onuDeviceEntry.pMibUploadFsm.pFsm.Event(ulEvUploadMib)
-		logger.Debugw("MibSync Msg", log.Fields{"state": string(onuDeviceEntry.pMibUploadFsm.pFsm.Current())})
+		_ = oo.pMibUploadFsm.pFsm.Event(ulEvUploadMib)
+		logger.Debugw("MibSync Msg", log.Fields{"state": string(oo.pMibUploadFsm.pFsm.Current())})
 	case LoadMibTemplateOk:
-		_ = onuDeviceEntry.pMibUploadFsm.pFsm.Event(ulEvSuccess)
-		logger.Debugw("MibSync Msg", log.Fields{"state": string(onuDeviceEntry.pMibUploadFsm.pFsm.Current())})
+		_ = oo.pMibUploadFsm.pFsm.Event(ulEvSuccess)
+		logger.Debugw("MibSync Msg", log.Fields{"state": string(oo.pMibUploadFsm.pFsm.Current())})
 	default:
-		logger.Warn("MibSync Msg", log.Fields{"Unknown message type received for device-id": onuDeviceEntry.deviceID, "msg.TestMessageVal": msg.TestMessageVal})
+		logger.Warn("MibSync Msg", log.Fields{"Unknown message type received for device-id": oo.deviceID, "msg.TestMessageVal": msg.TestMessageVal})
 	}
 }
 
-func (onuDeviceEntry *OnuDeviceEntry) handleOmciMibResetResponseMessage(msg OmciMessage) {
-	if onuDeviceEntry.pMibUploadFsm.pFsm.Is(ulStResettingMib) {
+func (oo *OnuDeviceEntry) handleOmciMibResetResponseMessage(msg OmciMessage) {
+	if oo.pMibUploadFsm.pFsm.Is(ulStResettingMib) {
 		msgLayer := (*msg.OmciPacket).Layer(omci.LayerTypeMibResetResponse)
 		if msgLayer != nil {
 			msgObj, msgOk := msgLayer.(*omci.MibResetResponse)
@@ -291,49 +291,49 @@
 				logger.Debugw("MibResetResponse Data", log.Fields{"data-fields": msgObj})
 				if msgObj.Result == me.Success {
 					// trigger retrieval of VendorId and SerialNumber
-					_ = onuDeviceEntry.pMibUploadFsm.pFsm.Event(ulEvGetVendorAndSerial)
+					_ = oo.pMibUploadFsm.pFsm.Event(ulEvGetVendorAndSerial)
 					return
 				}
-				logger.Errorw("Omci MibResetResponse Error", log.Fields{"device-id": onuDeviceEntry.deviceID, "Error": msgObj.Result})
+				logger.Errorw("Omci MibResetResponse Error", log.Fields{"device-id": oo.deviceID, "Error": msgObj.Result})
 			} else {
-				logger.Errorw("Omci Msg layer could not be assigned", log.Fields{"device-id": onuDeviceEntry.deviceID})
+				logger.Errorw("Omci Msg layer could not be assigned", log.Fields{"device-id": oo.deviceID})
 			}
 		} else {
-			logger.Errorw("Omci Msg layer could not be detected", log.Fields{"device-id": onuDeviceEntry.deviceID})
+			logger.Errorw("Omci Msg layer could not be detected", log.Fields{"device-id": oo.deviceID})
 		}
 	} else {
-		logger.Errorw("Wrong Omci MibResetResponse received", log.Fields{"in state ": onuDeviceEntry.pMibUploadFsm.pFsm.Current,
-			"device-id": onuDeviceEntry.deviceID})
+		logger.Errorw("Wrong Omci MibResetResponse received", log.Fields{"in state ": oo.pMibUploadFsm.pFsm.Current,
+			"device-id": oo.deviceID})
 	}
-	logger.Info("MibSync Msg", log.Fields{"Stopped handling of MibSyncChan for device-id": onuDeviceEntry.deviceID})
-	_ = onuDeviceEntry.pMibUploadFsm.pFsm.Event(ulEvStop)
+	logger.Info("MibSync Msg", log.Fields{"Stopped handling of MibSyncChan for device-id": oo.deviceID})
+	_ = oo.pMibUploadFsm.pFsm.Event(ulEvStop)
 
 }
 
-func (onuDeviceEntry *OnuDeviceEntry) handleOmciMibUploadResponseMessage(msg OmciMessage) {
+func (oo *OnuDeviceEntry) handleOmciMibUploadResponseMessage(msg OmciMessage) {
 	msgLayer := (*msg.OmciPacket).Layer(omci.LayerTypeMibUploadResponse)
 	if msgLayer == nil {
-		logger.Errorw("Omci Msg layer could not be detected", log.Fields{"device-id": onuDeviceEntry.deviceID})
+		logger.Errorw("Omci Msg layer could not be detected", log.Fields{"device-id": oo.deviceID})
 		return
 	}
 	msgObj, msgOk := msgLayer.(*omci.MibUploadResponse)
 	if !msgOk {
-		logger.Errorw("Omci Msg layer could not be assigned", log.Fields{"device-id": onuDeviceEntry.deviceID})
+		logger.Errorw("Omci Msg layer could not be assigned", log.Fields{"device-id": oo.deviceID})
 		return
 	}
-	logger.Debugw("MibUploadResponse Data for:", log.Fields{"device-id": onuDeviceEntry.deviceID, "data-fields": msgObj})
+	logger.Debugw("MibUploadResponse Data for:", log.Fields{"device-id": oo.deviceID, "data-fields": msgObj})
 	/* to be verified / reworked !!! */
-	onuDeviceEntry.PDevOmciCC.uploadNoOfCmds = msgObj.NumberOfCommands
-	if onuDeviceEntry.PDevOmciCC.uploadSequNo < onuDeviceEntry.PDevOmciCC.uploadNoOfCmds {
-		_ = onuDeviceEntry.PDevOmciCC.sendMibUploadNext(context.TODO(), ConstDefaultOmciTimeout, true)
+	oo.PDevOmciCC.uploadNoOfCmds = msgObj.NumberOfCommands
+	if oo.PDevOmciCC.uploadSequNo < oo.PDevOmciCC.uploadNoOfCmds {
+		_ = oo.PDevOmciCC.sendMibUploadNext(context.TODO(), ConstDefaultOmciTimeout, true)
 	} else {
-		logger.Errorw("Invalid number of commands received for:", log.Fields{"device-id": onuDeviceEntry.deviceID, "uploadNoOfCmds": onuDeviceEntry.PDevOmciCC.uploadNoOfCmds})
+		logger.Errorw("Invalid number of commands received for:", log.Fields{"device-id": oo.deviceID, "uploadNoOfCmds": oo.PDevOmciCC.uploadNoOfCmds})
 		//TODO right action?
-		_ = onuDeviceEntry.pMibUploadFsm.pFsm.Event(ulEvTimeout)
+		_ = oo.pMibUploadFsm.pFsm.Event(ulEvTimeout)
 	}
 }
 
-func (onuDeviceEntry *OnuDeviceEntry) handleOmciMibUploadNextResponseMessage(msg OmciMessage) {
+func (oo *OnuDeviceEntry) handleOmciMibUploadNextResponseMessage(msg OmciMessage) {
 	msgLayer := (*msg.OmciPacket).Layer(omci.LayerTypeMibUploadNextResponse)
 
 	//TODO: temporary change due to VOL-3532
@@ -344,151 +344,151 @@
 	if msgLayer != nil {
 		msgObj, msgOk := msgLayer.(*omci.MibUploadNextResponse)
 		if !msgOk {
-			logger.Errorw("Omci Msg layer could not be assigned", log.Fields{"device-id": onuDeviceEntry.deviceID})
+			logger.Errorw("Omci Msg layer could not be assigned", log.Fields{"device-id": oo.deviceID})
 			return
 		}
-		logger.Debugw("MibUploadNextResponse Data for:", log.Fields{"device-id": onuDeviceEntry.deviceID, "data-fields": msgObj})
+		logger.Debugw("MibUploadNextResponse Data for:", log.Fields{"device-id": oo.deviceID, "data-fields": msgObj})
 		meClassID := msgObj.ReportedME.GetClassID()
 		meEntityID := msgObj.ReportedME.GetEntityID()
 		meAttributes := msgObj.ReportedME.GetAttributeValueMap()
 
-		onuDeviceEntry.pOnuDB.PutMe(meClassID, meEntityID, meAttributes)
+		oo.pOnuDB.PutMe(meClassID, meEntityID, meAttributes)
 	} else {
-		logger.Warnw("msgLayer could not be decoded - temporary workaround for VOL-3532 in place!", log.Fields{"device-id": onuDeviceEntry.deviceID})
+		logger.Warnw("msgLayer could not be decoded - temporary workaround for VOL-3532 in place!", log.Fields{"device-id": oo.deviceID})
 	}
-	if onuDeviceEntry.PDevOmciCC.uploadSequNo < onuDeviceEntry.PDevOmciCC.uploadNoOfCmds {
-		_ = onuDeviceEntry.PDevOmciCC.sendMibUploadNext(context.TODO(), ConstDefaultOmciTimeout, true)
+	if oo.PDevOmciCC.uploadSequNo < oo.PDevOmciCC.uploadNoOfCmds {
+		_ = oo.PDevOmciCC.sendMibUploadNext(context.TODO(), ConstDefaultOmciTimeout, true)
 	} else {
-		onuDeviceEntry.pOnuDB.logMeDb()
-		err := onuDeviceEntry.createAndPersistMibTemplate()
+		oo.pOnuDB.logMeDb()
+		err := oo.createAndPersistMibTemplate()
 		if err != nil {
-			logger.Errorw("MibSync - MibTemplate - Failed to create and persist the mib template", log.Fields{"error": err, "device-id": onuDeviceEntry.deviceID})
+			logger.Errorw("MibSync - MibTemplate - Failed to create and persist the mib template", log.Fields{"error": err, "device-id": oo.deviceID})
 		}
 
-		_ = onuDeviceEntry.pMibUploadFsm.pFsm.Event(ulEvSuccess)
+		_ = oo.pMibUploadFsm.pFsm.Event(ulEvSuccess)
 	}
 }
 
-func (onuDeviceEntry *OnuDeviceEntry) handleOmciGetResponseMessage(msg OmciMessage) error {
+func (oo *OnuDeviceEntry) handleOmciGetResponseMessage(msg OmciMessage) error {
 	var err error = nil
 	msgLayer := (*msg.OmciPacket).Layer(omci.LayerTypeGetResponse)
 	if msgLayer == nil {
-		logger.Errorw("omci Msg layer could not be detected for GetResponse - handling of MibSyncChan stopped", log.Fields{"device-id": onuDeviceEntry.deviceID})
-		_ = onuDeviceEntry.pMibUploadFsm.pFsm.Event(ulEvStop)
-		return fmt.Errorf("omci Msg layer could not be detected for GetResponse - handling of MibSyncChan stopped: %s", onuDeviceEntry.deviceID)
+		logger.Errorw("omci Msg layer could not be detected for GetResponse - handling of MibSyncChan stopped", log.Fields{"device-id": oo.deviceID})
+		_ = oo.pMibUploadFsm.pFsm.Event(ulEvStop)
+		return fmt.Errorf("omci Msg layer could not be detected for GetResponse - handling of MibSyncChan stopped: %s", oo.deviceID)
 	}
 	msgObj, msgOk := msgLayer.(*omci.GetResponse)
 	if !msgOk {
-		logger.Errorw("omci Msg layer could not be assigned for GetResponse - handling of MibSyncChan stopped", log.Fields{"device-id": onuDeviceEntry.deviceID})
-		_ = onuDeviceEntry.pMibUploadFsm.pFsm.Event(ulEvStop)
-		return fmt.Errorf("omci Msg layer could not be assigned for GetResponse - handling of MibSyncChan stopped: %s", onuDeviceEntry.deviceID)
+		logger.Errorw("omci Msg layer could not be assigned for GetResponse - handling of MibSyncChan stopped", log.Fields{"device-id": oo.deviceID})
+		_ = oo.pMibUploadFsm.pFsm.Event(ulEvStop)
+		return fmt.Errorf("omci Msg layer could not be assigned for GetResponse - handling of MibSyncChan stopped: %s", oo.deviceID)
 	}
-	logger.Debugw("MibSync FSM - GetResponse Data", log.Fields{"device-id": onuDeviceEntry.deviceID, "data-fields": msgObj})
+	logger.Debugw("MibSync FSM - GetResponse Data", log.Fields{"device-id": oo.deviceID, "data-fields": msgObj})
 	if msgObj.Result == me.Success {
-		entityID := onuDeviceEntry.PDevOmciCC.pLastTxMeInstance.GetEntityID()
-		if msgObj.EntityClass == onuDeviceEntry.PDevOmciCC.pLastTxMeInstance.GetClassID() && msgObj.EntityInstance == entityID {
+		entityID := oo.PDevOmciCC.pLastTxMeInstance.GetEntityID()
+		if msgObj.EntityClass == oo.PDevOmciCC.pLastTxMeInstance.GetClassID() && msgObj.EntityInstance == entityID {
 			meAttributes := msgObj.Attributes
-			meInstance := onuDeviceEntry.PDevOmciCC.pLastTxMeInstance.GetName()
-			logger.Debugf("MibSync FSM - GetResponse Data for %s", log.Fields{"device-id": onuDeviceEntry.deviceID, "data-fields": msgObj}, meInstance)
+			meInstance := oo.PDevOmciCC.pLastTxMeInstance.GetName()
+			logger.Debugf("MibSync FSM - GetResponse Data for %s", log.Fields{"device-id": oo.deviceID, "data-fields": msgObj}, meInstance)
 			switch meInstance {
 			case "OnuG":
-				onuDeviceEntry.vendorID = trimStringFromInterface(meAttributes["VendorId"])
+				oo.vendorID = trimStringFromInterface(meAttributes["VendorId"])
 				snBytes, _ := me.InterfaceToOctets(meAttributes["SerialNumber"])
 				if onugSerialNumberLen == len(snBytes) {
 					snVendorPart := fmt.Sprintf("%s", snBytes[:4])
 					snNumberPart := hex.EncodeToString(snBytes[4:])
-					onuDeviceEntry.serialNumber = snVendorPart + snNumberPart
-					logger.Debugw("MibSync FSM - GetResponse Data for Onu-G - VendorId/SerialNumber", log.Fields{"device-id": onuDeviceEntry.deviceID,
-						"onuDeviceEntry.vendorID": onuDeviceEntry.vendorID, "onuDeviceEntry.serialNumber": onuDeviceEntry.serialNumber})
+					oo.serialNumber = snVendorPart + snNumberPart
+					logger.Debugw("MibSync FSM - GetResponse Data for Onu-G - VendorId/SerialNumber", log.Fields{"device-id": oo.deviceID,
+						"onuDeviceEntry.vendorID": oo.vendorID, "onuDeviceEntry.serialNumber": oo.serialNumber})
 				} else {
-					logger.Infow("MibSync FSM - SerialNumber has wrong length - fill serialNumber with zeros", log.Fields{"device-id": onuDeviceEntry.deviceID, "length": len(snBytes)})
-					onuDeviceEntry.serialNumber = cEmptySerialNumberString
+					logger.Infow("MibSync FSM - SerialNumber has wrong length - fill serialNumber with zeros", log.Fields{"device-id": oo.deviceID, "length": len(snBytes)})
+					oo.serialNumber = cEmptySerialNumberString
 				}
 				// trigger retrieval of EquipmentId
-				_ = onuDeviceEntry.pMibUploadFsm.pFsm.Event(ulEvGetEquipmentID)
+				_ = oo.pMibUploadFsm.pFsm.Event(ulEvGetEquipmentID)
 				return nil
 			case "Onu2G":
-				onuDeviceEntry.equipmentID = trimStringFromInterface(meAttributes["EquipmentId"])
-				logger.Debugw("MibSync FSM - GetResponse Data for Onu2-G - EquipmentId", log.Fields{"device-id": onuDeviceEntry.deviceID,
-					"onuDeviceEntry.equipmentID": onuDeviceEntry.equipmentID})
+				oo.equipmentID = trimStringFromInterface(meAttributes["EquipmentId"])
+				logger.Debugw("MibSync FSM - GetResponse Data for Onu2-G - EquipmentId", log.Fields{"device-id": oo.deviceID,
+					"onuDeviceEntry.equipmentID": oo.equipmentID})
 				// trigger retrieval of 1st SW-image info
-				_ = onuDeviceEntry.pMibUploadFsm.pFsm.Event(ulEvGetFirstSwVersion)
+				_ = oo.pMibUploadFsm.pFsm.Event(ulEvGetFirstSwVersion)
 				return nil
 			case "SoftwareImage":
 				if entityID <= secondSwImageMeID {
-					onuDeviceEntry.swImages[entityID].version = trimStringFromInterface(meAttributes["Version"])
-					onuDeviceEntry.swImages[entityID].isActive = meAttributes["IsActive"].(uint8)
+					oo.swImages[entityID].version = trimStringFromInterface(meAttributes["Version"])
+					oo.swImages[entityID].isActive = meAttributes["IsActive"].(uint8)
 					logger.Debugw("MibSync FSM - GetResponse Data for SoftwareImage - Version/IsActive",
-						log.Fields{"device-id": onuDeviceEntry.deviceID, "entityID": entityID,
-							"version": onuDeviceEntry.swImages[entityID].version, "isActive": onuDeviceEntry.swImages[entityID].isActive})
+						log.Fields{"device-id": oo.deviceID, "entityID": entityID,
+							"version": oo.swImages[entityID].version, "isActive": oo.swImages[entityID].isActive})
 				} else {
-					err = fmt.Errorf("mibSync FSM - Failed to GetResponse Data for SoftwareImage: %s", onuDeviceEntry.deviceID)
+					err = fmt.Errorf("mibSync FSM - Failed to GetResponse Data for SoftwareImage: %s", oo.deviceID)
 				}
 				if firstSwImageMeID == entityID {
-					_ = onuDeviceEntry.pMibUploadFsm.pFsm.Event(ulEvGetSecondSwVersion)
+					_ = oo.pMibUploadFsm.pFsm.Event(ulEvGetSecondSwVersion)
 					return nil
 				} else if secondSwImageMeID == entityID {
-					_ = onuDeviceEntry.pMibUploadFsm.pFsm.Event(ulEvGetMacAddress)
+					_ = oo.pMibUploadFsm.pFsm.Event(ulEvGetMacAddress)
 					return nil
 				}
 			case "IpHostConfigData":
 				macBytes, _ := me.InterfaceToOctets(meAttributes["MacAddress"])
 				if omciMacAddressLen == len(macBytes) {
-					onuDeviceEntry.macAddress = hex.EncodeToString(macBytes[:])
-					logger.Debugw("MibSync FSM - GetResponse Data for IpHostConfigData - MacAddress", log.Fields{"device-id": onuDeviceEntry.deviceID,
-						"onuDeviceEntry.macAddress": onuDeviceEntry.macAddress})
+					oo.macAddress = hex.EncodeToString(macBytes[:])
+					logger.Debugw("MibSync FSM - GetResponse Data for IpHostConfigData - MacAddress", log.Fields{"device-id": oo.deviceID,
+						"onuDeviceEntry.macAddress": oo.macAddress})
 				} else {
-					logger.Infow("MibSync FSM - MacAddress wrong length - fill macAddress with zeros", log.Fields{"device-id": onuDeviceEntry.deviceID, "length": len(macBytes)})
-					onuDeviceEntry.macAddress = cEmptyMacAddrString
+					logger.Infow("MibSync FSM - MacAddress wrong length - fill macAddress with zeros", log.Fields{"device-id": oo.deviceID, "length": len(macBytes)})
+					oo.macAddress = cEmptyMacAddrString
 				}
 				// trigger retrieval of mib template
-				_ = onuDeviceEntry.pMibUploadFsm.pFsm.Event(ulEvGetMibTemplate)
+				_ = oo.pMibUploadFsm.pFsm.Event(ulEvGetMibTemplate)
 				return nil
 			}
 		}
 	} else if msgObj.Result == me.UnknownInstance {
-		logger.Debugw("MibSync FSM - Unknown Instance in GetResponse Data", log.Fields{"device-id": onuDeviceEntry.deviceID, "data-fields": msgObj})
-		entityID := onuDeviceEntry.PDevOmciCC.pLastTxMeInstance.GetEntityID()
-		if msgObj.EntityClass == onuDeviceEntry.PDevOmciCC.pLastTxMeInstance.GetClassID() && msgObj.EntityInstance == entityID {
-			meInstance := onuDeviceEntry.PDevOmciCC.pLastTxMeInstance.GetName()
+		logger.Debugw("MibSync FSM - Unknown Instance in GetResponse Data", log.Fields{"device-id": oo.deviceID, "data-fields": msgObj})
+		entityID := oo.PDevOmciCC.pLastTxMeInstance.GetEntityID()
+		if msgObj.EntityClass == oo.PDevOmciCC.pLastTxMeInstance.GetClassID() && msgObj.EntityInstance == entityID {
+			meInstance := oo.PDevOmciCC.pLastTxMeInstance.GetName()
 			switch meInstance {
 			case "IpHostConfigData":
 				logger.Debugf("MibSync FSM - Unknown Instance for IpHostConfigData received - ONU doesn't support ME - fill macAddress with zeros",
-					log.Fields{"device-id": onuDeviceEntry.deviceID, "data-fields": msgObj})
-				onuDeviceEntry.macAddress = cEmptyMacAddrString
+					log.Fields{"device-id": oo.deviceID, "data-fields": msgObj})
+				oo.macAddress = cEmptyMacAddrString
 				// trigger retrieval of mib template
-				_ = onuDeviceEntry.pMibUploadFsm.pFsm.Event(ulEvGetMibTemplate)
+				_ = oo.pMibUploadFsm.pFsm.Event(ulEvGetMibTemplate)
 				return nil
 			default:
-				logger.Debugf("MibSync FSM - Unknown Instance in GetResponse Data for %s", log.Fields{"device-id": onuDeviceEntry.deviceID, "data-fields": msgObj}, meInstance)
+				logger.Debugf("MibSync FSM - Unknown Instance in GetResponse Data for %s", log.Fields{"device-id": oo.deviceID, "data-fields": msgObj}, meInstance)
 			}
 		}
 	} else {
-		logger.Errorw("mibSync FSM - Omci GetResponse Error", log.Fields{"Error": msgObj.Result, "device-id": onuDeviceEntry.deviceID})
-		err = fmt.Errorf("mibSync FSM - Omci GetResponse Error: %s", onuDeviceEntry.deviceID)
+		logger.Errorw("mibSync FSM - Omci GetResponse Error", log.Fields{"Error": msgObj.Result, "device-id": oo.deviceID})
+		err = fmt.Errorf("mibSync FSM - Omci GetResponse Error: %s", oo.deviceID)
 	}
-	logger.Info("MibSync Msg", log.Fields{"Stopped handling of MibSyncChan for device-id": onuDeviceEntry.deviceID})
-	_ = onuDeviceEntry.pMibUploadFsm.pFsm.Event(ulEvStop)
+	logger.Info("MibSync Msg", log.Fields{"Stopped handling of MibSyncChan for device-id": oo.deviceID})
+	_ = oo.pMibUploadFsm.pFsm.Event(ulEvStop)
 	return err
 }
 
-func (onuDeviceEntry *OnuDeviceEntry) handleOmciMessage(msg OmciMessage) {
-	logger.Debugw("MibSync Msg", log.Fields{"OmciMessage received for device-id": onuDeviceEntry.deviceID,
+func (oo *OnuDeviceEntry) handleOmciMessage(msg OmciMessage) {
+	logger.Debugw("MibSync Msg", log.Fields{"OmciMessage received for device-id": oo.deviceID,
 		"msgType": msg.OmciMsg.MessageType, "msg": msg})
 	//further analysis could be done here based on msg.OmciMsg.Payload, e.g. verification of error code ...
 	switch msg.OmciMsg.MessageType {
 	case omci.MibResetResponseType:
-		onuDeviceEntry.handleOmciMibResetResponseMessage(msg)
+		oo.handleOmciMibResetResponseMessage(msg)
 
 	case omci.MibUploadResponseType:
-		onuDeviceEntry.handleOmciMibUploadResponseMessage(msg)
+		oo.handleOmciMibUploadResponseMessage(msg)
 
 	case omci.MibUploadNextResponseType:
-		onuDeviceEntry.handleOmciMibUploadNextResponseMessage(msg)
+		oo.handleOmciMibUploadNextResponseMessage(msg)
 
 	case omci.GetResponseType:
 		//TODO: error handling
-		_ = onuDeviceEntry.handleOmciGetResponseMessage(msg)
+		_ = oo.handleOmciGetResponseMessage(msg)
 
 	default:
 		log.Warnw("Unknown Message Type", log.Fields{"msgType": msg.OmciMsg.MessageType})
@@ -510,24 +510,41 @@
 	return fmt.Sprintf("%s", bytes.Trim(ifBytes, "\x00"))
 }
 
-func (onuDeviceEntry *OnuDeviceEntry) mibDbVolatileDict() error {
+func (oo *OnuDeviceEntry) mibDbVolatileDict() error {
 	logger.Debug("MibVolatileDict- running from default Entry code")
 	return errors.New("not_implemented")
 }
 
 // createAndPersistMibTemplate method creates a mib template for the device id when operator enables the ONU device for the first time.
 // We are creating a placeholder for "SerialNumber" for ME Class ID 6 and 256 and "MacAddress" for ME Class ID 134 in the template
-// and then storing the template into etcd "service/voltha/omci_mibs/templates/verdor_id/equipment_id/software_version" path.
-func (onuDeviceEntry *OnuDeviceEntry) createAndPersistMibTemplate() error {
-	path := fmt.Sprintf(cSuffixMibTemplateKvStore, onuDeviceEntry.vendorID, onuDeviceEntry.equipmentID, onuDeviceEntry.activeSwVersion)
-	logger.Debugw("MibSync - MibTemplate - key name", log.Fields{"path": path})
-	currentTime := time.Now()
+// and then storing the template into etcd "service/voltha/omci_mibs/go_templates/verdor_id/equipment_id/software_version" path.
+func (oo *OnuDeviceEntry) createAndPersistMibTemplate() error {
+	logger.Debugw("MibSync - MibTemplate - path name", log.Fields{"path": oo.mibTemplatePath,
+		"device-id": oo.deviceID})
 
+	oo.pOpenOnuAc.lockMibTemplateGenerated.Lock()
+	if mibTemplateIsGenerated, exist := oo.pOpenOnuAc.mibTemplatesGenerated[oo.mibTemplatePath]; exist {
+		if mibTemplateIsGenerated {
+			logger.Debugw("MibSync - MibTemplate - another thread has already started to generate it - skip",
+				log.Fields{"path": oo.mibTemplatePath, "device-id": oo.deviceID})
+			oo.pOpenOnuAc.lockMibTemplateGenerated.Unlock()
+			return nil
+		}
+		logger.Debugw("MibSync - MibTemplate - previous generation attempt seems to be failed - try again",
+			log.Fields{"path": oo.mibTemplatePath, "device-id": oo.deviceID})
+	} else {
+		logger.Debugw("MibSync - MibTemplate - first ONU-instance of this kind - start generation",
+			log.Fields{"path": oo.mibTemplatePath, "device-id": oo.deviceID})
+	}
+	oo.pOpenOnuAc.mibTemplatesGenerated[oo.mibTemplatePath] = true
+	oo.pOpenOnuAc.lockMibTemplateGenerated.Unlock()
+
+	currentTime := time.Now()
 	templateMap := make(map[string]interface{})
-	templateMap["TemplateName"] = path
+	templateMap["TemplateName"] = oo.mibTemplatePath
 	templateMap["TemplateCreated"] = currentTime.Format("2006-01-02 15:04:05.000000")
 
-	firstLevelMap := onuDeviceEntry.pOnuDB.meDb
+	firstLevelMap := oo.pOnuDB.meDb
 	for firstLevelKey, firstLevelValue := range firstLevelMap {
 		logger.Debugw("MibSync - MibTemplate - firstLevelKey", log.Fields{"firstLevelKey": firstLevelKey})
 		classID := strconv.Itoa(int(firstLevelKey))
@@ -556,15 +573,21 @@
 	}
 	mibTemplate, err := json.Marshal(&templateMap)
 	if err != nil {
-		logger.Errorw("MibSync - MibTemplate - Failed to marshal mibTemplate", log.Fields{"error": err, "device-id": onuDeviceEntry.deviceID})
+		logger.Errorw("MibSync - MibTemplate - Failed to marshal mibTemplate", log.Fields{"error": err, "device-id": oo.deviceID})
+		oo.pOpenOnuAc.lockMibTemplateGenerated.Lock()
+		oo.pOpenOnuAc.mibTemplatesGenerated[oo.mibTemplatePath] = false
+		oo.pOpenOnuAc.lockMibTemplateGenerated.Unlock()
 		return err
 	}
-	err = onuDeviceEntry.mibTemplateKVStore.Put(context.TODO(), path, string(mibTemplate))
+	err = oo.mibTemplateKVStore.Put(context.TODO(), oo.mibTemplatePath, string(mibTemplate))
 	if err != nil {
-		logger.Errorw("MibSync - MibTemplate - Failed to store template in etcd", log.Fields{"error": err, "device-id": onuDeviceEntry.deviceID})
+		logger.Errorw("MibSync - MibTemplate - Failed to store template in etcd", log.Fields{"error": err, "device-id": oo.deviceID})
+		oo.pOpenOnuAc.lockMibTemplateGenerated.Lock()
+		oo.pOpenOnuAc.mibTemplatesGenerated[oo.mibTemplatePath] = false
+		oo.pOpenOnuAc.lockMibTemplateGenerated.Unlock()
 		return err
 	}
-	logger.Debugw("MibSync - MibTemplate - Stored the template to etcd", log.Fields{"device-id": onuDeviceEntry.deviceID})
+	logger.Debugw("MibSync - MibTemplate - Stored the template to etcd", log.Fields{"device-id": oo.deviceID})
 	return nil
 }
 
diff --git a/internal/pkg/onuadaptercore/onu_device_entry.go b/internal/pkg/onuadaptercore/onu_device_entry.go
index 66dfabd..2f726a4 100644
--- a/internal/pkg/onuadaptercore/onu_device_entry.go
+++ b/internal/pkg/onuadaptercore/onu_device_entry.go
@@ -221,12 +221,14 @@
 type OnuDeviceEntry struct {
 	deviceID              string
 	baseDeviceHandler     *deviceHandler
+	pOpenOnuAc            *OpenONUAC
 	coreProxy             adapterif.CoreProxy
 	adapterProxy          adapterif.AdapterProxy
 	PDevOmciCC            *omciCC
 	pOnuDB                *onuDeviceDB
 	mibTemplateKVStore    *db.Backend
 	sOnuPersistentData    onuPersistentData
+	mibTemplatePath       string
 	onuKVStoreMutex       sync.RWMutex
 	onuKVStore            *db.Backend
 	onuKVStorePath        string
@@ -257,15 +259,14 @@
 
 //newOnuDeviceEntry returns a new instance of a OnuDeviceEntry
 //mib_db (as well as not inluded alarm_db not really used in this code? VERIFY!!)
-func newOnuDeviceEntry(ctx context.Context, deviceID string, kVStoreHost string, kVStorePort int, kvStoreType string, deviceHandler *deviceHandler,
-	coreProxy adapterif.CoreProxy, adapterProxy adapterif.AdapterProxy,
-	supportedFsmsPtr *OmciDeviceFsms) *OnuDeviceEntry {
-	logger.Infow("init-onuDeviceEntry", log.Fields{"device-id": deviceID})
+func newOnuDeviceEntry(ctx context.Context, dh *deviceHandler) *OnuDeviceEntry {
+	logger.Infow("init-onuDeviceEntry", log.Fields{"device-id": dh.deviceID})
 	var onuDeviceEntry OnuDeviceEntry
-	onuDeviceEntry.deviceID = deviceID
-	onuDeviceEntry.baseDeviceHandler = deviceHandler
-	onuDeviceEntry.coreProxy = coreProxy
-	onuDeviceEntry.adapterProxy = adapterProxy
+	onuDeviceEntry.deviceID = dh.deviceID
+	onuDeviceEntry.baseDeviceHandler = dh
+	onuDeviceEntry.pOpenOnuAc = dh.pOpenOnuAc
+	onuDeviceEntry.coreProxy = dh.coreProxy
+	onuDeviceEntry.adapterProxy = dh.AdapterProxy
 	onuDeviceEntry.devState = DeviceStatusInit
 	onuDeviceEntry.sOnuPersistentData.PersUniConfig = make([]uniPersConfig, 0)
 	onuDeviceEntry.chOnuKvProcessingStep = make(chan uint8)
@@ -275,8 +276,8 @@
 	//are per ONU Vendor
 	//
 	// MIB Synchronization Database - possible overloading from arguments
-	if supportedFsmsPtr != nil {
-		onuDeviceEntry.supportedFsms = *supportedFsmsPtr
+	if dh.pOpenOnuAc.pSupportedFsms != nil {
+		onuDeviceEntry.supportedFsms = *dh.pOpenOnuAc.pSupportedFsms
 	} else {
 		//var mibSyncFsm = NewMibSynchronizer()
 		// use some internaö defaults, if not defined from outside
@@ -305,7 +306,7 @@
 
 	// Omci related Mib upload sync state machine
 	mibUploadChan := make(chan Message, 2048)
-	onuDeviceEntry.pMibUploadFsm = NewAdapterFsm("MibUpload", deviceID, mibUploadChan)
+	onuDeviceEntry.pMibUploadFsm = NewAdapterFsm("MibUpload", dh.deviceID, mibUploadChan)
 	onuDeviceEntry.pMibUploadFsm.pFsm = fsm.NewFSM(
 		ulStDisabled,
 		fsm.Events{
@@ -370,7 +371,7 @@
 	)
 	// Omci related Mib download state machine
 	mibDownloadChan := make(chan Message, 2048)
-	onuDeviceEntry.pMibDownloadFsm = NewAdapterFsm("MibDownload", deviceID, mibDownloadChan)
+	onuDeviceEntry.pMibDownloadFsm = NewAdapterFsm("MibDownload", dh.deviceID, mibDownloadChan)
 	onuDeviceEntry.pMibDownloadFsm.pFsm = fsm.NewFSM(
 		dlStDisabled,
 		fsm.Events{
@@ -406,21 +407,21 @@
 		},
 	)
 	if onuDeviceEntry.pMibDownloadFsm == nil || onuDeviceEntry.pMibDownloadFsm.pFsm == nil {
-		logger.Errorw("MibDownloadFsm could not be instantiated", log.Fields{"device-id": deviceID})
+		logger.Errorw("MibDownloadFsm could not be instantiated", log.Fields{"device-id": dh.deviceID})
 		// TODO some specifc error treatment - or waiting for crash ?
 	}
 
 	onuDeviceEntry.mibTemplateKVStore = onuDeviceEntry.baseDeviceHandler.setBackend(cBasePathMibTemplateKvStore)
 	if onuDeviceEntry.mibTemplateKVStore == nil {
 		logger.Errorw("Can't access mibTemplateKVStore - no backend connection to service",
-			log.Fields{"device-id": deviceID, "service": cBasePathMibTemplateKvStore})
+			log.Fields{"device-id": dh.deviceID, "service": cBasePathMibTemplateKvStore})
 	}
 
 	onuDeviceEntry.onuKVStorePath = onuDeviceEntry.deviceID
 	onuDeviceEntry.onuKVStore = onuDeviceEntry.baseDeviceHandler.setBackend(cBasePathOnuKVStore)
 	if onuDeviceEntry.onuKVStore == nil {
 		logger.Errorw("Can't access onuKVStore - no backend connection to service",
-			log.Fields{"device-id": deviceID, "service": cBasePathOnuKVStore})
+			log.Fields{"device-id": dh.deviceID, "service": cBasePathOnuKVStore})
 	}
 
 	// Alarm Synchronization Database
diff --git a/internal/pkg/onuadaptercore/openonu.go b/internal/pkg/onuadaptercore/openonu.go
index eeeb437..bbf7c2a 100644
--- a/internal/pkg/onuadaptercore/openonu.go
+++ b/internal/pkg/onuadaptercore/openonu.go
@@ -39,6 +39,7 @@
 type OpenONUAC struct {
 	deviceHandlers              map[string]*deviceHandler
 	deviceHandlersCreateChan    map[string]chan bool //channels for deviceHandler create events
+	lockDeviceHandlersMap       sync.RWMutex
 	coreProxy                   adapterif.CoreProxy
 	adapterProxy                adapterif.AdapterProxy
 	eventProxy                  adapterif.EventProxy
@@ -50,12 +51,13 @@
 	KVStorePort                 int
 	KVStoreType                 string
 	KVStoreTimeout              time.Duration
+	mibTemplatesGenerated       map[string]bool
+	lockMibTemplateGenerated    sync.RWMutex
 	exitChannel                 chan int
 	HeartbeatCheckInterval      time.Duration
 	HeartbeatFailReportInterval time.Duration
 	AcceptIncrementalEvto       bool
 	//GrpcTimeoutInterval         time.Duration
-	lockDeviceHandlersMap      sync.RWMutex
 	pSupportedFsms             *OmciDeviceFsms
 	maxTimeoutInterAdapterComm time.Duration
 }
@@ -68,6 +70,7 @@
 	openOnuAc.exitChannel = make(chan int, 1)
 	openOnuAc.deviceHandlers = make(map[string]*deviceHandler)
 	openOnuAc.deviceHandlersCreateChan = make(map[string]chan bool)
+	openOnuAc.lockDeviceHandlersMap = sync.RWMutex{}
 	openOnuAc.kafkaICProxy = kafkaICProxy
 	openOnuAc.config = cfg
 	openOnuAc.numOnus = cfg.OnuNumber
@@ -79,12 +82,13 @@
 	openOnuAc.KVStorePort = cfg.KVStorePort
 	openOnuAc.KVStoreType = cfg.KVStoreType
 	openOnuAc.KVStoreTimeout = cfg.KVStoreTimeout
+	openOnuAc.mibTemplatesGenerated = make(map[string]bool)
+	openOnuAc.lockMibTemplateGenerated = sync.RWMutex{}
 	openOnuAc.HeartbeatCheckInterval = cfg.HeartbeatCheckInterval
 	openOnuAc.HeartbeatFailReportInterval = cfg.HeartbeatFailReportInterval
 	openOnuAc.AcceptIncrementalEvto = cfg.AccIncrEvto
 	openOnuAc.maxTimeoutInterAdapterComm = cfg.MaxTimeoutInterAdapterComm
 	//openOnuAc.GrpcTimeoutInterval = cfg.GrpcTimeoutInterval
-	openOnuAc.lockDeviceHandlersMap = sync.RWMutex{}
 
 	openOnuAc.pSupportedFsms = &OmciDeviceFsms{
 		"mib-synchronizer": {