b5ed5b16751fb77a1f4c44cacb52a0099e2bc2cd
[sdc/sdc-distribution-client.git] /
1 #    Licensed under the Apache License, Version 2.0 (the "License"); you may
2 #    not use this file except in compliance with the License. You may obtain
3 #    a copy of the License at
4 #
5 #         http://www.apache.org/licenses/LICENSE-2.0
6 #
7 #    Unless required by applicable law or agreed to in writing, software
8 #    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9 #    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 #    License for the specific language governing permissions and limitations
11 #    under the License.
12
13 from toscaparser.common.exception import ExceptionCollector
14 from toscaparser.common.exception import UnknownFieldError
15 from toscaparser.elements.capabilitytype import CapabilityTypeDef
16 import toscaparser.elements.interfaces as ifaces
17 from toscaparser.elements.interfaces import InterfacesDef
18 from toscaparser.elements.relationshiptype import RelationshipType
19 from toscaparser.elements.statefulentitytype import StatefulEntityType
20 from org.openecomp.sdc.toscaparser.jython.elements import JyNodeType
21
22
23 class NodeType(StatefulEntityType, JyNodeType):
24     '''TOSCA built-in node type.'''
25     SECTIONS = (DERIVED_FROM, METADATA, PROPERTIES, VERSION, DESCRIPTION, ATTRIBUTES, REQUIREMENTS, CAPABILITIES, INTERFACES, ARTIFACTS) = \
26                ('derived_from', 'metadata', 'properties', 'version',
27                 'description', 'attributes', 'requirements', 'capabilities',
28                 'interfaces', 'artifacts')
29
30     def __init__(self, ntype, custom_def=None):
31         super(NodeType, self).__init__(ntype, self.NODE_PREFIX, custom_def)
32         self.ntype = ntype
33         self.custom_def = custom_def
34         self._validate_keys()
35     
36     def getJyRequirements(self):
37         return self.requirements        
38
39     @property
40     def parent_type(self):
41         '''Return a node this node is derived from.'''
42         if not hasattr(self, 'defs'):
43             return None
44         pnode = self.derived_from(self.defs)
45         if pnode:
46             return NodeType(pnode, self.custom_def)
47
48     @property
49     def relationship(self):
50         '''Return a dictionary of relationships to other node types.
51
52         This method returns a dictionary of named relationships that nodes
53         of the current node type (self) can have to other nodes (of specific
54         types) in a TOSCA template.
55
56         '''
57         relationship = {}
58         requires = self.get_all_requirements()
59         if requires:
60             # NOTE(sdmonov): Check if requires is a dict.
61             # If it is a dict convert it to a list of dicts.
62             # This is needed because currently the code below supports only
63             # lists as requirements definition. The following check will
64             # make sure if a map (dict) was provided it will be converted to
65             # a list before proceeding to the parsing.
66             if isinstance(requires, dict):
67                 requires = [{key: value} for key, value in requires.items()]
68
69             keyword = None
70             node_type = None
71             for require in requires:
72                 for key, req in require.items():
73                     if 'relationship' in req:
74                         relation = req.get('relationship')
75                         if 'type' in relation:
76                             relation = relation.get('type')
77                         node_type = req.get('node')
78                         value = req
79                         if node_type:
80                             keyword = 'node'
81                         else:
82                             # If value is a dict and has a type key
83                             # we need to lookup the node type using
84                             # the capability type
85                             value = req
86                             if isinstance(value, dict):
87                                 captype = value['capability']
88                                 value = (self.
89                                          _get_node_type_by_cap(key, captype))
90                             relation = self._get_relation(key, value)
91                             keyword = key
92                             node_type = value
93                 rtype = RelationshipType(relation, keyword, self.custom_def)
94                 relatednode = NodeType(node_type, self.custom_def)
95                 relationship[rtype] = relatednode
96         return relationship
97
98     def _get_node_type_by_cap(self, key, cap):
99         '''Find the node type that has the provided capability
100
101         This method will lookup all node types if they have the
102         provided capability.
103         '''
104
105         # Filter the node types
106         node_types = [node_type for node_type in self.TOSCA_DEF.keys()
107                       if node_type.startswith(self.NODE_PREFIX) and
108                       node_type != 'tosca.nodes.Root']
109
110         for node_type in node_types:
111             node_def = self.TOSCA_DEF[node_type]
112             if isinstance(node_def, dict) and 'capabilities' in node_def:
113                 node_caps = node_def['capabilities']
114                 for value in node_caps.values():
115                     if isinstance(value, dict) and \
116                             'type' in value and value['type'] == cap:
117                         return node_type
118
119     def _get_relation(self, key, ndtype):
120         relation = None
121         ntype = NodeType(ndtype)
122         caps = ntype.get_capabilities()
123         if caps and key in caps.keys():
124             c = caps[key]
125             for r in self.RELATIONSHIP_TYPE:
126                 rtypedef = ntype.TOSCA_DEF[r]
127                 for properties in rtypedef.values():
128                     if c.type in properties:
129                         relation = r
130                         break
131                 if relation:
132                     break
133                 else:
134                     for properties in rtypedef.values():
135                         if c.parent_type in properties:
136                             relation = r
137                             break
138         return relation
139
140     def get_capabilities_objects(self):
141         '''Return a list of capability objects.'''
142         typecapabilities = []
143         caps = self.get_value(self.CAPABILITIES, None, True)
144         if caps:
145             # 'name' is symbolic name of the capability
146             # 'value' is a dict { 'type': <capability type name> }
147             for name, value in caps.items():
148                 ctype = value.get('type')
149                 cap = CapabilityTypeDef(name, ctype, self.type,
150                                         self.custom_def)
151                 typecapabilities.append(cap)
152         return typecapabilities
153
154     def get_capabilities(self):
155         '''Return a dictionary of capability name-objects pairs.'''
156         return {cap.name: cap
157                 for cap in self.get_capabilities_objects()}
158
159     @property
160     def requirements(self):
161         return self.get_value(self.REQUIREMENTS, None, True)
162
163     def get_all_requirements(self):
164         return self.requirements
165
166     @property
167     def interfaces(self):
168         return self.get_value(self.INTERFACES)
169
170     @property
171     def lifecycle_inputs(self):
172         '''Return inputs to life cycle operations if found.'''
173         inputs = []
174         interfaces = self.interfaces
175         if interfaces:
176             for name, value in interfaces.items():
177                 if name == ifaces.LIFECYCLE:
178                     for x, y in value.items():
179                         if x == 'inputs':
180                             for i in y.iterkeys():
181                                 inputs.append(i)
182         return inputs
183
184     @property
185     def lifecycle_operations(self):
186         '''Return available life cycle operations if found.'''
187         ops = None
188         interfaces = self.interfaces
189         if interfaces:
190             i = InterfacesDef(self.type, ifaces.LIFECYCLE)
191             ops = i.lifecycle_ops
192         return ops
193
194     def get_capability(self, name):
195         caps = self.get_capabilities()
196         if caps and name in caps.keys():
197             return caps[name].value
198
199     def get_capability_type(self, name):
200         captype = self.get_capability(name)
201         if captype and name in captype.keys():
202             return captype[name].value
203
204     def _validate_keys(self):
205         if self.defs:
206             for key in self.defs.keys():
207                 if key not in self.SECTIONS:
208                     ExceptionCollector.appendException(
209                         UnknownFieldError(what='Nodetype"%s"' % self.ntype,
210                                           field=key))