Making CCN FIBEntry issue ccndc with hostname resolved to IP, since PlanetLab name...
[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 import socket
30 import time
31
32
33 # TODO: Add rest of options for ccndc!!!
34 #       Implement ENTRY DELETE!!
35
36 @clsinit_copy
37 class LinuxFIBEntry(LinuxApplication):
38     _rtype = "LinuxFIBEntry"
39
40     @classmethod
41     def _register_attributes(cls):
42         uri = Attribute("uri",
43                 "URI prefix to match and route for this FIB entry",
44                 default = "ccnx:/",
45                 flags = Flags.ExecReadOnly)
46
47         protocol = Attribute("protocol",
48                 "Transport protocol used in network connection to peer "
49                 "for this FIB entry. One of 'udp' or 'tcp'.",
50                 type = Types.Enumerate, 
51                 default = "udp",
52                 allowed = ["udp", "tcp"],
53                 flags = Flags.ExecReadOnly)
54
55         host = Attribute("host",
56                 "Peer hostname used in network connection for this FIB entry. ",
57                 flags = Flags.ExecReadOnly)
58
59         port = Attribute("port",
60                 "Peer port address used in network connection to peer "
61                 "for this FIB entry.",
62                 flags = Flags.ExecReadOnly)
63
64         ip = Attribute("ip",
65                 "Peer host public IP used in network connection for this FIB entry. ",
66                 flags = Flags.ReadOnly)
67
68         cls._register_attribute(uri)
69         cls._register_attribute(protocol)
70         cls._register_attribute(host)
71         cls._register_attribute(port)
72         cls._register_attribute(ip)
73
74     @classmethod
75     def _register_traces(cls):
76         ping = Trace("ping", "Ping to the peer end")
77         mtr = Trace("mtr", "Mtr to the peer end")
78         traceroute = Trace("traceroute", "Tracerout to the peer end")
79
80         cls._register_trace(ping)
81         cls._register_trace(mtr)
82         cls._register_trace(traceroute)
83
84     def __init__(self, ec, guid):
85         super(LinuxFIBEntry, self).__init__(ec, guid)
86         self._home = "fib-%s" % self.guid
87         self._ping = None
88         self._mtr = None
89         self._traceroute = None
90
91     @property
92     def ccnd(self):
93         ccnd = self.get_connected(LinuxCCND.rtype())
94         if ccnd: return ccnd[0]
95         return None
96
97     @property
98     def node(self):
99         if self.ccnd: return self.ccnd.node
100         return None
101
102     def trace(self, name, attr = TraceAttr.ALL, block = 512, offset = 0):
103         if name == "ping":
104             return self.ec.trace(self._ping, "stdout", attr, block, offset)
105         if name == "mtr":
106             return self.ec.trace(self._mtr, "stdout", attr, block, offset)
107         if name == "traceroute":
108             return self.ec.trace(self._traceroute, "stdout", attr, block, offset)
109
110         return super(LinuxFIBEntry, self).trace(name, attr, block, offset)
111         
112     def deploy(self):
113         # Wait until associated ccnd is provisioned
114         if not self.ccnd or self.ccnd.state < ResourceState.READY:
115             # ccnr needs to wait until ccnd is deployed and running
116             self.ec.schedule(reschedule_delay, self.deploy)
117         else:
118             try:
119                 if not self.get("ip"):
120                     host = self.get("host")
121                     ip = socket.gethostbyname(host)
122                     self.set("ip", ip)
123
124                 if not self.get("command"):
125                     self.set("command", self._start_command)
126
127                 if not self.get("env"):
128                     self.set("env", self._environment)
129
130                 command = self.get("command")
131
132                 self.info("Deploying command '%s' " % command)
133
134                 self.discover()
135                 self.provision()
136                 self.configure()
137             except:
138                 self.fail()
139                 raise
140  
141             self.debug("----- READY ---- ")
142             self._ready_time = tnow()
143             self._state = ResourceState.READY
144
145     def upload_start_command(self):
146         command = self.get("command")
147         env = self.get("env")
148
149         # We want to make sure the FIB entries are created
150         # before the experiment starts.
151         # Run the command as a bash script in the background, 
152         # in the host ( but wait until the command has
153         # finished to continue )
154         env = env and self.replace_paths(env)
155         command = self.replace_paths(command)
156
157         # ccndc seems to return exitcode OK even if a (dns) error
158         # occurred, so we need to account for this case here. 
159         (out, err), proc = self.execute_command(command, 
160                 env, blocking = True)
161
162         if proc.poll():
163             self._state = ResourceState.FAILED
164             msg = "Failed to execute command"
165             self.error(msg, out, err)
166             raise RuntimeError, msg
167         
168     def configure(self):
169         if self.trace_enabled("ping"):
170             self.info("Configuring PING trace")
171             self._ping = self.ec.register_resource("LinuxPing")
172             self.ec.set(self._ping, "printTimestamp", True)
173             self.ec.set(self._ping, "target", self.get("host"))
174             self.ec.register_connection(self._ping, self.node.guid)
175             # schedule ping deploy
176             self.ec.deploy(guids=[self._ping], group = self.deployment_group)
177
178         if self.trace_enabled("mtr"):
179             self.info("Configuring MTR trace")
180             self._mtr = self.ec.register_resource("LinuxMtr")
181             self.ec.set(self._mtr, "noDns", True)
182             self.ec.set(self._mtr, "printTimestamp", True)
183             self.ec.set(self._mtr, "continuous", True)
184             self.ec.set(self._mtr, "target", self.get("host"))
185             self.ec.register_connection(self._mtr, self.node.guid)
186             # schedule mtr deploy
187             self.ec.deploy(guids=[self._mtr], group = self.deployment_group)
188
189         if self.trace_enabled("traceroute"):
190             self.info("Configuring TRACEROUTE trace")
191             self._traceroute = self.ec.register_resource("LinuxTraceroute")
192             self.ec.set(self._traceroute, "printTimestamp", True)
193             self.ec.set(self._traceroute, "continuous", True)
194             self.ec.set(self._traceroute, "target", self.get("host"))
195             self.ec.register_connection(self._traceroute, self.node.guid)
196             # schedule mtr deploy
197             self.ec.deploy(guids=[self._traceroute], group = self.deployment_group)
198
199     def start(self):
200         if self._state in [ResourceState.READY, ResourceState.STARTED]:
201             command = self.get("command")
202             self.info("Starting command '%s'" % command)
203
204             self._start_time = tnow()
205             self._state = ResourceState.STARTED
206         else:
207             msg = " Failed to execute command '%s'" % command
208             self.error(msg, out, err)
209             self._state = ResourceState.FAILED
210             raise RuntimeError, msg
211
212     def stop(self):
213         command = self.get('command')
214         env = self.get('env')
215         
216         if self.state == ResourceState.STARTED:
217             self.info("Stopping command '%s'" % command)
218
219             command = self._stop_command
220             (out, err), proc = self.execute_command(command, env)
221
222             if proc.poll():
223                 pass
224
225             self._stop_time = tnow()
226             self._state = ResourceState.STOPPED
227
228     @property
229     def state(self):
230         return self._state
231
232     @property
233     def _start_command(self):
234         uri = self.get("uri") or ""
235         protocol = self.get("protocol") or ""
236         ip = self.get("ip") or "" 
237         port = self.get("port") or ""
238
239         # add ccnx:/example.com/ udp 224.0.0.204 52428
240         return "ccndc add %(uri)s %(protocol)s %(host)s %(port)s" % ({
241             "uri" : uri,
242             "protocol": protocol,
243             "host": ip,
244             "port": port
245             })
246
247     @property
248     def _stop_command(self):
249         uri = self.get("uri") or ""
250         protocol = self.get("protocol") or ""
251         ip = self.get("ip") or ""
252         port = self.get("port") or ""
253
254         # add ccnx:/example.com/ udp 224.0.0.204 52428
255         return "ccndc del %(uri)s %(protocol)s %(host)s %(port)s" % ({
256             "uri" : uri,
257             "protocol": protocol,
258             "host": ip,
259             "port": port
260             })
261
262     @property
263     def _environment(self):
264         return self.ccnd.path
265        
266     def valid_connection(self, guid):
267         # TODO: Validate!
268         return True
269