Recovery policy for testbeds, and recovery implementation in PlanetLab.
[nepi.git] / src / nepi / core / metadata.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 from nepi.core.attributes import Attribute, AttributesMap
5 from nepi.core.connector import ConnectorType
6 from nepi.core.factory import Factory
7 import sys
8 import getpass
9 import nepi.util.environ
10 from nepi.util import tags, validation
11 from nepi.util.constants import ATTR_NEPI_TESTBED_ENVIRONMENT_SETUP, \
12         DeploymentConfiguration as DC, \
13         AttributeCategories as AC
14
15 class Parallel(object):
16     def __init__(self, factory, maxthreads = 16):
17         self.factory = factory
18         self.maxthreads = maxthreads
19
20 class MetadataInfo(object):
21     @property
22     def connector_types(self):
23         """ dictionary of dictionaries with allowed connection information.
24             connector_id: dict({
25                 "help": help text, 
26                 "name": connector type name,
27                 "max": maximum number of connections allowed (-1 for no limit),
28                 "min": minimum number of connections allowed
29             }),
30         """
31         raise NotImplementedError
32
33     @property
34     def connections(self):
35         """ array of dictionaries with allowed connection information.
36         dict({
37             "from": (testbed_id1, factory_id1, connector_type_name1),
38             "to": (testbed_id2, factory_id2, connector_type_name2),
39             "init_code": connection function to invoke for connection initiation
40             "compl_code": connection function to invoke for connection 
41                 completion
42             "can_cross": whether the connection can be done across testbed 
43                             instances
44          }),
45         """
46         raise NotImplementedError
47
48     @property
49     def attributes(self):
50         """ dictionary of dictionaries of all available attributes.
51             attribute_id: dict({
52                 "name": attribute name,
53                 "help": help text,
54                 "type": attribute type, 
55                 "value": default attribute value,
56                 "range": (maximum, minimun) values else None if not defined,
57                 "allowed": array of posible values,
58                 "flags": attributes flags,
59                 "validation_function": validation function for the attribute
60                 "category": category for the attribute
61             })
62         """
63         raise NotImplementedError
64
65     @property
66     def traces(self):
67         """ dictionary of dictionaries of all available traces.
68             trace_id: dict({
69                 "name": trace name,
70                 "help": help text
71             })
72         """
73         raise NotImplementedError
74
75     @property
76     def create_order(self):
77         """ list of factory ids that indicates the order in which the elements
78         should be instantiated. If wrapped within a Parallel instance, they
79         will be instantiated in parallel.
80         """
81         raise NotImplementedError
82
83     @property
84     def configure_order(self):
85         """ list of factory ids that indicates the order in which the elements
86         should be configured. If wrapped within a Parallel instance, they
87         will be configured in parallel.
88         """
89         raise NotImplementedError
90
91     @property
92     def preconfigure_order(self):
93         """ list of factory ids that indicates the order in which the elements
94         should be preconfigured. If wrapped within a Parallel instance, they
95         will be configured in parallel.
96         
97         Default: same as configure_order
98         """
99         return self.configure_order
100
101     @property
102     def prestart_order(self):
103         """ list of factory ids that indicates the order in which the elements
104         should be prestart-configured. If wrapped within a Parallel instance, they
105         will be configured in parallel.
106         
107         Default: same as configure_order
108         """
109         return self.configure_order
110
111     @property
112     def start_order(self):
113         """ list of factory ids that indicates the order in which the elements
114         should be started. If wrapped within a Parallel instance, they
115         will be started in parallel.
116         
117         Default: same as configure_order
118         """
119         return self.configure_order
120
121     @property
122     def factories_info(self):
123         """ dictionary of dictionaries of factory specific information
124             factory_id: dict({
125                 "help": help text,
126                 "category": category the element belongs to,
127                 "create_function": function for element instantiation,
128                 "start_function": function for element starting,
129                 "stop_function": function for element stoping,
130                 "status_function": function for retrieving element status,
131                 "preconfigure_function": function for element preconfiguration,
132                     (just after connections are made, 
133                     just before netrefs are resolved)
134                 "configure_function": function for element configuration,
135                 "prestart_function": function for pre-start
136                     element configuration (just before starting applications),
137                     useful for synchronization of background setup tasks or
138                     lazy instantiation or configuration of attributes
139                     that require connection/cross-connection state before
140                     being created.
141                     After this point, all applications should be able to run.
142                 "factory_attributes": list of references to attribute_ids,
143                 "box_attributes": list of regerences to attribute_ids,
144                 "traces": list of references to trace_id
145                 "tags": list of references to tag_id
146                 "connector_types": list of references to connector_types
147            })
148         """
149         raise NotImplementedError
150
151     @property
152     def testbed_attributes(self):
153         """ dictionary of attributes for testbed instance configuration
154             attributes_id = dict({
155                 "name": attribute name,
156                 "help": help text,
157                 "type": attribute type, 
158                 "value": default attribute value,
159                 "range": (maximum, minimun) values else None if not defined,
160                 "allowed": array of posible values,
161                 "flags": attributes flags,
162                 "validation_function": validation function for the attribute
163                 "category": category for the attribute
164              })
165             ]
166         """
167         raise NotImplementedError
168
169     @property
170     def testbed_id(self):
171         """ ID for the testbed """
172         raise NotImplementedError
173
174     @property
175     def testbed_version(self):
176         """ version for the testbed """
177         raise NotImplementedError
178
179 class Metadata(object):
180     # These attributes should be added to all boxes
181     STANDARD_BOX_ATTRIBUTES = dict({
182         "label" : dict({
183             "name" : "label",
184             "validation_function" : validation.is_string,
185             "type" : Attribute.STRING,
186             "flags" : Attribute.ExecReadOnly |\
187                     Attribute.ExecImmutable |\
188                     Attribute.Metadata,
189             "help" : "A unique identifier for referring to this box",
190         }),
191      })
192
193     # These are the attribute definitions for tagged attributes
194     STANDARD_TAGGED_ATTRIBUTES_DEFINITIONS = dict({
195         "maxAddresses" : dict({
196             "name" : "maxAddresses",
197             "validation_function" : validation.is_integer,
198             "type" : Attribute.INTEGER,
199             "value" : 1,
200             "flags" : Attribute.DesignReadOnly |\
201                     Attribute.ExecInvisible |\
202                     Attribute.Metadata,
203             "help" : "The maximum allowed number of addresses",
204             }),
205         })
206
207     # Attributes to be added to all boxes with specific tags
208     STANDARD_TAGGED_BOX_ATTRIBUTES = dict({
209         tags.ALLOW_ADDRESSES : ["maxAddresses"],
210         tags.HAS_ADDRESSES : ["maxAddresses"],
211     })
212
213     # These attributes should be added to all testbeds
214     STANDARD_TESTBED_ATTRIBUTES = dict({
215         "home_directory" : dict({
216             "name" : "homeDirectory",
217             "validation_function" : validation.is_string,
218             "help" : "Path to the directory where traces and other files will be stored",
219             "type" : Attribute.STRING,
220             "value" : "",
221             "flags" : Attribute.ExecReadOnly |\
222                     Attribute.ExecImmutable |\
223                     Attribute.Metadata,
224             }),
225         "label" : dict({
226             "name" : "label",
227             "validation_function" : validation.is_string,
228             "type" : Attribute.STRING,
229             "flags" : Attribute.ExecReadOnly |\
230                     Attribute.ExecImmutable |\
231                     Attribute.Metadata,
232             "help" : "A unique identifier for referring to this testbed",
233             }),
234         })
235     
236     # These attributes should be added to all testbeds
237     DEPLOYMENT_ATTRIBUTES = dict({
238         # TESTBED DEPLOYMENT ATTRIBUTES
239         DC.DEPLOYMENT_ENVIRONMENT_SETUP : dict({
240             "name" : DC.DEPLOYMENT_ENVIRONMENT_SETUP,
241             "validation_function" : validation.is_string,
242             "help" : "Shell commands to run before spawning TestbedController processes",
243             "type" : Attribute.STRING,
244             "flags" : Attribute.ExecReadOnly |\
245                     Attribute.ExecImmutable |\
246                     Attribute.Metadata,
247             "category" : AC.CATEGORY_DEPLOYMENT,
248         }),
249         DC.DEPLOYMENT_MODE: dict({
250             "name" : DC.DEPLOYMENT_MODE,
251             "help" : "Instance execution mode",
252             "type" : Attribute.ENUM,
253             "value" : DC.MODE_SINGLE_PROCESS,
254             "allowed" : [
255                     DC.MODE_DAEMON,
256                     DC.MODE_SINGLE_PROCESS
257                 ],
258            "flags" : Attribute.ExecReadOnly |\
259                     Attribute.ExecImmutable |\
260                     Attribute.Metadata,
261             "validation_function" : validation.is_enum,
262             "category" : AC.CATEGORY_DEPLOYMENT,
263             }),
264         DC.DEPLOYMENT_COMMUNICATION : dict({
265             "name" : DC.DEPLOYMENT_COMMUNICATION,
266             "help" : "Instance communication mode",
267             "type" : Attribute.ENUM,
268             "value" : DC.ACCESS_LOCAL,
269             "allowed" : [
270                     DC.ACCESS_LOCAL,
271                     DC.ACCESS_SSH
272                 ],
273             "flags" : Attribute.ExecReadOnly |\
274                     Attribute.ExecImmutable |\
275                     Attribute.Metadata,
276             "validation_function" : validation.is_enum,
277             "category" : AC.CATEGORY_DEPLOYMENT,
278             }),
279         DC.DEPLOYMENT_HOST : dict({
280             "name" : DC.DEPLOYMENT_HOST,
281             "help" : "Host where the testbed will be executed",
282             "type" : Attribute.STRING,
283             "value" : "localhost",
284             "flags" : Attribute.ExecReadOnly |\
285                     Attribute.ExecImmutable |\
286                     Attribute.Metadata,
287             "validation_function" : validation.is_string,
288             "category" : AC.CATEGORY_DEPLOYMENT,
289             }),
290         DC.DEPLOYMENT_USER : dict({
291             "name" : DC.DEPLOYMENT_USER,
292             "help" : "User on the Host to execute the testbed",
293             "type" : Attribute.STRING,
294             "value" : getpass.getuser(),
295             "flags" : Attribute.ExecReadOnly |\
296                     Attribute.ExecImmutable |\
297                     Attribute.Metadata,
298             "validation_function" : validation.is_string,
299             "category" : AC.CATEGORY_DEPLOYMENT,
300             }),
301         DC.DEPLOYMENT_KEY : dict({
302             "name" : DC.DEPLOYMENT_KEY,
303             "help" : "Path to SSH key to use for connecting",
304             "type" : Attribute.STRING,
305             "flags" : Attribute.ExecReadOnly |\
306                     Attribute.ExecImmutable |\
307                     Attribute.Metadata,
308             "validation_function" : validation.is_string,
309             "category" : AC.CATEGORY_DEPLOYMENT,
310             }),
311         DC.DEPLOYMENT_PORT : dict({
312             "name" : DC.DEPLOYMENT_PORT,
313             "help" : "Port on the Host",
314             "type" : Attribute.INTEGER,
315             "value" : 22,
316             "flags" : Attribute.ExecReadOnly |\
317                     Attribute.ExecImmutable |\
318                     Attribute.Metadata,
319             "validation_function" : validation.is_integer,
320             "category" : AC.CATEGORY_DEPLOYMENT,
321             }),
322         DC.ROOT_DIRECTORY : dict({
323             "name" : DC.ROOT_DIRECTORY,
324             "help" : "Root directory for storing process files",
325             "type" : Attribute.STRING,
326             "value" : ".",
327             "flags" : Attribute.ExecReadOnly |\
328                     Attribute.ExecImmutable |\
329                     Attribute.Metadata,
330             "validation_function" : validation.is_string, # TODO: validation.is_path
331             "category" : AC.CATEGORY_DEPLOYMENT,
332             }),
333         DC.USE_AGENT : dict({
334             "name" : DC.USE_AGENT,
335             "help" : "Use -A option for forwarding of the authentication agent, if ssh access is used", 
336             "type" : Attribute.BOOL,
337             "value" : False,
338             "flags" : Attribute.ExecReadOnly |\
339                     Attribute.ExecImmutable |\
340                     Attribute.Metadata,
341             "validation_function" : validation.is_bool,
342             "category" : AC.CATEGORY_DEPLOYMENT,
343             }),
344         DC.LOG_LEVEL : dict({
345             "name" : DC.LOG_LEVEL,
346             "help" : "Log level for instance",
347             "type" : Attribute.ENUM,
348             "value" : DC.ERROR_LEVEL,
349             "allowed" : [
350                     DC.ERROR_LEVEL,
351                     DC.DEBUG_LEVEL
352                 ],
353             "flags" : Attribute.ExecReadOnly |\
354                     Attribute.ExecImmutable |\
355                     Attribute.Metadata,
356             "validation_function" : validation.is_enum,
357             "category" : AC.CATEGORY_DEPLOYMENT,
358             }),
359         DC.RECOVERY_POLICY : dict({
360             "name" : DC.RECOVERY_POLICY,
361             "help" : "Specifies what action to take in the event of a failure.", 
362             "type" : Attribute.ENUM,
363             "value" : DC.POLICY_FAIL,
364             "allowed" : [
365                     DC.POLICY_FAIL,
366                     DC.POLICY_RECOVER,
367                     DC.POLICY_RESTART,
368                 ],
369             "flags" : Attribute.ExecReadOnly |\
370                     Attribute.ExecImmutable |\
371                     Attribute.Metadata,
372             "validation_function" : validation.is_enum,
373             "category" : AC.CATEGORY_DEPLOYMENT,
374             }),
375         })
376     PROXY_ATTRIBUTES = dict({
377         DC.RECOVER : dict({
378             "name" : DC.RECOVER,
379             "help" : "Do not intantiate testbeds, rather, reconnect to already-running instances. Used to recover from a dead controller.", 
380             "type" : Attribute.BOOL,
381             "value" : False,
382             "flags" : Attribute.ExecReadOnly |\
383                     Attribute.ExecImmutable |\
384                     Attribute.Metadata,
385             "validation_function" : validation.is_bool,
386             "category" : AC.CATEGORY_DEPLOYMENT,
387             }),
388         })
389     PROXY_ATTRIBUTES.update(DEPLOYMENT_ATTRIBUTES)
390   
391     # These attributes could appear in the boxes attribute list
392     STANDARD_BOX_ATTRIBUTE_DEFINITIONS = dict({
393         "tun_proto" : dict({
394             "name" : "tun_proto", 
395             "help" : "TUNneling protocol used",
396             "type" : Attribute.STRING,
397             "flags" : Attribute.DesignInvisible | \
398                     Attribute.ExecInvisible | \
399                     Attribute.ExecImmutable | \
400                     Attribute.Metadata,
401             "validation_function" : validation.is_string,
402             }),
403         "tun_key" : dict({
404             "name" : "tun_key", 
405             "help" : "Randomly selected TUNneling protocol cryptographic key. "
406                      "Endpoints must agree to use the minimum (in lexicographic order) "
407                      "of both the remote and local sides.",
408             "type" : Attribute.STRING,
409             "flags" : Attribute.DesignInvisible | \
410                     Attribute.ExecInvisible | \
411                     Attribute.ExecImmutable | \
412                     Attribute.Metadata,
413             "validation_function" : validation.is_string,
414             }),
415         "tun_addr" : dict({
416             "name": "tun_addr", 
417             "help" : "Address (IP, unix socket, whatever) of the tunnel endpoint",
418             "type" : Attribute.STRING,
419             "flags" : Attribute.DesignInvisible | \
420                     Attribute.ExecInvisible | \
421                     Attribute.ExecImmutable | \
422                     Attribute.Metadata,
423             "validation_function" : validation.is_string,
424             }),
425         "tun_port" : dict({
426             "name" : "tun_port", 
427             "help" : "IP port of the tunnel endpoint",
428             "type" : Attribute.INTEGER,
429             "flags" : Attribute.DesignInvisible | \
430                     Attribute.ExecInvisible | \
431                     Attribute.ExecImmutable | \
432                     Attribute.Metadata,
433             "validation_function" : validation.is_integer,
434             }),
435         ATTR_NEPI_TESTBED_ENVIRONMENT_SETUP : dict({
436             "name" : ATTR_NEPI_TESTBED_ENVIRONMENT_SETUP,
437             "help" : "Commands to set up the environment needed to run NEPI testbeds",
438             "type" : Attribute.STRING,
439             "flags" : Attribute.DesignInvisible | \
440                     Attribute.ExecInvisible | \
441                     Attribute.ExecImmutable | \
442                     Attribute.Metadata,
443             "validation_function" : validation.is_string
444             }),
445         })
446     
447     STANDARD_TESTBED_ATTRIBUTES.update(DEPLOYMENT_ATTRIBUTES.copy())
448
449     def __init__(self, testbed_id):
450         self._testbed_id = testbed_id
451         metadata_module = self._load_metadata_module()
452         self._metadata = metadata_module.MetadataInfo()
453         if testbed_id != self._metadata.testbed_id:
454             raise RuntimeError("Bad testbed id. Asked for %s, got %s" % \
455                     (testbed_id, self._metadata.testbed_id ))
456
457     @property
458     def create_order(self):
459         return self._metadata.create_order
460
461     @property
462     def configure_order(self):
463         return self._metadata.configure_order
464
465     @property
466     def preconfigure_order(self):
467         return self._metadata.preconfigure_order
468
469     @property
470     def prestart_order(self):
471         return self._metadata.prestart_order
472
473     @property
474     def start_order(self):
475         return self._metadata.start_order
476
477     @property
478     def testbed_version(self):
479         return self._metadata.testbed_version
480
481     @property
482     def testbed_id(self):
483         return self._testbed_id
484     
485     @property
486     def supported_recovery_policies(self):
487         return self._metadata.supported_recovery_policies
488
489     def testbed_attributes(self):
490         attributes = AttributesMap()
491         testbed_attributes = self._testbed_attributes()
492         self._add_attributes(attributes.add_attribute, testbed_attributes)
493         return attributes
494
495     def build_factories(self):
496         factories = list()
497         for factory_id, info in self._metadata.factories_info.iteritems():
498             create_function = info.get("create_function")
499             start_function = info.get("start_function")
500             stop_function = info.get("stop_function")
501             status_function = info.get("status_function")
502             configure_function = info.get("configure_function")
503             preconfigure_function = info.get("preconfigure_function")
504             prestart_function = info.get("prestart_function")
505             help = info["help"]
506             category = info["category"]
507             factory = Factory(factory_id, 
508                     create_function, 
509                     start_function,
510                     stop_function, 
511                     status_function, 
512                     configure_function, 
513                     preconfigure_function,
514                     prestart_function,
515                     help,
516                     category)
517                     
518             factory_attributes = self._factory_attributes(info)
519             self._add_attributes(factory.add_attribute, factory_attributes)
520             box_attributes = self._box_attributes(info)
521             self._add_attributes(factory.add_box_attribute, box_attributes)
522             
523             self._add_traces(factory, info)
524             self._add_tags(factory, info)
525             self._add_connector_types(factory, info)
526             factories.append(factory)
527         return factories
528
529     def _load_metadata_module(self):
530         mod_name = nepi.util.environ.find_testbed(self._testbed_id) + ".metadata"
531         if not mod_name in sys.modules:
532             __import__(mod_name)
533         return sys.modules[mod_name]
534
535     def _testbed_attributes(self):
536         # standar attributes
537         attributes = self.STANDARD_TESTBED_ATTRIBUTES.copy()
538         # custom attributes
539         attributes.update(self._metadata.testbed_attributes.copy())
540         return attributes
541         
542     def _factory_attributes(self, info):
543         tagged_attributes = self._tagged_attributes(info)
544         if "factory_attributes" in info:
545             definitions = self._metadata.attributes.copy()
546             # filter attributes corresponding to the factory_id
547             factory_attributes = self._filter_attributes(info["factory_attributes"], 
548                 definitions)
549         else:
550             factory_attributes = dict()
551         attributes = dict(tagged_attributes.items() + \
552                 factory_attributes.items())
553         return attributes
554
555     def _box_attributes(self, info):
556         tagged_attributes = self._tagged_attributes(info)
557         if "box_attributes" in info:
558             definitions = self.STANDARD_BOX_ATTRIBUTE_DEFINITIONS.copy()
559             definitions.update(self._metadata.attributes)
560             box_attributes = self._filter_attributes(info["box_attributes"], 
561                 definitions)
562         else:
563             box_attributes = dict()
564         attributes = dict(tagged_attributes.items() + \
565                 box_attributes.items())
566         attributes.update(self.STANDARD_BOX_ATTRIBUTES.copy())
567         return attributes
568
569     def _tagged_attributes(self, info):
570         tagged_attributes = dict()
571         for tag_id in info.get("tags", []):
572             if tag_id in self.STANDARD_TAGGED_BOX_ATTRIBUTES:
573                 attr_list = self.STANDARD_TAGGED_BOX_ATTRIBUTES[tag_id]
574                 attributes = self._filter_attributes(attr_list,
575                     self.STANDARD_TAGGED_ATTRIBUTES_DEFINITIONS)
576                 tagged_attributes.update(attributes)
577         return tagged_attributes
578
579     def _filter_attributes(self, attr_list, definitions):
580         # filter attributes not corresponding to the factory
581         attributes = dict((attr_id, definitions[attr_id]) \
582            for attr_id in attr_list)
583         return attributes
584
585     def _add_attributes(self, add_attr_func, attributes):
586         for attr_id, attr_info in attributes.iteritems():
587             name = attr_info["name"]
588             help = attr_info["help"]
589             type = attr_info["type"] 
590             value = attr_info.get("value")
591             range = attr_info.get("range")
592             allowed = attr_info.get("allowed")
593             flags = attr_info.get("flags")
594             validation_function = attr_info["validation_function"]
595             category = attr_info.get("category")
596             add_attr_func(name, help, type, value, range, allowed, flags, 
597                     validation_function, category)
598
599     def _add_traces(self, factory, info):
600         for trace_id in info.get("traces", []):
601             trace_info = self._metadata.traces[trace_id]
602             name = trace_info["name"]
603             help = trace_info["help"]
604             factory.add_trace(name, help)
605
606     def _add_tags(self, factory, info):
607         for tag_id in info.get("tags", []):
608             factory.add_tag(tag_id)
609
610     def _add_connector_types(self, factory, info):
611         if "connector_types" in info:
612             from_connections = dict()
613             to_connections = dict()
614             for connection in self._metadata.connections:
615                 from_ = connection["from"]
616                 to = connection["to"]
617                 can_cross = connection["can_cross"]
618                 init_code = connection.get("init_code")
619                 compl_code = connection.get("compl_code")
620                 if from_ not in from_connections:
621                     from_connections[from_] = list()
622                 if to not in to_connections:
623                     to_connections[to] = list()
624                 from_connections[from_].append((to, can_cross, init_code, 
625                     compl_code))
626                 to_connections[to].append((from_, can_cross, init_code,
627                     compl_code))
628             for connector_id in info["connector_types"]:
629                 connector_type_info = self._metadata.connector_types[
630                         connector_id]
631                 name = connector_type_info["name"]
632                 help = connector_type_info["help"]
633                 max = connector_type_info["max"]
634                 min = connector_type_info["min"]
635                 testbed_id = self._testbed_id
636                 factory_id = factory.factory_id
637                 connector_type = ConnectorType(testbed_id, factory_id, name, 
638                         help, max, min)
639                 connector_key = (testbed_id, factory_id, name)
640                 if connector_key in to_connections:
641                     for (from_, can_cross, init_code, compl_code) in \
642                             to_connections[connector_key]:
643                         (testbed_id_from, factory_id_from, name_from) = from_
644                         connector_type.add_from_connection(testbed_id_from, 
645                                 factory_id_from, name_from, can_cross, 
646                                 init_code, compl_code)
647                 if connector_key in from_connections:
648                     for (to, can_cross, init_code, compl_code) in \
649                             from_connections[(testbed_id, factory_id, name)]:
650                         (testbed_id_to, factory_id_to, name_to) = to
651                         connector_type.add_to_connection(testbed_id_to, 
652                                 factory_id_to, name_to, can_cross, init_code,
653                                 compl_code)
654                 factory.add_connector_type(connector_type)
655