[VOL-4120] openonu-adapter-go: support command "voltctl device onuimage list <onu-id>"

Change-Id: If6bc1a94663c09881059b1f91d34944dccec52f3
diff --git a/VERSION b/VERSION
index 8c2e99f..e3d07d7 100755
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-1.3.1-dev203
+1.3.1-dev204
diff --git a/go.mod b/go.mod
index b2343b8..f110351 100644
--- a/go.mod
+++ b/go.mod
@@ -10,7 +10,7 @@
 	github.com/google/gopacket v1.1.17
 	github.com/looplab/fsm v0.2.0
 	github.com/opencord/omci-lib-go v1.1.0
-	github.com/opencord/voltha-lib-go/v4 v4.3.1
+	github.com/opencord/voltha-lib-go/v4 v4.3.4
 	github.com/opencord/voltha-protos/v4 v4.1.4
 	github.com/stretchr/testify v1.6.1
 	google.golang.org/grpc v1.25.1 // indirect
diff --git a/go.sum b/go.sum
index 15abc56..73a7d82 100644
--- a/go.sum
+++ b/go.sum
@@ -152,9 +152,9 @@
 github.com/onsi/gomega v1.4.2/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
 github.com/opencord/omci-lib-go v1.1.0 h1:ICc29xMslz9fNqtvnN9tzS0yxRlugzKx0fUGABlwHNM=
 github.com/opencord/omci-lib-go v1.1.0/go.mod h1:moNk4j00XaM3olsu4a8lRAqGmcZJoyIbxtSr+VERLq4=
-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.4 h1:+v+d1EfvtUjtotnA7ONuHJpG3Dnwqf5HA1caQPHCCGs=
+github.com/opencord/voltha-lib-go/v4 v4.3.4/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.4 h1:mpE4y7zRmoEXMX4seurWBWQ97u2a4rAf8gY2qONjz8I=
 github.com/opencord/voltha-protos/v4 v4.1.4/go.mod h1:W/OIFIyvFh/C0vchRUuarIsMylEhzCRM9pNxLvkPtKc=
 github.com/opentracing/opentracing-go v1.1.0 h1:pWlfV3Bxv7k65HYwkikxat0+s3pV4bsqf19k25Ur8rU=
diff --git a/internal/pkg/onuadaptercore/device_handler.go b/internal/pkg/onuadaptercore/device_handler.go
index af5cb57..ba969a1 100644
--- a/internal/pkg/onuadaptercore/device_handler.go
+++ b/internal/pkg/onuadaptercore/device_handler.go
@@ -1337,6 +1337,28 @@
 	}
 }
 
+func (dh *deviceHandler) getOnuImages(ctx context.Context) (*voltha.OnuImages, error) {
+
+	var onuImageStatus *OnuImageStatus
+
+	pDevEntry := dh.getOnuDeviceEntry(ctx, false)
+	if pDevEntry != nil {
+		onuImageStatus = NewOnuImageStatus(pDevEntry)
+		pDevEntry.mutexOnuImageStatus.Lock()
+		pDevEntry.pOnuImageStatus = onuImageStatus
+		pDevEntry.mutexOnuImageStatus.Unlock()
+
+	} else {
+		logger.Errorw(ctx, "No valid OnuDevice - aborting", log.Fields{"device-id": dh.deviceID})
+		return nil, fmt.Errorf("no-valid-OnuDevice-aborting")
+	}
+	images, err := onuImageStatus.getOnuImageStatus(ctx)
+	pDevEntry.mutexOnuImageStatus.Lock()
+	pDevEntry.pOnuImageStatus = nil
+	pDevEntry.mutexOnuImageStatus.Unlock()
+	return images, err
+}
+
 //  deviceHandler methods that implement the adapters interface requests## end #########
 // #####################################################################################
 
@@ -1919,6 +1941,11 @@
 	if pDevEntry.PDevOmciCC != nil {
 		pDevEntry.PDevOmciCC.CancelRequestMonitoring()
 	}
+	pDevEntry.mutexOnuImageStatus.RLock()
+	if pDevEntry.pOnuImageStatus != nil {
+		pDevEntry.pOnuImageStatus.CancelProcessing(ctx)
+	}
+	pDevEntry.mutexOnuImageStatus.RUnlock()
 
 	if includingMibSyncFsm {
 		pDevEntry.CancelProcessing(ctx)
diff --git a/internal/pkg/onuadaptercore/mib_sync.go b/internal/pkg/onuadaptercore/mib_sync.go
index 29e0a2a..564be6f 100644
--- a/internal/pkg/onuadaptercore/mib_sync.go
+++ b/internal/pkg/onuadaptercore/mib_sync.go
@@ -18,7 +18,6 @@
 package adaptercoreonu
 
 import (
-	"bytes"
 	"context"
 	"encoding/hex"
 	"encoding/json"
@@ -601,7 +600,7 @@
 			case "OnuG":
 				oo.mutexLastTxParamStruct.RUnlock()
 				oo.mutexPersOnuConfig.Lock()
-				oo.sOnuPersistentData.PersVendorID = trimStringFromInterface(meAttributes["VendorId"])
+				oo.sOnuPersistentData.PersVendorID = TrimStringFromMeOctet(meAttributes["VendorId"])
 				snBytes, _ := me.InterfaceToOctets(meAttributes["SerialNumber"])
 				if onugSerialNumberLen == len(snBytes) {
 					snVendorPart := fmt.Sprintf("%s", snBytes[:4])
@@ -620,7 +619,7 @@
 			case "Onu2G":
 				oo.mutexLastTxParamStruct.RUnlock()
 				oo.mutexPersOnuConfig.Lock()
-				oo.sOnuPersistentData.PersEquipmentID = trimStringFromInterface(meAttributes["EquipmentId"])
+				oo.sOnuPersistentData.PersEquipmentID = TrimStringFromMeOctet(meAttributes["EquipmentId"])
 				logger.Debugw(ctx, "MibSync FSM - GetResponse Data for Onu2-G - EquipmentId", log.Fields{"device-id": oo.deviceID,
 					"onuDeviceEntry.equipmentID": oo.sOnuPersistentData.PersEquipmentID})
 				oo.mutexPersOnuConfig.Unlock()
@@ -682,7 +681,7 @@
 func (oo *OnuDeviceEntry) handleSwImageIndications(ctx context.Context, entityID uint16, meAttributes me.AttributeValueMap) {
 	imageIsCommitted := meAttributes["IsCommitted"].(uint8)
 	imageIsActive := meAttributes["IsActive"].(uint8)
-	imageVersion := trimStringFromInterface(meAttributes["Version"])
+	imageVersion := TrimStringFromMeOctet(meAttributes["Version"])
 	oo.mutexPersOnuConfig.RLock()
 	logger.Infow(ctx, "MibSync FSM - GetResponse Data for SoftwareImage",
 		log.Fields{"device-id": oo.deviceID, "entityID": entityID,
@@ -829,11 +828,6 @@
 	return false
 }
 
-func trimStringFromInterface(input interface{}) string {
-	ifBytes, _ := me.InterfaceToOctets(input)
-	return fmt.Sprintf("%s", bytes.Trim(ifBytes, "\x00"))
-}
-
 func (oo *OnuDeviceEntry) mibDbVolatileDict(ctx context.Context) error {
 	logger.Debug(ctx, "MibVolatileDict- running from default Entry code")
 	return errors.New("not_implemented")
diff --git a/internal/pkg/onuadaptercore/omci_onu_upgrade.go b/internal/pkg/onuadaptercore/omci_onu_upgrade.go
index 3da030d..19a9ff0 100644
--- a/internal/pkg/onuadaptercore/omci_onu_upgrade.go
+++ b/internal/pkg/onuadaptercore/omci_onu_upgrade.go
@@ -1254,7 +1254,7 @@
 			meAttributes := msgObj.Attributes
 			imageIsCommitted := meAttributes["IsCommitted"].(uint8)
 			imageIsActive := meAttributes["IsActive"].(uint8)
-			imageVersion := trimStringFromInterface(meAttributes["Version"])
+			imageVersion := TrimStringFromMeOctet(meAttributes["Version"])
 			logger.Debugw(ctx, "OnuUpgradeFsm - GetResponse Data for SoftwareImage",
 				log.Fields{"device-id": oFsm.deviceID, "entityID": msgObj.EntityInstance,
 					"version": imageVersion, "isActive": imageIsActive, "isCommitted": imageIsCommitted})
diff --git a/internal/pkg/onuadaptercore/onu_device_entry.go b/internal/pkg/onuadaptercore/onu_device_entry.go
index 9544efa..4ada5d9 100644
--- a/internal/pkg/onuadaptercore/onu_device_entry.go
+++ b/internal/pkg/onuadaptercore/onu_device_entry.go
@@ -213,6 +213,10 @@
 	//swIsInactive = 0  not yet used
 	swIsActive = 1
 )
+const ( //definitions as per G.988 softwareImage::IsValid
+	//swIsInvalid = 0  not yet used
+	swIsValid = 1
+)
 const onuDataMeID = 0
 const onugMeID = 0
 const onu2gMeID = 0
@@ -279,6 +283,8 @@
 	onuKVStoreProcResult      error //error indication of processing
 	chOnuKvProcessingStep     chan uint8
 	onuSwImageIndications     sSwImageIndications
+	mutexOnuImageStatus       sync.RWMutex
+	pOnuImageStatus           *OnuImageStatus
 	//lockDeviceEntries           sync.RWMutex
 	mibDbClass    func(context.Context) error
 	supportedFsms OmciDeviceFsms
diff --git a/internal/pkg/onuadaptercore/onu_image_status.go b/internal/pkg/onuadaptercore/onu_image_status.go
new file mode 100755
index 0000000..fb34a26
--- /dev/null
+++ b/internal/pkg/onuadaptercore/onu_image_status.go
@@ -0,0 +1,250 @@
+/*
+ * 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 adaptercoreonu provides the utility for onu devices, flows and statistics
+package adaptercoreonu
+
+import (
+	"context"
+	"encoding/hex"
+	"fmt"
+	"sync"
+	"time"
+
+	"github.com/opencord/omci-lib-go"
+	me "github.com/opencord/omci-lib-go/generated"
+	"github.com/opencord/voltha-lib-go/v4/pkg/log"
+	"github.com/opencord/voltha-protos/v4/go/voltha"
+)
+
+//OnuImageStatus implements methods to get status info of onu images
+type OnuImageStatus struct {
+	pDevEntry              *OnuDeviceEntry
+	deviceID               string
+	requestedAttributes    me.AttributeValueMap
+	mutexWaitingForResp    sync.RWMutex
+	waitingForResp         bool
+	respChannel            chan Message
+	mutexPLastTxMeInstance sync.RWMutex
+	pLastTxMeInstance      *me.ManagedEntity
+}
+
+const (
+	cImgVersion     = "Version"
+	cImgIsCommitted = "IsCommitted"
+	cImgIsActive    = "IsActive"
+	cImgIsValid     = "IsValid"
+	cImgProductCode = "ProductCode"
+	cImgImageHash   = "ImageHash"
+)
+
+//NewOnuImageStatus creates a new instance of OnuImageStatus
+func NewOnuImageStatus(pDevEntry *OnuDeviceEntry) *OnuImageStatus {
+	return &OnuImageStatus{
+		pDevEntry:           pDevEntry,
+		deviceID:            pDevEntry.deviceID,
+		requestedAttributes: make(me.AttributeValueMap),
+		waitingForResp:      false,
+		respChannel:         make(chan Message),
+	}
+}
+func (oo *OnuImageStatus) getOnuImageStatus(ctx context.Context) (*voltha.OnuImages, error) {
+
+	var images voltha.OnuImages
+
+	if oo.pDevEntry.PDevOmciCC == nil {
+		logger.Errorw(ctx, "omciCC not ready to receive omci messages", log.Fields{"device-id": oo.deviceID})
+		return nil, fmt.Errorf("omciCC-not-ready-to-receive-omci-messages")
+	}
+	for i := firstSwImageMeID; i <= secondSwImageMeID; i++ {
+		logger.Debugw(ctx, "getOnuImageStatus for image id", log.Fields{"image-id": i, "device-id": oo.deviceID})
+
+		var image voltha.OnuImage
+
+		// TODO: Since the summed length of the attributes exceeds the capacity of a single response,
+		// it is distributed on several requests here. It should be discussed whether, in the course of a refactoring,
+		// a global mechanism should be implemented that automates this distribution - which would entail quite some
+		// changes on the respective receiver sides.
+
+		oo.requestedAttributes = me.AttributeValueMap{cImgVersion: "", cImgIsCommitted: 0, cImgIsActive: 0, cImgIsValid: 0}
+		if err := oo.requestOnuImageAttributes(ctx, uint16(i), &image); err != nil {
+			logger.Errorw(ctx, err.Error(), log.Fields{"requestedAttributes": oo.requestedAttributes, "device-id": oo.deviceID})
+			return nil, err
+		}
+		oo.requestedAttributes = me.AttributeValueMap{cImgProductCode: ""}
+		if err := oo.requestOnuImageAttributes(ctx, uint16(i), &image); err != nil {
+			logger.Errorw(ctx, err.Error(), log.Fields{"requestedAttributes": oo.requestedAttributes, "device-id": oo.deviceID})
+			return nil, err
+		}
+		oo.requestedAttributes = me.AttributeValueMap{cImgImageHash: 0}
+		if err := oo.requestOnuImageAttributes(ctx, uint16(i), &image); err != nil {
+			logger.Errorw(ctx, err.Error(), log.Fields{"requestedAttributes": oo.requestedAttributes, "device-id": oo.deviceID})
+			return nil, err
+		}
+		images.Items = append(images.Items, &image)
+	}
+	logger.Debugw(ctx, "images of the ONU", log.Fields{"images": images})
+	return &images, nil
+}
+
+func (oo *OnuImageStatus) requestOnuImageAttributes(ctx context.Context, imageID uint16, image *voltha.OnuImage) error {
+	oo.mutexPLastTxMeInstance.Lock()
+	meInstance, err := oo.pDevEntry.PDevOmciCC.sendGetMe(log.WithSpanFromContext(context.TODO(), ctx), me.SoftwareImageClassID,
+		imageID, oo.requestedAttributes, oo.pDevEntry.pOpenOnuAc.omciTimeout, true, oo.respChannel)
+	if err != nil {
+		oo.mutexPLastTxMeInstance.Unlock()
+		logger.Errorw(ctx, "can't send omci request to get data for image id", log.Fields{"image-id": imageID, "device-id": oo.deviceID})
+		return fmt.Errorf("can't-send-omci-request-to-get-data-for-image-id-%d", imageID)
+	}
+	oo.pLastTxMeInstance = meInstance
+	oo.mutexPLastTxMeInstance.Unlock()
+
+	if err = oo.waitForGetOnuImageStatus(ctx, image); err != nil {
+		logger.Errorw(ctx, err.Error(), log.Fields{"device-id": oo.deviceID})
+		return err
+	}
+	return nil
+}
+
+func (oo *OnuImageStatus) waitForGetOnuImageStatus(ctx context.Context, image *voltha.OnuImage) error {
+	oo.setWaitingForResp(true)
+	select {
+	// maybe be also some outside cancel (but no context modeled for the moment ...)
+	case <-ctx.Done():
+		logger.Errorw(ctx, "waitForGetOnuImageStatus context done", log.Fields{"device-id": oo.deviceID})
+		oo.setWaitingForResp(false)
+		return fmt.Errorf("wait-for-image-status-context-done")
+	case <-time.After(oo.pDevEntry.PDevOmciCC.GetMaxOmciTimeoutWithRetries() * time.Second):
+		logger.Errorw(ctx, "waitForGetOnuImageStatus timeout", log.Fields{"device-id": oo.deviceID})
+		oo.setWaitingForResp(false)
+		return fmt.Errorf("wait-for-image-status-timeout")
+	case message, ok := <-oo.respChannel:
+		if !ok {
+			logger.Errorw(ctx, "waitForGetOnuImageStatus response error", log.Fields{"device-id": oo.deviceID})
+			oo.setWaitingForResp(false)
+			return fmt.Errorf("wait-for-image-status-response-error")
+		}
+		switch message.Type {
+		case OMCI:
+			msg, _ := message.Data.(OmciMessage)
+			oo.setWaitingForResp(false)
+			return oo.processGetOnuImageStatusResp(ctx, msg, image)
+		case TestMsg:
+			msg, _ := message.Data.(TestMessage)
+			if msg.TestMessageVal == AbortMessageProcessing {
+				logger.Info(ctx, "waitForGetOnuImageStatus abort msg received", log.Fields{"device-id": oo.deviceID})
+				oo.setWaitingForResp(false)
+				return fmt.Errorf("wait-for-image-status-abort-msg-received")
+			}
+		default:
+			logger.Errorw(ctx, "waitForGetOnuImageStatus wrong msg type received", log.Fields{"msgType": message.Type, "device-id": oo.deviceID})
+			oo.setWaitingForResp(false)
+			return fmt.Errorf("wait-for-image-status-response-error")
+		}
+	}
+	logger.Errorw(ctx, "waitForGetOnuImageStatus processing error", log.Fields{"device-id": oo.deviceID})
+	oo.setWaitingForResp(false)
+	return fmt.Errorf("wait-for-image-status-processing-error")
+
+}
+
+func (oo *OnuImageStatus) processGetOnuImageStatusResp(ctx context.Context, msg OmciMessage, image *voltha.OnuImage) error {
+	if msg.OmciMsg.MessageType != omci.GetResponseType {
+		logger.Errorw(ctx, "processGetOnuImageStatusResp wrong response type received", log.Fields{"respType": msg.OmciMsg.MessageType, "device-id": oo.deviceID})
+		return fmt.Errorf("process-image-status-response-error")
+	}
+	msgLayer := (*msg.OmciPacket).Layer(omci.LayerTypeGetResponse)
+	if msgLayer == nil {
+		logger.Errorw(ctx, "processGetOnuImageStatusResp omci Msg layer not found", log.Fields{"device-id": oo.deviceID})
+		return fmt.Errorf("process-image-status-response-error")
+	}
+	msgObj, msgOk := msgLayer.(*omci.GetResponse)
+	if !msgOk {
+		logger.Errorw(ctx, "processGetOnuImageStatusResp omci msgObj layer could not be found", log.Fields{"device-id": oo.deviceID})
+		return fmt.Errorf("process-image-status-response-error")
+	}
+	oo.mutexPLastTxMeInstance.RLock()
+	if oo.pLastTxMeInstance != nil {
+		if msgObj.EntityClass == oo.pLastTxMeInstance.GetClassID() &&
+			msgObj.EntityInstance == oo.pLastTxMeInstance.GetEntityID() {
+			oo.mutexPLastTxMeInstance.RUnlock()
+
+			meAttributes := msgObj.Attributes
+			logger.Debugw(ctx, "processGetOnuImageStatusResp omci attributes received", log.Fields{"attributes": meAttributes, "device-id": oo.deviceID})
+
+			for k := range oo.requestedAttributes {
+				switch k {
+				case cImgIsCommitted:
+					if meAttributes[cImgIsCommitted].(uint8) == swIsCommitted {
+						image.IsCommited = true
+					} else {
+						image.IsCommited = false
+					}
+				case cImgIsActive:
+					if meAttributes[cImgIsActive].(uint8) == swIsActive {
+						image.IsActive = true
+					} else {
+						image.IsActive = false
+					}
+				case cImgIsValid:
+					if meAttributes[cImgIsValid].(uint8) == swIsValid {
+						image.IsValid = true
+					} else {
+						image.IsValid = false
+					}
+				case cImgVersion:
+					image.Version = TrimStringFromMeOctet(meAttributes[cImgVersion])
+				case cImgProductCode:
+					image.ProductCode = TrimStringFromMeOctet(meAttributes[cImgProductCode])
+				case cImgImageHash:
+					bytes, _ := me.InterfaceToOctets(meAttributes[cImgImageHash])
+					image.Hash = hex.EncodeToString(bytes)
+				}
+			}
+			return nil
+		}
+		oo.mutexPLastTxMeInstance.RUnlock()
+		logger.Errorw(ctx, "processGetOnuImageStatusResp wrong MeInstance received", log.Fields{"device-id": oo.deviceID})
+		return fmt.Errorf("process-image-status-response-error")
+	}
+	oo.mutexPLastTxMeInstance.RUnlock()
+	logger.Errorw(ctx, "processGetOnuImageStatusResp pLastTxMeInstance is nil", log.Fields{"device-id": oo.deviceID})
+	return fmt.Errorf("process-image-status-response-error")
+}
+func (oo *OnuImageStatus) setWaitingForResp(value bool) {
+	oo.mutexWaitingForResp.Lock()
+	oo.waitingForResp = value
+	oo.mutexWaitingForResp.Unlock()
+}
+func (oo *OnuImageStatus) isWaitingForResp() bool {
+	oo.mutexWaitingForResp.RLock()
+	value := oo.waitingForResp
+	oo.mutexWaitingForResp.RUnlock()
+	return value
+}
+
+//CancelProcessing ensures that interrupted processing is canceled while waiting for a response
+func (oo *OnuImageStatus) CancelProcessing(ctx context.Context) {
+	if oo.isWaitingForResp() {
+		abortMsg := Message{
+			Type: TestMsg,
+			Data: TestMessage{
+				TestMessageVal: AbortMessageProcessing,
+			},
+		}
+		oo.respChannel <- abortMsg
+	}
+}
diff --git a/internal/pkg/onuadaptercore/openonu.go b/internal/pkg/onuadaptercore/openonu.go
index 805944c..d4089b5 100644
--- a/internal/pkg/onuadaptercore/openonu.go
+++ b/internal/pkg/onuadaptercore/openonu.go
@@ -825,7 +825,16 @@
 
 // Get_onu_images retrieves the ONU SW image status information via OMCI
 func (oo *OpenONUAC) Get_onu_images(ctx context.Context, deviceID string) (*voltha.OnuImages, error) {
-	return nil, errors.New("unImplemented")
+	logger.Infow(ctx, "Get_onu_images", log.Fields{"device-id": deviceID})
+	if handler := oo.getDeviceHandler(ctx, deviceID, false); handler != nil {
+		var err error
+		if images, err := handler.getOnuImages(ctx); err == nil {
+			return images, nil
+		}
+		return nil, fmt.Errorf(fmt.Sprintf("%s-%s", err, deviceID))
+	}
+	logger.Warnw(ctx, "no handler found for Get_onu_images", log.Fields{"device-id": deviceID})
+	return nil, fmt.Errorf(fmt.Sprintf("handler-not-found-%s", deviceID))
 }
 
 // Activate_onu_image initiates the activation of the image for the requested ONU(s)
diff --git a/internal/pkg/onuadaptercore/openonu_utils.go b/internal/pkg/onuadaptercore/openonu_utils.go
index 2d17b05..51e5e81 100644
--- a/internal/pkg/onuadaptercore/openonu_utils.go
+++ b/internal/pkg/onuadaptercore/openonu_utils.go
@@ -18,12 +18,16 @@
 package adaptercoreonu
 
 import (
+	"bytes"
 	"encoding/binary"
 	"errors"
+	"fmt"
 	"net"
 	"regexp"
 	"strconv"
 	"strings"
+
+	me "github.com/opencord/omci-lib-go/generated"
 )
 
 // GetTpIDFromTpPath extracts TpID from the TpPath.
@@ -81,3 +85,9 @@
 
 	return int16(val)
 }
+
+// TrimStringFromMeOctet trim string out of Me octet
+func TrimStringFromMeOctet(input interface{}) string {
+	ifBytes, _ := me.InterfaceToOctets(input)
+	return fmt.Sprintf("%s", bytes.Trim(ifBytes, "\x00"))
+}
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/modules.txt b/vendor/modules.txt
index e0360fb..518edfc 100644
--- a/vendor/modules.txt
+++ b/vendor/modules.txt
@@ -65,7 +65,7 @@
 ## explicit
 github.com/opencord/omci-lib-go
 github.com/opencord/omci-lib-go/generated
-# github.com/opencord/voltha-lib-go/v4 v4.3.1
+# github.com/opencord/voltha-lib-go/v4 v4.3.4
 ## explicit
 github.com/opencord/voltha-lib-go/v4/pkg/adapters
 github.com/opencord/voltha-lib-go/v4/pkg/adapters/adapterif