Do not keep label guids, they're not immediately useful.
[nepi.git] / src / nepi / core / execute.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 from nepi.core.attributes import Attribute, AttributesMap
5 from nepi.util import proxy, validation
6 from nepi.util.constants import STATUS_FINISHED
7 from nepi.util.parser._xml import XmlExperimentParser
8 import sys
9 import re
10
11 ATTRIBUTE_PATTERN_BASE = re.compile(r"\{#\[(?P<label>[-a-zA-Z0-9._]*)\](?P<expr>(?P<component>\.addr\[[0-9]+\]|\.route\[[0-9]+\]|\.trace\[[0-9]+\]|).\[(?P<attribute>[-a-zA-Z0-9._]*)\])#}")
12 ATTRIBUTE_PATTERN_GUID_SUB = r"{#[%(guid)s]%(expr)s#}"
13
14 class ConnectorType(object):
15     def __init__(self, testbed_id, factory_id, name, max = -1, min = 0):
16         super(ConnectorType, self).__init__()
17         if max == -1:
18             max = sys.maxint
19         elif max <= 0:
20                 raise RuntimeError(
21              "The maximum number of connections allowed need to be more than 0")
22         if min < 0:
23             raise RuntimeError(
24              "The minimum number of connections allowed needs to be at least 0")
25         # connector_type_id -- univoquely identifies a connector type 
26         # across testbeds
27         self._connector_type_id = (testbed_id.lower(), factory_id.lower(), 
28                 name.lower())
29         # name -- display name for the connector type
30         self._name = name
31         # max -- maximum amount of connections that this type support, 
32         # -1 for no limit
33         self._max = max
34         # min -- minimum amount of connections required by this type of connector
35         self._min = min
36         # from_connections -- connections where the other connector is the "From"
37         # to_connections -- connections where the other connector is the "To"
38         # keys in the dictionary correspond to the 
39         # connector_type_id for possible connections. The value is a tuple:
40         # (can_cross, connect)
41         # can_cross: indicates if the connection is allowed accros different
42         #    testbed instances
43         # code: is the connection function to be invoked when the elements
44         #    are connected
45         self._from_connections = dict()
46         self._to_connections = dict()
47
48     @property
49     def connector_type_id(self):
50         return self._connector_type_id
51
52     @property
53     def name(self):
54         return self._name
55
56     @property
57     def max(self):
58         return self._max
59
60     @property
61     def min(self):
62         return self._min
63
64     def add_from_connection(self, testbed_id, factory_id, name, can_cross, code):
65         self._from_connections[(testbed_id.lower(), factory_id.lower(),
66             name.lower())] = (can_cross, code)
67
68     def add_to_connection(self, testbed_id, factory_id, name, can_cross, code):
69         self._to_connections[(testbed_id.lower(), factory_id.lower(), 
70             name.lower())] = (can_cross, code)
71
72     def can_connect(self, testbed_id, factory_id, name, count, 
73             must_cross = False):
74         connector_type_id = (testbed_id.lower(), factory_id.lower(),
75             name.lower())
76         if connector_type_id in self._from_connections:
77             (can_cross, code) = self._from_connections[connector_type_id]
78         elif connector_type_id in self._to_connections:
79             (can_cross, code) = self._to_connections[connector_type_id]
80         else:
81             return False
82         return not must_cross or can_cross
83
84     def code_to_connect(self, testbed_id, factory_id, name):
85         connector_type_id = (testbed_id.lower(), factory_id.lower(), 
86             name.lower())        
87         if not connector_type_id in self._to_connections.keys():
88             return False
89         (can_cross, code) = self._to_connections[connector_type_id]
90         return code
91
92 # TODO: create_function, start_function, stop_function, status_function 
93 # need a definition!
94 class Factory(AttributesMap):
95     def __init__(self, factory_id, create_function, start_function, 
96             stop_function, status_function, configure_function,
97             allow_addresses = False, allow_routes = False):
98         super(Factory, self).__init__()
99         self._factory_id = factory_id
100         self._allow_addresses = (allow_addresses == True)
101         self._allow_routes = (allow_routes == True)
102         self._create_function = create_function
103         self._start_function = start_function
104         self._stop_function = stop_function
105         self._status_function = status_function
106         self._configure_function = configure_function
107         self._connector_types = dict()
108         self._traces = list()
109         self._box_attributes = AttributesMap()
110
111     @property
112     def factory_id(self):
113         return self._factory_id
114
115     @property
116     def allow_addresses(self):
117         return self._allow_addresses
118
119     @property
120     def allow_routes(self):
121         return self._allow_routes
122
123     @property
124     def box_attributes(self):
125         return self._box_attributes
126
127     @property
128     def create_function(self):
129         return self._create_function
130
131     @property
132     def start_function(self):
133         return self._start_function
134
135     @property
136     def stop_function(self):
137         return self._stop_function
138
139     @property
140     def status_function(self):
141         return self._status_function
142
143     @property
144     def configure_function(self):
145         return self._configure_function
146
147     @property
148     def traces(self):
149         return self._traces
150
151     def connector_type(self, name):
152         return self._connector_types[name]
153
154     def add_connector_type(self, connector_type):
155         self._connector_types[connector_type.name] = connector_type
156
157     def add_trace(self, trace_id):
158         self._traces.append(trace_id)
159
160     def add_box_attribute(self, name, help, type, value = None, range = None,
161         allowed = None, flags = Attribute.NoFlags, validation_function = None):
162         self._box_attributes.add_attribute(name, help, type, value, range, 
163                 allowed, flags, validation_function)
164
165 class TestbedInstance(object):
166     def __init__(self, testbed_id, testbed_version):
167         self._testbed_id = testbed_id
168         self._testbed_version = testbed_version
169
170     @property
171     def guids(self):
172         raise NotImplementedError
173
174     def defer_configure(self, name, value):
175         """Instructs setting a configuartion attribute for the testbed instance"""
176         raise NotImplementedError
177
178     def defer_create(self, guid, factory_id):
179         """Instructs creation of element """
180         raise NotImplementedError
181
182     def defer_create_set(self, guid, name, value):
183         """Instructs setting an initial attribute on an element"""
184         raise NotImplementedError
185
186     def defer_factory_set(self, guid, name, value):
187         """Instructs setting an attribute on a factory"""
188         raise NotImplementedError
189
190     def defer_connect(self, guid1, connector_type_name1, guid2, 
191             connector_type_name2): 
192         """Instructs creation of a connection between the given connectors"""
193         raise NotImplementedError
194
195     def defer_cross_connect(self, guid, connector_type_name, cross_guid, 
196             cross_testbed_id, cross_factory_id, cross_connector_type_name):
197         """
198         Instructs creation of a connection between the given connectors 
199         of different testbed instances
200         """
201         raise NotImplementedError
202
203     def defer_add_trace(self, guid, trace_id):
204         """Instructs the addition of a trace"""
205         raise NotImplementedError
206
207     def defer_add_address(self, guid, address, netprefix, broadcast): 
208         """Instructs the addition of an address"""
209         raise NotImplementedError
210
211     def defer_add_route(self, guid, destination, netprefix, nexthop):
212         """Instructs the addition of a route"""
213         raise NotImplementedError
214
215     def do_setup(self):
216         """After do_setup the testbed initial configuration is done"""
217         raise NotImplementedError
218
219     def do_create(self):
220         """
221         After do_create all instructed elements are created and 
222         attributes setted
223         """
224         raise NotImplementedError
225
226     def do_connect(self):
227         """
228         After do_connect all internal connections between testbed elements
229         are done
230         """
231         raise NotImplementedError
232
233     def do_configure(self):
234         """After do_configure elements are configured"""
235         raise NotImplementedError
236
237     def do_cross_connect(self):
238         """
239         After do_cross_connect all external connections between different testbed 
240         elements are done
241         """
242         raise NotImplementedError
243
244     def start(self):
245         raise NotImplementedError
246
247     def stop(self):
248         raise NotImplementedError
249
250     def set(self, time, guid, name, value):
251         raise NotImplementedError
252
253     def get(self, time, guid, name):
254         raise NotImplementedError
255
256     def action(self, time, guid, action):
257         raise NotImplementedError
258
259     def status(self, guid):
260         raise NotImplementedError
261
262     def trace(self, guid, trace_id):
263         raise NotImplementedError
264
265     def shutdown(self):
266         raise NotImplementedError
267
268 class ExperimentController(object):
269     def __init__(self, experiment_xml):
270         self._experiment_xml = experiment_xml
271         self._testbeds = dict()
272         self._access_config = dict()
273
274     @property
275     def experiment_xml(self):
276         return self._experiment_xml
277
278     def set_access_configuration(self, testbed_guid, access_config):
279         self._access_config[testbed_guid] = access_config
280
281     def trace(self, testbed_guid, guid, trace_id):
282         return self._testbeds[testbed_guid].trace(guid, trace_id)
283
284     def start(self):
285         self._create_testbed_instances()
286         for testbed in self._testbeds.values():
287             testbed.do_setup()
288         for testbed in self._testbeds.values():
289             testbed.do_create()
290             testbed.do_connect()
291             testbed.do_configure()
292         for testbed in self._testbeds.values():
293             testbed.do_cross_connect()
294         for testbed in self._testbeds.values():
295             testbed.start()
296
297     def stop(self):
298        for testbed in self._testbeds.values():
299            testbed.stop()
300
301     def is_finished(self, guid):
302         for testbed in self._testbeds.values():
303             for guid_ in testbed.guids:
304                 if guid_ == guid:
305                     return testbed.status(guid) == STATUS_FINISHED
306         raise RuntimeError("No element exists with guid %d" % guid)    
307
308     def shutdown(self):
309        for testbed in self._testbeds.values():
310            testbed.shutdown()
311
312     def _create_testbed_instances(self):
313         parser = XmlExperimentParser()
314         data = parser.from_xml_to_data(self._experiment_xml)
315         element_guids = list()
316         label_guids = dict()
317         data_guids = data.guids
318         for guid in data_guids:
319             if data.is_testbed_data(guid):
320                 (testbed_id, testbed_version) = data.get_testbed_data(guid)
321                 access_config = None if guid not in self._access_config else\
322                         self._access_config[guid]
323                 testbed = proxy.create_testbed_instance(testbed_id, 
324                         testbed_version, access_config)
325                 for (name, value) in data.get_attribute_data(guid):
326                     testbed.defer_configure(name, value)
327                 self._testbeds[guid] = testbed
328             else:
329                 element_guids.append(guid)
330                 label = data.get_attribute_data(guid, "label")
331                 if label is not None:
332                     if label in label_guids:
333                         raise RuntimeError, "Label %r is not unique" % (label,)
334                     label_guids[label] = guid
335         for guid in data_guids:
336             if not data.is_testbed_data(guid):
337                 for name, value in data.get_attribute_data(guid):
338                     if isinstance(value, basestring):
339                         match = ATTRIBUTE_PATTERN_BASE.search(value)
340                         if match:
341                             label = match.group("label")
342                             ref_guid = label_guids.get(label)
343                             if ref_guid is not None:
344                                 value = ATTRIBUTE_PATTERN_BASE.sub(
345                                     ATTRIBUTE_PATTERN_GUID_SUB % dict(
346                                         guid=ref_guid,
347                                         expr=match.group("expr"),
348                                         label=label), 
349                                     value)
350                                 data.set_attribute_data(guid, name, value)
351         self._program_testbed_instances(element_guids, data)
352
353     def _program_testbed_instances(self, element_guids, data):
354         for guid in element_guids:
355             (testbed_guid, factory_id) = data.get_box_data(guid)
356             testbed = self._testbeds[testbed_guid]
357             testbed.defer_create(guid, factory_id)
358             for (name, value) in data.get_attribute_data(guid):
359                 testbed.defer_create_set(guid, name, value)
360
361         for guid in element_guids: 
362             (testbed_guid, factory_id) = data.get_box_data(guid)
363             testbed = self._testbeds[testbed_guid]
364             for (connector_type_name, other_guid, other_connector_type_name) \
365                     in data.get_connection_data(guid):
366                 (testbed_guid, factory_id) = data.get_box_data(guid)
367                 (other_testbed_guid, other_factory_id) = data.get_box_data(
368                         other_guid)
369                 if testbed_guid == other_testbed_guid:
370                     testbed.defer_connect(guid, connector_type_name, other_guid, 
371                         other_connector_type_name)
372                 else:
373                     testbed.defer_cross_connect(guid, connector_type_name, other_guid, 
374                         other_testbed_id, other_factory_id, other_connector_type_name)
375             for trace_id in data.get_trace_data(guid):
376                 testbed.defer_add_trace(guid, trace_id)
377             for (autoconf, address, netprefix, broadcast) in \
378                     data.get_address_data(guid):
379                 if address != None:
380                     testbed.defer_add_address(guid, address, netprefix, broadcast)
381             for (destination, netprefix, nexthop) in data.get_route_data(guid):
382                 testbed.defer_add_route(guid, destination, netprefix, nexthop)
383