Added LinuxPing and LinuxMtr RMs
[nepi.git] / src / nepi / resources / linux / ccn / fibentry.py
1 #
2 #    NEPI, a framework to manage network experiments
3 #    Copyright (C) 2013 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 clsinit_copy, ResourceState, \
23     ResourceAction, reschedule_delay
24 from nepi.resources.linux.application import LinuxApplication
25 from nepi.resources.linux.ccn.ccnd import LinuxCCND
26 from nepi.util.timefuncs import tnow
27
28 import os
29
30
31 # TODO: Add rest of options for ccndc!!!
32 #       Implement ENTRY DELETE!!
33
34 @clsinit_copy
35 class LinuxFIBEntry(LinuxApplication):
36     _rtype = "LinuxFIBEntry"
37
38     @classmethod
39     def _register_attributes(cls):
40         uri = Attribute("uri",
41                 "URI prefix to match and route for this FIB entry",
42                 default = "ccnx:/",
43                 flags = Flags.ExecReadOnly)
44
45         protocol = Attribute("protocol",
46                 "Transport protocol used in network connection to peer "
47                 "for this FIB entry. One of 'udp' or 'tcp'.",
48                 type = Types.Enumerate, 
49                 default = "udp",
50                 allowed = ["udp", "tcp"],
51                 flags = Flags.ExecReadOnly)
52
53         host = Attribute("host",
54                 "Peer host used in network connection for this FIB entry. ",
55                 flags = Flags.ExecReadOnly)
56
57         port = Attribute("port",
58                 "Peer port address used in network connection to peer "
59                 "for this FIB entry.",
60                 flags = Flags.ExecReadOnly)
61
62         cls._register_attribute(uri)
63         cls._register_attribute(protocol)
64         cls._register_attribute(host)
65         cls._register_attribute(port)
66
67     @classmethod
68     def _register_traces(cls):
69         ping = Trace("ping", "Continuous ping to the peer end")
70
71         cls._register_trace(ping)
72
73     def __init__(self, ec, guid):
74         super(LinuxFIBEntry, self).__init__(ec, guid)
75         self._home = "fib-%s" % self.guid
76
77     @property
78     def ccnd(self):
79         ccnd = self.get_connected(LinuxCCND.rtype())
80         if ccnd: return ccnd[0]
81         return None
82
83     @property
84     def node(self):
85         if self.ccnd: return self.ccnd.node
86         return None
87
88     def deploy(self):
89         # Wait until associated ccnd is provisioned
90         if not self.ccnd or self.ccnd.state < ResourceState.READY:
91             # ccnr needs to wait until ccnd is deployed and running
92             self.ec.schedule(reschedule_delay, self.deploy)
93         else:
94             try:
95                 if not self.get("command"):
96                     self.set("command", self._start_command)
97
98                 if not self.get("env"):
99                     self.set("env", self._environment)
100
101                 command = self.get("command")
102
103                 self.info("Deploying command '%s' " % command)
104
105                 self.discover()
106                 self.provision()
107                 self.configure()
108             except:
109                 self.fail()
110                 raise
111  
112             self.debug("----- READY ---- ")
113             self._ready_time = tnow()
114             self._state = ResourceState.READY
115
116     def upload_start_command(self):
117         command = self.get("command")
118         env = self.get("env")
119
120         if command:
121             # We want to make sure the FIB entries are created
122             # before the experiment starts.
123             # Run the command as a bash script in the background, 
124             # in the host ( but wait until the command has
125             # finished to continue )
126             env = env and self.replace_paths(env)
127             command = self.replace_paths(command)
128
129             (out, err), proc = self.execute_command(command, env)
130
131             if proc.poll():
132                 self._state = ResourceState.FAILED
133                 msg = "Failed to execute command"
134                 self.error(msg, out, err)
135                 raise RuntimeError, msg
136
137     def configure(self):
138         if not self.trace_enabled("ping"):
139             return
140
141         ping_script = """echo "Staring PING %(host)s at date `date +'%Y%m%d%H%M%S'`"; ping %(host)s""" % ({
142             "host": self.get("host")}) 
143         ping_file = os.path.join(self.run_home, "ping.sh")
144         self.node.upload(ping_script,
145                 ping_file,
146                 text = True, 
147                 overwrite = False)
148
149         command = """bash %s""" % ping_file
150         (out, err), proc = self.node.run(command, self.run_home, 
151             stdout = "ping",
152             stderr = "ping_stderr",
153             pidfile = "ping_pidfile")
154
155         # Wait for pid file to be generated
156         pid, ppid = self.node.wait_pid(self.run_home, "ping_pidfile")
157
158         # If the process is not running, check for error information
159         # on the remote machine
160         if not pid or not ppid:
161             (out, err), proc = self.node.check_errors(self.run_home,
162                     stderr = "ping_pidfile") 
163
164             # Out is what was written in the stderr file
165             if err:
166                 self.fail()
167                 msg = " Failed to deploy ping trace command '%s' " % command
168                 self.error(msg, out, err)
169                 raise RuntimeError, msg
170
171             #while true; do echo `date +'%Y%m%d%H%M%S'`; mtr --no-dns --report -c 1 roseval.pl.sophia.inria.fr;sleep 2;done
172  
173     def start(self):
174         if self._state in [ResourceState.READY, ResourceState.STARTED]:
175             command = self.get("command")
176             self.info("Starting command '%s'" % command)
177
178             self._start_time = tnow()
179             self._state = ResourceState.STARTED
180         else:
181             msg = " Failed to execute command '%s'" % command
182             self.error(msg, out, err)
183             self._state = ResourceState.FAILED
184             raise RuntimeError, msg
185
186     def stop(self):
187         command = self.get('command')
188         env = self.get('env')
189         
190         if self.state == ResourceState.STARTED:
191             self.info("Stopping command '%s'" % command)
192
193             command = self._stop_command
194             (out, err), proc = self.execute_command(command, env)
195
196             if proc.poll():
197                 pass
198
199             # now stop the ping trace
200             if self.trace_enabled("ping"):
201                pid, ppid = self.node.wait_pid(self.run_home, "ping_pidfile")
202                (out, err), proc = self.node.kill(pid, ppid)
203
204             self._stop_time = tnow()
205             self._state = ResourceState.STOPPED
206
207     @property
208     def state(self):
209         return self._state
210
211     @property
212     def _start_command(self):
213         uri = self.get("uri") or ""
214         protocol = self.get("protocol") or ""
215         host = self.get("host") or ""
216         port = self.get("port") or ""
217
218         # add ccnx:/example.com/ udp 224.0.0.204 52428
219         return "ccndc add %(uri)s %(protocol)s %(host)s %(port)s" % ({
220             "uri" : uri,
221             "protocol": protocol,
222             "host": host,
223             "port": port
224             })
225
226     @property
227     def _stop_command(self):
228         uri = self.get("uri") or ""
229         protocol = self.get("protocol") or ""
230         host = self.get("host") or ""
231         port = self.get("port") or ""
232
233         # add ccnx:/example.com/ udp 224.0.0.204 52428
234         return "ccndc del %(uri)s %(protocol)s %(host)s %(port)s" % ({
235             "uri" : uri,
236             "protocol": protocol,
237             "host": host,
238             "port": port
239             })
240
241     @property
242     def _environment(self):
243         return self.ccnd.path
244        
245     def valid_connection(self, guid):
246         # TODO: Validate!
247         return True
248