52d3ddf7aa27bf0c230f7796775b91174c67b9e5
[nepi.git] / src / nepi / core / design.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 """
5 Experiment design API
6 """
7
8 from nepi.core.attributes import AttributesMap, Attribute
9 from nepi.core.metadata import Metadata
10 from nepi.util import validation
11 from nepi.util.constants import AF_INET, AF_INET6
12 from nepi.util.guid import GuidGenerator
13 from nepi.util.graphical_info import GraphicalInfo
14 from nepi.util.parser._xml import XmlExperimentParser
15 import sys
16
17 class ConnectorType(object):
18     def __init__(self, testbed_id, factory_id, name, help, max = -1, min = 0):
19         super(ConnectorType, self).__init__()
20         if max == -1:
21             max = sys.maxint
22         elif max <= 0:
23                 raise RuntimeError(
24              "The maximum number of connections allowed need to be more than 0")
25         if min < 0:
26             raise RuntimeError(
27              "The minimum number of connections allowed needs to be at least 0")
28         # connector_type_id -- univoquely identifies a connector type 
29         # across testbeds
30         self._connector_type_id = (testbed_id.lower(), factory_id.lower(), 
31                 name.lower())
32         # name -- display name for the connector type
33         self._name = name
34         # help -- help text
35         self._help = help
36         # max -- maximum amount of connections that this type support, 
37         # -1 for no limit
38         self._max = max
39         # min -- minimum amount of connections required by this type of connector
40         self._min = min
41         # allowed_connections -- keys in the dictionary correspond to the 
42         # connector_type_id for possible connections. The value indicates if
43         # the connection is allowed accros different testbed instances
44         self._allowed_connections = dict()
45
46     @property
47     def connector_type_id(self):
48         return self._connector_type_id
49
50     @property
51     def help(self):
52         return self._help
53
54     @property
55     def name(self):
56         return self._name
57
58     @property
59     def max(self):
60         return self._max
61
62     @property
63     def min(self):
64         return self._min
65
66     def add_allowed_connection(self, testbed_id, factory_id, name, can_cross):
67         self._allowed_connections[(testbed_id.lower(), 
68             factory_id.lower(), name.lower())] = can_cross
69
70     def can_connect(self, connector_type_id, testbed_guid1, testbed_guid2):
71         if not connector_type_id in self._allowed_connections.keys():
72             return False
73         can_cross = self._allowed_connections[connector_type_id]
74         return can_cross or (testbed_guid1 == testbed_guid2)
75
76 class Connector(object):
77     """A Connector sepcifies the connection points in an Object"""
78     def __init__(self, box, connector_type):
79         super(Connector, self).__init__()
80         self._box = box
81         self._connector_type = connector_type
82         self._connections = list()
83
84     @property
85     def box(self):
86         return self._box
87
88     @property
89     def connector_type(self):
90         return self._connector_type
91
92     @property
93     def connections(self):
94         return self._connections
95
96     def is_full(self):
97         """Return True if the connector has the maximum number of connections
98         """
99         return len(self.connections) == self.connector_type.max
100
101     def is_complete(self):
102         """Return True if the connector has the minimum number of connections
103         """
104         return len(self.connections) >= self.connector_type.min
105
106     def is_connected(self, connector):
107         return connector in self._connections
108
109     def connect(self, connector):
110         if not self.can_connect(connector) or not connector.can_connect(self):
111             raise RuntimeError("Could not connect.")
112         self._connections.append(connector)
113         connector._connections.append(self)
114
115     def disconnect(self, connector):
116         if connector not in self._connections or\
117                 self not in connector._connections:
118                 raise RuntimeError("Could not disconnect.")
119         self._connections.remove(connector)
120         connector._connections.remove(self)
121
122     def can_connect(self, connector):
123         if self.is_full() or connector.is_full():
124             return False
125         if self.is_connected(connector):
126             return False
127         connector_type_id = connector.connector_type.connector_type_id
128         testbed_guid1 = self.box.testbed_guid
129         testbed_guid2 = connector.box.testbed_guid
130         return self.connector_type.can_connect(connector_type_id, 
131                 testbed_guid1, testbed_guid2)
132
133     def destroy(self):
134         for connector in self.connections:
135             self.disconnect(connector)
136         self._box = self._connectors = None
137
138 class Trace(AttributesMap):
139     def __init__(self, trace_id, help, enabled = False):
140         super(Trace, self).__init__()
141         self._trace_id = trace_id
142         self._help = help       
143         self.enabled = enabled
144     
145     @property
146     def trace_id(self):
147         return self._trace_id
148
149     @property
150     def help(self):
151         return self._help
152
153 class Address(AttributesMap):
154     def __init__(self, family):
155         super(Address, self).__init__()
156         self.add_attribute(name = "AutoConfigure", 
157                 help = "If set, this address will automatically be assigned", 
158                 type = Attribute.BOOL,
159                 value = False,
160                 validation_function = validation.is_bool)
161         self.add_attribute(name = "Family",
162                 help = "Address family type: AF_INET, AFT_INET6", 
163                 type = Attribute.INTEGER, 
164                 value = family,
165                 readonly = True)
166         address_validation = validation.is_ip4_address if family == AF_INET \
167                         else validation.is_ip6_address
168         self.add_attribute(name = "Address",
169                 help = "Address number", 
170                 type = Attribute.STRING,
171                 validation_function = address_validation)
172         prefix_range = (0, 32) if family == AF_INET else (0, 128)
173         self.add_attribute(name = "NetPrefix",
174                 help = "Network prefix for the address", 
175                 type = Attribute.INTEGER, 
176                 range = prefix_range,
177                 value = 24 if family == AF_INET else 64,
178                 validation_function = validation.is_integer)
179         if family == AF_INET:
180             self.add_attribute(name = "Broadcast",
181                     help = "Broadcast address", 
182                     type = Attribute.STRING,
183                     validation_function = validation.is_ip4_address)
184                 
185 class Route(AttributesMap):
186     def __init__(self, family):
187         super(Route, self).__init__()
188         self.add_attribute(name = "Family",
189                 help = "Address family type: AF_INET, AFT_INET6", 
190                 type = Attribute.INTEGER, 
191                 value = family,
192                 readonly = True)
193         address_validation = validation.is_ip4_address if family == AF_INET \
194                         else validation.is_ip6_address
195         self.add_attribute(name = "Destination", 
196                 help = "Network destintation",
197                 type = Attribute.STRING, 
198                 validation_function = address_validation)
199         prefix_range = (0, 32) if family == AF_INET else (0, 128)
200         self.add_attribute(name = "NetPrefix",
201                 help = "Network destination prefix", 
202                 type = Attribute.INTEGER, 
203                 prefix_range = prefix_range,
204                 validation_function = validation.is_integer)
205         self.add_attribute(name = "NextHop",
206                 help = "Address for the next hop", 
207                 type = Attribute.STRING,
208                 validation_function = address_validation)
209         self.add_attribute(name = "Interface",
210                 help = "Local interface address", 
211                 type = Attribute.STRING,
212                 validation_function = address_validation)
213
214 class Box(AttributesMap):
215     def __init__(self, guid, factory, testbed_guid, container = None):
216         super(Box, self).__init__()
217         # guid -- global unique identifier
218         self._guid = guid
219         # factory_id -- factory identifier or name
220         self._factory_id = factory.factory_id
221         # testbed_guid -- parent testbed guid
222         self._testbed_guid = testbed_guid
223         # container -- boxes can be nested inside other 'container' boxes
224         self._container = container
225         # traces -- list of available traces for the box
226         self._traces = dict()
227         # connectors -- list of available connectors for the box
228         self._connectors = dict()
229         # factory_attributes -- factory attributes for box construction
230         self._factory_attributes = list()
231         # graphical_info -- GUI position information
232         self.graphical_info = GraphicalInfo(str(self._guid))
233
234         for connector_type in factory.connector_types:
235             connector = Connector(self, connector_type)
236             self._connectors[connector_type.name] = connector
237         for trace in factory.traces:
238             tr = Trace(trace.trace_id, trace.help, trace.enabled)
239             self._traces[trace.trace_id] = tr
240         for attr in factory.box_attributes:
241             self.add_attribute(attr.name, attr.help, attr.type, attr.value, 
242                     attr.range, attr.allowed, attr.readonly, attr.visible, 
243                     attr.validation_function)
244         for attr in factory.attributes:
245             self._factory_attributes.append(attr)
246
247     @property
248     def guid(self):
249         return self._guid
250
251     @property
252     def factory_id(self):
253         return self._factory_id
254
255     @property
256     def testbed_guid(self):
257         return self._testbed_guid
258
259     @property
260     def container(self):
261         return self._container
262
263     @property
264     def connectors(self):
265         return self._connectors.values()
266
267     @property
268     def traces(self):
269         return self._traces.values()
270
271     @property
272     def factory_attributes(self):
273         return self._factory_attributes
274
275     @property
276     def addresses(self):
277         return []
278
279     @property
280     def routes(self):
281         return []
282
283     def connector(self, name):
284         return self._connectors[name]
285
286     def trace(self, trace_id):
287         return self._traces[trace_id]
288
289     def destroy(self):
290         super(Box, self).destroy()
291         for c in self.connectors:
292             c.destroy()         
293         for t in self.traces:
294             t.destroy()
295         self._connectors = self._traces = self._factory_attributes = None
296
297 class AddressableBox(Box):
298     def __init__(self, guid, factory, testbed_guid, container = None):
299         super(AddressableBox, self).__init__(guid, factory, testbed_guid, 
300                 container)
301         self._family = factory.get_attribute_value("Family")
302         # maximum number of addresses this box can have
303         self._max_addresses = factory.get_attribute_value("MaxAddresses")
304         self._addresses = list()
305
306     @property
307     def addresses(self):
308         return self._addresses
309
310     @property
311     def max_addresses(self):
312         return self._max_addresses
313
314     def add_address(self):
315         if len(self._addresses) == self.max_addresses:
316             raise RuntimeError("Maximun number of addresses for this box reached.")
317         address = Address(family = self._family)
318         self._addresses.append(address)
319         return address
320
321     def delete_address(self, address):
322         self._addresses.remove(address)
323         del address
324
325     def destroy(self):
326         super(AddressableBox, self).destroy()
327         for address in self.addresses:
328             self.delete_address(address)
329         self._addresses = None
330
331 class RoutingTableBox(Box):
332     def __init__(self, guid, factory, container = None):
333         super(RoutingTableBox, self).__init__(guid, factory, container)
334         self._routes = list()
335
336     @property
337     def routes(self):
338         return self._routes
339
340     def add_route(self, family):
341         route = Route(family = family)
342         self._routes.append(route)
343         return route
344
345     def delete_route(self, route):
346         self._route.remove(route)
347         del route
348
349     def destroy(self):
350         super(RoutingTableBox, self).destroy()
351         for route in self.routes:
352             self.delete_route(route)
353         self._route = None
354
355 class Factory(AttributesMap):
356     def __init__(self, factory_id, allow_addresses = False, 
357             allow_routes = False, Help = None, category = None):
358         super(Factory, self).__init__()
359         self._factory_id = factory_id
360         self._allow_addresses = (allow_addresses == True)
361         self._allow_routes = (allow_routes == True)
362         self._help = help
363         self._category = category
364         self._connector_types = list()
365         self._traces = list()
366         self._box_attributes = list()
367
368     @property
369     def factory_id(self):
370         return self._factory_id
371
372     @property
373     def allow_addresses(self):
374         return self._allow_addresses
375
376     @property
377     def allow_routes(self):
378         return self._allow_routes
379
380     @property
381     def help(self):
382         return self._help
383
384     @property
385     def category(self):
386         return self._category
387
388     @property
389     def connector_types(self):
390         return self._connector_types
391
392     @property
393     def traces(self):
394         return self._traces
395
396     @property
397     def box_attributes(self):
398         return self._box_attributes
399
400     def add_connector_type(self, connector_type):
401         self._connector_types.append(connector_type)
402
403     def add_trace(self, trace_id, help, enabled = False):
404         trace = Trace(trace_id, help, enabled)
405         self._traces.append(trace)
406
407     def add_box_attribute(self, name, help, type, value = None, range = None,
408         allowed = None, readonly = False, visible = True, 
409         validation_function = None):
410         attribute = Attribute(name, help, type, value, range, allowed, readonly,
411                 visible, validation_function)
412         self._box_attributes.append(attribute)
413
414     def create(self, guid, testbed_description):
415         if self._allow_addresses:
416             return AddressableBox(guid, self, testbed_description.guid)
417         elif self._allow_routes:
418             return RoutingTableBox(guid, self, testbed_description.guid)
419         else:
420             return Box(guid, self, testbed_description.guid)
421
422     def destroy(self):
423         super(Factory, self).destroy()
424         self._connector_types = None
425
426 class FactoriesProvider(object):
427     def __init__(self, testbed_id, testbed_version):
428         super(FactoriesProvider, self).__init__()
429         self._testbed_id = testbed_id
430         self._testbed_version = testbed_version
431         self._factories = dict()
432
433         metadata = Metadata(testbed_id, testbed_version) 
434         for factory in metadata.build_design_factories():
435             self.add_factory(factory)
436
437     @property
438     def testbed_id(self):
439         return self._testbed_id
440
441     @property
442     def testbed_version(self):
443         return self._testbed_version
444
445     @property
446     def factories(self):
447         return self._factories.values()
448
449     def factory(self, factory_id):
450         return self._factories[factory_id]
451
452     def add_factory(self, factory):
453         self._factories[factory.factory_id] = factory
454
455     def remove_factory(self, factory_id):
456         del self._factories[factory_id]
457
458 class TestbedDescription(AttributesMap):
459     def __init__(self, guid_generator, provider):
460         super(TestbedDescription, self).__init__()
461         self._guid_generator = guid_generator
462         self._guid = guid_generator.next()
463         self._provider = provider
464         self._boxes = dict()
465         self.graphical_info = GraphicalInfo(str(self._guid))
466
467     @property
468     def guid(self):
469         return self._guid
470
471     @property
472     def provider(self):
473         return self._provider
474
475     @property
476     def boxes(self):
477         return self._boxes.values()
478
479     def box(self, guid):
480         return self._boxes[guid] if guid in self._boxes else None
481
482     def create(self, factory_id):
483         guid = self._guid_generator.next()
484         factory = self._provider.factory(factory_id)
485         box = factory.create(guid, self)
486         self._boxes[guid] = box
487         return box
488
489     def delete(self, guid):
490         box = self._boxes[guid]
491         del self._boxes[guid]
492         box.destroy()
493
494     def destroy(self):
495         for guid, box in self._boxes.iteritems():
496             box.destroy()
497         self._boxes = None
498
499 class ExperimentDescription(object):
500     def __init__(self, guid = 0):
501         self._guid_generator = GuidGenerator(guid)
502         self._testbed_descriptions = dict()
503
504     @property
505     def testbed_descriptions(self):
506         return self._testbed_descriptions.values()
507
508     def to_xml(self):
509         parser = XmlExperimentParser()
510         return parser.to_xml(self)
511
512     def from_xml(self, xml):
513         parser = XmlExperimentParser()
514         parser.from_xml(self, xml)
515
516     def testbed_description(self, guid):
517         return self._testbed_descriptions[guid] \
518                 if guid in self._testbed_descriptions else None
519
520     def box(self, guid):
521         for testbed_description in self._testbed_descriptions.values():
522             box = testbed_description.box(guid)
523             if box: return box
524         return None
525
526     def add_testbed_description(self, provider):
527         testbed_description = TestbedDescription(self._guid_generator, 
528                 provider)
529         guid = testbed_description.guid
530         self._testbed_descriptions[guid] = testbed_description
531         return testbed_description
532
533     def remove_testbed_description(self, testbed_description):
534         guid = testbed_description.guid
535         del self._testbed_descriptions[guid]
536
537     def destroy(self):
538         for testbed_description in self.testbed_descriptions:
539             testbed_description.destroy()
540
541 # TODO: When the experiment xml is passed to the controller to execute it
542 # NetReferences in the xml need to be solved
543 #
544 #targets = re.findall(r"%target:(.*?)%", command)
545 #for target in targets:
546 #   try:
547 #      (family, address, port) = resolve_netref(target, AF_INET, 
548 #          self.server.experiment )
549 #      command = command.replace("%%target:%s%%" % target, address.address)
550 #   except:
551 #       continue
552