Various small fixes to Linux CCN 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", "Ping to the peer end")
70         mtr = Trace("mtr", "Mtr to the peer end")
71         traceroute = Trace("traceroute", "Tracerout to the peer end")
72
73         cls._register_trace(ping)
74         cls._register_trace(mtr)
75         cls._register_trace(traceroute)
76
77     def __init__(self, ec, guid):
78         super(LinuxFIBEntry, self).__init__(ec, guid)
79         self._home = "fib-%s" % self.guid
80         self._ping = None
81         self._mtr = None
82         self._traceroute = None
83
84     @property
85     def ccnd(self):
86         ccnd = self.get_connected(LinuxCCND.rtype())
87         if ccnd: return ccnd[0]
88         return None
89
90     @property
91     def node(self):
92         if self.ccnd: return self.ccnd.node
93         return None
94
95     def trace(self, name, attr = TraceAttr.ALL, block = 512, offset = 0):
96         if name == "ping":
97             return self.ec.trace(self._ping, "stdout", attr, block, offset)
98         if name == "mtr":
99             return self.ec.trace(self._mtr, "stdout", attr, block, offset)
100         if name == "traceroute":
101             return self.ec.trace(self._traceroute, "stdout", attr, block, offset)
102
103         return super(LinuxFIBEntry, self).trace(name, attr, block, offset)
104         
105     def deploy(self):
106         # Wait until associated ccnd is provisioned
107         if not self.ccnd or self.ccnd.state < ResourceState.READY:
108             # ccnr needs to wait until ccnd is deployed and running
109             self.ec.schedule(reschedule_delay, self.deploy)
110         else:
111             try:
112                 if not self.get("command"):
113                     self.set("command", self._start_command)
114
115                 if not self.get("env"):
116                     self.set("env", self._environment)
117
118                 command = self.get("command")
119
120                 self.info("Deploying command '%s' " % command)
121
122                 self.discover()
123                 self.provision()
124                 self.configure()
125             except:
126                 self.fail()
127                 raise
128  
129             self.debug("----- READY ---- ")
130             self._ready_time = tnow()
131             self._state = ResourceState.READY
132
133     def upload_start_command(self):
134         command = self.get("command")
135         env = self.get("env")
136
137         # We want to make sure the FIB entries are created
138         # before the experiment starts.
139         # Run the command as a bash script in the background, 
140         # in the host ( but wait until the command has
141         # finished to continue )
142         env = env and self.replace_paths(env)
143         command = self.replace_paths(command)
144
145         (out, err), proc = self.execute_command(command, env)
146
147         if proc.poll():
148             self._state = ResourceState.FAILED
149             msg = "Failed to execute command"
150             self.error(msg, out, err)
151             raise RuntimeError, msg
152
153     def configure(self):
154         if self.trace_enabled("ping"):
155             self.info("Configuring PING trace")
156             self._ping = self.ec.register_resource("LinuxPing")
157             self.ec.set(self._ping, "printTimestamp", True)
158             self.ec.set(self._ping, "target", self.get("host"))
159             self.ec.register_connection(self._ping, self.node.guid)
160             # schedule ping deploy
161             self.ec.deploy(group=[self._ping])
162
163         if self.trace_enabled("mtr"):
164             self.info("Configuring MTR trace")
165             self._mtr = self.ec.register_resource("LinuxMtr")
166             self.ec.set(self._mtr, "noDns", True)
167             self.ec.set(self._mtr, "printTimestamp", True)
168             self.ec.set(self._mtr, "continuous", True)
169             self.ec.set(self._mtr, "target", self.get("host"))
170             self.ec.register_connection(self._mtr, self.node.guid)
171             # schedule mtr deploy
172             self.ec.deploy(group=[self._mtr])
173
174         if self.trace_enabled("traceroute"):
175             self.info("Configuring TRACEROUTE trace")
176             self._traceroute = self.ec.register_resource("LinuxTraceroute")
177             self.ec.set(self._traceroute, "printTimestamp", True)
178             self.ec.set(self._traceroute, "continuous", True)
179             self.ec.set(self._traceroute, "target", self.get("host"))
180             self.ec.register_connection(self._traceroute, self.node.guid)
181             # schedule mtr deploy
182             self.ec.deploy(group=[self._traceroute])
183
184     def start(self):
185         if self._state in [ResourceState.READY, ResourceState.STARTED]:
186             command = self.get("command")
187             self.info("Starting command '%s'" % command)
188
189             self._start_time = tnow()
190             self._state = ResourceState.STARTED
191         else:
192             msg = " Failed to execute command '%s'" % command
193             self.error(msg, out, err)
194             self._state = ResourceState.FAILED
195             raise RuntimeError, msg
196
197     def stop(self):
198         command = self.get('command')
199         env = self.get('env')
200         
201         if self.state == ResourceState.STARTED:
202             self.info("Stopping command '%s'" % command)
203
204             command = self._stop_command
205             (out, err), proc = self.execute_command(command, env)
206
207             if proc.poll():
208                 pass
209
210             self._stop_time = tnow()
211             self._state = ResourceState.STOPPED
212
213     @property
214     def state(self):
215         return self._state
216
217     @property
218     def _start_command(self):
219         uri = self.get("uri") or ""
220         protocol = self.get("protocol") or ""
221         host = self.get("host") or ""
222         port = self.get("port") or ""
223
224         # add ccnx:/example.com/ udp 224.0.0.204 52428
225         return "ccndc add %(uri)s %(protocol)s %(host)s %(port)s" % ({
226             "uri" : uri,
227             "protocol": protocol,
228             "host": host,
229             "port": port
230             })
231
232     @property
233     def _stop_command(self):
234         uri = self.get("uri") or ""
235         protocol = self.get("protocol") or ""
236         host = self.get("host") or ""
237         port = self.get("port") or ""
238
239         # add ccnx:/example.com/ udp 224.0.0.204 52428
240         return "ccndc del %(uri)s %(protocol)s %(host)s %(port)s" % ({
241             "uri" : uri,
242             "protocol": protocol,
243             "host": host,
244             "port": port
245             })
246
247     @property
248     def _environment(self):
249         return self.ccnd.path
250        
251     def valid_connection(self, guid):
252         # TODO: Validate!
253         return True
254