28a4e104549e3865c131e020e98bee2aa237e22a
[nepi.git] / src / nepi / resources / linux / ns3 / ns3simulation.py
1 #
2 #    NEPI, a framework to manage network experiments
3 #    Copyright (C) 2014 INRIA
4 #
5 #    This program is free software: you can redistribute it and/or modify
6 #    it under the terms of the GNU General Public License as published by
7 #    the Free Software Foundation, either version 3 of the License, or
8 #    (at your option) any later version.
9 #
10 #    This program is distributed in the hope that it will be useful,
11 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
12 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 #    GNU General Public License for more details.
14 #
15 #    You should have received a copy of the GNU General Public License
16 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 #
18 # Author: Alina Quereilhac <alina.quereilhac@inria.fr>
19
20 from nepi.execution.attribute import Attribute, Flags, Types
21 from nepi.execution.trace import Trace, TraceAttr
22 from nepi.execution.resource import ResourceManager, clsinit_copy, \
23         ResourceState, ResourceFactory, reschedule_delay
24 from nepi.resources.linux.application import LinuxApplication
25 from nepi.util.timefuncs import tnow, tdiffsec
26 from nepi.resources.ns3.ns3simulation import NS3Simulation
27 from nepi.resources.ns3.ns3wrapper import SIMULATOR_UUID, GLOBAL_VALUE_UUID, \
28         IPV4_GLOBAL_ROUTING_HELPER_UUID
29 from nepi.resources.linux.ns3.ns3client import LinuxNS3Client
30
31 import os
32 import time
33 import threading
34
35 ## TODO: Clean up DCE part. All that is DCE specific should go
36 ##       in the linux ns3dceapplication.py
37
38 @clsinit_copy
39 class LinuxNS3Simulation(LinuxApplication, NS3Simulation):
40     _rtype = "LinuxNS3Simulation"
41
42     @classmethod
43     def _register_attributes(cls):
44         impl_type = Attribute("simulatorImplementationType",
45                 "The object class to use as the simulator implementation",
46             allowed = ["ns3::DefaultSimulatorImpl", "ns3::RealtimeSimulatorImpl"],
47             default = "ns3::DefaultSimulatorImpl",
48             type = Types.Enumerate,
49             flags = Flags.Design)
50
51         sched_type = Attribute("schedulerType",
52                 "The object class to use as the scheduler implementation",
53                 allowed = ["ns3::MapScheduler",
54                             "ns3::ListScheduler",
55                             "ns3::HeapScheduler",
56                             "ns3::MapScheduler",
57                             "ns3::CalendarScheduler"
58                     ],
59             default = "ns3::MapScheduler",
60             type = Types.Enumerate,
61             flags = Flags.Design)
62
63         check_sum = Attribute("checksumEnabled",
64                 "A global switch to enable all checksums for all protocols",
65             default = False,
66             type = Types.Bool,
67             flags = Flags.Design)
68
69         ns_log = Attribute("nsLog",
70             "NS_LOG environment variable. " \
71                     " Will only generate output if ns-3 is compiled in DEBUG mode. ",
72             flags = Flags.Design)
73
74         verbose = Attribute("verbose",
75             "True to output debugging info from the ns3 client-server communication",
76             type = Types.Bool,
77             flags = Flags.Design)
78
79         enable_dump = Attribute("enableDump",
80             "Enable dumping the remote executed ns-3 commands to a script "
81             "in order to later reproduce and debug the experiment",
82             type = Types.Bool,
83             default = False,
84             flags = Flags.Design)
85
86         build_mode = Attribute("buildMode",
87             "Mode used to build ns-3 with waf. One if: debug, release, oprimized ",
88             default = "optimized", 
89             allowed = ["debug", "release", "optimized"],
90             type = Types.Enumerate,
91             flags = Flags.Design)
92
93         ns3_version = Attribute("ns3Version",
94             "Version of ns-3 to install from nsam repo",
95             #default = "ns-3.19", 
96             default = "ns-3.20", 
97             #default = "ns-3-dev", 
98             flags = Flags.Design)
99
100         pybindgen_version = Attribute("pybindgenVersion",
101             "Version of pybindgen to install from bazar repo",
102             #default = "864", 
103             default = "868", 
104             #default = "876", 
105             flags = Flags.Design)
106
107         dce_version = Attribute("dceVersion",
108             "Version of dce to install from nsam repo (tag branch for repo)",
109             default = "dce-1.3", 
110             #default = "dce-dev", 
111             flags = Flags.Design)
112
113         populate_routing_tables = Attribute("populateRoutingTables",
114             "Invokes  Ipv4GlobalRoutingHelper.PopulateRoutingTables() ",
115             default = False,
116             type = Types.Bool,
117             flags = Flags.Design)
118
119         stoptime = Attribute("stopTime",
120             "Time at which the simulation will stop",
121             flags = Flags.Design)
122
123         cls._register_attribute(impl_type)
124         cls._register_attribute(sched_type)
125         cls._register_attribute(check_sum)
126         cls._register_attribute(ns_log)
127         cls._register_attribute(enable_dump)
128         cls._register_attribute(verbose)
129         cls._register_attribute(build_mode)
130         cls._register_attribute(ns3_version)
131         cls._register_attribute(pybindgen_version)
132         cls._register_attribute(dce_version)
133         cls._register_attribute(populate_routing_tables)
134         cls._register_attribute(stoptime)
135
136     def __init__(self, ec, guid):
137         LinuxApplication.__init__(self, ec, guid)
138         NS3Simulation.__init__(self)
139
140         self._client = None
141         self._home = "ns3-simu-%s" % self.guid
142         self._socket_name = "ns3-%s.sock" % os.urandom(4).encode('hex')
143         self._dce_manager_helper_uuid = None
144         self._dce_application_helper_uuid = None
145         self._enable_dce = None
146
147     @property
148     def socket_name(self):
149         return self._socket_name
150
151     @property
152     def remote_socket(self):
153         return os.path.join(self.run_home, self.socket_name)
154
155     def trace(self, name, attr = TraceAttr.ALL, block = 512, offset = 0):
156         # stout needs to get flushed on the ns-3 server side, else we will 
157         # get an empty stream. We try twice to retrieve the stream
158         # if we get empty stdout since the stream might not be
159         # flushed immediately.
160         if name.endswith("stdout"):
161             self._client.flush() 
162             result = LinuxApplication.trace(self, name, attr, block, offset)
163             if result:
164                 return result
165             # Let the stream be flushed
166             time.sleep(1)
167
168         return LinuxApplication.trace(self, name, attr, block, offset)
169
170     def upload_sources(self):
171         self.node.mkdir(os.path.join(self.node.src_dir, "ns3wrapper"))
172
173         # upload ns3 wrapper python script
174         ns3_wrapper = os.path.join(os.path.dirname(__file__), "..", "..", "ns3", 
175                 "ns3wrapper.py")
176
177         self.node.upload(ns3_wrapper,
178                 os.path.join(self.node.src_dir, "ns3wrapper", "ns3wrapper.py"),
179                 overwrite = False)
180
181         # upload ns3 wrapper debug python script
182         ns3_wrapper_debug = os.path.join(os.path.dirname(__file__), "..", "..", "ns3", 
183                 "ns3wrapper_debug.py")
184
185         self.node.upload(ns3_wrapper_debug,
186                 os.path.join(self.node.src_dir, "ns3wrapper", "ns3wrapper_debug.py"),
187                 overwrite = False)
188
189         # upload ns3_server python script
190         ns3_server = os.path.join(os.path.dirname(__file__), "..", "..", "ns3",
191                 "ns3server.py")
192
193         self.node.upload(ns3_server,
194                 os.path.join(self.node.src_dir, "ns3wrapper", "ns3server.py"),
195                 overwrite = False)
196
197         if self.node.use_rpm:
198             # upload pygccxml sources
199             pygccxml_tar = os.path.join(os.path.dirname(__file__), "dependencies",
200                     "%s.tar.gz" % self.pygccxml_version)
201
202             self.node.upload(pygccxml_tar,
203                     os.path.join(self.node.src_dir, "%s.tar.gz" % self.pygccxml_version),
204                     overwrite = False)
205
206         # Upload user defined ns-3 sources
207         self.node.mkdir(os.path.join(self.node.src_dir, "ns-3"))
208         src_dir = os.path.join(self.node.src_dir, "ns-3")
209
210         super(LinuxNS3Simulation, self).upload_sources(src_dir = src_dir)
211     
212     def upload_extra_sources(self, sources = None, src_dir = None):
213         return super(LinuxNS3Simulation, self).upload_sources(
214                 sources = sources, 
215                 src_dir = src_dir)
216
217     def upload_start_command(self):
218         command = self.get("command")
219         env = self.get("env")
220
221         # We want to make sure the ccnd is running
222         # before the experiment starts.
223         # Run the command as a bash script in background,
224         # in the host ( but wait until the command has
225         # finished to continue )
226         env = self.replace_paths(env)
227         command = self.replace_paths(command)
228
229         shfile = os.path.join(self.app_home, "start.sh")
230         self.node.upload_command(command, 
231                     shfile = shfile,
232                     env = env,
233                     overwrite = True)
234
235         # Run the ns3wrapper 
236         self._run_in_background()
237
238         # Wait until the remote socket is created
239         self.wait_remote_socket()
240
241     def configure(self):
242         if self.has_changed("simulatorImplementationType"):
243             simu_type = self.get("simulatorImplementationType")
244             stype = self.create("StringValue", simu_type)
245             self.invoke(GLOBAL_VALUE_UUID, "Bind", "SimulatorImplementationType", stype)
246
247         if self.has_changed("checksumEnabled"):
248             check_sum = self.get("checksumEnabled")
249             btrue = self.create("BooleanValue", check_sum)    
250             self.invoke(GLOBAL_VALUE_UUID, "Bind", "ChecksumEnabled", btrue)
251         
252         if self.has_changed("schedulerType"):
253             sched_type = self.get("schedulerType")
254             stype = self.create("StringValue", sched_type)
255             self.invoke(GLOBAL_VALUE_UUID, "Bind", "SchedulerType", btrue)
256         
257     def do_deploy(self):
258         if not self.node or self.node.state < ResourceState.READY:
259             self.debug("---- RESCHEDULING DEPLOY ---- node state %s " % self.node.state )
260             
261             # ccnd needs to wait until node is deployed and running
262             self.ec.schedule(reschedule_delay, self.deploy)
263         else:
264             if not self.get("command"):
265                 self.set("command", self._start_command)
266             
267             if not self.get("depends"):
268                 self.set("depends", self._dependencies)
269
270             if self.get("sources"):
271                 sources = self.get("sources")
272                 source = sources.split(" ")[0]
273                 basename = os.path.basename(source)
274                 version = ( basename.strip().replace(".tar.gz", "")
275                     .replace(".tar","")
276                     .replace(".gz","")
277                     .replace(".zip","") )
278
279                 self.set("ns3Version", version)
280                 self.set("sources", source)
281
282             if not self.get("build"):
283                 self.set("build", self._build)
284
285             if not self.get("install"):
286                 self.set("install", self._install)
287
288             if not self.get("env"):
289                 self.set("env", self._environment)
290
291             self.do_discover()
292             self.do_provision()
293
294             # Create client
295             self._client = LinuxNS3Client(self)
296
297             self.configure()
298             
299             self.set_ready()
300
301     def do_start(self):
302         """ Starts simulation execution
303
304         """
305         self.info("Starting")
306
307         if self.state == ResourceState.READY:
308             if self.get("populateRoutingTables") == True:
309                 self.invoke(IPV4_GLOBAL_ROUTING_HELPER_UUID, "PopulateRoutingTables")
310
311             self._client.start()
312
313             """
314             XXX: Is this necessary??
315             # Wait until the Simulation is actually started before setting the state
316             is_running = False
317             for i in xrange(200):
318                 is_running = self.invoke(SIMULATOR_UUID, "isRunning")
319                 is_finished = self.invoke(SIMULATOR_UUID, "isFinished")
320             
321                 if is_running or is_finished:
322                     break
323                 else:
324                     time.sleep(1)
325             else:
326                 if not is_running:
327                     msg = " Simulation did not start"
328                     self.error(msg)
329                     raise RuntimeError
330             """
331
332             self.set_started()
333         else:
334             msg = " Failed to execute command '%s'" % command
335             self.error(msg, out, err)
336             raise RuntimeError, msg
337
338     def do_stop(self):
339         """ Stops simulation execution
340
341         """
342         if self.state == ResourceState.STARTED:
343             time = None
344             if self.get("stopTime"):
345                 time = self.get("stopTime")
346
347             self._client.stop(time=time) 
348             self.set_stopped()
349
350     def do_release(self):
351         self.info("Releasing resource")
352
353         tear_down = self.get("tearDown")
354         if tear_down:
355             self.node.execute(tear_down)
356
357         self.do_stop()
358         self._client.shutdown()
359         LinuxApplication.do_stop(self)
360         
361         super(LinuxApplication, self).do_release()
362
363     @property
364     def enable_dce(self):
365         if self._enable_dce is None:
366             from nepi.resources.ns3.ns3dceapplication import NS3BaseDceApplication
367             rclass = ResourceFactory.get_resource_type(
368                     NS3BaseDceApplication.get_rtype())
369             
370             self._enable_dce = False
371             for guid in self.ec.resources:
372                 rm = self.ec.get_resource(guid)
373                 if isinstance(rm, rclass):
374                     self._enable_dce = True
375                     break
376
377         return self._enable_dce
378
379     @property
380     def _start_command(self):
381         command = [] 
382
383         command.append("PYTHONPATH=$PYTHONPATH:${SRC}/ns3wrapper/")
384         
385         command.append("python ${SRC}/ns3wrapper/ns3server.py -S %s" % \
386                 os.path.basename(self.remote_socket) )
387
388         ns_log = self.get("nsLog")
389         if ns_log:
390             command.append("-L '%s'" % ns_log)
391
392         if self.get("enableDump"):
393             command.append("-D")
394
395         if self.get("verbose"):
396             command.append("-v")
397
398         command = " ".join(command)
399         return command
400
401     @property
402     def _dependencies(self):
403         if self.node.use_rpm:
404             return ( " gcc gcc-c++ python python-devel mercurial bzr tcpdump socat gccxml unzip")
405         elif self.node.use_deb:
406             return ( " gcc g++ python python-dev mercurial bzr tcpdump socat gccxml python-pygccxml unzip")
407         return ""
408
409     @property
410     def ns3_repo(self):
411         return "http://code.nsnam.org"
412
413     @property
414     def pygccxml_version(self):
415         return "pygccxml-1.0.0"
416
417     @property
418     def dce_repo(self):
419         return "http://code.nsnam.org/ns-3-dce"
420         #eturn "http://code.nsnam.org/epmancini/ns-3-dce"
421
422     @property
423     def dce_version(self):
424         dce_version = self.get("dceVersion")
425         return dce_version or "dce-dev"
426
427     @property
428     def ns3_build_location(self):
429         location = "${BIN}/ns-3/%(ns3_version)s%(dce_version)s/%(build_mode)s/build" \
430                     % {
431                         "ns3_version": self.get("ns3Version"),
432                         "dce_version": "-%s" % self.get("dceVersion") \
433                                 if self.enable_dce else "", 
434                         "build_mode": self.get("buildMode"),
435                       }
436
437         return location
438  
439
440     @property
441     def ns3_src_location(self):
442         location = "${SRC}/ns-3/%(ns3_version)s" \
443                     % {
444                         "ns3_version": self.get("ns3Version"),
445                       }
446
447         return location
448  
449     @property
450     def dce_src_location(self):
451         location = "${SRC}/ns-3-dce/%(dce_version)s" \
452                    % {
453                         "dce_version": self.get("dceVersion"),
454                      }
455
456         return location
457
458     @property
459     def _clone_ns3_command(self):
460         source = self.get("sources")
461         
462         if not source:
463             clone_ns3_cmd = "hg clone %(ns3_repo)s/%(ns3_version)s %(ns3_src)s" \
464                     % {
465                         "ns3_version": self.get("ns3Version"),
466                         "ns3_repo": self.ns3_repo,  
467                         "ns3_src": self.ns3_src_location,
468                       }
469         else:
470             if source.find(".tar.gz") > -1:
471                 clone_ns3_cmd = ( 
472                             "tar xzf ${SRC}/ns-3/%(basename)s " 
473                             " --strip-components=1 -C %(ns3_src)s"
474                             ) % {
475                                 "basename": os.path.basename(source),
476                                 "ns3_src": self.ns3_src_location,
477                                 }
478             elif source.find(".tar") > -1:
479                 clone_ns3_cmd = ( 
480                             "tar xf ${SRC}/ns-3/%(basename)s " 
481                             " --strip-components=1 -C %(ns3_src)s"
482                             ) % {
483                                 "basename": os.path.basename(source),
484                                 "ns3_src": self.ns3_src_location,
485                                 }
486             elif source.find(".zip") > -1:
487                 basename = os.path.basename(source)
488                 bare_basename = basename.replace(".zip", "") 
489
490                 clone_ns3_cmd = ( 
491                             "unzip ${SRC}/ns-3/%(basename)s && "
492                             "mv ${SRC}/ns-3/%(bare_basename)s %(ns3_src)s"
493                             ) % {
494                                 "bare_basename": basename_name,
495                                 "basename": basename,
496                                 "ns3_src": self.ns3_src_location,
497                                 }
498
499         return clone_ns3_cmd
500
501     @property
502     def _clone_dce_command(self):
503         clone_dce_cmd = " echo 'DCE will not be built' "
504
505         if self.enable_dce:
506             dce_version = self.dce_version
507             dce_tag = ""
508             if dce_version != "dce-dev":
509                 dce_tag = "-r %s" % dce_version
510
511             clone_dce_cmd = (
512                         # DCE installation
513                         # Test if dce is alredy cloned
514                         " ( "
515                         "  ( "
516                         "    ( test -d %(dce_src)s ) "
517                         "   && echo 'dce binaries found, nothing to do'"
518                         "  ) "
519                         " ) "
520                         "  || " 
521                         # Get dce source code
522                         " ( "
523                         "   mkdir -p %(dce_src)s && "
524                         "   hg clone %(dce_repo)s %(dce_tag)s %(dce_src)s"
525                         " ) "
526                      ) % {
527                             "dce_repo": self.dce_repo,
528                             "dce_tag": dce_tag,
529                             "dce_src": self.dce_src_location,
530                          }
531
532         return clone_dce_cmd
533
534     @property
535     def _build(self):
536         # If the user defined local sources for ns-3, we uncompress the sources
537         # on the remote sources directory. Else we clone ns-3 from the official repo.
538         clone_ns3_cmd = self._clone_ns3_command
539         clone_dce_cmd = self._clone_dce_command
540
541         ns3_build_cmd = (
542                 # NS3 installation
543                 "( "
544                 " ( "
545                 # Test if ns-3 is alredy cloned
546                 "  ((( test -d %(ns3_src)s ) || "
547                 "    ( test -d ${NS3BINDINGS:='None'} && test -d ${NS3LIBRARIES:='None'})) "
548                 "  && echo 'ns-3 binaries found, nothing to do' )"
549                 " ) "
550                 "  || " 
551                 # If not, install ns-3 and its dependencies
552                 " (   "
553                 # Install pygccxml
554                 "   (   "
555                 "     ( "
556                 "       python -c 'import pygccxml' && "
557                 "       echo 'pygccxml not found' "
558                 "     ) "
559                 "      || "
560                 "     ( "
561                 "       tar xf ${SRC}/%(pygccxml_version)s.tar.gz -C ${SRC} && "
562                 "       cd ${SRC}/%(pygccxml_version)s && "
563                 "       python setup.py build && "
564                 "       sudo -S python setup.py install "
565                 "     ) "
566                 "   ) " 
567                 # Install pybindgen
568                 "  && "
569                 "   (   "
570                 "     ( "
571                 "       test -d ${SRC}/pybindgen/%(pybindgen_version)s && "
572                 "       echo 'binaries found, nothing to do' "
573                 "     ) "
574                 "      || "
575                 # If not, clone and build
576                 "      ( cd ${SRC} && "
577                 "        mkdir -p ${SRC}/pybindgen && "
578                 "        bzr checkout lp:pybindgen -r %(pybindgen_version)s ${SRC}/pybindgen/%(pybindgen_version)s && "
579                 "        cd ${SRC}/pybindgen/%(pybindgen_version)s && "
580                 "        ./waf configure && "
581                 "        ./waf "
582                 "      ) "
583                 "   ) " 
584                 " && "
585                 # Get ns-3 source code
586                 "  ( "
587                 "     mkdir -p %(ns3_src)s && "
588                 "     %(clone_ns3_cmd)s "
589                 "  ) "
590                 " ) "
591                 ") "
592                 " && "
593                 "( "
594                 "   %(clone_dce_cmd)s "
595                 ") "
596              ) % { 
597                     "ns3_src": self.ns3_src_location,
598                     "pybindgen_version": self.get("pybindgenVersion"),
599                     "pygccxml_version": self.pygccxml_version,
600                     "clone_ns3_cmd": clone_ns3_cmd,
601                     "clone_dce_cmd": clone_dce_cmd,
602                  }
603
604         return ns3_build_cmd
605
606     @property
607     def _install_dce_command(self):
608         install_dce_cmd = " echo 'DCE will not be installed'"
609
610         if self.enable_dce:
611             install_dce_cmd = (
612                         " ( "
613                         "   ((test -d %(ns3_build)s/bin_dce ) && "
614                         "    echo 'dce binaries found, nothing to do' )"
615                         " ) "
616                         " ||" 
617                         " (   "
618                          # If not, copy build to dce
619                         "  cd %(dce_src)s && "
620                         "  rm -rf %(dce_src)s/build && "
621                         "  ./waf configure %(enable_opt)s --with-pybindgen=${SRC}/pybindgen/%(pybindgen_version)s "
622                         "  --prefix=%(ns3_build)s --with-ns3=%(ns3_build)s && "
623                         "  ./waf build && "
624                         "  ./waf install && "
625                         "  [ ! -e %(ns3_build)s/lib/python/site-packages/ns/dce.so ] && "
626                         "   mv %(ns3_build)s/lib*/python*/site-packages/ns/dce.so %(ns3_build)s/lib/python/site-packages/ns/ "
627                         " )"
628                 ) % { 
629                     "pybindgen_version": self.get("pybindgenVersion"),
630                     "enable_opt": "--enable-opt" if  self.get("buildMode") == "optimized" else "",
631                     "ns3_build": self.ns3_build_location,
632                     "dce_src": self.dce_src_location,
633                      }
634
635         return install_dce_cmd
636
637     @property
638     def _install(self):
639         install_dce_cmd = self._install_dce_command
640
641         install_ns3_cmd = (
642                  # Test if ns-3 is alredy installed
643                 "("
644                 " ( "
645                 "  ( ( (test -d %(ns3_build)s/lib ) || "
646                 "    (test -d ${NS3BINDINGS:='None'} && test -d ${NS3LIBRARIES:='None'}) ) && "
647                 "    echo 'binaries found, nothing to do' )"
648                 " ) "
649                 " ||" 
650                 " (   "
651                  # If not, copy ns-3 build to bin
652                 "  mkdir -p %(ns3_build)s && "
653                 "  cd %(ns3_src)s && "
654                 "  rm -rf %(ns3_src)s/build && "
655                 "  ./waf configure -d %(build_mode)s --with-pybindgen=${SRC}/pybindgen/%(pybindgen_version)s "
656                 "  --prefix=%(ns3_build)s && "
657                 "  ./waf build && "
658                 "  ./waf install && "
659                 "  mv %(ns3_build)s/lib*/python* %(ns3_build)s/lib/python "
660                 " )"
661                 ") "
662                 " && "
663                 "( "
664                 "   %(install_dce_cmd)s "
665                 ") "
666               ) % { 
667                     "pybindgen_version": self.get("pybindgenVersion"),
668                     "build_mode": self.get("buildMode"),
669                     "install_dce_cmd": install_dce_cmd,
670                     "ns3_build": self.ns3_build_location,
671                     "ns3_src": self.ns3_src_location,
672                  }
673
674         return install_ns3_cmd
675
676     @property
677     def _environment(self):
678         env = []
679         env.append("PYTHONPATH=$PYTHONPATH:${NS3BINDINGS:=%(ns3_build)s/lib/python/site-packages}" % { 
680                     "ns3_build": self.ns3_build_location
681                  })
682         # If NS3LIBRARIES is defined and not empty, assign its value, 
683         # if not assign ns3_build_home/lib/ to NS3LIBRARIES and LD_LIBARY_PATH
684         env.append("LD_LIBRARY_PATH=${NS3LIBRARIES:=%(ns3_build)s/lib}" % { 
685                     "ns3_build": self.ns3_build_location
686                  })
687         env.append("DCE_PATH=$NS3LIBRARIES/../bin_dce")
688         env.append("DCE_ROOT=$NS3LIBRARIES/..")
689
690         return " ".join(env) 
691
692     def replace_paths(self, command):
693         """
694         Replace all special path tags with shell-escaped actual paths.
695         """
696         return ( command
697             .replace("${USR}", self.node.usr_dir)
698             .replace("${LIB}", self.node.lib_dir)
699             .replace("${BIN}", self.node.bin_dir)
700             .replace("${SRC}", self.node.src_dir)
701             .replace("${SHARE}", self.node.share_dir)
702             .replace("${EXP}", self.node.exp_dir)
703             .replace("${EXP_HOME}", self.node.exp_home)
704             .replace("${APP_HOME}", self.app_home)
705             .replace("${RUN_HOME}", self.run_home)
706             .replace("${NODE_HOME}", self.node.node_home)
707             .replace("${HOME}", self.node.home_dir)
708             # If NS3LIBRARIES is defined and not empty, use that value, 
709             # if not use ns3_build_home/lib/
710             .replace("${BIN_DCE}", "${NS3LIBRARIES-%s/lib}/../bin_dce" % \
711                     self.ns3_build_location)
712             )
713
714     def valid_connection(self, guid):
715         # TODO: Validate!
716         return True
717
718     def wait_remote_socket(self):
719         """ Waits until the remote socket is created
720         """
721         command = " [ -e %s ] && echo 'DONE' " % self.remote_socket
722
723         for i in xrange(200):
724             (out, err), proc = self.node.execute(command, retry = 1, 
725                     with_lock = True)
726
727             if out.find("DONE") > -1:
728                 break
729         else:
730             raise RuntimeError("Remote socket not found at %s" % \
731                     self.remote_socket)
732     
733