[ODTN] Netconf inject capabilities and Nokia openconfig device discovery

Author:    Quan PHAM VAN <quan.pham_van@nokia.com>

Change-Id: I6bb639f0af3d1083922c4e631b8958a94d822886
diff --git a/drivers/odtn-driver/BUCK b/drivers/odtn-driver/BUCK
index 77736e0..86d34bd 100644
--- a/drivers/odtn-driver/BUCK
+++ b/drivers/odtn-driver/BUCK
@@ -14,6 +14,7 @@
 
 BUNDLES = [
     ':onos-drivers-odtn-driver',
+    '//drivers/utilities:onos-drivers-utilities',
 #     '//lib:commons-jxpath',
 #     '//lib:commons-beanutils', # jxpath dependency
 #     '//lib:jdom',  # jxpath dependency
@@ -35,6 +36,7 @@
     included_bundles = BUNDLES,
     required_apps = [
         'org.onosproject.netconf',
+        'org.onosproject.config',
         'org.onosproject.odtn-api',
     ],
 )
diff --git a/drivers/odtn-driver/BUILD b/drivers/odtn-driver/BUILD
index 1c8aa8c..28b5474 100644
--- a/drivers/odtn-driver/BUILD
+++ b/drivers/odtn-driver/BUILD
@@ -12,6 +12,7 @@
 
 BUNDLES = [
     ":onos-drivers-odtn-driver",
+    "//drivers/utilities:onos-drivers-utilities",
     #     "//lib:commons-jxpath",
     #     "//lib:commons-beanutils", # jxpath dependency
     #     "//lib:jdom",  # jxpath dependency
@@ -31,6 +32,7 @@
     included_bundles = BUNDLES,
     required_apps = [
         "org.onosproject.netconf",
+        "org.onosproject.config",
         "org.onosproject.odtn-api",
     ],
     title = "ODTN Driver",
diff --git a/drivers/odtn-driver/src/main/java/org/onosproject/drivers/odtn/NokiaOpenConfigDeviceDiscovery.java b/drivers/odtn-driver/src/main/java/org/onosproject/drivers/odtn/NokiaOpenConfigDeviceDiscovery.java
new file mode 100644
index 0000000..2324614
--- /dev/null
+++ b/drivers/odtn-driver/src/main/java/org/onosproject/drivers/odtn/NokiaOpenConfigDeviceDiscovery.java
@@ -0,0 +1,290 @@
+/*
+ * Copyright 2018-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 org.onosproject.drivers.odtn;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableList;
+import com.google.common.io.CharSource;
+import org.apache.commons.configuration.HierarchicalConfiguration;
+import org.apache.commons.configuration.XMLConfiguration;
+import org.apache.commons.configuration.tree.xpath.XPathExpressionEngine;
+import org.onlab.packet.ChassisId;
+import org.onosproject.drivers.utilities.XmlConfigParser;
+import org.onosproject.net.DefaultAnnotations;
+import org.onosproject.net.Device;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.Port.Type;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.device.DeviceDescription;
+import org.onosproject.net.device.DeviceDescriptionDiscovery;
+import org.onosproject.net.device.DefaultPortDescription.Builder;
+import org.onosproject.net.device.DefaultDeviceDescription;
+import org.onosproject.net.device.PortDescription;
+import org.onosproject.net.device.DefaultPortDescription;
+import org.onosproject.net.driver.AbstractHandlerBehaviour;
+import org.onosproject.netconf.NetconfController;
+import org.onosproject.netconf.NetconfDevice;
+import org.onosproject.netconf.NetconfException;
+import org.onosproject.netconf.NetconfSession;
+import org.onosproject.odtn.behaviour.OdtnDeviceDescriptionDiscovery;
+import org.slf4j.Logger;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.stream.Collectors;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Nokia OpenConfig based device and port discovery.
+ */
+public class NokiaOpenConfigDeviceDiscovery
+        extends AbstractHandlerBehaviour
+        implements OdtnDeviceDescriptionDiscovery, DeviceDescriptionDiscovery {
+
+    private static final Logger log = getLogger(NokiaOpenConfigDeviceDiscovery.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 OPTICAL_CHANNEL = "OCH";
+    private static final String TRANSCEIVER = "TRANSCEIVER";
+
+    //TODO should be loaded from a file config or something else
+    //The user and password are different from the user and password in the netconf-cfg file
+    private static final String USER_NAME = "admin";
+    private static final String PASSWORD = "admin";
+
+    @Override
+    public DeviceDescription discoverDeviceDetails() {
+        DeviceId did = data().deviceId();
+        NetconfSession ns = getNetconfSessionAndLogin(did, USER_NAME, PASSWORD);
+        if (ns == null) {
+            log.error("DiscoverDeviceDetails called with null session for {}", did);
+            return null;
+        }
+        log.info("Discovering device details {}", handler().data().deviceId());
+        String hwVersion = "1830", swVersion = "OpenAgent";
+        try {
+            String reply = ns.requestSync(buildGetSystemSoftwareRpc());
+            XMLConfiguration cfg = (XMLConfiguration) XmlConfigParser.loadXmlString(getDataOfRpcReply(reply));
+            hwVersion = cfg.getString("components.component.state.description");
+            swVersion = cfg.getString("components.component.state.version");
+        } catch (NetconfException e) {
+            log.error("Error discovering device details on {}", data().deviceId(), e);
+        }
+        return new DefaultDeviceDescription(handler().data().deviceId().uri(),
+                Device.Type.ROADM_OTN,
+                "NOKIA",
+                hwVersion,
+                swVersion,
+                "",
+                new ChassisId("1"));
+    }
+
+    @Override
+    public List<PortDescription> discoverPortDetails() {
+        DeviceId did = data().deviceId();
+        XMLConfiguration cfg = new XMLConfiguration();
+        NetconfSession ns = getNetconfSessionAndLogin(did, USER_NAME, PASSWORD);
+        if (ns == null) {
+            log.error("discoverPorts called with null session for {}", did);
+            return ImmutableList.of();
+        }
+        log.info("Discovering ports details {}", handler().data().deviceId());
+        try {
+            String reply = ns.requestSync(buildGetPlatformComponentsRpc());
+            String data = getDataOfRpcReply(reply);
+            if (data == null) {
+                log.error("No valid response found from {}:\n{}", did, reply);
+                return ImmutableList.of();
+            }
+            cfg.load(CharSource.wrap(data).openStream());
+            return discoverPorts(cfg);
+        } catch (Exception e) {
+            log.error("Error discovering port details on {}", data().deviceId(), e);
+            return ImmutableList.of();
+        }
+    }
+
+    /**
+     * Parses port information from OpenConfig XML configuration.
+     *
+     * @param cfg tree where the root node is {@literal <data>}
+     * @return List of ports
+     */
+    @VisibleForTesting
+    private List<PortDescription> discoverPorts(XMLConfiguration cfg) {
+        // If we want to use XPath
+        cfg.setExpressionEngine(new XPathExpressionEngine());
+        // converting components into PortDescription.
+        List<HierarchicalConfiguration> components = cfg.configurationsAt("components/component");
+        return components.stream()
+                .map(this::toPortDescriptionInternal)
+                .filter(Objects::nonNull)
+                .collect(Collectors.toList());
+    }
+
+    /**
+     * Converts Component subtree to PortDescription.
+     *
+     * @param component subtree to parse
+     * @return PortDescription or null if component is not an ONOS Port
+     */
+    private PortDescription toPortDescriptionInternal(HierarchicalConfiguration component) {
+        Map<String, String> props = new HashMap<>();
+        String name = component.getString("name");
+        String type = component.getString("state/type");
+        checkNotNull(name, "name not found");
+        checkNotNull(type, "state/type not found");
+        props.put(OdtnDeviceDescriptionDiscovery.OC_NAME, name);
+        props.put(OdtnDeviceDescriptionDiscovery.OC_TYPE, type);
+        Builder builder = DefaultPortDescription.builder();
+        if (type.equals("oc-platform-types:PORT")) {
+            String subComponentName = component.getString("subcomponents/subcomponent/name");
+            String[] textStr = subComponentName.split("-");
+            String portComponentType = textStr[0];
+            String portComponentIndex = textStr[textStr.length - 1];
+            builder.withPortNumber(PortNumber.portNumber(Long.parseLong(portComponentIndex), subComponentName));
+            if (portComponentType.equals(OPTICAL_CHANNEL)) {
+                builder.type(Type.OCH);
+                props.putIfAbsent(PORT_TYPE, OdtnPortType.LINE.value());
+                props.putIfAbsent(CONNECTION_ID, portComponentIndex);
+            } else if (portComponentType.equals(TRANSCEIVER)) {
+                builder.type(Type.PACKET);
+                props.putIfAbsent(PORT_TYPE, OdtnPortType.CLIENT.value());
+                props.putIfAbsent(CONNECTION_ID, portComponentIndex);
+            } else {
+                log.debug("Unknown port component type {}", type);
+                return null;
+            }
+        } else {
+            log.debug("Another component type {}", type);
+            return null;
+        }
+
+        builder.annotations(DefaultAnnotations.builder().putAll(props).build());
+        return builder.build();
+    }
+
+    /**
+     * Login to the device by providing the correct user and password in order to configure the device
+     * Returns the NetconfSession with the device for which the method was called.
+     *
+     * @param deviceId device indetifier
+     * @param userName
+     * @param passwd
+     * @return The netconf session or null
+     */
+    private NetconfSession getNetconfSessionAndLogin(DeviceId deviceId, String userName, String passwd) {
+        NetconfController nc = handler().get(NetconfController.class);
+        NetconfDevice ndev = nc.getDevicesMap().get(deviceId);
+        if (ndev == null) {
+            log.debug("netconf device " + deviceId + " is not found, returning null session");
+            return null;
+        }
+        NetconfSession ns = ndev.getSession();
+        if (ns == null) {
+            log.error("discoverPorts called with null session for {}", deviceId);
+            return null;
+        }
+        try {
+            String reply = ns.requestSync(buildLoginRpc(userName, passwd));
+            if (reply.contains("<ok/>")) {
+                return ns;
+            } else {
+                log.debug(reply);
+                return null;
+            }
+        } catch (NetconfException e) {
+            log.error("can not login to device", e);
+        }
+        return null;
+    }
+
+    //crude way of removing rpc-reply envelope (copy from netconf session)
+    private String getDataOfRpcReply(String rpcReply) {
+        String data = null;
+        int begin = rpcReply.indexOf("<data>");
+        int end = rpcReply.lastIndexOf("</data>");
+        if (begin != -1 && end != -1) {
+            data = (String) rpcReply.subSequence(begin, end + "</data>".length());
+        } else {
+            data = rpcReply;
+        }
+        return data;
+    }
+
+    /**
+     * Construct a rpc request message to get system software component.
+     *
+     * @return RPC message
+     */
+    private String buildGetSystemSoftwareRpc() {
+
+        StringBuilder rpc = new StringBuilder(RPC_TAG_NETCONF_BASE);
+        rpc.append("<get>");
+        rpc.append("<filter type='subtree'>");
+        rpc.append("<components xmlns=\"http://openconfig.net/yang/platform\">");
+        rpc.append("<component>");
+        rpc.append("<name>SYSTEM-SOFTWARE</name>");
+        rpc.append("</component>");
+        rpc.append("</components>");
+        rpc.append("</filter>");
+        rpc.append("</get>");
+        rpc.append(RPC_CLOSE_TAG);
+        return rpc.toString();
+    }
+
+    /**
+     * Construct a rpc request message to get openconfig platform components.
+     *
+     * @return RPC message
+     */
+    private String buildGetPlatformComponentsRpc() {
+        StringBuilder rpc = new StringBuilder(RPC_TAG_NETCONF_BASE);
+        rpc.append("<get>");
+        rpc.append("<filter type='subtree'>");
+        rpc.append("<components xmlns=\"http://openconfig.net/yang/platform\"></components>");
+        rpc.append("</filter>");
+        rpc.append("</get>");
+        rpc.append(RPC_CLOSE_TAG);
+        return rpc.toString();
+    }
+
+    /**
+     * Construct a rpc login message.
+     *
+     * @param userName
+     * @param passwd
+     * @return RPC message
+     */
+    private String buildLoginRpc(String userName, String passwd) {
+        StringBuilder rpc = new StringBuilder(RPC_TAG_NETCONF_BASE);
+        rpc.append("<login xmlns=\"http://nokia.com/yang/nokia-security\">");
+        rpc.append("<username>");
+        rpc.append(userName);
+        rpc.append("</username>");
+        rpc.append("<password>");
+        rpc.append(passwd);
+        rpc.append("</password>");
+        rpc.append("</login>");
+        rpc.append(RPC_CLOSE_TAG);
+        return rpc.toString();
+    }
+
+}
diff --git a/drivers/odtn-driver/src/main/resources/odtn-drivers.xml b/drivers/odtn-driver/src/main/resources/odtn-drivers.xml
index 4c44783..bb59920 100644
--- a/drivers/odtn-driver/src/main/resources/odtn-drivers.xml
+++ b/drivers/odtn-driver/src/main/resources/odtn-drivers.xml
@@ -35,5 +35,41 @@
         <behaviour api="org.onosproject.odtn.behaviour.ConfigurableTransceiver"
                    impl="org.onosproject.odtn.behaviour.PlainTransceiver"/>
     </driver>
+    <driver name="nokia-1830" manufacturer="nokia" hwVersion="1830" swVersion="R10.1.1">
+        <behaviour api="org.onosproject.net.device.DeviceDescriptionDiscovery"
+                   impl="org.onosproject.drivers.odtn.NokiaOpenConfigDeviceDiscovery"/>
+        <behaviour api="org.onosproject.odtn.behaviour.OdtnDeviceDescriptionDiscovery"
+                   impl="org.onosproject.drivers.odtn.NokiaOpenConfigDeviceDiscovery"/>
+        <behaviour api="org.onosproject.odtn.behaviour.ConfigurableTransceiver"
+                   impl="org.onosproject.odtn.behaviour.PlainTransceiver"/>
+        <property name="netconfClientCapability">urn:ietf:params:netconf:base:1.0|
+            urn:ietf:params:netconf:capability:writable-running:1.0|
+            urn:ietf:params:netconf:capability:notification:1.0|
+            urn:ietf:params:netconf:capability:interleave:1.0|
+            urn:ietf:params:netconf:capability:rollback-on-error:1.0|
+            http://nokia.com/yang/nokia-security?module=nokia-security&amp;revision=2017-05-10|
+            http://openconfig.net/yang/terminal-device?module=openconfig-terminal-device&amp;revision=2017-07-08|
+            http://openconfig.net/yang/platform?module=openconfig-platform&amp;revision=2016-12-22|
+            http://openconfig.net/yang/telemetry?module=openconfig-telemetry&amp;revision=2017-08-24|
+            http://openconfig.net/yang/rpc-api?module=openconfig-rpc&amp;revision=2016-04-05|
+            http://openconfig.net/yang/alarms?module=openconfig-alarms&amp;revision=2018-01-16|
+            http://openconfig.net/yang/system?module=openconfig-system&amp;revision=2018-01-21|
+            http://openconfig.net/yang/rpc-types?module=openconfig-rpc-types&amp;revision=2016-04-05|
+            http://openconfig.net/yang/transport-types?module=openconfig-transport-types&amp;revision=2017-08-16|
+            http://openconfig.net/yang/platform-types?module=openconfig-platform-types&amp;revision=2017-08-16|
+            http://openconfig.net/yang/platform/linecard?module=openconfig-platform-linecard&amp;revision=2017-08-03|
+            http://openconfig.net/yang/platform/transceiver?module=openconfig-platform-transceiver&amp;revision=2017-07-08|
+            http://openconfig.net/yang/transport-line-common?module=openconfig-transport-line-common&amp;revision=2017-07-08|
+            http://openconfig.net/yang/telemetry-types?module=openconfig-telemetry-types&amp;revision=2017-08-24|
+            http://openconfig.net/yang/openconfig-ext?module=openconfig-extensions&amp;revision=2017-04-11|
+            http://openconfig.net/yang/types/inet?module=openconfig-inet-types&amp;revision=2017-08-24|
+            http://openconfig.net/yang/alarms/types?module=openconfig-alarm-types&amp;revision=2018-01-16|
+            http://nokia.com/yang/nokia-openconfig-userlabel-ext?module=nokia-openconfig-userlabel-ext&amp;revision=2017-12-10|
+            http://nokia.com/yang/nokia-openconfig-exttypes?module=nokia-openconfig-exttypes&amp;revision=2017-10-26|
+            http://nokia.com/yang/nokia-openconfig-telemetry-ext?module=nokia-openconfig-telemetry-ext&amp;revision=2017-11-13|
+            http://openconfig.net/yang/openconfig-types?module=openconfig-types&amp;revision=2017-08-16|
+            http://openconfig.net/yang/types/yang?module=openconfig-yang-types&amp;revision=2017-07-30|
+            urn:ietf:params:xml:ns:yang:ietf-yang-types?module=ietf-yang-types&amp;revision=2013-07-15</property>
+    </driver>
 </drivers>
 
diff --git a/protocols/netconf/ctl/src/main/java/org/onosproject/netconf/ctl/impl/NetconfSessionMinaImpl.java b/protocols/netconf/ctl/src/main/java/org/onosproject/netconf/ctl/impl/NetconfSessionMinaImpl.java
index 2385f94..8a086b5 100644
--- a/protocols/netconf/ctl/src/main/java/org/onosproject/netconf/ctl/impl/NetconfSessionMinaImpl.java
+++ b/protocols/netconf/ctl/src/main/java/org/onosproject/netconf/ctl/impl/NetconfSessionMinaImpl.java
@@ -21,6 +21,7 @@
 import com.google.common.base.Objects;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Sets;
 import org.apache.sshd.client.SshClient;
 import org.apache.sshd.client.channel.ClientChannel;
 import org.apache.sshd.client.future.ConnectFuture;
@@ -29,10 +30,15 @@
 import org.apache.sshd.common.FactoryManager;
 import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider;
 import org.bouncycastle.jce.provider.BouncyCastleProvider;
-import org.bouncycastle.openssl.PEMParser;
 import org.bouncycastle.openssl.PEMKeyPair;
+import org.bouncycastle.openssl.PEMParser;
 import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
+import org.onlab.osgi.DefaultServiceDirectory;
+import org.onlab.osgi.ServiceDirectory;
 import org.onlab.util.SharedExecutors;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.driver.Driver;
+import org.onosproject.net.driver.DriverService;
 import org.onosproject.netconf.AbstractNetconfSession;
 import org.onosproject.netconf.NetconfDeviceInfo;
 import org.onosproject.netconf.NetconfDeviceOutputEvent;
@@ -43,8 +49,6 @@
 import org.onosproject.netconf.NetconfSessionFactory;
 import org.onosproject.netconf.NetconfTransportException;
 import org.slf4j.Logger;
-import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.slf4j.LoggerFactory.getLogger;
 
 import java.io.CharArrayReader;
 import java.io.IOException;
@@ -54,14 +58,15 @@
 import java.security.PublicKey;
 import java.security.spec.InvalidKeySpecException;
 import java.security.spec.X509EncodedKeySpec;
-import java.util.LinkedHashSet;
-import java.util.Map;
-import java.util.Set;
-import java.util.List;
+import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.Collection;
 import java.util.Collections;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
 import java.util.Optional;
-import java.util.ArrayList;
+import java.util.Set;
 import java.util.concurrent.CompletableFuture;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.CopyOnWriteArrayList;
@@ -72,6 +77,9 @@
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static org.slf4j.LoggerFactory.getLogger;
+
 /**
  * Implementation of a NETCONF session to talk to a device.
  */
@@ -110,6 +118,9 @@
     private static final String MSGLEN_REGEX_PATTERN = "\n#\\d+\n";
     private static final String NETCONF_10_CAPABILITY = "urn:ietf:params:netconf:base:1.0";
     private static final String NETCONF_11_CAPABILITY = "urn:ietf:params:netconf:base:1.1";
+    private static final String NETCONF_CLIENT_CAPABILITY = "netconfClientCapability";
+
+    private static ServiceDirectory directory = new DefaultServiceDirectory();
 
     private String sessionID;
     private final AtomicInteger messageIdInteger = new AtomicInteger(1);
@@ -137,17 +148,19 @@
     private int replyTimeout;
     private int idleTimeout;
 
-
     private ClientChannel channel = null;
     private ClientSession session = null;
     private SshClient client = null;
 
-
     public NetconfSessionMinaImpl(NetconfDeviceInfo deviceInfo) throws NetconfException {
         this.deviceInfo = deviceInfo;
         replies = new ConcurrentHashMap<>();
         errorReplies = new ArrayList<>();
-
+        Set<String> capabilities = getClientCapabilites(deviceInfo.getDeviceId());
+        if (!capabilities.isEmpty()) {
+            capabilities.addAll(Sets.newHashSet(onosCapabilities));
+            setOnosCapabilities(capabilities);
+        }
         // FIXME should not immediately start session on construction
         // setOnosCapabilities() is useless due to this behavior
         startConnection();
@@ -163,6 +176,28 @@
         startConnection();
     }
 
+    /**
+     * Get the list of the netconf client capabilities from device driver property.
+     *
+     * @param deviceId the deviceID for which to recover the capabilities from the driver.
+     * @return the String list of clientCapability property, or null if it is not configured
+     */
+    public Set<String> getClientCapabilites(DeviceId deviceId) {
+        Set<String> capabilities = new LinkedHashSet<>();
+        DriverService driverService = directory.get(DriverService.class);
+        Driver driver = driverService.getDriver(deviceId);
+        if (driver == null) {
+            return capabilities;
+        }
+        String clientCapabilities = driver.getProperty(NETCONF_CLIENT_CAPABILITY);
+        if (clientCapabilities == null) {
+            return capabilities;
+        }
+        String[] textStr = clientCapabilities.split("\\|");
+        capabilities.addAll(Arrays.asList(textStr));
+        return capabilities;
+    }
+
     private void startConnection() throws NetconfException {
         connectTimeout = deviceInfo.getConnectTimeoutSec().orElse(
                                 NetconfControllerImpl.netconfConnectTimeout);
diff --git a/protocols/netconf/ctl/src/test/java/org/onosproject/netconf/ctl/impl/NetconfSessionMinaImplTest.java b/protocols/netconf/ctl/src/test/java/org/onosproject/netconf/ctl/impl/NetconfSessionMinaImplTest.java
index 02c4214..d6cf94b 100644
--- a/protocols/netconf/ctl/src/test/java/org/onosproject/netconf/ctl/impl/NetconfSessionMinaImplTest.java
+++ b/protocols/netconf/ctl/src/test/java/org/onosproject/netconf/ctl/impl/NetconfSessionMinaImplTest.java
@@ -27,11 +27,16 @@
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.onlab.junit.TestTools;
+import org.onlab.junit.TestUtils;
+import org.onlab.osgi.ServiceDirectory;
+import org.onlab.osgi.TestServiceDirectory;
+import org.onlab.packet.Ip4Address;
+import org.onosproject.net.driver.DriverService;
+import org.onosproject.net.driver.DriverServiceAdapter;
+import org.onosproject.netconf.DatastoreId;
 import org.onosproject.netconf.NetconfDeviceInfo;
 import org.onosproject.netconf.NetconfException;
 import org.onosproject.netconf.NetconfSession;
-import org.onosproject.netconf.DatastoreId;
-import org.onlab.packet.Ip4Address;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -49,11 +54,11 @@
 import java.util.regex.Pattern;
 
 import static org.hamcrest.Matchers.containsInAnyOrder;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.fail;
 import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
 import static org.onosproject.netconf.DatastoreId.CANDIDATE;
 import static org.onosproject.netconf.DatastoreId.RUNNING;
 import static org.onosproject.netconf.DatastoreId.STARTUP;
@@ -116,6 +121,9 @@
             .add("urn:ietf:params:netconf:capability:validate:1.1")
             .build();
 
+    private static final ServiceDirectory TEST_DIRECTORY =
+            new TestServiceDirectory()
+                    .add(DriverService.class, new DriverServiceAdapter());
 
     private static NetconfSession session1;
     private static NetconfSession session2;
@@ -138,6 +146,9 @@
                         return TEST_USERNAME.equals(username) && TEST_PASSWORD.equals(password);
                     }
                 });
+
+        TestUtils.setField(NetconfSessionMinaImpl.class, "directory", TEST_DIRECTORY);
+
         sshServerNetconf.setPort(portNumber);
         SimpleGeneratorHostKeyProvider provider = new SimpleGeneratorHostKeyProvider();
         provider.setFile(new File(TEST_SERFILE));
@@ -192,6 +203,7 @@
             session4.close();
         }
 
+        TestUtils.setField(NetconfSessionMinaImpl.class, "directory", null);
         sshServerNetconf.stop();
     }