modification to use cluster version

Change-Id: Iaf169507577deba20d548348532a2e0b91a03249
refs: #3652
diff --git a/ndn/ndn_host.py b/ndn/ndn_host.py
index 70d2ffb..7c727ab 100644
--- a/ndn/ndn_host.py
+++ b/ndn/ndn_host.py
@@ -1,6 +1,6 @@
 # -*- Mode:python; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
 #
-# Copyright (C) 2015-2016, The University of Memphis,
+# Copyright (C) 2015-2017, The University of Memphis,
 #                          Arizona Board of Regents,
 #                          Regents of the University of California.
 #
@@ -24,9 +24,9 @@
 # This file incorporates work covered by the following copyright and
 # permission notice:
 #
-#   Mininet 2.2.1 License
+#   Mininet 2.3.0d1 License
 #
-#   Copyright (c) 2013-2015 Open Networking Laboratory
+#   Copyright (c) 2013-2016 Open Networking Laboratory
 #   Copyright (c) 2009-2012 Bob Lantz and The Board of Trustees of
 #   The Leland Stanford Junior University
 #
@@ -59,6 +59,8 @@
 #   without specific, written prior permission.
 
 from mininet.node import CPULimitedHost, Host, Node
+from mininet.examples.cluster import RemoteMixin
+
 from ndn.nfd import Nfd
 
 class NdnHostCommon():
@@ -150,3 +152,7 @@
         "Stop node."
         self.nfd.stop()
         Host.terminate(self)
+
+class RemoteNdnHost(RemoteMixin, NdnHost):
+    "A node on a remote server"
+    pass
diff --git a/ndn/nlsr.py b/ndn/nlsr.py
index 43176b4..3a4b522 100644
--- a/ndn/nlsr.py
+++ b/ndn/nlsr.py
@@ -1,6 +1,6 @@
 # -*- Mode:python; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
 #
-# Copyright (C) 2015-2016, The University of Memphis,
+# Copyright (C) 2015-2017, The University of Memphis,
 #                          Arizona Board of Regents,
 #                          Regents of the University of California.
 #
@@ -22,12 +22,15 @@
 # If not, see <http://www.gnu.org/licenses/>.
 
 from mininet.clean import sh
+from mininet.examples.cluster import RemoteMixin
 
 from ndn.ndn_application import NdnApplication
+from ndn.util import ssh, scp
 
-import os
 import shutil
+import os
 import textwrap
+from subprocess import call
 
 class Nlsr(NdnApplication):
     def __init__(self, node):
@@ -60,7 +63,7 @@
         securityDir = "{}/security".format(workDir)
 
         if not os.path.exists(securityDir):
-                os.mkdir(securityDir)
+            os.mkdir(securityDir)
 
         # Create root certificate
         rootName = "/ndn"
@@ -71,8 +74,12 @@
         for host in net.hosts:
             nodeSecurityFolder = "{}/security".format(host.homeFolder)
 
-            if not os.path.exists(nodeSecurityFolder):
-                os.mkdir(nodeSecurityFolder)
+            host.cmd("mkdir -p %s" % nodeSecurityFolder)
+
+            # Create temp folders for remote nodes on this machine (localhost) to store site.key file
+            # from RemoteNodes
+            if not os.path.exists(nodeSecurityFolder) and isinstance(host, RemoteMixin) and host.isRemote:
+                os.makedirs(nodeSecurityFolder)
 
             shutil.copyfile("{}/root.cert".format(securityDir), "{}/root.cert".format(nodeSecurityFolder))
 
@@ -82,8 +89,25 @@
             siteCertFile = "{}/site.cert".format(nodeSecurityFolder)
             Nlsr.createKey(host, siteName, siteKeyFile)
 
+            # Copy siteKeyFile from remote for ndnsec-certgen
+            if isinstance(host, RemoteMixin) and host.isRemote:
+                login = "mininet@{}".format(host.server)
+                src = "{}:{}".format(login, siteKeyFile)
+                dst = siteKeyFile
+                scp(src, dst)
+
             # Root key is in root namespace, must sign site key and then install on host
             sh("ndnsec-certgen -N {} -s {} -p {} {} > {}".format(siteName, rootName, siteName, siteKeyFile, siteCertFile))
+
+            # Copy root.cert and site.cert from localhost to remote host
+            if isinstance(host, RemoteMixin) and host.isRemote:
+                login = "mininet@{}".format(host.server)
+                src = "{}/site.cert".format(nodeSecurityFolder)
+                src2 = "{}/root.cert".format(nodeSecurityFolder)
+                dst = "{}:/tmp/".format(login)
+                scp(src, src2, dst)
+                host.cmd("mv /tmp/*.cert {}".format(nodeSecurityFolder))
+
             host.cmd("ndnsec-cert-install -f {}".format(siteCertFile))
 
             # Create operator certificate
@@ -106,7 +130,6 @@
     ROUTING_HYPERBOLIC = "hr"
 
     def __init__(self, node, isSecurityEnabled):
-        node.cmd("sudo cp /usr/local/etc/mini-ndn/nlsr.conf nlsr.conf")
         self.node = node
         self.isSecurityEnabled = isSecurityEnabled
 
@@ -120,30 +143,29 @@
 
     def createConfigFile(self):
 
-        filePath = "%s/nlsr.conf" % self.node.homeFolder
+        tmp_conf = "/tmp/nlsr.conf"
 
-        configFile = open(filePath, 'r')
-        oldContent = configFile.read()
+        configFile = open(tmp_conf, 'w')
+        configFile.write(self.__getConfig())
         configFile.close()
 
-        newContent = oldContent.replace("$GENERAL_SECTION", self.__getGeneralSection())
-        newContent = newContent.replace("$NEIGHBORS_SECTION", self.__getNeighborsSection())
-        newContent = newContent.replace("$HYPERBOLIC_SECTION", self.__getHyperbolicSection())
-        newContent = newContent.replace("$FIB_SECTION", self.__getFibSection())
-        newContent = newContent.replace("$ADVERTISING_SECTION", self.__getAdvertisingSection())
-        newContent = newContent.replace("$SECURITY_SECTION", self.__getSecuritySection())
+        # If this node is a remote node scp the nlsr.conf file to its /tmp/nlsr.conf
+        if isinstance(self.node, RemoteMixin) and self.node.isRemote:
+            login = "mininet@%s" % self.node.server
+            src = tmp_conf
+            dst = "%s:%s" % (login, tmp_conf)
+            scp(src, dst)
 
-        configFile = open(filePath, 'w')
-        configFile.write(newContent)
-        configFile.close()
+        # Copy nlsr.conf to home folder
+        self.node.cmd("mv %s nlsr.conf" % tmp_conf)
 
     def __getConfig(self):
 
-        config =  self.__getGeneralSection()
-        config += self.__getNeighborsSection()
-        config += self.__getHyperbolicSection()
-        config += self.__getFibSection()
-        config += self.__getAdvertisingSection()
+        config  = self.__getGeneralSection() + "\n"
+        config += self.__getNeighborsSection() + "\n"
+        config += self.__getHyperbolicSection() + "\n"
+        config += self.__getFibSection() + "\n"
+        config += self.__getAdvertisingSection() + "\n"
         config += self.__getSecuritySection()
 
         return config
diff --git a/ndn/placer.py b/ndn/placer.py
new file mode 100644
index 0000000..ba521b8
--- /dev/null
+++ b/ndn/placer.py
@@ -0,0 +1,87 @@
+# -*- Mode:python; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
+#
+# Copyright (C) 2015-2017, The University of Memphis,
+#                          Arizona Board of Regents,
+#                          Regents of the University of California.
+#
+# This file is part of Mini-NDN.
+# See AUTHORS.md for a complete list of Mini-NDN authors and contributors.
+#
+# Mini-NDN is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# Mini-NDN is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with Mini-NDN, e.g., in COPYING.md file.
+# If not, see <http://www.gnu.org/licenses/>.
+#
+# This file incorporates work covered by the following copyright and
+# permission notice:
+#
+#   Mininet 2.3.0d1 License
+#
+#   Copyright (c) 2013-2016 Open Networking Laboratory
+#   Copyright (c) 2009-2012 Bob Lantz and The Board of Trustees of
+#   The Leland Stanford Junior University
+#
+#   Original authors: Bob Lantz and Brandon Heller
+#
+#   We are making Mininet available for public use and benefit with the
+#   expectation that others will use, modify and enhance the Software and
+#   contribute those enhancements back to the community. However, since we
+#   would like to make the Software available for broadest use, with as few
+#   restrictions as possible permission is hereby granted, free of charge, to
+#   any person obtaining a copy of this Software to deal in the Software
+#   under the copyrights without restriction, including without limitation
+#   the rights to use, copy, modify, merge, publish, distribute, sublicense,
+#   and/or sell copies of the Software, and to permit persons to whom the
+#   Software is furnished to do so, subject to the following conditions:
+#
+#   The above copyright notice and this permission notice shall be included
+#   in all copies or substantial portions of the Software.
+#
+#   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+#   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+#   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+#   IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+#   CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+#   TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+#   SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#
+#   The name and trademarks of copyright holder(s) may NOT be used in
+#   advertising or publicity pertaining to the Software or any derivatives
+#   without specific, written prior permission.
+
+from mininet.examples.cluster import Placer
+
+nodePlace = []
+
+class PopulatePlacement():
+    def __init__( self, placeList ):
+        global nodePlace
+        nodePlace = placeList
+
+class GuidedPlacer( Placer ):
+    "Guided placement"
+    def __init__( self, *args, **kwargs ):
+        Placer.__init__( self, *args, **kwargs )
+        self.count = 0
+
+    def place( self, nodename ):
+        assert nodename  #please pylint
+        while(True):
+            global nodePlace
+            if nodePlace[self.count] != 0:
+                nodePlace[self.count] -= 1
+                # args[self.count] is not zero, hence return the server at that position
+                # so that if args[0] is 7 and servers[0] is Europa then place 7 nodes on Europa
+                return self.servers[self.count]
+            else:
+                # while makes sure we go back to the if after this
+                self.count += 1
diff --git a/ndn/remote_ndn_link.py b/ndn/remote_ndn_link.py
new file mode 100644
index 0000000..6dd64f3
--- /dev/null
+++ b/ndn/remote_ndn_link.py
@@ -0,0 +1,90 @@
+# -*- Mode:python; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
+#
+# Copyright (C) 2015-2017, The University of Memphis,
+#                          Arizona Board of Regents,
+#                          Regents of the University of California.
+#
+# This file is part of Mini-NDN.
+# See AUTHORS.md for a complete list of Mini-NDN authors and contributors.
+#
+# Mini-NDN is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# Mini-NDN is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with Mini-NDN, e.g., in COPYING.md file.
+# If not, see <http://www.gnu.org/licenses/>.
+#
+# This file incorporates work covered by the following copyright and
+# permission notice:
+#
+#   Mininet 2.3.0d1 License
+#
+#   Copyright (c) 2013-2016 Open Networking Laboratory
+#   Copyright (c) 2009-2012 Bob Lantz and The Board of Trustees of
+#   The Leland Stanford Junior University
+#
+#   Original authors: Bob Lantz and Brandon Heller
+#
+#   We are making Mininet available for public use and benefit with the
+#   expectation that others will use, modify and enhance the Software and
+#   contribute those enhancements back to the community. However, since we
+#   would like to make the Software available for broadest use, with as few
+#   restrictions as possible permission is hereby granted, free of charge, to
+#   any person obtaining a copy of this Software to deal in the Software
+#   under the copyrights without restriction, including without limitation
+#   the rights to use, copy, modify, merge, publish, distribute, sublicense,
+#   and/or sell copies of the Software, and to permit persons to whom the
+#   Software is furnished to do so, subject to the following conditions:
+#
+#   The above copyright notice and this permission notice shall be included
+#   in all copies or substantial portions of the Software.
+#
+#   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+#   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+#   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+#   IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+#   CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+#   TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+#   SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+#
+#   The name and trademarks of copyright holder(s) may NOT be used in
+#   advertising or publicity pertaining to the Software or any derivatives
+#   without specific, written prior permission.
+
+from mininet.link import TCLink
+from mininet.examples.cluster import RemoteLink, RemoteGRELink
+
+class RemoteNdnLink( TCLink, RemoteLink ):
+    "A RemoteLink is a link between nodes which may be on different servers"
+
+    def __init__( self, node1, node2, **kwargs ):
+        """Initialize a RemoteLink
+           see Link() for parameters"""
+        # Create links on remote node
+        self.node1 = node1
+        self.node2 = node2
+        self.tunnel = None
+        kwargs.setdefault( 'params1', {} )
+        kwargs.setdefault( 'params2', {} )
+        self.cmd = None  # satisfy pylint
+        TCLink.__init__( self, node1, node2, **kwargs )
+
+class RemoteGRENdnLink( TCLink, RemoteGRELink ):
+    def __init__(self, node1, node2, **kwargs):
+        """Initialize a RemoteLink
+           see Link() for parameters"""
+        # Create links on remote node
+        self.node1 = node1
+        self.node2 = node2
+        self.tunnel = None
+        kwargs.setdefault( 'params1', {} )
+        kwargs.setdefault( 'params2', {} )
+        self.cmd = None  # satisfy pylint
+        TCLink.__init__( self, node1, node2, **kwargs )
diff --git a/ndn/util.py b/ndn/util.py
new file mode 100644
index 0000000..19a5356
--- /dev/null
+++ b/ndn/util.py
@@ -0,0 +1,39 @@
+# -*- Mode:python; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
+#
+# Copyright (C) 2015-2017, The University of Memphis,
+#                          Arizona Board of Regents,
+#                          Regents of the University of California.
+#
+# This file is part of Mini-NDN.
+# See AUTHORS.md for a complete list of Mini-NDN authors and contributors.
+#
+# Mini-NDN is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# Mini-NDN is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with Mini-NDN, e.g., in COPYING.md file.
+# If not, see <http://www.gnu.org/licenses/>.
+
+from subprocess import call
+
+sshbase = [ 'ssh', '-q', '-t', '-i/home/mininet/.ssh/id_rsa' ]
+scpbase = [ 'scp', '-i', '/home/mininet/.ssh/id_rsa' ]
+devnull = open('/dev/null', 'w')
+
+def ssh(login, cmd):
+    rcmd = sshbase + [login, cmd]
+    call(rcmd, stdout=devnull, stderr=devnull)
+
+def scp(*args):
+    tmp = []
+    for arg in args:
+        tmp.append(arg)
+    rcmd = scpbase + tmp
+    call(rcmd, stdout=devnull, stderr=devnull)