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