Initially working version of PlanetLab testbed implementation.
[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, TIME_NOW
7 from nepi.util.parser._xml import XmlExperimentParser
8 import sys
9 import re
10 import threading
11 import ConfigParser
12 import os
13
14 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._]*)\])#}")
15 ATTRIBUTE_PATTERN_GUID_SUB = r"{#[%(guid)s]%(expr)s#}"
16 COMPONENT_PATTERN = re.compile(r"(?P<kind>[a-z]*)\[(?P<index>.*)\]")
17
18 class ConnectorType(object):
19     def __init__(self, testbed_id, factory_id, name, max = -1, min = 0):
20         super(ConnectorType, self).__init__()
21         if max == -1:
22             max = sys.maxint
23         elif max <= 0:
24                 raise RuntimeError(
25              "The maximum number of connections allowed need to be more than 0")
26         if min < 0:
27             raise RuntimeError(
28              "The minimum number of connections allowed needs to be at least 0")
29         # connector_type_id -- univoquely identifies a connector type 
30         # across testbeds
31         self._connector_type_id = (testbed_id.lower(), factory_id.lower(), 
32                 name.lower())
33         # name -- display name for the connector type
34         self._name = name
35         # max -- maximum amount of connections that this type support, 
36         # -1 for no limit
37         self._max = max
38         # min -- minimum amount of connections required by this type of connector
39         self._min = min
40         # from_connections -- connections where the other connector is the "From"
41         # to_connections -- connections where the other connector is the "To"
42         # keys in the dictionary correspond to the 
43         # connector_type_id for possible connections. The value is a tuple:
44         # (can_cross, connect)
45         # can_cross: indicates if the connection is allowed accros different
46         #    testbed instances
47         # code: is the connection function to be invoked when the elements
48         #    are connected
49         self._from_connections = dict()
50         self._to_connections = dict()
51
52     @property
53     def connector_type_id(self):
54         return self._connector_type_id
55
56     @property
57     def name(self):
58         return self._name
59
60     @property
61     def max(self):
62         return self._max
63
64     @property
65     def min(self):
66         return self._min
67
68     def add_from_connection(self, testbed_id, factory_id, name, can_cross, code):
69         self._from_connections[(testbed_id.lower(), factory_id.lower(),
70             name.lower())] = (can_cross, code)
71
72     def add_to_connection(self, testbed_id, factory_id, name, can_cross, code):
73         self._to_connections[(testbed_id.lower(), factory_id.lower(), 
74             name.lower())] = (can_cross, code)
75
76     def can_connect(self, testbed_id, factory_id, name, count, 
77             must_cross = False):
78         connector_type_id = (testbed_id.lower(), factory_id.lower(),
79             name.lower())
80         if connector_type_id in self._from_connections:
81             (can_cross, code) = self._from_connections[connector_type_id]
82         elif connector_type_id in self._to_connections:
83             (can_cross, code) = self._to_connections[connector_type_id]
84         else:
85             return False
86         return not must_cross or can_cross
87
88     def code_to_connect(self, testbed_id, factory_id, name):
89         connector_type_id = (testbed_id.lower(), factory_id.lower(), 
90             name.lower())        
91         if not connector_type_id in self._to_connections.keys():
92             return False
93         (can_cross, code) = self._to_connections[connector_type_id]
94         return code
95
96 # TODO: create_function, start_function, stop_function, status_function 
97 # need a definition!
98 class Factory(AttributesMap):
99     def __init__(self, factory_id, create_function, start_function, 
100             stop_function, status_function, 
101             configure_function, preconfigure_function,
102             allow_addresses = False, allow_routes = False):
103         super(Factory, self).__init__()
104         self._factory_id = factory_id
105         self._allow_addresses = (allow_addresses == True)
106         self._allow_routes = (allow_routes == True)
107         self._create_function = create_function
108         self._start_function = start_function
109         self._stop_function = stop_function
110         self._status_function = status_function
111         self._configure_function = configure_function
112         self._preconfigure_function = preconfigure_function
113         self._connector_types = dict()
114         self._traces = list()
115         self._box_attributes = AttributesMap()
116
117     @property
118     def factory_id(self):
119         return self._factory_id
120
121     @property
122     def allow_addresses(self):
123         return self._allow_addresses
124
125     @property
126     def allow_routes(self):
127         return self._allow_routes
128
129     @property
130     def box_attributes(self):
131         return self._box_attributes
132
133     @property
134     def create_function(self):
135         return self._create_function
136
137     @property
138     def start_function(self):
139         return self._start_function
140
141     @property
142     def stop_function(self):
143         return self._stop_function
144
145     @property
146     def status_function(self):
147         return self._status_function
148
149     @property
150     def configure_function(self):
151         return self._configure_function
152
153     @property
154     def preconfigure_function(self):
155         return self._preconfigure_function
156
157     @property
158     def traces(self):
159         return self._traces
160
161     def connector_type(self, name):
162         return self._connector_types[name]
163
164     def add_connector_type(self, connector_type):
165         self._connector_types[connector_type.name] = connector_type
166
167     def add_trace(self, trace_id):
168         self._traces.append(trace_id)
169
170     def add_box_attribute(self, name, help, type, value = None, range = None,
171         allowed = None, flags = Attribute.NoFlags, validation_function = None):
172         self._box_attributes.add_attribute(name, help, type, value, range, 
173                 allowed, flags, validation_function)
174
175 class TestbedController(object):
176     def __init__(self, testbed_id, testbed_version):
177         self._testbed_id = testbed_id
178         self._testbed_version = testbed_version
179
180     @property
181     def guids(self):
182         raise NotImplementedError
183
184     def defer_configure(self, name, value):
185         """Instructs setting a configuartion attribute for the testbed instance"""
186         raise NotImplementedError
187
188     def defer_create(self, guid, factory_id):
189         """Instructs creation of element """
190         raise NotImplementedError
191
192     def defer_create_set(self, guid, name, value):
193         """Instructs setting an initial attribute on an element"""
194         raise NotImplementedError
195
196     def defer_factory_set(self, guid, name, value):
197         """Instructs setting an attribute on a factory"""
198         raise NotImplementedError
199
200     def defer_connect(self, guid1, connector_type_name1, guid2, 
201             connector_type_name2): 
202         """Instructs creation of a connection between the given connectors"""
203         raise NotImplementedError
204
205     def defer_cross_connect(self, guid, connector_type_name, cross_guid, 
206             cross_testbed_id, cross_factory_id, cross_connector_type_name):
207         """
208         Instructs creation of a connection between the given connectors 
209         of different testbed instances
210         """
211         raise NotImplementedError
212
213     def defer_add_trace(self, guid, trace_id):
214         """Instructs the addition of a trace"""
215         raise NotImplementedError
216
217     def defer_add_address(self, guid, address, netprefix, broadcast): 
218         """Instructs the addition of an address"""
219         raise NotImplementedError
220
221     def defer_add_route(self, guid, destination, netprefix, nexthop):
222         """Instructs the addition of a route"""
223         raise NotImplementedError
224
225     def do_setup(self):
226         """After do_setup the testbed initial configuration is done"""
227         raise NotImplementedError
228
229     def do_create(self):
230         """
231         After do_create all instructed elements are created and 
232         attributes setted
233         """
234         raise NotImplementedError
235
236     def do_connect(self):
237         """
238         After do_connect all internal connections between testbed elements
239         are done
240         """
241         raise NotImplementedError
242
243     def do_configure(self):
244         """After do_configure elements are configured"""
245         raise NotImplementedError
246
247     def do_cross_connect(self):
248         """
249         After do_cross_connect all external connections between different testbed 
250         elements are done
251         """
252         raise NotImplementedError
253
254     def start(self):
255         raise NotImplementedError
256
257     def stop(self):
258         raise NotImplementedError
259
260     def set(self, time, guid, name, value):
261         raise NotImplementedError
262
263     def get(self, time, guid, name):
264         raise NotImplementedError
265     
266     def get_route(self, guid, index, attribute):
267         """
268         Params:
269             
270             guid: guid of box to query
271             index: number of routing entry to fetch
272             attribute: one of Destination, NextHop, NetPrefix
273         """
274         raise NotImplementedError
275
276     def get_address(self, guid, index, attribute='Address'):
277         """
278         Params:
279             
280             guid: guid of box to query
281             index: number of inteface to select
282             attribute: one of Address, NetPrefix, Broadcast
283         """
284         raise NotImplementedError
285
286     def action(self, time, guid, action):
287         raise NotImplementedError
288
289     def status(self, guid):
290         raise NotImplementedError
291
292     def trace(self, guid, trace_id, attribute='value'):
293         raise NotImplementedError
294
295     def shutdown(self):
296         raise NotImplementedError
297
298 class ExperimentController(object):
299     def __init__(self, experiment_xml, root_dir):
300         self._experiment_xml = experiment_xml
301         self._testbeds = dict()
302         self._access_config = dict()
303         self._netrefs = dict()
304         self._root_dir = root_dir
305
306         self.persist_experiment_xml()
307
308     @property
309     def experiment_xml(self):
310         return self._experiment_xml
311
312     def persist_experiment_xml(self):
313         xml_path = os.path.join(self._root_dir, "experiment.xml")
314         f = open(xml_path, "w")
315         f.write(self._experiment_xml)
316         f.close()
317
318     def set_access_configuration(self, testbed_guid, access_config):
319         self._access_config[testbed_guid] = access_config
320
321     def trace(self, testbed_guid, guid, trace_id, attribute='value'):
322         return self._testbeds[testbed_guid].trace(guid, trace_id, attribute)
323
324     @staticmethod
325     def _parallel(callables):
326         threads = [ threading.Thread(target=callable) for callable in callables ]
327         for thread in threads:
328             thread.start()
329         for thread in threads:
330             thread.join()
331
332     def start(self):
333         self._create_testbed_instances()
334         
335         # persist testbed connection data, for potential recovery
336         self._persist_testbed_proxies()
337         
338         # perform setup in parallel for all test beds,
339         # wait for all threads to finish
340         self._parallel([testbed.do_setup 
341                         for testbed in self._testbeds.itervalues()])
342         
343         # perform create-connect in parallel, wait
344         # (internal connections only)
345         self._parallel([lambda : (testbed.do_create(), 
346                                   testbed.do_connect(),
347                                   testbed.do_preconfigure())
348                         for testbed in self._testbeds.itervalues()])
349         
350         # resolve netrefs
351         self.do_netrefs(fail_if_undefined=True)
352         
353         # perform do_configure in parallel for al testbeds
354         # (it's internal configuration for each)
355         self._parallel([testbed.do_configure
356                         for testbed in self._testbeds.itervalues()])
357
358         # cross-connect (cannot be done in parallel)
359         for testbed in self._testbeds.values():
360             testbed.do_cross_connect()
361         
362         # start experiment (parallel start on all testbeds)
363         self._parallel([testbed.start
364                         for testbed in self._testbeds.itervalues()])
365
366     def _persist_testbed_proxies(self):
367         TRANSIENT = ('Recover',)
368         
369         # persist access configuration for all testbeds, so that
370         # recovery mode can reconnect to them if it becomes necessary
371         conf = ConfigParser.RawConfigParser()
372         for testbed_guid, testbed_config in self._access_config.iteritems():
373             testbed_guid = str(testbed_guid)
374             conf.add_section(testbed_guid)
375             for attr in testbed_config.attributes_name:
376                 if attr not in TRANSIENT:
377                     conf.set(testbed_guid, attr, 
378                         testbed_config.get_attribute_value(attr))
379         
380         f = open(os.path.join(self._root_dir, 'access_config.ini'), 'w')
381         conf.write(f)
382         f.close()
383     
384     def _load_testbed_proxies(self):
385         TYPEMAP = {
386             STRING : 'get',
387             INTEGER : 'getint',
388             FLOAT : 'getfloat',
389             BOOLEAN : 'getboolean',
390         }
391         
392         conf = ConfigParser.RawConfigParser()
393         conf.read(os.path.join(self._root_dir, 'access_config.ini'))
394         for testbed_guid in conf.sections():
395             testbed_config = proxy.AccessConfiguration()
396             for attr in conf.options(testbed_guid):
397                 testbed_config.set_attribute_value(attr, 
398                     conf.get(testbed_guid, attr) )
399                 
400             testbed_guid = str(testbed_guid)
401             conf.add_section(testbed_guid)
402             for attr in testbed_config.attributes_name:
403                 if attr not in TRANSIENT:
404                     getter = getattr(conf, TYPEMAP.get(
405                         testbed_config.get_attribute_type(attr),
406                         'get') )
407                     testbed_config.set_attribute_value(
408                         testbed_guid, attr, getter(attr))
409     
410     def _unpersist_testbed_proxies(self):
411         try:
412             os.remove(os.path.join(self._root_dir, 'access_config.ini'))
413         except:
414             # Just print exceptions, this is just cleanup
415             import traceback
416             traceback.print_exc(file=sys.stderr)
417
418     def stop(self):
419        for testbed in self._testbeds.values():
420            testbed.stop()
421        self._unpersist_testbed_proxies()
422    
423     def recover(self):
424         # reload perviously persisted testbed access configurations
425         self._load_testbed_proxies()
426         
427         # recreate testbed proxies by reconnecting only
428         self._create_testbed_instances(recover=True)
429
430     def is_finished(self, guid):
431         for testbed in self._testbeds.values():
432             for guid_ in testbed.guids:
433                 if guid_ == guid:
434                     return testbed.status(guid) == STATUS_FINISHED
435         raise RuntimeError("No element exists with guid %d" % guid)    
436
437     def shutdown(self):
438        for testbed in self._testbeds.values():
439            testbed.shutdown()
440
441     @staticmethod
442     def _netref_component_split(component):
443         match = COMPONENT_PATTERN.match(component)
444         if match:
445             return match.group("kind"), match.group("index")
446         else:
447             return component, None
448
449     def do_netrefs(self, fail_if_undefined = False):
450         COMPONENT_GETTERS = {
451             'addr' :
452                 lambda testbed, guid, index, name : 
453                     testbed.get_address(guid, index, name),
454             'route' :
455                 lambda testbed, guid, index, name : 
456                     testbed.get_route(guid, index, name),
457             'trace' :
458                 lambda testbed, guid, index, name : 
459                     testbed.trace(guid, index, name),
460             '' : 
461                 lambda testbed, guid, index, name : 
462                     testbed.get(TIME_NOW, guid, name),
463         }
464         
465         for (testbed_guid, guid), attrs in self._netrefs.iteritems():
466             testbed = self._testbeds[testbed_guid]
467             for name in attrs:
468                 value = testbed.get(TIME_NOW, guid, name)
469                 if isinstance(value, basestring):
470                     match = ATTRIBUTE_PATTERN_BASE.search(value)
471                     if match:
472                         label = match.group("label")
473                         if label.startswith('GUID-'):
474                             ref_guid = int(label[5:])
475                             if ref_guid:
476                                 expr = match.group("expr")
477                                 component = match.group("component")[1:] # skip the dot
478                                 attribute = match.group("attribute")
479                                 
480                                 # split compound components into component kind and index
481                                 # eg: 'addr[0]' -> ('addr', '0')
482                                 component, component_index = self._netref_component_split(component)
483                                 
484                                 # find object and resolve expression
485                                 for ref_testbed in self._testbeds.itervalues():
486                                     if component not in COMPONENT_GETTERS:
487                                         raise ValueError, "Malformed netref: %r - unknown component" % (expr,)
488                                     else:
489                                         value = COMPONENT_GETTERS[component](
490                                             ref_testbed, ref_guid, component_index, attribute)
491                                         if value: 
492                                             break
493                                 else:
494                                     # couldn't find value
495                                     if fail_if_undefined:
496                                         raise ValueError, "Unresolvable GUID: %r, in netref: %r" % (ref_guid, expr)
497
498     def _create_testbed_instances(self, recover = False):
499         parser = XmlExperimentParser()
500         data = parser.from_xml_to_data(self._experiment_xml)
501         element_guids = list()
502         label_guids = dict()
503         data_guids = data.guids
504         netrefs = self._netrefs
505         for guid in data_guids:
506             if data.is_testbed_data(guid):
507                 (testbed_id, testbed_version) = data.get_testbed_data(guid)
508                 access_config = None if guid not in self._access_config else\
509                         self._access_config[guid]
510                 
511                 if recover and access_config is None:
512                     # need to create one
513                     access_config = self._access_config[guid] = proxy.AccessConfiguration()
514                 if access_config is not None:
515                     # force recovery mode 
516                     access_config.set_attribute_value("recover",recover)
517                 
518                 testbed = proxy.create_testbed_instance(testbed_id, 
519                         testbed_version, access_config)
520                 for (name, value) in data.get_attribute_data(guid):
521                     testbed.defer_configure(name, value)
522                 self._testbeds[guid] = testbed
523             else:
524                 element_guids.append(guid)
525                 label = data.get_attribute_data(guid, "label")
526                 if label is not None:
527                     if label in label_guids:
528                         raise RuntimeError, "Label %r is not unique" % (label,)
529                     label_guids[label] = guid
530         for guid in data_guids:
531             if not data.is_testbed_data(guid):
532                 for name, value in data.get_attribute_data(guid):
533                     if isinstance(value, basestring):
534                         match = ATTRIBUTE_PATTERN_BASE.search(value)
535                         if match:
536                             label = match.group("label")
537                             if not label.startswith('GUID-'):
538                                 ref_guid = label_guids.get(label)
539                                 if ref_guid is not None:
540                                     value = ATTRIBUTE_PATTERN_BASE.sub(
541                                         ATTRIBUTE_PATTERN_GUID_SUB % dict(
542                                             guid='GUID-%d' % (ref_guid,),
543                                             expr=match.group("expr"),
544                                             label=label), 
545                                         value)
546                                     data.set_attribute_data(guid, name, value)
547                                     
548                                     # memorize which guid-attribute pairs require
549                                     # postprocessing, to avoid excessive controller-testbed
550                                     # communication at configuration time
551                                     # (which could require high-latency network I/O)
552                                     (testbed_guid, factory_id) = data.get_box_data(guid)
553                                     netrefs.setdefault((testbed_guid,guid),set()).add(name)
554         if not recover:
555             self._program_testbed_instances(element_guids, data)
556
557     def _program_testbed_instances(self, element_guids, data):
558         for guid in element_guids:
559             (testbed_guid, factory_id) = data.get_box_data(guid)
560             testbed = self._testbeds[testbed_guid]
561             testbed.defer_create(guid, factory_id)
562             for (name, value) in data.get_attribute_data(guid):
563                 testbed.defer_create_set(guid, name, value)
564
565         for guid in element_guids: 
566             (testbed_guid, factory_id) = data.get_box_data(guid)
567             testbed = self._testbeds[testbed_guid]
568             for (connector_type_name, other_guid, other_connector_type_name) \
569                     in data.get_connection_data(guid):
570                 (testbed_guid, factory_id) = data.get_box_data(guid)
571                 (other_testbed_guid, other_factory_id) = data.get_box_data(
572                         other_guid)
573                 if testbed_guid == other_testbed_guid:
574                     testbed.defer_connect(guid, connector_type_name, other_guid, 
575                         other_connector_type_name)
576                 else:
577                     testbed.defer_cross_connect(guid, connector_type_name, other_guid, 
578                         other_testbed_id, other_factory_id, other_connector_type_name)
579             for trace_id in data.get_trace_data(guid):
580                 testbed.defer_add_trace(guid, trace_id)
581             for (autoconf, address, netprefix, broadcast) in \
582                     data.get_address_data(guid):
583                 if address != None:
584                     testbed.defer_add_address(guid, address, netprefix, broadcast)
585             for (destination, netprefix, nexthop) in data.get_route_data(guid):
586                 testbed.defer_add_route(guid, destination, netprefix, nexthop)
587