[GEANT] Command device-interfaces added.

Change-Id: If70eedc5e8e0d83bc4d31c556fbf8382cbe97cec
diff --git a/drivers/cisco/src/main/java/org/onosproject/drivers/cisco/InterfaceConfigCiscoIosImpl.java b/drivers/cisco/src/main/java/org/onosproject/drivers/cisco/InterfaceConfigCiscoIosImpl.java
index a8259a8..ae703cf 100644
--- a/drivers/cisco/src/main/java/org/onosproject/drivers/cisco/InterfaceConfigCiscoIosImpl.java
+++ b/drivers/cisco/src/main/java/org/onosproject/drivers/cisco/InterfaceConfigCiscoIosImpl.java
@@ -22,6 +22,7 @@
 import org.onosproject.drivers.utilities.XmlConfigParser;
 import org.onosproject.net.DeviceId;
 import org.onosproject.net.behaviour.InterfaceConfig;
+import org.onosproject.net.device.DeviceInterfaceDescription;
 import org.onosproject.net.driver.AbstractHandlerBehaviour;
 import org.onosproject.netconf.NetconfController;
 import org.onosproject.netconf.NetconfException;
@@ -45,6 +46,7 @@
 
     /**
      * Adds an access interface to a VLAN.
+     *
      * @param deviceId the device ID
      * @param intf the name of the interface
      * @param vlanId the VLAN ID
@@ -72,6 +74,7 @@
 
     /**
      * Builds a request to add an access interface to a VLAN.
+     *
      * @param intf the name of the interface
      * @param vlanId the VLAN ID
      * @return the request string.
@@ -107,6 +110,7 @@
 
     /**
      * Removes an access interface to a VLAN.
+     *
      * @param deviceId the device ID
      * @param intf the name of the interface
      * @return the result of operation
@@ -133,6 +137,7 @@
 
     /**
      * Builds a request to remove an access interface from a VLAN.
+     *
      * @param intf the name of the interface
      * @return the request string.
      */
@@ -166,6 +171,7 @@
 
     /**
      *  Adds a trunk interface for VLANs.
+     *
      * @param deviceId the device ID
      * @param intf the name of the interface
      * @param vlanIds the VLAN IDs
@@ -193,6 +199,7 @@
 
     /**
      * Builds a request to configure an interface as trunk for VLANs.
+     *
      * @param intf the name of the interface
      * @param vlanIds the VLAN IDs
      * @return the request string.
@@ -229,7 +236,8 @@
     }
 
     /**
-     *  Removes trunk mode configuration from an interface.
+     * Removes trunk mode configuration from an interface.
+     *
      * @param deviceId the device ID
      * @param intf the name of the interface
      * @return the result of operation
@@ -256,6 +264,7 @@
 
     /**
      * Builds a request to remove trunk mode configuration from an interface.
+     *
      * @param intf the name of the interface
      * @return the request string.
      */
@@ -292,6 +301,7 @@
 
     /**
      * Builds a string with comma separated VLAN-IDs.
+     *
      * @param vlanIds the VLAN IDs
      * @return the string including the VLAN-IDs
      */
@@ -308,5 +318,54 @@
         return  vlansStringBuilder.toString();
     }
 
+    /**
+     * Provides the interfaces configured on a device.
+     *
+     * @param deviceId the device ID
+     * @return the list of the configured interfaces
+     */
+    @Override
+    public List<DeviceInterfaceDescription> getInterfaces(DeviceId deviceId) {
+        NetconfController controller =
+                checkNotNull(handler().get(NetconfController.class));
+
+        NetconfSession session = controller.getDevicesMap().get(handler()
+                                 .data().deviceId()).getSession();
+        String reply;
+        try {
+            reply = session.requestSync(getConfigBuilder());
+        } catch (NetconfException e) {
+            log.error("Failed to retrieve configuration from device {}.",
+                      deviceId, e);
+            return null;
+        }
+
+        return XmlParserCisco.getInterfacesFromConfig(XmlConfigParser.loadXml(
+                new ByteArrayInputStream(reply.getBytes(StandardCharsets.UTF_8))));
+    }
+
+    /**
+     * Builds a request for getting configuration from device.
+     *
+     * @return the request string.
+     */
+    private String getConfigBuilder() {
+        StringBuilder rpc =
+                new StringBuilder("<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ");
+        rpc.append("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">");
+        rpc.append("<get-config>");
+        rpc.append("<source>");
+        rpc.append("<running/>");
+        rpc.append("</source>");
+        rpc.append("<filter>");
+        rpc.append("<config-format-xml>");
+        rpc.append("</config-format-xml>");
+        rpc.append("</filter>");
+        rpc.append("</get-config>");
+        rpc.append("</rpc>");
+
+        return rpc.toString();
+    }
+
 }
 
diff --git a/drivers/cisco/src/main/java/org/onosproject/drivers/cisco/XmlParserCisco.java b/drivers/cisco/src/main/java/org/onosproject/drivers/cisco/XmlParserCisco.java
new file mode 100644
index 0000000..9ab9c55
--- /dev/null
+++ b/drivers/cisco/src/main/java/org/onosproject/drivers/cisco/XmlParserCisco.java
@@ -0,0 +1,144 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * 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 org.onosproject.drivers.cisco;
+
+import com.google.common.collect.Lists;
+import org.apache.commons.configuration.HierarchicalConfiguration;
+import org.onlab.packet.VlanId;
+import org.onosproject.net.device.DefaultDeviceInterfaceDescription;
+import org.onosproject.net.device.DeviceInterfaceDescription;
+
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * Parser for Netconf XML configurations and replies from Cisco devices.
+ */
+public final class XmlParserCisco {
+
+    private static final String TRUNK_MODE_KEY =
+            "ConfigIf-Configuration.switchport.mode.trunk";
+    private static final String ACCESS_KEY =
+            "ConfigIf-Configuration.switchport.access.vlan.VLANIDVLANPortAccessMode";
+    private static final String TRUNK_VLAN_KEY =
+            "ConfigIf-Configuration.switchport.trunk.allowed.vlan.VLANIDsAllowedVLANsPortTrunkingMode";
+    private static final String RATE_LIMIT_KEY =
+            "ConfigIf-Configuration.srr-queue.bandwidth.limit.EnterBandwidthLimitInterfaceAsPercentage";
+    private static final short NO_LIMIT = -1;
+
+    private XmlParserCisco() {
+        // Not to be called.
+    }
+
+    /**
+     * Parses device configuration and returns the descriptions of the device
+     * interfaces.
+     *
+     * @param cfg an hierarchical configuration
+     * @return list of interface descriptions for the device
+     */
+
+    public static List<DeviceInterfaceDescription> getInterfacesFromConfig(
+            HierarchicalConfiguration cfg) {
+        List<DeviceInterfaceDescription> intfs = Lists.newArrayList();
+        List<HierarchicalConfiguration> subtrees =
+                cfg.configurationsAt("data.xml-config-data.Device-Configuration.interface");
+        for (HierarchicalConfiguration intfConfig :subtrees) {
+            String intfName = getInterfaceName(intfConfig);
+            DeviceInterfaceDescription.Mode intfMode = getInterfaceMode(intfConfig);
+            List<VlanId> intfVlans = getInterfaceVlans(intfConfig, intfMode);
+            short intfLimit = getInterfaceLimit(intfConfig);
+            boolean intfLimited = (intfLimit == NO_LIMIT ?  false : true);
+            DeviceInterfaceDescription intf =
+                    new DefaultDeviceInterfaceDescription(intfName,
+                                                          intfMode,
+                                                          intfVlans,
+                                                          intfLimited,
+                                                          intfLimit);
+            intfs.add(intf);
+        }
+        return intfs;
+    }
+
+    private static String getInterfaceName(HierarchicalConfiguration intfConfig) {
+        return intfConfig.getString("Param");
+    }
+
+    private static DeviceInterfaceDescription.Mode
+    getInterfaceMode(HierarchicalConfiguration intfConfig) {
+        if (intfConfig.containsKey(TRUNK_MODE_KEY)) {
+            return DeviceInterfaceDescription.Mode.TRUNK;
+        } else if (intfConfig.containsKey(ACCESS_KEY)) {
+            return DeviceInterfaceDescription.Mode.ACCESS;
+        } else {
+            return DeviceInterfaceDescription.Mode.NORMAL;
+        }
+    }
+
+    private static List<VlanId> getInterfaceVlans(
+            HierarchicalConfiguration intfConfig,
+            DeviceInterfaceDescription.Mode mode) {
+        List<VlanId> vlans = Lists.newArrayList();
+        if (mode == DeviceInterfaceDescription.Mode.ACCESS) {
+            vlans.add(getVlanForAccess(intfConfig));
+        } else if (mode == DeviceInterfaceDescription.Mode.TRUNK) {
+            vlans.addAll(getVlansForTrunk(intfConfig));
+        }
+        return vlans;
+    }
+
+    private static VlanId getVlanForAccess(HierarchicalConfiguration intfConfig) {
+        if (intfConfig.containsKey(ACCESS_KEY)) {
+            return VlanId.vlanId(intfConfig.getString(ACCESS_KEY));
+        }
+        return null;
+    }
+
+    private static List<VlanId> getVlansForTrunk(HierarchicalConfiguration intfConfig) {
+        if (intfConfig.containsKey(TRUNK_VLAN_KEY)) {
+            return parseVlans(intfConfig.getStringArray(TRUNK_VLAN_KEY));
+        }
+        return null;
+    }
+
+    private static List<VlanId> parseVlans(String[] vlansString) {
+        List<VlanId> vlans = Lists.newArrayList();
+        List<String> items = Arrays.asList(vlansString);
+        for (String item: items) {
+            int index = item.indexOf("-");
+            if (index == -1) {
+                // Not a range o values
+                vlans.add(VlanId.vlanId(item));
+            } else {
+                // A range of values separated with "-"
+                short lowerVlan = Short.parseShort(item.substring(0, index));
+                short higherVlan = Short.parseShort(item.substring(index + 1));
+                for (short i = lowerVlan; i <= higherVlan; i++) {
+                    vlans.add(VlanId.vlanId(i));
+                }
+            }
+        }
+        return vlans;
+    }
+
+    private static short getInterfaceLimit(HierarchicalConfiguration intfConfig) {
+        if (intfConfig.containsKey(RATE_LIMIT_KEY)) {
+            return intfConfig.getShort(RATE_LIMIT_KEY);
+        }
+        return NO_LIMIT;
+    }
+}
diff --git a/drivers/cisco/src/test/java/org/onosproject/drivers/cisco/XmlParserCiscoTest.java b/drivers/cisco/src/test/java/org/onosproject/drivers/cisco/XmlParserCiscoTest.java
new file mode 100644
index 0000000..f9eaf7f
--- /dev/null
+++ b/drivers/cisco/src/test/java/org/onosproject/drivers/cisco/XmlParserCiscoTest.java
@@ -0,0 +1,108 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * 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 org.onosproject.drivers.cisco;
+
+import com.google.common.collect.Lists;
+import org.apache.commons.configuration.HierarchicalConfiguration;
+import org.junit.Test;
+import org.onlab.packet.VlanId;
+import org.onosproject.drivers.utilities.XmlConfigParser;
+import org.onosproject.net.device.DefaultDeviceInterfaceDescription;
+import org.onosproject.net.device.DeviceInterfaceDescription;
+
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+
+/**
+ * Tests the parser for Netconf XML configurations and replies from Cisco devices.
+ */
+public class XmlParserCiscoTest {
+
+    private static final String INTF_NAME_1 = "GigabitEthernet0/1";
+    private static final String INTF_NAME_2 = "GigabitEthernet0/2";
+    private static final String INTF_NAME_3 = "GigabitEthernet0/3";
+    private static final String INTF_NAME_4 = "GigabitEthernet0/4";
+    private static final String INTF_NAME_5 = "GigabitEthernet0/5";
+    private static final VlanId ACCESS_VLAN = VlanId.vlanId((short) 100);
+    private static final VlanId TRUNK_VLAN_1 = VlanId.vlanId((short) 200);
+    private static final VlanId TRUNK_VLAN_2 = VlanId.vlanId((short) 201);
+    private static final VlanId TRUNK_VLAN_3 = VlanId.vlanId((short) 300);
+    private static final VlanId TRUNK_VLAN_4 = VlanId.vlanId((short) 301);
+    private static final VlanId TRUNK_VLAN_5 = VlanId.vlanId((short) 302);
+    private static final short NO_RATE_LIMIT = -1;
+    private static final short RATE_LIMIT_1 = 75;
+    private static final short RATE_LIMIT_2 = 50;
+    private static final boolean NO_LIMIT = false;
+    private static final boolean WITH_LIMIT = true;
+    private static final String CONFIG_XML_FILE = "/testGetConfig.xml";
+
+    @Test
+    public void controllersConfig() {
+        InputStream streamOrig = getClass().getResourceAsStream(CONFIG_XML_FILE);
+        HierarchicalConfiguration cfgOrig = XmlConfigParser.loadXml(streamOrig);
+        List<DeviceInterfaceDescription> actualIntfs =
+                XmlParserCisco.getInterfacesFromConfig(cfgOrig);
+        assertEquals("Interfaces were not retrieved from configuration",
+                     getExpectedIntfs(), actualIntfs);
+    }
+
+    private List<DeviceInterfaceDescription> getExpectedIntfs() {
+        List<DeviceInterfaceDescription> intfs = new ArrayList<>();
+        intfs.add(new DefaultDeviceInterfaceDescription(INTF_NAME_1,
+                                                        DeviceInterfaceDescription.Mode.NORMAL,
+                                                        Lists.newArrayList(),
+                                                        NO_LIMIT,
+                                                        NO_RATE_LIMIT));
+
+        List<VlanId> accessList = new ArrayList<>();
+        accessList.add(ACCESS_VLAN);
+        intfs.add(new DefaultDeviceInterfaceDescription(INTF_NAME_2,
+                                                        DeviceInterfaceDescription.Mode.ACCESS,
+                                                        accessList,
+                                                        NO_LIMIT,
+                                                        NO_RATE_LIMIT));
+
+        List<VlanId> trunkList1 = new ArrayList<>();
+        trunkList1.add(TRUNK_VLAN_1);
+        trunkList1.add(TRUNK_VLAN_2);
+        intfs.add(new DefaultDeviceInterfaceDescription(INTF_NAME_3,
+                                                        DeviceInterfaceDescription.Mode.TRUNK,
+                                                        trunkList1,
+                                                        NO_LIMIT,
+                                                        NO_RATE_LIMIT));
+
+        intfs.add(new DefaultDeviceInterfaceDescription(INTF_NAME_4,
+                                                        DeviceInterfaceDescription.Mode.NORMAL,
+                                                        Lists.newArrayList(),
+                                                        WITH_LIMIT,
+                                                        RATE_LIMIT_1));
+
+        List<VlanId> trunkList2 = new ArrayList<>();
+        trunkList2.add(TRUNK_VLAN_3);
+        trunkList2.add(TRUNK_VLAN_4);
+        trunkList2.add(TRUNK_VLAN_5);
+        intfs.add(new DefaultDeviceInterfaceDescription(INTF_NAME_5,
+                                                        DeviceInterfaceDescription.Mode.TRUNK,
+                                                        trunkList2,
+                                                        WITH_LIMIT,
+                                                        RATE_LIMIT_2));
+        return intfs;
+    }
+}
\ No newline at end of file
diff --git a/drivers/cisco/src/test/resources/testGetConfig.xml b/drivers/cisco/src/test/resources/testGetConfig.xml
new file mode 100644
index 0000000..349a032
--- /dev/null
+++ b/drivers/cisco/src/test/resources/testGetConfig.xml
@@ -0,0 +1,71 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright 2016-present Open Networking Laboratory
+  ~
+  ~ 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.
+  -->
+    <rpc-reply message-id="101" xmlns="urn:ietf:params:netconf:base:1.0">
+    <data><xml-config-data><Device-Configuration xmlns="urn:cisco:xml-pi">
+    <version><Param>15.0</Param></version>
+    <service operation="delete" ><pad/></service>
+    <service><timestamps><debug><datetime><msec/></datetime></debug></timestamps></service>
+    <service><timestamps><log><datetime><msec/></datetime></log></timestamps></service>
+    <service operation="delete" ><password-encryption/></service>
+    <hostname><SystemNetworkName>switch02</SystemNetworkName></hostname>
+    <boot-start-marker></boot-start-marker>
+    <boot-end-marker></boot-end-marker>
+    <system><mtu><routing><MTUSizeBytes>1500</MTUSizeBytes></routing></mtu></system>
+    <mls><qos/></mls>
+    <cts operation="delete" ><server><test><all><enable/></all></test></server></cts>
+    <X-Interface>cts server test all idle-time 0</X-Interface>
+    <X-Interface>cts server test all deadtime 0</X-Interface>
+    <spanning-tree><mode><pvst/></mode></spanning-tree>
+    <spanning-tree><extend><system-id/></extend></spanning-tree>
+    <vlan><internal><allocation><policy><ascending/></policy></allocation></internal></vlan>
+    <lldp><run/></lldp>
+    <interface><Param>GigabitEthernet0/1</Param>
+        <ConfigIf-Configuration>
+        </ConfigIf-Configuration>
+    </interface>
+    <interface><Param>GigabitEthernet0/2</Param>
+        <ConfigIf-Configuration>
+            <switchport><access><vlan><VLANIDVLANPortAccessMode>100</VLANIDVLANPortAccessMode></vlan></access></switchport>
+        </ConfigIf-Configuration>
+    </interface>
+    <interface><Param>GigabitEthernet0/3</Param>
+        <ConfigIf-Configuration>
+            <switchport><trunk><encapsulation><dot1q/></encapsulation></trunk></switchport>
+            <switchport><trunk><allowed><vlan><VLANIDsAllowedVLANsPortTrunkingMode>200,201</VLANIDsAllowedVLANsPortTrunkingMode></vlan></allowed></trunk></switchport>
+            <switchport><mode><trunk/></mode></switchport>
+        </ConfigIf-Configuration>
+    </interface>
+    <interface><Param>GigabitEthernet0/4</Param>
+        <ConfigIf-Configuration>
+            <srr-queue><bandwidth><limit><EnterBandwidthLimitInterfaceAsPercentage>75</EnterBandwidthLimitInterfaceAsPercentage></limit></bandwidth></srr-queue>
+        </ConfigIf-Configuration>
+    </interface>
+    <interface><Param>GigabitEthernet0/5</Param>
+        <ConfigIf-Configuration>
+            <switchport><trunk><encapsulation><dot1q/></encapsulation></trunk></switchport>
+            <switchport><trunk><allowed><vlan><VLANIDsAllowedVLANsPortTrunkingMode>300-302</VLANIDsAllowedVLANsPortTrunkingMode></vlan></allowed></trunk></switchport>
+            <switchport><mode><trunk/></mode></switchport>
+            <srr-queue><bandwidth><limit><EnterBandwidthLimitInterfaceAsPercentage>50</EnterBandwidthLimitInterfaceAsPercentage></limit></bandwidth></srr-queue>
+        </ConfigIf-Configuration>
+    </interface>
+    <ip><http><server/></http></ip>
+    <ip><http><secure-server/></http></ip>
+    <netconf><max-sessions><MaxNETCONFSessions>5</MaxNETCONFSessions></max-sessions></netconf>
+    <netconf><lock-time><MaxNETCONFConfigLockTimeSeconds>120</MaxNETCONFConfigLockTimeSeconds></lock-time></netconf>
+    <netconf><ssh/></netconf>
+    <end></end>
+</Device-Configuration></xml-config-data></data></rpc-reply>