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