[ONOS-4654] NETCONF function for FUJITSU OLT #1

Change-Id: I3565d127252de732d249ed5dd919874d6438c2fa
diff --git a/drivers/fujitsu/src/main/java/org/onosproject/drivers/fujitsu/FujitsuVoltControllerConfig.java b/drivers/fujitsu/src/main/java/org/onosproject/drivers/fujitsu/FujitsuVoltControllerConfig.java
new file mode 100644
index 0000000..b61916e
--- /dev/null
+++ b/drivers/fujitsu/src/main/java/org/onosproject/drivers/fujitsu/FujitsuVoltControllerConfig.java
@@ -0,0 +1,139 @@
+/*
+ * 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.fujitsu;
+
+import com.google.common.collect.ImmutableList;
+import org.apache.commons.configuration.HierarchicalConfiguration;
+import org.onosproject.drivers.utilities.XmlConfigParser;
+import org.onlab.packet.IpAddress;
+import org.onosproject.mastership.MastershipService;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.behaviour.ControllerConfig;
+import org.onosproject.net.behaviour.ControllerInfo;
+import org.onosproject.net.driver.AbstractHandlerBehaviour;
+import org.onosproject.net.driver.DriverHandler;
+import org.onosproject.netconf.NetconfController;
+import org.slf4j.Logger;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Implementation to get and set parameters available in VOLT NE
+ * through the Netconf protocol.
+ */
+public class FujitsuVoltControllerConfig extends AbstractHandlerBehaviour
+        implements ControllerConfig {
+
+    private final Logger log = getLogger(FujitsuVoltControllerConfig.class);
+
+    private static final String DOT = ".";
+    private static final String VOLT_NE_NAMESPACE =
+            "xmlns=\"http://fujitsu.com/ns/volt/1.1\"";
+    private static final String DATA = "data";
+    private static final String VOLT_NE = "volt-ne";
+    private static final String VOLT_OFCONFIG = "volt-ofconfig";
+    private static final String OF_CONTROLLERS = "of-controllers";
+    private static final String OF_CONTROLLER = "of-controller";
+    private static final String CONTROLLER_INFO = "controller-info";
+    private static final String REPORT_ALL = "report-all";
+    private static final String IP_ADDRESS = "ip-address";
+    private static final String PORT = "port";
+    private static final String PROTOCOL = "protocol";
+
+    private static final String VOLT_NE_OPEN = "<" + VOLT_NE + " ";
+    private static final String VOLT_NE_CLOSE = "</" + VOLT_NE + ">";
+    private static final String VOLT_OFCONFIG_EL = "<" + VOLT_OFCONFIG + "/>\n";
+
+    private static final String VOLT_DATACONFIG = DATA + DOT + VOLT_NE + DOT +
+            VOLT_OFCONFIG + DOT + OF_CONTROLLERS + DOT + OF_CONTROLLER;
+
+    @Override
+    public List<ControllerInfo> getControllers() {
+        DriverHandler handler = handler();
+        NetconfController controller = handler.get(NetconfController.class);
+        MastershipService mastershipService = handler.get(MastershipService.class);
+        DeviceId ncDeviceId = handler.data().deviceId();
+        checkNotNull(controller, "Netconf controller is null");
+        List<ControllerInfo> controllers = new ArrayList<>();
+        if (mastershipService.isLocalMaster(ncDeviceId)) {
+            try {
+                StringBuilder request = new StringBuilder();
+                request.append(VOLT_NE_OPEN).append(VOLT_NE_NAMESPACE).append(">\n");
+                request.append(VOLT_OFCONFIG_EL);
+                request.append(VOLT_NE_CLOSE);
+
+                String reply;
+                reply = controller.
+                    getDevicesMap().get(ncDeviceId).getSession().
+                    get(request.toString(), REPORT_ALL);
+                log.debug("Reply XML {}", reply);
+                controllers.addAll(parseStreamVoltControllers(XmlConfigParser.
+                    loadXml(new ByteArrayInputStream(reply.getBytes(StandardCharsets.UTF_8)))));
+            } catch (IOException e) {
+                log.error("Cannot communicate to device {} ", ncDeviceId);
+            }
+        } else {
+            log.warn("I'm not master for {} please use master, {} to execute command",
+                     ncDeviceId,
+                     mastershipService.getMasterFor(ncDeviceId));
+        }
+        return ImmutableList.copyOf(controllers);
+    }
+
+    @Override
+    public void setControllers(List<ControllerInfo> controllers) {
+        // TODO update later
+        log.warn("Operation not supported");
+    }
+
+    /**
+     * Parses XML string to get controller information.
+     *
+     * @param cfg a hierarchical configuration
+     * @return a list of controllers
+     */
+    private List<ControllerInfo> parseStreamVoltControllers(HierarchicalConfiguration cfg) {
+        List<ControllerInfo> controllers = new ArrayList<>();
+        List<HierarchicalConfiguration> fields =
+                cfg.configurationsAt(VOLT_DATACONFIG);
+
+        for (HierarchicalConfiguration sub : fields) {
+            List<HierarchicalConfiguration> childFields =
+                    sub.configurationsAt(CONTROLLER_INFO);
+
+            for (HierarchicalConfiguration child : childFields) {
+                ControllerInfo controller = new ControllerInfo(
+                        IpAddress.valueOf(child.getString(IP_ADDRESS)),
+                        Integer.parseInt(child.getString(PORT)),
+                        child.getString(PROTOCOL));
+
+                log.debug("VOLT: OFCONTROLLER:  PROTOCOL={}, IP={}, PORT={} ",
+                          controller.type(), controller.ip(), controller.port());
+                controllers.add(controller);
+            }
+        }
+        return controllers;
+    }
+
+}
diff --git a/drivers/fujitsu/src/main/resources/fujitsu-drivers.xml b/drivers/fujitsu/src/main/resources/fujitsu-drivers.xml
index d645440..1bdaf6b 100644
--- a/drivers/fujitsu/src/main/resources/fujitsu-drivers.xml
+++ b/drivers/fujitsu/src/main/resources/fujitsu-drivers.xml
@@ -21,5 +21,8 @@
         <behaviour api="org.onosproject.net.device.DeviceDescriptionDiscovery"
                    impl="org.onosproject.drivers.fujitsu.FujitsuT100DeviceDescription"/>
     </driver>
-</drivers>
-
+    <driver name="fujitsu-volt-netconf" manufacturer="Fujitsu" hwVersion="svkOLT" swVersion="v1.0">
+        <behaviour api="org.onosproject.net.behaviour.ControllerConfig"
+                   impl="org.onosproject.drivers.fujitsu.FujitsuVoltControllerConfig"/>
+    </driver>
+</drivers>
\ No newline at end of file
diff --git a/protocols/netconf/api/src/main/java/org/onosproject/netconf/NetconfSession.java b/protocols/netconf/api/src/main/java/org/onosproject/netconf/NetconfSession.java
index e5668ed..0668422 100644
--- a/protocols/netconf/api/src/main/java/org/onosproject/netconf/NetconfSession.java
+++ b/protocols/netconf/api/src/main/java/org/onosproject/netconf/NetconfSession.java
@@ -48,6 +48,18 @@
     String get(String request) throws NetconfException;
 
     /**
+     * Retrives the requested data.
+     *
+     * @param filterSchema XML subtrees to include in the reply
+     * @param withDefaultsMode with-defaults mode
+     * @return Server response
+     * @throws NetconfException when there is a problem in the communication process on
+     * the underlying connection
+     */
+    String get(String filterSchema, String withDefaultsMode)
+            throws NetconfException;
+
+    /**
      * Executes an synchronous RPC to the server.
      *
      * @param request the XML containing the RPC for the server.
diff --git a/protocols/netconf/ctl/src/main/java/org/onosproject/netconf/ctl/NetconfSessionImpl.java b/protocols/netconf/ctl/src/main/java/org/onosproject/netconf/ctl/NetconfSessionImpl.java
index 17f6187..487f4cc 100644
--- a/protocols/netconf/ctl/src/main/java/org/onosproject/netconf/ctl/NetconfSessionImpl.java
+++ b/protocols/netconf/ctl/src/main/java/org/onosproject/netconf/ctl/NetconfSessionImpl.java
@@ -58,8 +58,20 @@
     private static final String END_OF_RPC_OPEN_TAG = "\">";
     private static final String EQUAL = "=";
     private static final String NUMBER_BETWEEN_QUOTES_MATCHER = "\"+([0-9]+)+\"";
+    private static final String RPC_OPEN = "<rpc ";
+    private static final String RPC_CLOSE = "</rpc>";
+    private static final String GET_OPEN = "<get>";
+    private static final String GET_CLOSE = "</get>";
+    private static final String WITH_DEFAULT_OPEN = "<with-defaults ";
+    private static final String WITH_DEFAULT_CLOSE = "</with-defaults>";
+    private static final String FILTER_OPEN = "<filter type=\"subtree\">";
+    private static final String FILTER_CLOSE = "</filter>";
     private static final String XML_HEADER =
             "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
+    private static final String NETCONF_BASE_NAMESPACE =
+            "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"";
+    private static final String NETCONF_WITH_DEFAULTS_NAMESPACE =
+            "xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-with-defaults\"";
 
     private final AtomicInteger messageIdInteger = new AtomicInteger(0);
     private Connection netconfConnection;
@@ -76,13 +88,14 @@
 
     public NetconfSessionImpl(NetconfDeviceInfo deviceInfo) throws NetconfException {
         this.deviceInfo = deviceInfo;
+        this.netconfConnection = null;
+        this.sshSession = null;
         connectionActive = false;
         replies = new HashMap<>();
         errorReplies = new ArrayList<>();
         startConnection();
     }
 
-
     private void startConnection() throws NetconfException {
         if (!connectionActive) {
             netconfConnection = new Connection(deviceInfo.ip().toString(), deviceInfo.port());
@@ -105,7 +118,7 @@
                 }
             } catch (IOException e) {
                 log.error("Authentication connection to device {} failed: {} ",
-                                  deviceInfo.getDeviceId(), e.getMessage());
+                          deviceInfo.getDeviceId(), e.getMessage());
                 throw new NetconfException("Authentication connection to device " +
                                                    deviceInfo.getDeviceId() + " failed", e);
             }
@@ -233,6 +246,34 @@
     }
 
     @Override
+    public String get(String filterSchema, String withDefaultsMode) throws NetconfException {
+        StringBuilder rpc = new StringBuilder(XML_HEADER);
+        rpc.append(RPC_OPEN);
+        rpc.append(MESSAGE_ID_STRING);
+        rpc.append(EQUAL);
+        rpc.append("\"");
+        rpc.append(messageIdInteger.get());
+        rpc.append("\"  ");
+        rpc.append(NETCONF_BASE_NAMESPACE).append(">\n");
+        rpc.append(GET_OPEN).append(NEW_LINE);
+        if (filterSchema != null) {
+            rpc.append(FILTER_OPEN).append(NEW_LINE);
+            rpc.append(filterSchema).append(NEW_LINE);
+            rpc.append(FILTER_CLOSE).append(NEW_LINE);
+        }
+        if (withDefaultsMode != null) {
+            rpc.append(WITH_DEFAULT_OPEN).append(NETCONF_WITH_DEFAULTS_NAMESPACE).append(">");
+            rpc.append(withDefaultsMode).append(WITH_DEFAULT_CLOSE).append(NEW_LINE);
+        }
+        rpc.append(GET_CLOSE).append(NEW_LINE);
+        rpc.append(RPC_CLOSE).append(NEW_LINE);
+        rpc.append(ENDPATTERN);
+        String reply = sendRequest(rpc.toString());
+        checkReply(reply);
+        return reply;
+    }
+
+    @Override
     public String getConfig(String targetConfiguration) throws NetconfException {
         return getConfig(targetConfiguration, null);
     }