c8015cd225ac579274918204eb025406df4a5ddb
[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                 "tags": list of references to tag_id
138                 "connector_types": list of references to connector_types
139            })
140         """
141         raise NotImplementedError
142
143     @property
144     def testbed_attributes(self):
145         """ dictionary of attributes for testbed instance configuration
146             attributes_id = dict({
147                 "name": attribute name,
148                 "help": help text,
149                 "type": attribute type, 
150                 "value": default attribute value,
151                 "range": (maximum, minimun) values else None if not defined,
152                 "allowed": array of posible values,
153                 "flags": attributes flags,
154                 "validation_function": validation function for the attribute
155                 "category": category for the attribute
156              })
157             ]
158         """
159         raise NotImplementedError
160
161 class Metadata(object):
162     STANDARD_BOX_ATTRIBUTES = (
163         ("label", dict(
164             name = "label",
165             validation_function = validation.is_string,
166             type = Attribute.STRING,
167             flags = Attribute.DesignOnly,
168             help = "A unique identifier for referring to this box",
169         )),
170     )
171     
172     # Shorthand for DeploymentConfiguration
173     # Syntactic sugar to shorten stuff
174     DC = DeploymentConfiguration
175
176     STANDARD_TESTBED_ATTRIBUTES = (
177         ("home_directory", dict(
178             name = "homeDirectory",
179             validation_function = validation.is_string,
180             help = "Path to the directory where traces and other files will be stored",
181             type = Attribute.STRING,
182             value = "",
183             flags = Attribute.DesignOnly
184         )),
185     )
186     
187     DEPLOYMENT_ATTRIBUTES = (
188         # TESTBED DEPLOYMENT ATTRIBUTES
189         (DC.DEPLOYMENT_ENVIRONMENT_SETUP, dict(
190                 name = DC.DEPLOYMENT_ENVIRONMENT_SETUP,
191                 validation_function = validation.is_string,
192                 help = "Shell commands to run before spawning TestbedController processes",
193                 type = Attribute.STRING,
194                 flags = Attribute.DesignOnly,
195                 category = CATEGORY_DEPLOYMENT,
196         )),
197         (DC.DEPLOYMENT_MODE, dict(name = DC.DEPLOYMENT_MODE,
198                 help = "Instance execution mode",
199                 type = Attribute.ENUM,
200                 value = DC.MODE_SINGLE_PROCESS,
201                 allowed = [
202                     DC.MODE_DAEMON,
203                     DC.MODE_SINGLE_PROCESS
204                 ],
205                 flags = Attribute.DesignOnly,
206                 validation_function = validation.is_enum,
207                 category = CATEGORY_DEPLOYMENT,
208         )),
209         (DC.DEPLOYMENT_COMMUNICATION, dict(name = DC.DEPLOYMENT_COMMUNICATION,
210                 help = "Instance communication mode",
211                 type = Attribute.ENUM,
212                 value = DC.ACCESS_LOCAL,
213                 allowed = [
214                     DC.ACCESS_LOCAL,
215                     DC.ACCESS_SSH
216                 ],
217                 flags = Attribute.DesignOnly,
218                 validation_function = validation.is_enum,
219                 category = CATEGORY_DEPLOYMENT,
220         )),
221         (DC.DEPLOYMENT_HOST, dict(name = DC.DEPLOYMENT_HOST,
222                 help = "Host where the testbed will be executed",
223                 type = Attribute.STRING,
224                 value = "localhost",
225                 flags = Attribute.DesignOnly,
226                 validation_function = validation.is_string,
227                 category = CATEGORY_DEPLOYMENT,
228         )),
229         (DC.DEPLOYMENT_USER, dict(name = DC.DEPLOYMENT_USER,
230                 help = "User on the Host to execute the testbed",
231                 type = Attribute.STRING,
232                 value = getpass.getuser(),
233                 flags = Attribute.DesignOnly,
234                 validation_function = validation.is_string,
235                 category = CATEGORY_DEPLOYMENT,
236         )),
237         (DC.DEPLOYMENT_KEY, dict(name = DC.DEPLOYMENT_KEY,
238                 help = "Path to SSH key to use for connecting",
239                 type = Attribute.STRING,
240                 flags = Attribute.DesignOnly,
241                 validation_function = validation.is_string,
242                 category = CATEGORY_DEPLOYMENT,
243         )),
244         (DC.DEPLOYMENT_PORT, dict(name = DC.DEPLOYMENT_PORT,
245                 help = "Port on the Host",
246                 type = Attribute.INTEGER,
247                 value = 22,
248                 flags = Attribute.DesignOnly,
249                 validation_function = validation.is_integer,
250                 category = CATEGORY_DEPLOYMENT,
251         )),
252         (DC.ROOT_DIRECTORY, dict(name = DC.ROOT_DIRECTORY,
253                 help = "Root directory for storing process files",
254                 type = Attribute.STRING,
255                 value = ".",
256                 flags = Attribute.DesignOnly,
257                 validation_function = validation.is_string, # TODO: validation.is_path
258                 category = CATEGORY_DEPLOYMENT,
259         )),
260         (DC.USE_AGENT, dict(name = DC.USE_AGENT,
261                 help = "Use -A option for forwarding of the authentication agent, if ssh access is used", 
262                 type = Attribute.BOOL,
263                 value = False,
264                 flags = Attribute.DesignOnly,
265                 validation_function = validation.is_bool,
266                 category = CATEGORY_DEPLOYMENT,
267         )),
268         (DC.LOG_LEVEL, dict(name = DC.LOG_LEVEL,
269                 help = "Log level for instance",
270                 type = Attribute.ENUM,
271                 value = DC.ERROR_LEVEL,
272                 allowed = [
273                     DC.ERROR_LEVEL,
274                     DC.DEBUG_LEVEL
275                 ],
276                 flags = Attribute.DesignOnly,
277                 validation_function = validation.is_enum,
278                 category = CATEGORY_DEPLOYMENT,
279         )),
280         (DC.RECOVER, dict(name = DC.RECOVER,
281                 help = "Do not intantiate testbeds, rather, reconnect to already-running instances. Used to recover from a dead controller.", 
282                 type = Attribute.BOOL,
283                 value = False,
284                 flags = Attribute.DesignOnly,
285                 validation_function = validation.is_bool,
286                 category = CATEGORY_DEPLOYMENT,
287         )),
288     )
289     
290     STANDARD_TESTBED_ATTRIBUTES += DEPLOYMENT_ATTRIBUTES
291     
292     del DC
293     
294     
295     STANDARD_ATTRIBUTE_BUNDLES = {
296             "tun_proto" : dict({
297                 "name": "tun_proto", 
298                 "help": "TUNneling protocol used",
299                 "type": Attribute.STRING,
300                 "flags": Attribute.Invisible,
301                 "validation_function": validation.is_string,
302             }),
303             "tun_key" : dict({
304                 "name": "tun_key", 
305                 "help": "Randomly selected TUNneling protocol cryptographic key. "
306                         "Endpoints must agree to use the minimum (in lexicographic order) "
307                         "of both the remote and local sides.",
308                 "type": Attribute.STRING,
309                 "flags": Attribute.Invisible,
310                 "validation_function": validation.is_string,
311             }),
312             "tun_addr" : dict({
313                 "name": "tun_addr", 
314                 "help": "Address (IP, unix socket, whatever) of the tunnel endpoint",
315                 "type": Attribute.STRING,
316                 "flags": Attribute.Invisible,
317                 "validation_function": validation.is_string,
318             }),
319             "tun_port" : dict({
320                 "name": "tun_port", 
321                 "help": "IP port of the tunnel endpoint",
322                 "type": Attribute.INTEGER,
323                 "flags": Attribute.Invisible,
324                 "validation_function": validation.is_integer,
325             }),
326             ATTR_NEPI_TESTBED_ENVIRONMENT_SETUP : dict({
327                 "name": ATTR_NEPI_TESTBED_ENVIRONMENT_SETUP,
328                 "help": "Commands to set up the environment needed to run NEPI testbeds",
329                 "type": Attribute.STRING,
330                 "flags": Attribute.Invisible,
331                 "validation_function": validation.is_string
332             }),
333     }
334     
335
336     def __init__(self, testbed_id, version):
337         self._version = version
338         self._testbed_id = testbed_id
339         metadata_module = self._load_versioned_metadata_module()
340         self._metadata = metadata_module.VersionedMetadataInfo()
341
342     @property
343     def create_order(self):
344         return self._metadata.create_order
345
346     @property
347     def configure_order(self):
348         return self._metadata.configure_order
349
350     @property
351     def preconfigure_order(self):
352         return self._metadata.preconfigure_order
353
354     @property
355     def prestart_order(self):
356         return self._metadata.prestart_order
357
358     @property
359     def start_order(self):
360         return self._metadata.start_order
361
362     def testbed_attributes(self):
363         attributes = AttributesMap()
364
365         # standard attributes
366         self._add_standard_attributes(attributes, None, True, False,
367             self.STANDARD_TESTBED_ATTRIBUTES)
368         
369         # custom attributes - they override standard ones
370         for attr_info in self._metadata.testbed_attributes.values():
371             name = attr_info["name"]
372             help = attr_info["help"]
373             type = attr_info["type"] 
374             value = attr_info["value"] if "value" in attr_info else None
375             range = attr_info["range"] if "range" in attr_info else None
376             allowed = attr_info["allowed"] if "allowed" in attr_info else None
377             flags =  attr_info["flags"] if "flags" in attr_info \
378                     else Attribute.NoFlags
379             validation_function = attr_info["validation_function"]
380             category = attr_info["category"] if "category" in attr_info else None
381             attributes.add_attribute(name, help, type, value, 
382                     range, allowed, flags, validation_function, category)
383         
384         return attributes
385
386     def build_design_factories(self):
387         from nepi.core.design import Factory
388         factories = list()
389         for factory_id, info in self._metadata.factories_info.iteritems():
390             help = info["help"]
391             category = info["category"]
392             allow_addresses = info.get("allow_addresses", False)
393             allow_routes = info.get("allow_routes", False)
394             has_addresses = info.get("has_addresses", False)
395             has_routes = info.get("has_routes", False)
396             factory = Factory(factory_id, 
397                     allow_addresses, has_addresses,
398                     allow_routes, has_routes,
399                     help, category)
400             
401             # standard attributes
402             self._add_standard_attributes(factory, info, True, True,
403                 self.STANDARD_BOX_ATTRIBUTES)
404             
405             # custom attributes - they override standard ones
406             self._add_attributes(factory, info, "factory_attributes")
407             self._add_attributes(factory, info, "box_attributes", True)
408             
409             self._add_design_traces(factory, info)
410             self._add_tags(factory, info)
411             self._add_design_connector_types(factory, info)
412             factories.append(factory)
413         return factories
414
415     def build_execute_factories(self):
416         from nepi.core.execute import Factory
417         factories = list()
418         for factory_id, info in self._metadata.factories_info.iteritems():
419             create_function = info.get("create_function")
420             start_function = info.get("start_function")
421             stop_function = info.get("stop_function")
422             status_function = info.get("status_function")
423             configure_function = info.get("configure_function")
424             preconfigure_function = info.get("preconfigure_function")
425             prestart_function = info.get("prestart_function")
426             allow_addresses = info.get("allow_addresses", False)
427             allow_routes = info.get("allow_routes", False)
428             has_addresses = info.get("has_addresses", False)
429             has_routes = info.get("has_routes", False)
430             factory = Factory(factory_id, create_function, start_function,
431                     stop_function, status_function, 
432                     configure_function, preconfigure_function,
433                     prestart_function,
434                     allow_addresses, has_addresses,
435                     allow_routes, has_routes)
436                     
437             # standard attributes
438             self._add_standard_attributes(factory, info, False, True,
439                 self.STANDARD_BOX_ATTRIBUTES)
440             
441             # custom attributes - they override standard ones
442             self._add_attributes(factory, info, "factory_attributes")
443             self._add_attributes(factory, info, "box_attributes", True)
444             
445             self._add_execute_traces(factory, info)
446             self._add_tags(factory, info)
447             self._add_execute_connector_types(factory, info)
448             factories.append(factory)
449         return factories
450
451     def _load_versioned_metadata_module(self):
452         mod_name = "nepi.testbeds.%s.metadata_v%s" % (self._testbed_id.lower(),
453                 self._version)
454         if not mod_name in sys.modules:
455             __import__(mod_name)
456         return sys.modules[mod_name]
457
458     def _add_standard_attributes(self, factory, info, design, box, STANDARD_ATTRIBUTES):
459         if design:
460             attr_bundle = STANDARD_ATTRIBUTES
461         else:
462             # Only add non-DesignOnly attributes
463             def nonDesign(attr_info):
464                 return not (attr_info[1].get('flags',Attribute.NoFlags) & Attribute.DesignOnly)
465             attr_bundle = filter(nonDesign, STANDARD_ATTRIBUTES)
466         self._add_attributes(factory, info, None, box, 
467             attr_bundle = STANDARD_ATTRIBUTES)
468
469     def _add_attributes(self, factory, info, attr_key, box_attributes = False, attr_bundle = ()):
470         if not attr_bundle and info and attr_key in info:
471             definitions = self.STANDARD_ATTRIBUTE_BUNDLES.copy()
472             definitions.update(self._metadata.attributes)
473             attr_bundle = [ (attr_id, definitions[attr_id])
474                             for attr_id in info[attr_key] ]
475         for attr_id, attr_info in attr_bundle:
476             name = attr_info["name"]
477             help = attr_info["help"]
478             type = attr_info["type"] 
479             value = attr_info["value"] if "value" in attr_info else None
480             range = attr_info["range"] if "range" in attr_info else None
481             allowed = attr_info["allowed"] if "allowed" in attr_info \
482                     else None
483             flags = attr_info["flags"] if "flags" in attr_info \
484                     and attr_info["flags"] != None \
485                     else Attribute.NoFlags
486             validation_function = attr_info["validation_function"]
487             category = attr_info["category"] if "category" in attr_info else None
488             if box_attributes:
489                 factory.add_box_attribute(name, help, type, value, range, 
490                         allowed, flags, validation_function, category)
491             else:
492                 factory.add_attribute(name, help, type, value, range, 
493                         allowed, flags, validation_function, category)
494
495     def _add_design_traces(self, factory, info):
496         if "traces" in info:
497             for trace in info["traces"]:
498                 trace_info = self._metadata.traces[trace]
499                 trace_id = trace_info["name"]
500                 help = trace_info["help"]
501                 factory.add_trace(trace_id, help)
502
503     def _add_execute_traces(self, factory, info):
504         if "traces" in info:
505             for trace in info["traces"]:
506                 trace_info = self._metadata.traces[trace]
507                 trace_id = trace_info["name"]
508                 factory.add_trace(trace_id)
509
510     def _add_tags(self, factory, info):
511         if "tags" in info:
512             for tag_id in info["tags"]:
513                 factory.add_tag(tag_id)
514
515     def _add_design_connector_types(self, factory, info):
516         from nepi.core.design import ConnectorType
517         if "connector_types" in info:
518             connections = dict()
519             for connection in self._metadata.connections:
520                 from_ = connection["from"]
521                 to = connection["to"]
522                 can_cross = connection["can_cross"]
523                 if from_ not in connections:
524                     connections[from_] = list()
525                 if to not in connections:
526                     connections[to] = list()
527                 connections[from_].append((to, can_cross))
528                 connections[to].append((from_, can_cross))
529             for connector_id in info["connector_types"]:
530                 connector_type_info = self._metadata.connector_types[
531                         connector_id]
532                 name = connector_type_info["name"]
533                 help = connector_type_info["help"]
534                 max = connector_type_info["max"]
535                 min = connector_type_info["min"]
536                 testbed_id = self._testbed_id
537                 factory_id = factory.factory_id
538                 connector_type = ConnectorType(testbed_id, factory_id, name, 
539                         help, max, min)
540                 for (to, can_cross) in connections[(testbed_id, factory_id, 
541                         name)]:
542                     (testbed_id_to, factory_id_to, name_to) = to
543                     connector_type.add_allowed_connection(testbed_id_to, 
544                             factory_id_to, name_to, can_cross)
545                 factory.add_connector_type(connector_type)
546
547     def _add_execute_connector_types(self, factory, info):
548         from nepi.core.execute import ConnectorType
549         if "connector_types" in info:
550             from_connections = dict()
551             to_connections = dict()
552             for connection in self._metadata.connections:
553                 from_ = connection["from"]
554                 to = connection["to"]
555                 can_cross = connection["can_cross"]
556                 init_code = connection["init_code"] \
557                         if "init_code" in connection else None
558                 compl_code = connection["compl_code"] \
559                         if "compl_code" in connection else None
560                 if from_ not in from_connections:
561                     from_connections[from_] = list()
562                 if to not in to_connections:
563                     to_connections[to] = list()
564                 from_connections[from_].append((to, can_cross, init_code, 
565                     compl_code))
566                 to_connections[to].append((from_, can_cross, init_code,
567                     compl_code))
568             for connector_id in info["connector_types"]:
569                 connector_type_info = self._metadata.connector_types[
570                         connector_id]
571                 name = connector_type_info["name"]
572                 max = connector_type_info["max"]
573                 min = connector_type_info["min"]
574                 testbed_id = self._testbed_id
575                 factory_id = factory.factory_id
576                 connector_type = ConnectorType(testbed_id, factory_id, name, 
577                         max, min)
578                 connector_key = (testbed_id, factory_id, name)
579                 if connector_key in to_connections:
580                     for (from_, can_cross, init_code, compl_code) in \
581                             to_connections[connector_key]:
582                         (testbed_id_from, factory_id_from, name_from) = from_
583                         connector_type.add_from_connection(testbed_id_from, 
584                                 factory_id_from, name_from, can_cross, 
585                                 init_code, compl_code)
586                 if connector_key in from_connections:
587                     for (to, can_cross, init_code, compl_code) in \
588                             from_connections[(testbed_id, factory_id, name)]:
589                         (testbed_id_to, factory_id_to, name_to) = to
590                         connector_type.add_to_connection(testbed_id_to, 
591                                 factory_id_to, name_to, can_cross, init_code,
592                                 compl_code)
593                 factory.add_connector_type(connector_type)
594