[VOL-4173] Multi UNI changes in OLT adapter
- FindAllTpInstances method will read right KV store path
- Do not send US createTrafficSchedulers requests to the agent if the related AllocID is already created for other UNI ports of the ONU
- Addition of isAllocUsedByAnotherUNI control

Change-Id: I3a35220767ffc6792ac354e445dd960a946a5690
diff --git a/VERSION b/VERSION
index 47b322c..4d9d11c 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-3.4.1
+3.4.2
diff --git a/go.mod b/go.mod
index 317c90a..f95eaf8 100644
--- a/go.mod
+++ b/go.mod
@@ -7,7 +7,7 @@
 	github.com/gogo/protobuf v1.3.1
 	github.com/golang/protobuf v1.3.2
 	github.com/grpc-ecosystem/go-grpc-middleware v1.0.1-0.20190118093823-f849b5445de4
-	github.com/opencord/voltha-lib-go/v4 v4.3.1
+	github.com/opencord/voltha-lib-go/v4 v4.3.5
 	github.com/opencord/voltha-protos/v4 v4.1.8
 	go.etcd.io/etcd v0.0.0-20190930204107-236ac2a90522
 	google.golang.org/grpc v1.25.1
diff --git a/go.sum b/go.sum
index 58ce87a..5533f7b 100644
--- a/go.sum
+++ b/go.sum
@@ -141,9 +141,9 @@
 github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
 github.com/onsi/gomega v1.4.2 h1:3mYCb7aPxS/RU7TI1y4rkEn1oKmPRjNJLNEXgw7MH2I=
 github.com/onsi/gomega v1.4.2/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
-github.com/opencord/voltha-lib-go/v4 v4.3.1 h1:z2CgB3un53IgbYTsz+pdRtmQ3E6e6+PieGQDyHaQN1A=
-github.com/opencord/voltha-lib-go/v4 v4.3.1/go.mod h1:65GN71j4os0ApBRR+xbJ93iAMJMKIwVi/npG/hbPt8w=
-github.com/opencord/voltha-protos/v4 v4.1.1/go.mod h1:W/OIFIyvFh/C0vchRUuarIsMylEhzCRM9pNxLvkPtKc=
+github.com/opencord/voltha-lib-go/v4 v4.3.5 h1:7OcAW2B5qpR6yh7c5GqcwlLkSbTfXYhZSsHSFkDBYNw=
+github.com/opencord/voltha-lib-go/v4 v4.3.5/go.mod h1:x0a7TxyzxPFaiewkbFiuy0+ftX5w4zeCRlFyyGZ4hhw=
+github.com/opencord/voltha-protos/v4 v4.1.2/go.mod h1:W/OIFIyvFh/C0vchRUuarIsMylEhzCRM9pNxLvkPtKc=
 github.com/opencord/voltha-protos/v4 v4.1.8 h1:TeK0RlhKxGfrdIpcngJmbD7ttT5x9+Fyjn1haS/jh4s=
 github.com/opencord/voltha-protos/v4 v4.1.8/go.mod h1:W/OIFIyvFh/C0vchRUuarIsMylEhzCRM9pNxLvkPtKc=
 github.com/opentracing/opentracing-go v1.1.0 h1:pWlfV3Bxv7k65HYwkikxat0+s3pV4bsqf19k25Ur8rU=
diff --git a/internal/pkg/core/openolt_flowmgr.go b/internal/pkg/core/openolt_flowmgr.go
index eb35925..4ae86ac 100644
--- a/internal/pkg/core/openolt_flowmgr.go
+++ b/internal/pkg/core/openolt_flowmgr.go
@@ -558,21 +558,26 @@
 				"device-id": f.deviceHandler.device.Id}, err)
 	}
 
-	logger.Debugw(ctx, "sending-traffic-scheduler-create-to-device",
-		log.Fields{
-			"direction":     sq.direction,
-			"TrafficScheds": TrafficSched,
-			"device-id":     f.deviceHandler.device.Id})
-	if _, err := f.deviceHandler.Client.CreateTrafficSchedulers(ctx, &tp_pb.TrafficSchedulers{
-		IntfId: sq.intfID, OnuId: sq.onuID,
-		UniId: sq.uniID, PortNo: sq.uniPort,
-		TrafficScheds: TrafficSched}); err != nil {
-		return olterrors.NewErrAdapter("failed-to-create-traffic-schedulers-in-device", log.Fields{"TrafficScheds": TrafficSched}, err)
+	if allocExists := f.isAllocUsedByAnotherUNI(ctx, sq); !allocExists {
+		logger.Debugw(ctx, "sending-traffic-scheduler-create-to-device",
+			log.Fields{
+				"direction":     sq.direction,
+				"TrafficScheds": TrafficSched,
+				"device-id":     f.deviceHandler.device.Id,
+				"intfID":        sq.intfID,
+				"onuID":         sq.onuID,
+				"uniID":         sq.uniID})
+		if _, err := f.deviceHandler.Client.CreateTrafficSchedulers(ctx, &tp_pb.TrafficSchedulers{
+			IntfId: sq.intfID, OnuId: sq.onuID,
+			UniId: sq.uniID, PortNo: sq.uniPort,
+			TrafficScheds: TrafficSched}); err != nil {
+			return olterrors.NewErrAdapter("failed-to-create-traffic-schedulers-in-device", log.Fields{"TrafficScheds": TrafficSched}, err)
+		}
+		logger.Infow(ctx, "successfully-created-traffic-schedulers", log.Fields{
+			"direction":      sq.direction,
+			"traffic-queues": trafficQueues,
+			"device-id":      f.deviceHandler.device.Id})
 	}
-	logger.Infow(ctx, "successfully-created-traffic-schedulers", log.Fields{
-		"direction":      sq.direction,
-		"traffic-queues": trafficQueues,
-		"device-id":      f.deviceHandler.device.Id})
 
 	// On receiving the CreateTrafficQueues request, the driver should create corresponding
 	// downstream queues.
@@ -674,26 +679,46 @@
 				"traffic-queues": TrafficQueues,
 				"device-id":      f.deviceHandler.device.Id}, err)
 	}
-	logger.Infow(ctx, "removed-traffic-queues-successfully", log.Fields{"device-id": f.deviceHandler.device.Id})
-	if _, err = f.deviceHandler.Client.RemoveTrafficSchedulers(ctx, &tp_pb.TrafficSchedulers{
-		IntfId: sq.intfID, OnuId: sq.onuID,
-		UniId: sq.uniID, PortNo: sq.uniPort,
-		TrafficScheds: TrafficSched}); err != nil {
-		return olterrors.NewErrAdapter("unable-to-remove-traffic-schedulers-from-device",
-			log.Fields{
-				"intf-id":            sq.intfID,
-				"traffic-schedulers": TrafficSched,
-				"onu-id":             sq.onuID,
-				"uni-id":             sq.uniID,
-				"uni-port":           sq.uniPort}, err)
-	}
+	logger.Infow(ctx, "removed-traffic-queues-successfully", log.Fields{"device-id": f.deviceHandler.device.Id, "trafficQueues": TrafficQueues})
 
-	logger.Infow(ctx, "removed-traffic-schedulers-successfully",
-		log.Fields{"device-id": f.deviceHandler.device.Id,
-			"intf-id":  sq.intfID,
-			"onu-id":   sq.onuID,
-			"uni-id":   sq.uniID,
-			"uni-port": sq.uniPort})
+	if allocExists := f.isAllocUsedByAnotherUNI(ctx, sq); !allocExists {
+		if _, err = f.deviceHandler.Client.RemoveTrafficSchedulers(ctx, &tp_pb.TrafficSchedulers{
+			IntfId: sq.intfID, OnuId: sq.onuID,
+			UniId: sq.uniID, PortNo: sq.uniPort,
+			TrafficScheds: TrafficSched}); err != nil {
+			return olterrors.NewErrAdapter("unable-to-remove-traffic-schedulers-from-device",
+				log.Fields{
+					"intf-id":            sq.intfID,
+					"traffic-schedulers": TrafficSched,
+					"onu-id":             sq.onuID,
+					"uni-id":             sq.uniID,
+					"uni-port":           sq.uniPort}, err)
+		}
+
+		logger.Infow(ctx, "removed-traffic-schedulers-successfully",
+			log.Fields{"device-id": f.deviceHandler.device.Id,
+				"intf-id":  sq.intfID,
+				"onu-id":   sq.onuID,
+				"uni-id":   sq.uniID,
+				"uni-port": sq.uniPort})
+
+		if sq.direction == tp_pb.Direction_UPSTREAM {
+			allocID := sq.tpInst.(*tp.TechProfile).UsScheduler.AllocID
+			f.resourceMgr.FreeAllocID(ctx, sq.intfID, sq.onuID, sq.uniID, allocID)
+			// Delete the TCONT on the ONU.
+			uni := getUniPortPath(f.deviceHandler.device.Id, sq.intfID, int32(sq.onuID), int32(sq.uniID))
+			tpPath := f.getTPpath(ctx, sq.intfID, uni, sq.tpID)
+			if err := f.sendDeleteTcontToChild(ctx, sq.intfID, sq.onuID, sq.uniID, allocID, tpPath); err != nil {
+				logger.Errorw(ctx, "error-processing-delete-tcont-towards-onu",
+					log.Fields{
+						"intf":      sq.intfID,
+						"onu-id":    sq.onuID,
+						"uni-id":    sq.uniID,
+						"device-id": f.deviceHandler.device.Id,
+						"alloc-id":  allocID})
+			}
+		}
+	}
 
 	/* After we successfully remove the scheduler configuration on the OLT device,
 	 * delete the meter id on the KV store.
@@ -1947,7 +1972,7 @@
 	}
 	switch techprofileInst := techprofileInst.(type) {
 	case *tp.TechProfile:
-		ok, _ := f.isTechProfileUsedByAnotherGem(ctx, intfID, uint32(onuID), uint32(uniID), tpID, techprofileInst, uint32(gemPortID))
+		ok, _ := f.isTechProfileUsedByAnotherGem(ctx, intfID, uint32(onuID), uint32(uniID), techprofileInst, uint32(gemPortID))
 		if !ok {
 			if err := f.resourceMgr.RemoveTechProfileIDForOnu(ctx, intfID, uint32(onuID), uint32(uniID), tpID); err != nil {
 				logger.Warn(ctx, err)
@@ -1961,17 +1986,6 @@
 			if err := f.RemoveSchedulerQueues(ctx, schedQueue{direction: tp_pb.Direction_DOWNSTREAM, intfID: intfID, onuID: uint32(onuID), uniID: uint32(uniID), tpID: tpID, uniPort: portNum, tpInst: techprofileInst}); err != nil {
 				logger.Warn(ctx, err)
 			}
-			f.resourceMgr.FreeAllocID(ctx, intfID, uint32(onuID), uint32(uniID), techprofileInst.UsScheduler.AllocID)
-			// Delete the TCONT on the ONU.
-			if err := f.sendDeleteTcontToChild(ctx, intfID, uint32(onuID), uint32(uniID), techprofileInst.UsScheduler.AllocID, tpPath); err != nil {
-				logger.Errorw(ctx, "error-processing-delete-tcont-towards-onu",
-					log.Fields{
-						"intf":      intfID,
-						"onu-id":    onuID,
-						"uni-id":    uniID,
-						"device-id": f.deviceHandler.device.Id,
-						"alloc-id":  techprofileInst.UsScheduler.AllocID})
-			}
 		}
 	case *tp.EponProfile:
 		if err := f.resourceMgr.RemoveTechProfileIDForOnu(ctx, intfID, uint32(onuID), uint32(uniID), tpID); err != nil {
@@ -2981,7 +2995,7 @@
 
 }
 
-func (f *OpenOltFlowMgr) isTechProfileUsedByAnotherGem(ctx context.Context, ponIntf uint32, onuID uint32, uniID uint32, tpID uint32, tpInst *tp.TechProfile, gemPortID uint32) (bool, uint32) {
+func (f *OpenOltFlowMgr) isTechProfileUsedByAnotherGem(ctx context.Context, ponIntf uint32, onuID uint32, uniID uint32, tpInst *tp.TechProfile, gemPortID uint32) (bool, uint32) {
 	currentGemPorts := f.resourceMgr.GetCurrentGEMPortIDsForOnu(ctx, ponIntf, onuID, uniID)
 	tpGemPorts := tpInst.UpstreamGemPortAttributeList
 	for _, currentGemPort := range currentGemPorts {
@@ -2991,34 +3005,32 @@
 			}
 		}
 	}
-	if tpInst.InstanceCtrl.Onu == "single-instance" {
-		// The TP information for the given TP ID, PON ID, ONU ID, UNI ID should be removed.
-		if err := f.resourceMgr.RemoveTechProfileIDForOnu(ctx, ponIntf, onuID, uniID, tpID); err != nil {
-			logger.Warn(ctx, err)
-		}
-		if err := f.DeleteTechProfileInstance(ctx, ponIntf, onuID, uniID, "", tpID); err != nil {
-			logger.Warn(ctx, err)
-		}
+	logger.Debug(ctx, "tech-profile-is-not-in-use-by-any-gem")
+	return false, 0
+}
 
-		// Although we cleaned up TP Instance for the given (PON ID, ONU ID, UNI ID), the TP might
-		// still be used on other uni ports.
-		// So, we need to check and make sure that no other gem port is referring to the given TP ID
-		// on any other uni port.
-		tpInstances := f.techprofile[ponIntf].FindAllTpInstances(ctx, tpID, ponIntf, onuID).([]tp.TechProfile)
+func (f *OpenOltFlowMgr) isAllocUsedByAnotherUNI(ctx context.Context, sq schedQueue) bool {
+	tpInst := sq.tpInst.(*tp.TechProfile)
+	if tpInst.InstanceCtrl.Onu == "single-instance" && sq.direction == tp_pb.Direction_UPSTREAM {
+		tpInstances := f.techprofile[sq.intfID].FindAllTpInstances(ctx, f.deviceHandler.device.Id, sq.tpID, sq.intfID, sq.onuID).([]tp.TechProfile)
 		logger.Debugw(ctx, "got-single-instance-tp-instances", log.Fields{"tp-instances": tpInstances})
 		for i := 0; i < len(tpInstances); i++ {
 			tpI := tpInstances[i]
-			tpGemPorts := tpI.UpstreamGemPortAttributeList
-			for _, tpGemPort := range tpGemPorts {
-				if tpGemPort.GemportID != gemPortID {
-					logger.Debugw(ctx, "single-instance-tp-is-in-use-by-gem", log.Fields{"gemPort": tpGemPort.GemportID})
-					return true, tpGemPort.GemportID
-				}
+			if tpI.SubscriberIdentifier != tpInst.SubscriberIdentifier &&
+				tpI.UsScheduler.AllocID == tpInst.UsScheduler.AllocID {
+				logger.Debugw(ctx, "alloc-is-in-use",
+					log.Fields{
+						"device-id": f.deviceHandler.device.Id,
+						"intfID":    sq.intfID,
+						"onuID":     sq.onuID,
+						"uniID":     sq.uniID,
+						"allocID":   tpI.UsScheduler.AllocID,
+					})
+				return true
 			}
 		}
 	}
-	logger.Debug(ctx, "tech-profile-is-not-in-use-by-any-gem")
-	return false, 0
+	return false
 }
 
 func formulateClassifierInfoFromFlow(ctx context.Context, classifierInfo map[string]interface{}, flow *ofp.OfpFlowStats) {
diff --git a/pkg/mocks/mockTechprofile.go b/pkg/mocks/mockTechprofile.go
index c57dd54..e51f44a 100644
--- a/pkg/mocks/mockTechprofile.go
+++ b/pkg/mocks/mockTechprofile.go
@@ -195,7 +195,7 @@
 }
 
 // FindAllTpInstances to mock techprofile FindAllTpInstances method
-func (m MockTechProfile) FindAllTpInstances(ctx context.Context, techProfiletblID uint32, ponIntf uint32, onuID uint32) interface{} {
+func (m MockTechProfile) FindAllTpInstances(ctx context.Context, oltDeviceID string, tpID uint32, ponIntf uint32, onuID uint32) interface{} {
 	return []tp.TechProfile{}
 }
 
diff --git a/vendor/github.com/opencord/voltha-lib-go/v4/pkg/adapters/common/request_handler.go b/vendor/github.com/opencord/voltha-lib-go/v4/pkg/adapters/common/request_handler.go
index 020e799..b6cf1c0 100644
--- a/vendor/github.com/opencord/voltha-lib-go/v4/pkg/adapters/common/request_handler.go
+++ b/vendor/github.com/opencord/voltha-lib-go/v4/pkg/adapters/common/request_handler.go
@@ -852,8 +852,6 @@
 				logger.Warnw(ctx, "cannot-unmarshal-device", log.Fields{"error": err})
 				return nil, err
 			}
-		default:
-			return nil, errors.New("invalid argument")
 		}
 	}
 	return &deviceDownloadImageReq, nil
@@ -875,8 +873,6 @@
 				logger.Warnw(ctx, "cannot-unmarshal-device", log.Fields{"error": err})
 				return nil, err
 			}
-		default:
-			return nil, errors.New("invalid argument")
 		}
 	}
 	return &deviceImageReq, nil
@@ -894,10 +890,13 @@
 				logger.Warnw(ctx, "cannot-unmarshal-device", log.Fields{"error": err})
 				return "", err
 			}
-		default:
-			return "", errors.New("invalid argument")
 		}
 	}
+
+	if deviceId.Val == "" {
+		return "", errors.New("invalid argument")
+	}
+
 	return deviceId.Val, nil
 }
 
diff --git a/vendor/github.com/opencord/voltha-lib-go/v4/pkg/events/events_proxy.go b/vendor/github.com/opencord/voltha-lib-go/v4/pkg/events/events_proxy.go
index ebd48ab..910fec3 100644
--- a/vendor/github.com/opencord/voltha-lib-go/v4/pkg/events/events_proxy.go
+++ b/vendor/github.com/opencord/voltha-lib-go/v4/pkg/events/events_proxy.go
@@ -17,11 +17,13 @@
 package events
 
 import (
+	"container/ring"
 	"context"
 	"errors"
 	"fmt"
 	"strconv"
 	"strings"
+	"sync"
 	"time"
 
 	"github.com/golang/protobuf/ptypes"
@@ -31,9 +33,17 @@
 	"github.com/opencord/voltha-protos/v4/go/voltha"
 )
 
+// TODO: Make configurable through helm chart
+const EVENT_THRESHOLD = 1000
+
+type lastEvent struct{}
+
 type EventProxy struct {
-	kafkaClient kafka.Client
-	eventTopic  kafka.Topic
+	kafkaClient    kafka.Client
+	eventTopic     kafka.Topic
+	eventQueue     *EventQueue
+	queueCtx       context.Context
+	queueCancelCtx context.CancelFunc
 }
 
 func NewEventProxy(opts ...EventProxyOption) *EventProxy {
@@ -41,6 +51,8 @@
 	for _, option := range opts {
 		option(&proxy)
 	}
+	proxy.eventQueue = newEventQueue()
+	proxy.queueCtx, proxy.queueCancelCtx = context.WithCancel(context.Background())
 	return &proxy
 }
 
@@ -112,15 +124,7 @@
 		return err
 	}
 	event.EventType = &voltha.Event_RpcEvent{RpcEvent: rpcEvent}
-	if err := ep.sendEvent(ctx, &event); err != nil {
-		logger.Errorw(ctx, "Failed to send rpc event to KAFKA bus", log.Fields{"rpc-event": rpcEvent})
-		return err
-	}
-	logger.Debugw(ctx, "Successfully sent RPC event to KAFKA bus", log.Fields{"Id": event.Header.Id, "Category": event.Header.Category,
-		"SubCategory": event.Header.SubCategory, "Type": event.Header.Type, "TypeVersion": event.Header.TypeVersion,
-		"ReportedTs": event.Header.ReportedTs, "ResourceId": rpcEvent.ResourceId, "Context": rpcEvent.Context,
-		"RPCEventName": id})
-
+	ep.eventQueue.push(&event)
 	return nil
 
 }
@@ -195,3 +199,155 @@
 func (ep *EventProxy) SendLiveness(ctx context.Context) error {
 	return ep.kafkaClient.SendLiveness(ctx)
 }
+
+// Start the event proxy
+func (ep *EventProxy) Start() {
+	eq := ep.eventQueue
+	go eq.start(ep.queueCtx)
+	logger.Debugw(context.Background(), "event-proxy-starting...", log.Fields{"events-threashold": EVENT_THRESHOLD})
+	for {
+		// Notify the queue I am ready
+		eq.readyToSendToKafkaCh <- struct{}{}
+		// Wait for an event
+		elem, ok := <-eq.eventChannel
+		if !ok {
+			logger.Debug(context.Background(), "event-channel-closed-exiting")
+			break
+		}
+		// Check for last event
+		if _, ok := elem.(*lastEvent); ok {
+			// close the queuing loop
+			logger.Info(context.Background(), "received-last-event")
+			ep.queueCancelCtx()
+			break
+		}
+		ctx := context.Background()
+		event, ok := elem.(*voltha.Event)
+		if !ok {
+			logger.Warnw(ctx, "invalid-event", log.Fields{"element": elem})
+			continue
+		}
+		if err := ep.sendEvent(ctx, event); err != nil {
+			logger.Errorw(ctx, "failed-to-send-event-to-kafka-bus", log.Fields{"event": event})
+		} else {
+			logger.Debugw(ctx, "successfully-sent-rpc-event-to-kafka-bus", log.Fields{"id": event.Header.Id, "category": event.Header.Category,
+				"sub-category": event.Header.SubCategory, "type": event.Header.Type, "type-version": event.Header.TypeVersion,
+				"reported-ts": event.Header.ReportedTs, "event-type": event.EventType})
+		}
+	}
+}
+
+func (ep *EventProxy) Stop() {
+	ep.eventQueue.stop()
+}
+
+type EventQueue struct {
+	mutex                sync.RWMutex
+	eventChannel         chan interface{}
+	insertPosition       *ring.Ring
+	popPosition          *ring.Ring
+	dataToSendAvailable  chan struct{}
+	readyToSendToKafkaCh chan struct{}
+	eventQueueStopped    chan struct{}
+}
+
+func newEventQueue() *EventQueue {
+	ev := &EventQueue{
+		eventChannel:         make(chan interface{}),
+		insertPosition:       ring.New(EVENT_THRESHOLD),
+		dataToSendAvailable:  make(chan struct{}),
+		readyToSendToKafkaCh: make(chan struct{}),
+		eventQueueStopped:    make(chan struct{}),
+	}
+	ev.popPosition = ev.insertPosition
+	return ev
+}
+
+// push is invoked to push an event at the back of a queue
+func (eq *EventQueue) push(event interface{}) {
+	eq.mutex.Lock()
+
+	if eq.insertPosition != nil {
+		// Handle Queue is full.
+		// TODO: Current default is to overwrite old data if queue is full. Is there a need to
+		// block caller if max threshold is reached?
+		if eq.insertPosition.Value != nil && eq.insertPosition == eq.popPosition {
+			eq.popPosition = eq.popPosition.Next()
+		}
+
+		// Insert data and move pointer to next empty position
+		eq.insertPosition.Value = event
+		eq.insertPosition = eq.insertPosition.Next()
+
+		// Check for last event
+		if _, ok := event.(*lastEvent); ok {
+			eq.insertPosition = nil
+		}
+		eq.mutex.Unlock()
+		// Notify waiting thread of data availability
+		eq.dataToSendAvailable <- struct{}{}
+
+	} else {
+		logger.Debug(context.Background(), "event-queue-is-closed-as-insert-position-is-cleared")
+		eq.mutex.Unlock()
+	}
+}
+
+// start starts the routine that extracts an element from the event queue and
+// send it to the kafka sending routine to process.
+func (eq *EventQueue) start(ctx context.Context) {
+	logger.Info(ctx, "starting-event-queue")
+loop:
+	for {
+		select {
+		case <-eq.dataToSendAvailable:
+		//	Do nothing - use to prevent caller pushing data to block
+		case <-eq.readyToSendToKafkaCh:
+			{
+				// Kafka sending routine is ready to process an event
+				eq.mutex.Lock()
+				element := eq.popPosition.Value
+				if element == nil {
+					// No events to send. Wait
+					eq.mutex.Unlock()
+					select {
+					case _, ok := <-eq.dataToSendAvailable:
+						if !ok {
+							// channel closed
+							eq.eventQueueStopped <- struct{}{}
+							return
+						}
+					case <-ctx.Done():
+						logger.Info(ctx, "event-queue-context-done")
+						eq.eventQueueStopped <- struct{}{}
+						return
+					}
+					eq.mutex.Lock()
+					element = eq.popPosition.Value
+				}
+				eq.popPosition.Value = nil
+				eq.popPosition = eq.popPosition.Next()
+				eq.mutex.Unlock()
+				eq.eventChannel <- element
+			}
+		case <-ctx.Done():
+			logger.Info(ctx, "event-queue-context-done")
+			eq.eventQueueStopped <- struct{}{}
+			break loop
+		}
+	}
+	logger.Info(ctx, "event-queue-stopped")
+
+}
+
+func (eq *EventQueue) stop() {
+	// Flush all
+	eq.push(&lastEvent{})
+	<-eq.eventQueueStopped
+	eq.mutex.Lock()
+	close(eq.readyToSendToKafkaCh)
+	close(eq.dataToSendAvailable)
+	close(eq.eventChannel)
+	eq.mutex.Unlock()
+
+}
diff --git a/vendor/github.com/opencord/voltha-lib-go/v4/pkg/events/utils.go b/vendor/github.com/opencord/voltha-lib-go/v4/pkg/events/utils.go
new file mode 100644
index 0000000..fe3a017
--- /dev/null
+++ b/vendor/github.com/opencord/voltha-lib-go/v4/pkg/events/utils.go
@@ -0,0 +1,90 @@
+/*
+ * Copyright 2020-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package events
+
+import (
+	"fmt"
+	"strconv"
+
+	"github.com/opencord/voltha-protos/v4/go/voltha"
+)
+
+type ContextType string
+
+const (
+	// ContextAdminState is for the admin state of the Device in the context of the event
+	ContextAdminState ContextType = "admin-state"
+	// ContextConnectState is for the connect state of the Device in the context of the event
+	ContextConnectState ContextType = "connect-state"
+	// ContextOperState is for the operational state of the Device in the context of the event
+	ContextOperState ContextType = "oper-state"
+	// ContextPrevdminState is for the previous admin state of the Device in the context of the event
+	ContextPrevAdminState ContextType = "prev-admin-state"
+	// ContextPrevConnectState is for the previous connect state of the Device in the context of the event
+	ContextPrevConnectState ContextType = "prev-connect-state"
+	// ContextPrevOperState is for the previous operational state of the Device in the context of the event
+	ContextPrevOperState ContextType = "prev-oper-state"
+	// ContextDeviceID is for the previous operational state of the Device in the context of the event
+	ContextDeviceID ContextType = "id"
+	// ContextParentID is for the parent id in the context of the event
+	ContextParentID ContextType = "parent-id"
+	// ContextSerialNumber is for the serial number of the Device in the context of the event
+	ContextSerialNumber ContextType = "serial-number"
+	// ContextIsRoot is for the root flag of Device in the context of the event
+	ContextIsRoot ContextType = "is-root"
+	// ContextParentPort is for the parent interface id of child in the context of the event
+	ContextParentPort ContextType = "parent-port"
+)
+
+type EventName string
+
+const (
+	DeviceStateChangeEvent EventName = "DEVICE_STATE_CHANGE"
+)
+
+type EventAction string
+
+const (
+	Raise EventAction = "RAISE_EVENT"
+	Clear EventAction = "CLEAR_EVENT"
+)
+
+//CreateDeviceStateChangeEvent forms and returns a new DeviceStateChange Event
+func CreateDeviceStateChangeEvent(serialNumber string, deviceID string, parentID string,
+	prevOperStatus voltha.OperStatus_Types, prevConnStatus voltha.ConnectStatus_Types, prevAdminStatus voltha.AdminState_Types,
+	operStatus voltha.OperStatus_Types, connStatus voltha.ConnectStatus_Types, adminStatus voltha.AdminState_Types,
+	parentPort uint32, isRoot bool) *voltha.DeviceEvent {
+
+	context := make(map[string]string)
+	/* Populating event context */
+	context[string(ContextSerialNumber)] = serialNumber
+	context[string(ContextDeviceID)] = deviceID
+	context[string(ContextParentID)] = parentID
+	context[string(ContextPrevOperState)] = prevOperStatus.String()
+	context[string(ContextPrevConnectState)] = prevConnStatus.String()
+	context[string(ContextPrevAdminState)] = prevAdminStatus.String()
+	context[string(ContextOperState)] = operStatus.String()
+	context[string(ContextConnectState)] = connStatus.String()
+	context[string(ContextAdminState)] = adminStatus.String()
+	context[string(ContextIsRoot)] = strconv.FormatBool(isRoot)
+	context[string(ContextParentPort)] = strconv.FormatUint(uint64(parentPort), 10)
+
+	return &voltha.DeviceEvent{
+		Context:         context,
+		ResourceId:      deviceID,
+		DeviceEventName: fmt.Sprintf("%s_%s", string(DeviceStateChangeEvent), string(Raise)),
+	}
+}
diff --git a/vendor/github.com/opencord/voltha-lib-go/v4/pkg/techprofile/tech_profile.go b/vendor/github.com/opencord/voltha-lib-go/v4/pkg/techprofile/tech_profile.go
index 0f2741f..2d2332d 100644
--- a/vendor/github.com/opencord/voltha-lib-go/v4/pkg/techprofile/tech_profile.go
+++ b/vendor/github.com/opencord/voltha-lib-go/v4/pkg/techprofile/tech_profile.go
@@ -1351,11 +1351,11 @@
 }
 
 // FindAllTpInstances returns all TechProfile instances for a given TechProfile table-id, pon interface ID and onu ID.
-func (t *TechProfileMgr) FindAllTpInstances(ctx context.Context, techProfiletblID uint32, ponIntf uint32, onuID uint32) interface{} {
+func (t *TechProfileMgr) FindAllTpInstances(ctx context.Context, oltDeviceID string, tpID uint32, ponIntf uint32, onuID uint32) interface{} {
 	var tpTech TechProfile
 	var tpEpon EponProfile
 
-	onuTpInstancePath := fmt.Sprintf("%s/%d/pon-{%d}/onu-{%d}", t.resourceMgr.GetTechnology(), techProfiletblID, ponIntf, onuID)
+	onuTpInstancePath := fmt.Sprintf("%s/%d/olt-{%s}/pon-{%d}/onu-{%d}", t.resourceMgr.GetTechnology(), tpID, oltDeviceID, ponIntf, onuID)
 
 	if kvPairs, _ := t.config.KVBackend.List(ctx, onuTpInstancePath); kvPairs != nil {
 		tech := t.resourceMgr.GetTechnology()
diff --git a/vendor/github.com/opencord/voltha-lib-go/v4/pkg/techprofile/tech_profile_if.go b/vendor/github.com/opencord/voltha-lib-go/v4/pkg/techprofile/tech_profile_if.go
index 84d84ee..9aa3cbe 100644
--- a/vendor/github.com/opencord/voltha-lib-go/v4/pkg/techprofile/tech_profile_if.go
+++ b/vendor/github.com/opencord/voltha-lib-go/v4/pkg/techprofile/tech_profile_if.go
@@ -37,7 +37,7 @@
 	GetTrafficQueues(ctx context.Context, tp *TechProfile, Dir tp_pb.Direction) ([]*tp_pb.TrafficQueue, error)
 	GetMulticastTrafficQueues(ctx context.Context, tp *TechProfile) []*tp_pb.TrafficQueue
 	GetGemportForPbit(ctx context.Context, tp interface{}, Dir tp_pb.Direction, pbit uint32) interface{}
-	FindAllTpInstances(ctx context.Context, techProfiletblID uint32, ponIntf uint32, onuID uint32) interface{}
+	FindAllTpInstances(ctx context.Context, oltDeviceID string, tpID uint32, ponIntf uint32, onuID uint32) interface{}
 	GetResourceID(ctx context.Context, IntfID uint32, ResourceType string, NumIDs uint32) ([]uint32, error)
 	FreeResourceID(ctx context.Context, IntfID uint32, ResourceType string, ReleaseContent []uint32) error
 }
diff --git a/vendor/modules.txt b/vendor/modules.txt
index 7b9715b..f882960 100644
--- a/vendor/modules.txt
+++ b/vendor/modules.txt
@@ -56,7 +56,7 @@
 # github.com/jcmturner/gofork v1.0.0
 github.com/jcmturner/gofork/encoding/asn1
 github.com/jcmturner/gofork/x/crypto/pbkdf2
-# github.com/opencord/voltha-lib-go/v4 v4.3.1
+# github.com/opencord/voltha-lib-go/v4 v4.3.5
 ## explicit
 github.com/opencord/voltha-lib-go/v4/pkg/adapters
 github.com/opencord/voltha-lib-go/v4/pkg/adapters/adapterif