TOSCA to YANG Translator Initial commit
[osm/SO.git] / common / python / rift / mano / tosca_translator / rwmano / tosca / tosca_nfv_vnf.py
1 #
2 # Copyright 2016 RIFT.io Inc
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 #
16
17
18 from rift.mano.tosca_translator.common.utils import _
19 from rift.mano.tosca_translator.common.utils import convert_keys_to_python
20 from rift.mano.tosca_translator.rwmano.syntax.mano_resource import ManoResource
21 from toscaparser.functions import GetInput
22
23 from toscaparser.common.exception import ValidationError
24
25 try:
26 import gi
27 gi.require_version('RwVnfdYang', '1.0')
28
29 from gi.repository import RwVnfdYang
30 except ImportError:
31 pass
32 except ValueError:
33 pass
34
35
36 # Name used to dynamically load appropriate map class.
37 TARGET_CLASS_NAME = 'ToscaNfvVnf'
38
39
40 class ToscaNfvVnf(ManoResource):
41 '''Translate TOSCA node type tosca.nodes.nfv.vnf.'''
42
43 toscatype = 'tosca.nodes.nfv.VNF'
44
45 REQUIRED_PROPS = ['name', 'short-name', 'id', 'short-name', 'description',
46 'mgmt-interface']
47 OPTIONAL_PROPS = ['version', 'vendor', 'http-endpoint', 'monitoring-param',
48 'connection-point']
49 IGNORE_PROPS = ['port', 'monitoring_param']
50 TOSCA_CAPS = ['mgmt_interface', 'http_endpoint', 'monitoring_param_0',
51 'monitoring_param_1', 'connection_point']
52
53 def __init__(self, log, nodetemplate, metadata=None):
54 super(ToscaNfvVnf, self).__init__(log,
55 nodetemplate,
56 type_="vnfd",
57 metadata=metadata)
58 self._const_vnfd = {}
59 self._vnf_config = {}
60 self._vdus = []
61 self._policies = []
62 self._cps = []
63 self.vnf_type = nodetemplate.type
64 self._reqs = {}
65
66 def map_tosca_name_to_mano(self, name):
67 new_name = super().map_tosca_name_to_mano(name)
68 if new_name.startswith('monitoring-param'):
69 new_name = 'monitoring-param'
70 if new_name == 'polling-interval':
71 new_name = 'polling_interval_secs'
72 return new_name
73
74 def handle_properties(self):
75 tosca_props = self.get_tosca_props()
76 self.log.debug(_("VNF {0} with tosca properties: {1}").
77 format(self.name, tosca_props))
78
79 def get_vnf_config(config):
80 vnf_config = {}
81 for key, value in config.items():
82 new_key = self.map_tosca_name_to_mano(key)
83 if isinstance(value, dict):
84 sub_config = {}
85 for subkey, subvalue in value.items():
86 sub_config[self.map_tosca_name_to_mano(subkey)] = \
87 subvalue
88 vnf_config[new_key] = sub_config
89 else:
90 vnf_config[new_key] = value
91
92 if vnf_config['config-type'] != 'script':
93 err_msg = _("{}, Only script config supported "
94 "for now: {}"). \
95 format(self, vnf_config['config-type'])
96 self.log.error(err_msg)
97 raise ValidationError(message=err_msg)
98
99 # Replace config-details with actual name (config-type)
100 if ('config-type' in vnf_config and
101 'config-details' in vnf_config):
102 vnf_config[vnf_config['config-type']] = \
103 vnf_config.pop('config-details')
104 vnf_config.pop('config-type')
105
106 # Update config-delay and confgig-priortiy to correct struct
107 vnf_config['config-attributes'] = {}
108 if 'config-delay' in vnf_config:
109 vnf_config['config-attributes']['config-delay'] = \
110 vnf_config.pop('config-delay')
111 else:
112 vnf_config['config-attributes']['config-delay'] = 0
113 if 'config-priority' in vnf_config:
114 vnf_config['config-attributes']['config-priority'] = \
115 vnf_config.pop('config-priority')
116 return vnf_config
117
118 vnf_props = {}
119 for key, value in tosca_props.items():
120 if key == 'id':
121 self._const_vnfd['member-vnf-index'] = int(value)
122 self._const_vnfd['vnfd-id-ref'] = self.id
123 elif key == 'vnf_configuration':
124 self._vnf_config = get_vnf_config(value)
125 else:
126 vnf_props[key] = value
127
128 if 'name' not in vnf_props:
129 vnf_props['name'] = self.name
130
131 if 'short-name' not in vnf_props:
132 vnf_props['short-name'] = self.name
133
134 if 'id' not in vnf_props:
135 vnf_props['id'] = self.id
136
137 if 'vendor' not in vnf_props:
138 vnf_props['vendor'] = self.vendor
139
140 if 'description' not in vnf_props:
141 vnf_props['description'] = self.description
142
143 if 'start_by_default' in vnf_props:
144 self._const_vnfd['start-by-default'] = \
145 vnf_props.pop('start_by_default')
146 if 'logo' in self.metadata:
147 vnf_props['logo'] = self.metadata['logo']
148
149 self.log.debug(_("VNF {0} with constituent vnf: {1}").
150 format(self.name, self._const_vnfd))
151 self.log.debug(_("VNF {0} with properties: {1}").
152 format(self.name, vnf_props))
153 self.properties = vnf_props
154
155 def handle_capabilities(self):
156 tosca_caps = self.get_tosca_caps()
157 self.log.debug(_("VDU {0} tosca capabilites: {1}").
158 format(self.name, tosca_caps))
159
160 def get_props(props):
161 properties = {}
162 for key in props.keys():
163 value = props[key]
164 if isinstance(value, dict):
165 if 'get_property' in value:
166 val = self.get_property(value['get_property'])
167 value = val
168 properties[self.map_tosca_name_to_mano(key)] = value
169 return properties
170
171 for key, value in tosca_caps.items():
172 if key in ToscaNfvVnf.TOSCA_CAPS:
173 new_key = self.map_tosca_name_to_mano(key)
174 props = get_props(value)
175 if 'id' in props:
176 props['id'] = str(props['id'])
177 if 'protocol' in props:
178 props.pop('protocol')
179
180 # There is only one instance of mgmt interface, but others
181 # are a list
182 if key == 'mgmt_interface':
183 self.properties[new_key] = props
184 elif key == 'http_endpoint':
185 if new_key not in self.properties:
186 self.properties[new_key] = []
187 self.properties[new_key].append(props)
188 else:
189 if new_key not in self.properties:
190 self.properties[new_key] = []
191 self.properties[new_key].append(props)
192
193 self.log.debug(_("VDU {0} properties: {1}").
194 format(self.name, self.properties))
195
196 def handle_requirements(self, nodes, policies, vnf_type_to_vdus_map):
197 tosca_reqs = self.get_tosca_reqs()
198 for req in tosca_reqs:
199 for key, value in req.items():
200 if 'target' in value:
201 self._reqs[key] = value['target']
202
203 for policy in policies:
204 if hasattr(policy, '_vnf_name') and policy._vnf_name == self.name:
205 self._policies.append(policy)
206
207
208 if self.vnf_type in vnf_type_to_vdus_map:
209 for vdu_node_name in vnf_type_to_vdus_map[self.vnf_type]:
210 node = self.get_node_with_name(vdu_node_name, nodes)
211 if node:
212 self._vdus.append(node)
213 node._vnf = self
214 # Add the VDU id to mgmt-intf
215 if 'mgmt-interface' in self.properties:
216 self.properties['mgmt-interface']['vdu-id'] = \
217 node.id
218 if 'vdu' in self.properties['mgmt-interface']:
219 # Older yang
220 self.properties['mgmt-interface'].pop('vdu')
221 else:
222 err_msg = _("VNF {0}, VDU {1} specified not found"). \
223 format(self.name, target)
224 self.log.error(err_msg)
225 raise ValidationError(message=err_msg)
226
227 def generate_yang_model_gi(self, nsd, vnfds):
228 vnfd_cat = RwVnfdYang.YangData_Vnfd_VnfdCatalog()
229 vnfd = vnfd_cat.vnfd.add()
230 props = convert_keys_to_python(self.properties)
231 for key in ToscaNfvVnf.IGNORE_PROPS:
232 if key in props:
233 props.pop(key)
234 try:
235 vnfd.from_dict(props)
236 except Exception as e:
237 err_msg = _("{0} Exception updating vnfd from dict {1}: {2}"). \
238 format(self, props, e)
239 self.log.error(err_msg)
240 raise e
241 vnfds.append(vnfd_cat)
242
243 # Update the VDU properties
244 for vdu in self._vdus:
245 vdu.generate_yang_submodel_gi(vnfd)
246 for policy in self._policies:
247 policy.generate_yang_submodel_gi(vnfd)
248
249 # Update constituent vnfd in nsd
250 try:
251 props = convert_keys_to_python(self._const_vnfd)
252 nsd.constituent_vnfd.add().from_dict(props)
253 except Exception as e:
254 err_msg = _("{0} Exception constituent vnfd from dict {1}: {2}"). \
255 format(self, props, e)
256 self.log.error(err_msg)
257 raise e
258
259 # Update the vnf configuration info in mgmt_interface
260 props = convert_keys_to_python(self._vnf_config)
261 try:
262 vnfd.vnf_configuration.from_dict(props)
263 except Exception as e:
264 err_msg = _("{0} Exception vnfd mgmt intf from dict {1}: {2}"). \
265 format(self, props, e)
266 self.log.error(err_msg)
267 raise e
268
269 def generate_yang_model(self, nsd, vnfds, use_gi=False):
270 """Generate yang model for the node"""
271 self.log.debug(_("Generate YANG model for {0}").
272 format(self))
273
274 for key in ToscaNfvVnf.IGNORE_PROPS:
275 if key in self.properties:
276 self.properties.pop(key)
277
278 if use_gi:
279 return self.generate_yang_model_gi(nsd, vnfds)
280
281 vnfd = {}
282 vnfd.update(self.properties)
283 # Update vnf configuration on mgmt interface
284 vnfd['mgmt-interface']['vnf-configuration'] = self._vnf_config
285
286 # Update the VDU properties
287 vnfd['vdu'] = []
288 for vdu in self._vdus:
289 vnfd['vdu'].append(vdu.generate_yang_submodel())
290
291 vnfds.append(vnfd)
292
293 # Update constituent vnfd in nsd
294 if 'constituent-vnfd' not in nsd:
295 nsd['constituent-vnfd'] = []
296 nsd['constituent-vnfd'].append(self._const_vnfd)
297
298 def get_member_vnf_index(self):
299 return self._const_vnfd['member-vnf-index']
300
301 def get_supporting_files(self, files, desc_id=None):
302 files[self.id] = []
303 for vdu in self._vdus:
304 if vdu.image:
305 files[self.id].append({
306 'type': 'image',
307 'name': vdu.image,
308 },)
309 if vdu.cloud_init:
310 files[self.id].append({
311 'type': 'cloud_init',
312 'name': vdu.cloud_init,
313 },)