BER Driver Implementation

Change-Id: Ie215228ae4081ab0b984aafd757601a982ec84d2
diff --git a/core/api/src/main/java/org/onosproject/net/behaviour/BitErrorRateState.java b/core/api/src/main/java/org/onosproject/net/behaviour/BitErrorRateState.java
new file mode 100644
index 0000000..dbff5f1
--- /dev/null
+++ b/core/api/src/main/java/org/onosproject/net/behaviour/BitErrorRateState.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright 2019-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.
+ *
+ * This Work is contributed by Sterlite Technologies
+ */
+package org.onosproject.net.behaviour;
+
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.driver.HandlerBehaviour;
+
+import java.util.Optional;
+
+/*
+ * Interface to compute BitErrorRate(BER) value pre and post Forward Error Correction (FEC).
+ * BER is dependent on FEC value
+ */
+public interface BitErrorRateState extends HandlerBehaviour {
+
+    /**
+     * Get the BER value pre FEC.
+     *
+     * @param deviceId the device identifier
+     * @param port     the port identifier
+     * @return the decimal value of BER
+     */
+    Optional<Double> getPreFecBer(DeviceId deviceId, PortNumber port);
+
+    /**
+     * Get the BER value post FEC.
+     *
+     * @param deviceId the device identifier
+     * @param port     the port identifier
+     * @return the decimal value of BER
+     */
+    Optional<Double> getPostFecBer(DeviceId deviceId, PortNumber port);
+}
diff --git a/drivers/odtn-driver/src/main/java/org/onosproject/drivers/odtn/CassiniBitErrorRateState.java b/drivers/odtn-driver/src/main/java/org/onosproject/drivers/odtn/CassiniBitErrorRateState.java
new file mode 100644
index 0000000..d93f652
--- /dev/null
+++ b/drivers/odtn-driver/src/main/java/org/onosproject/drivers/odtn/CassiniBitErrorRateState.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright 2019-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.
+ *
+ * This Work is contributed by Sterlite Technologies
+ */
+package org.onosproject.drivers.odtn;
+
+import org.onlab.osgi.DefaultServiceDirectory;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.device.DeviceService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/*
+ * Driver Implementation of the BitErrorRateConfig for Cassini terminal devices.
+ */
+public class CassiniBitErrorRateState extends OpenconfigBitErrorRateState {
+
+    private static final Logger log = LoggerFactory.getLogger(CassiniBitErrorRateState.class);
+
+    private static final String OC_NAME = "oc-name";
+    private static final String PORT_NOT_PRESENT = "Port is not present";
+
+    /*
+     * This method is used for getting Cassini Component name.
+     * from DeviceService port annotations by key ("oc-name")
+     *
+     * @param deviceId the device identifier
+     * @param port the port identifier
+     * @return String value representing cassini component name
+     */
+    @Override
+    protected String ocName(DeviceId deviceId, PortNumber port) {
+        DeviceService deviceService = DefaultServiceDirectory.getService(DeviceService.class);
+        if (deviceService.getPort(deviceId, port) == null) {
+            throw new IllegalArgumentException(PORT_NOT_PRESENT);
+        }
+        return deviceService.getPort(deviceId, port).annotations().value(OC_NAME);
+    }
+}
diff --git a/drivers/odtn-driver/src/main/java/org/onosproject/drivers/odtn/OpenconfigBitErrorRateState.java b/drivers/odtn-driver/src/main/java/org/onosproject/drivers/odtn/OpenconfigBitErrorRateState.java
new file mode 100644
index 0000000..20b47e4
--- /dev/null
+++ b/drivers/odtn-driver/src/main/java/org/onosproject/drivers/odtn/OpenconfigBitErrorRateState.java
@@ -0,0 +1,191 @@
+/*
+ * Copyright 2019-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.
+ *
+ * This Work is contributed by Sterlite Technologies
+ */
+package org.onosproject.drivers.odtn;
+
+import org.apache.commons.configuration.HierarchicalConfiguration;
+import org.apache.commons.configuration.XMLConfiguration;
+import org.onosproject.drivers.odtn.util.NetconfSessionUtility;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.behaviour.BitErrorRateState;
+import org.onosproject.net.driver.AbstractHandlerBehaviour;
+import org.onosproject.netconf.NetconfController;
+import org.onosproject.netconf.NetconfSession;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Optional;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+/*
+ * Driver Implementation of the BitErrorRateConfig for OpenConfig terminal devices.
+ */
+public abstract class OpenconfigBitErrorRateState extends AbstractHandlerBehaviour implements BitErrorRateState {
+
+    private static final Logger log = LoggerFactory.getLogger(OpenconfigBitErrorRateState.class);
+
+    private static final String RPC_TAG_NETCONF_BASE =
+            "<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">";
+
+    private static final String RPC_CLOSE_TAG = "</rpc>";
+    private static final String PRE_FEC_BER_TAG = "pre-fec-ber";
+    private static final String POST_FEC_BER_TAG = "post-fec-ber";
+
+    /*
+     * This method returns the instance of NetconfController from DriverHandler.
+     */
+    private NetconfController getController() {
+        return handler().get(NetconfController.class);
+    }
+
+    /*
+     * This method is used for getting Openconfig Component name.
+     * from DeviceService port annotations by device specific key for component name
+     *
+     * @param deviceId the device identifier
+     * @param port the port identifier
+     * @return String value representing Openconfig component name
+     */
+    protected abstract String ocName(DeviceId deviceId, PortNumber port);
+
+    /**
+     * Get the BER value pre FEC.
+     *
+     * @param deviceId the device identifier
+     * @param port     the port identifier
+     * @return the decimal value of BER
+     */
+    @Override
+    public Optional<Double> getPreFecBer(DeviceId deviceId, PortNumber port) {
+        NetconfSession session = NetconfSessionUtility
+                .getNetconfSession(deviceId, getController());
+        checkNotNull(session);
+
+        String preFecBerFilter = generateBerFilter(deviceId, port, PRE_FEC_BER_TAG);
+        String rpcRequest = getConfigOperation(preFecBerFilter);
+        log.debug("RPC call for fetching Pre FEC BER : {}", rpcRequest);
+
+        XMLConfiguration xconf = NetconfSessionUtility.executeRpc(session, rpcRequest);
+
+        if (xconf == null) {
+            log.error("Error in executing Pre FEC BER RPC");
+            return Optional.empty();
+        }
+
+        try {
+            HierarchicalConfiguration config =
+                    xconf.configurationAt("data/components/component/transceiver/state/" + PRE_FEC_BER_TAG);
+            if (config == null || config.getString("instant") == null) {
+                return Optional.empty();
+            }
+            double ber = Float.valueOf(config.getString("instant")).doubleValue();
+            return Optional.of(ber);
+
+        } catch (IllegalArgumentException e) {
+            log.error("Error in fetching configuration : {}", e.getMessage());
+            return Optional.empty();
+        }
+    }
+
+    /**
+     * Get the BER value post FEC.
+     *
+     * @param deviceId the device identifier
+     * @param port     the port identifier
+     * @return the decimal value of BER
+     */
+    @Override
+    public Optional<Double> getPostFecBer(DeviceId deviceId, PortNumber port) {
+        NetconfSession session = NetconfSessionUtility
+                .getNetconfSession(deviceId, getController());
+        checkNotNull(session);
+
+        String postFecBerFilter = generateBerFilter(deviceId, port, POST_FEC_BER_TAG);
+        String rpcRequest = getConfigOperation(postFecBerFilter);
+        log.debug("RPC call for fetching Post FEC BER : {}", rpcRequest);
+
+        XMLConfiguration xconf = NetconfSessionUtility.executeRpc(session, rpcRequest);
+
+        if (xconf == null) {
+            log.error("Error in executing Post FEC BER RPC");
+            return Optional.empty();
+        }
+
+        try {
+            HierarchicalConfiguration config =
+                    xconf.configurationAt("data/components/component/transceiver/state/" + POST_FEC_BER_TAG);
+            if (config == null || config.getString("instant") == null) {
+                return Optional.empty();
+            }
+            double ber = Float.valueOf(config.getString("instant")).doubleValue();
+            return Optional.of(ber);
+
+        } catch (IllegalArgumentException e) {
+            log.error("Error in fetching configuration : {}", e.getMessage());
+            return Optional.empty();
+        }
+    }
+
+    /*
+     * This method is used for generating RPC for Netconf getconfig operation.
+     *
+     * @param filter the String representing the <filter> tag in Netconf RPC
+     * @return the String value representing Netconf getConfig Operation
+     */
+    private String getConfigOperation(String filter) {
+        StringBuilder rpcRequest = new StringBuilder();
+
+        rpcRequest.append(RPC_TAG_NETCONF_BASE)
+                .append("<get>")
+                .append("<filter>")
+                .append(filter)
+                .append("</filter>")
+                .append("</get>")
+                .append(RPC_CLOSE_TAG);
+
+        return rpcRequest.toString();
+    }
+
+    /**
+     * Generate the BER filter to be used in Netconf get-operation RPC.
+     *
+     * @param deviceId the device identifier
+     * @param port     the port identifier
+     * @param tag      the String value to identify the preFecBer / PostFecBer
+     * @return the String value representing the BER filter
+     */
+    private String generateBerFilter(DeviceId deviceId, PortNumber port, String tag) {
+        StringBuilder filter = new StringBuilder("<components xmlns=\"http://openconfig.net/yang/platform\">");
+        filter.append("<component>");
+        filter.append("<name>").append(ocName(deviceId, port)).append("</name>");
+        filter.append("<transceiver xmlns=\"http://openconfig.net/yang/platform/transceiver\">");
+        filter.append("<state>");
+        if (PRE_FEC_BER_TAG.equals(tag)) {
+            filter.append("<pre-fec-ber>").append("<instant/>").append("</pre-fec-ber>");
+        } else if (POST_FEC_BER_TAG.equals(tag)) {
+            filter.append("<post-fec-ber>").append("<instant/>").append("</post-fec-ber>");
+        }
+        filter.append("</state>");
+        filter.append("</transceiver>");
+        filter.append("</component>");
+        filter.append("</components>");
+
+        return filter.toString();
+    }
+}
diff --git a/drivers/odtn-driver/src/main/resources/odtn-drivers.xml b/drivers/odtn-driver/src/main/resources/odtn-drivers.xml
index 174b208..33cec52 100644
--- a/drivers/odtn-driver/src/main/resources/odtn-drivers.xml
+++ b/drivers/odtn-driver/src/main/resources/odtn-drivers.xml
@@ -81,6 +81,8 @@
                    impl="org.onosproject.drivers.odtn.CassiniTerminalDevicePowerConfig"/>
         <behaviour api="org.onosproject.net.behaviour.ModulationConfig"
                    impl="org.onosproject.drivers.odtn.CassiniModulationOpenConfig"/>
+        <behaviour api="org.onosproject.net.behaviour.BitErrorRateState"
+                   impl="org.onosproject.drivers.odtn.CassiniBitErrorRateState"/>
     </driver>
     <driver name="cassini-ocnos-old" manufacturer="Edgecore" hwVersion="cassini" swVersion="OcNOS">
         <behaviour api="org.onosproject.net.device.DeviceDescriptionDiscovery"
diff --git a/web/api/src/main/java/org/onosproject/rest/resources/BitErrorRateWebResource.java b/web/api/src/main/java/org/onosproject/rest/resources/BitErrorRateWebResource.java
new file mode 100644
index 0000000..c898c46
--- /dev/null
+++ b/web/api/src/main/java/org/onosproject/rest/resources/BitErrorRateWebResource.java
@@ -0,0 +1,140 @@
+/*
+ * Copyright 2019-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.
+ *
+ * This Work is contributed by Sterlite Technologies
+ */
+package org.onosproject.rest.resources;
+
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import org.onosproject.net.ConnectPoint;
+import org.onosproject.net.Device;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.behaviour.BitErrorRateState;
+import org.onosproject.net.device.DeviceService;
+import org.onosproject.rest.AbstractWebResource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+/*
+ * Rest APIs to Fetch the BER(bit error rate) pre/post FEC(Forward Error Correction).
+ */
+@Path("bit-error-rate")
+public class BitErrorRateWebResource extends AbstractWebResource {
+
+    private final Logger log = LoggerFactory.getLogger(getClass());
+
+    private static final String DEVICE_NOT_FOUND = "Device is not found";
+    private static final String BER_UNSUPPORTED = "Bit Error Rate is not supported";
+    private static final String PRE_FEC_BER = "pre-fec-ber";
+    private static final String POST_FEC_BER = "post-fec-ber";
+
+    /*
+     * This method returns the implemenation of BitErrorRateConfig interface.
+     *
+     * @param id the device identifier
+     * @return instance of BitErrorRateConfig driver implementation
+     */
+    private BitErrorRateState getBitErrorRateState(String id) {
+        Device device = get(DeviceService.class).getDevice(DeviceId.deviceId(id));
+        if (device == null) {
+            throw new IllegalArgumentException(DEVICE_NOT_FOUND);
+        }
+        if (device.is(BitErrorRateState.class)) {
+            return device.as(BitErrorRateState.class);
+        }
+        return null;
+    }
+
+    /*
+     * Get Request to fetch the BER value before FEC.
+     *
+     * @param connectPointStr connectPoint (device/portNumber)
+     * @return Json Response with pre FEC,BER value
+     */
+    @GET
+    @Path("{connectPoint}/pre_fec_ber")
+    @Produces(MediaType.APPLICATION_JSON)
+    public Response getPreFecBerValue(@PathParam("connectPoint") String connectPointStr) {
+        ConnectPoint connectPoint = ConnectPoint.deviceConnectPoint(connectPointStr);
+        BitErrorRateState bitErrorRateState = getBitErrorRateState(connectPoint.deviceId().toString());
+
+        if (bitErrorRateState == null) {
+            throw new IllegalArgumentException(BER_UNSUPPORTED);
+        }
+        ObjectNode result = encode(connectPoint.deviceId(), connectPoint.port(),
+                                   bitErrorRateState, PRE_FEC_BER);
+        return ok(result).build();
+    }
+
+    /*
+     * Get Request to fetch the BER value after FEC.
+     *
+     * @param connectPointStr connectPoint (device/portNumber)
+     * @return Json Response with post FEC,BER value
+     */
+    @GET
+    @Path("{connectPoint}/post_fec_ber")
+    @Produces(MediaType.APPLICATION_JSON)
+    public Response getPostFecBerValue(@PathParam("connectPoint") String connectPointStr) {
+        ConnectPoint connectPoint = ConnectPoint.deviceConnectPoint(connectPointStr);
+        BitErrorRateState bitErrorRateState = getBitErrorRateState(connectPoint.deviceId().toString());
+
+        if (bitErrorRateState == null) {
+            throw new IllegalArgumentException(BER_UNSUPPORTED);
+        }
+        ObjectNode result = encode(connectPoint.deviceId(), connectPoint.port(),
+                                   bitErrorRateState, POST_FEC_BER);
+        return ok(result).build();
+    }
+
+    /*
+     * This method generates the Json Response for BER.
+     *
+     * @param id device identifier
+     * @param portId port identifier
+     * @param bitErrorRateConfig BitErrorRateConfig object
+     * @param type String value to differentiate Pre/Post Fec, Ber value
+     * @return ObjectNode instance
+     */
+    private ObjectNode encode(DeviceId deviceId, PortNumber port,
+                              BitErrorRateState bitErrorRateConfig,
+                              String type) {
+        double ber = 0.0;
+
+        if (PRE_FEC_BER.equals(type)) {
+            ber = bitErrorRateConfig.getPreFecBer(deviceId, port).get();
+        } else if (POST_FEC_BER.equals(type)) {
+            ber = bitErrorRateConfig.getPostFecBer(deviceId, port).get();
+        } else {
+            log.error("Invalid type");
+            throw new IllegalArgumentException("Invalid type");
+        }
+        ObjectNode responseNode = mapper().createObjectNode();
+
+        responseNode.put("deviceId", deviceId.toString());
+        responseNode.put("portId", port.toString());
+        responseNode.put("ber", ber);
+
+        return responseNode;
+    }
+}
diff --git a/web/api/src/main/java/org/onosproject/rest/resources/CoreWebApplication.java b/web/api/src/main/java/org/onosproject/rest/resources/CoreWebApplication.java
index 3803f0d..e7ec6c7 100644
--- a/web/api/src/main/java/org/onosproject/rest/resources/CoreWebApplication.java
+++ b/web/api/src/main/java/org/onosproject/rest/resources/CoreWebApplication.java
@@ -29,34 +29,35 @@
     @Override
     public Set<Class<?>> getClasses() {
         return getClasses(ApiDocResource.class,
-                ApplicationsWebResource.class,
-                ComponentConfigWebResource.class,
-                NetworkConfigWebResource.class,
-                ClusterWebResource.class,
-                DevicesWebResource.class,
-                LinksWebResource.class,
-                HostsWebResource.class,
-                IntentsWebResource.class,
-                FlowsWebResource.class,
-                FlowObjectiveNextListWebResource.class,
-                GroupsWebResource.class,
-                MetersWebResource.class,
-                TopologyWebResource.class,
-                PathsWebResource.class,
-                StatisticsWebResource.class,
-                MetricsWebResource.class,
-                FlowObjectiveWebResource.class,
-                MulticastRouteWebResource.class,
-                DeviceKeyWebResource.class,
-                RegionsWebResource.class,
-                MastershipWebResource.class,
-                InvalidConfigExceptionMapper.class,
-                DiagnosticsWebResource.class,
-                UiPreferencesWebResource.class,
-                SystemInfoWebResource.class,
-                PacketProcessorsWebResource.class,
-                AuditFilter.class,
-                ModulationWebResource.class
+                          ApplicationsWebResource.class,
+                          ComponentConfigWebResource.class,
+                          NetworkConfigWebResource.class,
+                          ClusterWebResource.class,
+                          DevicesWebResource.class,
+                          LinksWebResource.class,
+                          HostsWebResource.class,
+                          IntentsWebResource.class,
+                          FlowsWebResource.class,
+                          FlowObjectiveNextListWebResource.class,
+                          GroupsWebResource.class,
+                          MetersWebResource.class,
+                          TopologyWebResource.class,
+                          PathsWebResource.class,
+                          StatisticsWebResource.class,
+                          MetricsWebResource.class,
+                          FlowObjectiveWebResource.class,
+                          MulticastRouteWebResource.class,
+                          DeviceKeyWebResource.class,
+                          RegionsWebResource.class,
+                          MastershipWebResource.class,
+                          InvalidConfigExceptionMapper.class,
+                          DiagnosticsWebResource.class,
+                          UiPreferencesWebResource.class,
+                          SystemInfoWebResource.class,
+                          PacketProcessorsWebResource.class,
+                          AuditFilter.class,
+                          ModulationWebResource.class,
+                          BitErrorRateWebResource.class
         );
     }
 }