[VOL-4673] Initial translation of data inside mountpoint

Change-Id: Icafbbe25fb4a6ef28049419b8e0eca793c0a0e19
diff --git a/internal/config/config.go b/internal/config/config.go
index d7e4916..d3be1fc 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -35,6 +35,7 @@
 	OnosRestEndpoint      string
 	OnosUser              string
 	OnosPassword          string
+	SchemaMountFilePath   string
 }
 
 // LoadConfig loads the BBF adapter configuration through
@@ -55,6 +56,7 @@
 	flag.StringVar(&conf.OnosRestEndpoint, "onos_rest_endpoint", conf.OnosRestEndpoint, "Endpoint of ONOS REST APIs")
 	flag.StringVar(&conf.OnosUser, "onos_user", conf.OnosUser, "Username for ONOS REST APIs")
 	flag.StringVar(&conf.OnosPassword, "onos_pass", conf.OnosPassword, "Password for ONOS REST APIs")
+	flag.StringVar(&conf.SchemaMountFilePath, "schema_mount_path", conf.SchemaMountFilePath, "Path to the XML file that defines schema-mounts for libyang")
 
 	flag.Parse()
 
@@ -77,5 +79,6 @@
 		OnosRestEndpoint:      "voltha-infra-onos-classic-hs.infra.svc:8181",
 		OnosUser:              "onos",
 		OnosPassword:          "rocks",
+		SchemaMountFilePath:   "/schema-mount.xml",
 	}
 }
diff --git a/internal/core/translation.go b/internal/core/translation.go
index bc7c692..634272c 100644
--- a/internal/core/translation.go
+++ b/internal/core/translation.go
@@ -19,14 +19,29 @@
 import (
 	"fmt"
 
+	"github.com/opencord/voltha-protos/v5/go/common"
 	"github.com/opencord/voltha-protos/v5/go/voltha"
 )
 
 const (
 	DeviceAggregationModel = "bbf-device-aggregation"
 	DevicesPath            = "/" + DeviceAggregationModel + ":devices"
-	DeviceTypeOlt          = "bbf-device-types:olt"
-	DeviceTypeOnu          = "bbf-device-types:onu"
+	HardwarePath           = "data/ietf-hardware:hardware"
+
+	//Device types
+	DeviceTypeOlt = "bbf-device-types:olt"
+	DeviceTypeOnu = "bbf-device-types:onu"
+
+	//Admin states
+	ietfAdminStateUnknown  = "unknown"
+	ietfAdminStateLocked   = "locked"
+	ietfAdminStateUnlocked = "unlocked"
+
+	//Oper states
+	ietfOperStateUnknown  = "unknown"
+	ietfOperStateDisabled = "disabled"
+	ietfOperStateEnabled  = "enabled"
+	ietfOperStateTesting  = "testing"
 )
 
 type YangItem struct {
@@ -39,20 +54,117 @@
 	return fmt.Sprintf("%s/device[name='%s']", DevicesPath, id)
 }
 
+//getDevicePath returns the yang path to the root of the device's hardware module in its data mountpoint
+func getDeviceHardwarePath(id string) string {
+	return fmt.Sprintf("%s/device[name='%s']/%s/component[name='%s']", DevicesPath, id, HardwarePath, id)
+}
+
+//ietfHardwareAdminState returns the string that represents the ietf-hardware admin state
+//enum value corresponding to the one of VOLTHA
+func ietfHardwareAdminState(volthaAdminState voltha.AdminState_Types) string {
+	//TODO: verify this mapping is correct
+	switch volthaAdminState {
+	case common.AdminState_UNKNOWN:
+		return ietfAdminStateUnknown
+	case common.AdminState_PREPROVISIONED:
+	case common.AdminState_DOWNLOADING_IMAGE:
+	case common.AdminState_ENABLED:
+		return ietfAdminStateUnlocked
+	case common.AdminState_DISABLED:
+		return ietfAdminStateLocked
+	}
+
+	//TODO: does something map to "shutting-down" ?
+
+	return ietfAdminStateUnknown
+}
+
+//ietfHardwareOperState returns the string that represents the ietf-hardware oper state
+//enum value corresponding to the one of VOLTHA
+func ietfHardwareOperState(volthaOperState voltha.OperStatus_Types) string {
+	//TODO: verify this mapping is correct
+	switch volthaOperState {
+	case common.OperStatus_UNKNOWN:
+		return ietfOperStateUnknown
+	case common.OperStatus_TESTING:
+		return ietfOperStateTesting
+	case common.OperStatus_ACTIVE:
+		return ietfOperStateEnabled
+	case common.OperStatus_DISCOVERED:
+	case common.OperStatus_ACTIVATING:
+	case common.OperStatus_FAILED:
+	case common.OperStatus_RECONCILING:
+	case common.OperStatus_RECONCILING_FAILED:
+		return ietfOperStateDisabled
+	}
+
+	return ietfOperStateUnknown
+}
+
 //translateDevice returns a slice of yang items that represent a voltha device
 func translateDevice(device voltha.Device) []YangItem {
 	devicePath := getDevicePath(device.Id)
+	hardwarePath := getDeviceHardwarePath(device.Id)
 
-	typeItem := YangItem{}
-	typeItem.Path = fmt.Sprintf("%s/type", devicePath)
+	result := []YangItem{}
 
+	//Device type
 	if device.Root {
-		typeItem.Value = DeviceTypeOlt
+		result = append(result, YangItem{
+			Path:  fmt.Sprintf("%s/type", devicePath),
+			Value: DeviceTypeOlt,
+		})
 	} else {
-		typeItem.Value = DeviceTypeOnu
+		result = append(result, YangItem{
+			Path:  fmt.Sprintf("%s/type", devicePath),
+			Value: DeviceTypeOnu,
+		})
 	}
 
-	return []YangItem{typeItem}
+	//Vendor name
+	result = append(result, YangItem{
+		Path:  fmt.Sprintf("%s/mfg-name", hardwarePath),
+		Value: device.Vendor,
+	})
+
+	//Model
+	result = append(result, YangItem{
+		Path:  fmt.Sprintf("%s/model-name", hardwarePath),
+		Value: device.Model,
+	})
+
+	//Hardware version
+	result = append(result, YangItem{
+		Path:  fmt.Sprintf("%s/hardware-rev", hardwarePath),
+		Value: device.HardwareVersion,
+	})
+
+	//Firmware version
+	result = append(result, YangItem{
+		Path:  fmt.Sprintf("%s/firmware-rev", hardwarePath),
+		Value: device.FirmwareVersion,
+	})
+
+	//Serial number
+	result = append(result, YangItem{
+		Path:  fmt.Sprintf("%s/serial-num", hardwarePath),
+		Value: device.SerialNumber,
+	})
+
+	//Administrative state
+	//Translates VOLTHA admin state enum to ietf-hardware enum
+	result = append(result, YangItem{
+		Path:  fmt.Sprintf("%s/state/admin-state", hardwarePath),
+		Value: ietfHardwareAdminState(device.AdminState),
+	})
+
+	//Operative state
+	result = append(result, YangItem{
+		Path:  fmt.Sprintf("%s/state/oper-state", hardwarePath),
+		Value: ietfHardwareOperState(device.OperStatus),
+	})
+
+	return result
 }
 
 //translateDevices returns a slice of yang items that represent a list of voltha devices
diff --git a/internal/sysrepo/plugin.c b/internal/sysrepo/plugin.c
index f3ff6a3..08e7978 100644
--- a/internal/sysrepo/plugin.c
+++ b/internal/sysrepo/plugin.c
@@ -23,12 +23,26 @@
 
 //CGO can't see raw structs
 typedef struct lyd_node lyd_node;
+typedef struct ly_ctx ly_ctx;
 
-//Exported by sysrepo.go
+//Provides data for the schema-mount extension
+LY_ERR mountpoint_ext_data_clb(
+    const struct lysc_ext_instance *ext,
+    void *user_data,
+    void **ext_data,
+    ly_bool *ext_data_free)
+{
+    *ext_data = (lyd_node*) user_data;
+    *ext_data_free = 0;
+    return LY_SUCCESS;
+}
+
+// Exported by sysrepo.go
 sr_error_t get_devices_cb(sr_session_ctx_t *session, lyd_node **parent);
 
-//The wrapper function is needed because CGO cannot express const char*
-//and thus it can't match sysrepo's callback signature
+//The wrapper functions are needed because CGO cannot express some keywords
+//such as "const", and thus it can't match sysrepo's callback signature
+
 int get_devices_cb_wrapper(
     sr_session_ctx_t *session,
     uint32_t subscription_id,
diff --git a/internal/sysrepo/sysrepo.go b/internal/sysrepo/sysrepo.go
index 4ab96ff..3a4dc79 100644
--- a/internal/sysrepo/sysrepo.go
+++ b/internal/sysrepo/sysrepo.go
@@ -22,6 +22,8 @@
 import (
 	"context"
 	"fmt"
+	"io/ioutil"
+	"os"
 	"unsafe"
 
 	"github.com/opencord/voltha-lib-go/v7/pkg/log"
@@ -29,15 +31,23 @@
 )
 
 type SysrepoPlugin struct {
-	connection   *C.sr_conn_ctx_t
-	session      *C.sr_session_ctx_t
-	subscription *C.sr_subscription_ctx_t
+	connection      *C.sr_conn_ctx_t
+	session         *C.sr_session_ctx_t
+	subscription    *C.sr_subscription_ctx_t
+	schemaMountData *C.lyd_node
 }
 
-func errorMsg(code C.int) string {
+func srErrorMsg(code C.int) string {
 	return C.GoString(C.sr_strerror(code))
 }
 
+func lyErrorMsg(ly_ctx *C.ly_ctx) string {
+	lyErrString := C.ly_errmsg(ly_ctx)
+	defer freeCString(lyErrString)
+
+	return C.GoString(lyErrString)
+}
+
 func freeCString(str *C.char) {
 	if str != nil {
 		C.free(unsafe.Pointer(str))
@@ -53,11 +63,16 @@
 
 	//libyang context
 	ly_ctx := C.sr_acquire_context(conn)
+	defer C.sr_release_context(conn)
 	if ly_ctx == nil {
 		return fmt.Errorf("null-libyang-context")
 	}
 
 	for _, item := range items {
+		if item.Value == "" {
+			continue
+		}
+
 		logger.Debugw(ctx, "updating-yang-item", log.Fields{"item": item})
 
 		path := C.CString(item.Path)
@@ -68,9 +83,7 @@
 			freeCString(path)
 			freeCString(value)
 
-			lyErrString := C.ly_errmsg(ly_ctx)
-			err := fmt.Errorf("libyang-new-path-failed: %d %s", lyErr, C.GoString(lyErrString))
-			freeCString(lyErrString)
+			err := fmt.Errorf("libyang-new-path-failed: %d %s", lyErr, lyErrorMsg(ly_ctx))
 
 			return err
 		}
@@ -91,7 +104,7 @@
 	errCode = C.sr_connect(C.SR_CONN_DEFAULT, &p.connection)
 	if errCode != C.SR_ERR_OK {
 		err := fmt.Errorf("sysrepo-connect-error")
-		logger.Errorw(ctx, err.Error(), log.Fields{"errCode": errCode, "errMsg": errorMsg(errCode)})
+		logger.Errorw(ctx, err.Error(), log.Fields{"errCode": errCode, "errMsg": srErrorMsg(errCode)})
 		return err
 	}
 
@@ -99,7 +112,7 @@
 	errCode = C.sr_session_start(p.connection, C.SR_DS_RUNNING, &p.session)
 	if errCode != C.SR_ERR_OK {
 		err := fmt.Errorf("sysrepo-session-error")
-		logger.Errorw(ctx, err.Error(), log.Fields{"errCode": errCode, "errMsg": errorMsg(errCode)})
+		logger.Errorw(ctx, err.Error(), log.Fields{"errCode": errCode, "errMsg": srErrorMsg(errCode)})
 
 		_ = p.Stop(ctx)
 
@@ -147,7 +160,7 @@
 	return C.SR_ERR_OK
 }
 
-func StartNewPlugin(ctx context.Context) (*SysrepoPlugin, error) {
+func StartNewPlugin(ctx context.Context, schemaMountFilePath string) (*SysrepoPlugin, error) {
 	plugin := &SysrepoPlugin{}
 
 	//Open a session to sysrepo
@@ -156,8 +169,34 @@
 		return nil, err
 	}
 
-	//TODO: could be useful to set it according to the adapter log level
-	C.sr_log_stderr(C.SR_LL_WRN)
+	//Read the schema-mount file
+	if _, err := os.Stat(schemaMountFilePath); err != nil {
+		//The file cannot be found
+		return nil, fmt.Errorf("plugin-startup-schema-mount-file-not-found: %v", err)
+	}
+
+	smBuffer, err := ioutil.ReadFile(schemaMountFilePath)
+	if err != nil {
+		return nil, fmt.Errorf("plugin-startup-cannot-read-schema-mount-file: %v", err)
+	}
+
+	smString := C.CString(string(smBuffer))
+	defer freeCString(smString)
+
+	ly_ctx := C.sr_acquire_context(plugin.connection)
+	defer C.sr_release_context(plugin.connection)
+	if ly_ctx == nil {
+		return nil, fmt.Errorf("plugin-startup-null-libyang-context")
+	}
+
+	//Parse the schema-mount file into libyang nodes, and save them into the plugin data
+	lyErrCode := C.lyd_parse_data_mem(ly_ctx, smString, C.LYD_XML, C.LYD_PARSE_STRICT, C.LYD_VALIDATE_PRESENT, &plugin.schemaMountData)
+	if lyErrCode != C.LY_SUCCESS {
+		return nil, fmt.Errorf("plugin-startup-cannot-parse-schema-mount: %v", lyErrorMsg(ly_ctx))
+	}
+
+	//Bind the callback needed to support schema-mount
+	C.sr_set_ext_data_cb(plugin.connection, C.function(C.mountpoint_ext_data_clb), unsafe.Pointer(plugin.schemaMountData))
 
 	//Set callbacks for events
 
@@ -179,7 +218,7 @@
 	)
 	if errCode != C.SR_ERR_OK {
 		err := fmt.Errorf("sysrepo-failed-subscription-to-get-events")
-		logger.Errorw(ctx, err.Error(), log.Fields{"errCode": errCode, "errMsg": errorMsg(errCode)})
+		logger.Errorw(ctx, err.Error(), log.Fields{"errCode": errCode, "errMsg": srErrorMsg(errCode)})
 		return nil, err
 	}
 
@@ -191,12 +230,15 @@
 func (p *SysrepoPlugin) Stop(ctx context.Context) error {
 	var errCode C.int
 
+	//Free the libyang nodes for external schema-mount data
+	C.lyd_free_all(p.schemaMountData)
+
 	//Frees subscription
 	if p.subscription != nil {
 		errCode = C.sr_unsubscribe(p.subscription)
 		if errCode != C.SR_ERR_OK {
 			err := fmt.Errorf("failed-to-close-sysrepo-subscription")
-			logger.Errorw(ctx, err.Error(), log.Fields{"errCode": errCode, "errMsg": errorMsg(errCode)})
+			logger.Errorw(ctx, err.Error(), log.Fields{"errCode": errCode, "errMsg": srErrorMsg(errCode)})
 			return err
 		}
 		p.subscription = nil
@@ -207,7 +249,7 @@
 		errCode = C.sr_session_stop(p.session)
 		if errCode != C.SR_ERR_OK {
 			err := fmt.Errorf("failed-to-close-sysrepo-session")
-			logger.Errorw(ctx, err.Error(), log.Fields{"errCode": errCode, "errMsg": errorMsg(errCode)})
+			logger.Errorw(ctx, err.Error(), log.Fields{"errCode": errCode, "errMsg": srErrorMsg(errCode)})
 			return err
 		}
 		p.session = nil
@@ -218,7 +260,7 @@
 		errCode = C.sr_disconnect(p.connection)
 		if errCode != C.SR_ERR_OK {
 			err := fmt.Errorf("failed-to-close-sysrepo-connection")
-			logger.Errorw(ctx, err.Error(), log.Fields{"errCode": errCode, "errMsg": errorMsg(errCode)})
+			logger.Errorw(ctx, err.Error(), log.Fields{"errCode": errCode, "errMsg": srErrorMsg(errCode)})
 			return err
 		}
 		p.connection = nil