Bug 240 - NS Scaling
[osm/SO.git] / models / openmano / python / rift / openmano / rift2openmano.py
1 #!/usr/bin/env python3
2
3 #
4 # Copyright 2016 RIFT.IO Inc
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17 #
18
19 import argparse
20 import collections
21 import logging
22 import math
23 import os
24 import sys
25 import tempfile
26 import yaml
27
28 import gi
29 gi.require_version('RwYang', '1.0')
30 gi.require_version('RwVnfdYang', '1.0')
31 gi.require_version('RwNsdYang', '1.0')
32
33 from gi.repository import (
34 RwYang,
35 RwVnfdYang,
36 RwNsdYang,
37 )
38
39 import rift.package.store
40 import rift.package.cloud_init
41
42 logger = logging.getLogger("rift2openmano.py")
43
44
45 class VNFNotFoundError(Exception):
46 pass
47
48
49 class RiftNSD(object):
50 model = RwYang.Model.create_libncx()
51 model.load_module('nsd')
52 model.load_module('rw-nsd')
53
54 def __init__(self, descriptor):
55 self._nsd = descriptor
56
57 def __str__(self):
58 return str(self._nsd)
59
60 @property
61 def name(self):
62 return self._nsd.name
63
64 @property
65 def id(self):
66 return self._nsd.id
67
68 @property
69 def vnfd_ids(self):
70 return [c.vnfd_id_ref for c in self._nsd.constituent_vnfd]
71
72 @property
73 def constituent_vnfds(self):
74 return self._nsd.constituent_vnfd
75
76 @property
77 def scaling_group_descriptor(self):
78 return self._nsd.scaling_group_descriptor
79
80 @property
81 def vlds(self):
82 return self._nsd.vld
83
84 @property
85 def cps(self):
86 return self._nsd.connection_point
87
88 @property
89 def description(self):
90 return self._nsd.description
91
92 @classmethod
93 def from_xml_file_hdl(cls, hdl):
94 hdl.seek(0)
95 descriptor = RwNsdYang.YangData_Nsd_NsdCatalog_Nsd()
96 descriptor.from_xml_v2(RiftNSD.model, hdl.read())
97 return cls(descriptor)
98
99 @classmethod
100 def from_yaml_file_hdl(cls, hdl):
101 hdl.seek(0)
102 descriptor = RwNsdYang.YangData_Nsd_NsdCatalog_Nsd()
103 descriptor.from_yaml(RiftNSD.model, hdl.read())
104 return cls(descriptor)
105
106 @classmethod
107 def from_dict(cls, nsd_dict):
108 descriptor = RwNsdYang.YangData_Nsd_NsdCatalog_Nsd.from_dict(nsd_dict)
109 return cls(descriptor)
110
111
112 class RiftVNFD(object):
113 model = RwYang.Model.create_libncx()
114 model.load_module('vnfd')
115 model.load_module('rw-vnfd')
116
117 def __init__(self, descriptor):
118 self._vnfd = descriptor
119
120 def __str__(self):
121 return str(self._vnfd)
122
123 @property
124 def id(self):
125 return self._vnfd.id
126
127 @property
128 def name(self):
129 return self._vnfd.name
130
131 @property
132 def description(self):
133 return self._vnfd.description
134
135 @property
136 def cps(self):
137 return self._vnfd.connection_point
138
139 @property
140 def vdus(self):
141 return self._vnfd.vdu
142
143 @property
144 def internal_vlds(self):
145 return self._vnfd.internal_vld
146
147 @classmethod
148 def from_xml_file_hdl(cls, hdl):
149 hdl.seek(0)
150 descriptor = RwVnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd()
151 descriptor.from_xml_v2(RiftVNFD.model, hdl.read())
152 return cls(descriptor)
153
154 @classmethod
155 def from_yaml_file_hdl(cls, hdl):
156 hdl.seek(0)
157 descriptor = RwVnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd()
158 descriptor.from_yaml(RiftVNFD.model, hdl.read())
159 return cls(descriptor)
160
161 @classmethod
162 def from_dict(cls, vnfd_dict):
163 descriptor = RwVnfdYang.YangData_Vnfd_VnfdCatalog_Vnfd.from_dict(vnfd_dict)
164 return cls(descriptor)
165
166
167 def is_writable_directory(dir_path):
168 """ Returns True if dir_path is writable, False otherwise
169
170 Arguments:
171 dir_path - A directory path
172 """
173 if not os.path.exists(dir_path):
174 raise ValueError("Directory does not exist: %s", dir_path)
175
176 try:
177 testfile = tempfile.TemporaryFile(dir=dir_path)
178 testfile.close()
179 except OSError:
180 return False
181
182 return True
183
184
185 def create_vnfd_from_files(vnfd_file_hdls):
186 """ Create a list of RiftVNFD instances from xml/yaml file handles
187
188 Arguments:
189 vnfd_file_hdls - Rift VNFD XML/YAML file handles
190
191 Returns:
192 A list of RiftVNFD instances
193 """
194 vnfd_dict = {}
195 for vnfd_file_hdl in vnfd_file_hdls:
196 if vnfd_file_hdl.name.endswith("yaml") or vnfd_file_hdl.name.endswith("yaml"):
197 vnfd = RiftVNFD.from_yaml_file_hdl(vnfd_file_hdl)
198 else:
199 vnfd = RiftVNFD.from_xml_file_hdl(vnfd_file_hdl)
200 vnfd_dict[vnfd.id] = vnfd
201
202 return vnfd_dict
203
204
205 def create_nsd_from_file(nsd_file_hdl):
206 """ Create a list of RiftNSD instances from yaml/xml file handles
207
208 Arguments:
209 nsd_file_hdls - Rift NSD XML/yaml file handles
210
211 Returns:
212 A list of RiftNSD instances
213 """
214 if nsd_file_hdl.name.endswith("yaml") or nsd_file_hdl.name.endswith("yaml"):
215 nsd = RiftNSD.from_yaml_file_hdl(nsd_file_hdl)
216 else:
217 nsd = RiftNSD.from_xml_file_hdl(nsd_file_hdl)
218 return nsd
219
220
221 def ddict():
222 return collections.defaultdict(dict)
223
224 def convert_vnfd_name(vnfd_name, member_idx):
225 return vnfd_name + "__" + str(member_idx)
226
227
228 def rift2openmano_nsd(rift_nsd, rift_vnfds, openmano_vnfd_ids, rift_vnfd_id=None):
229 if rift_vnfd_id is None:
230 for vnfd_id in rift_nsd.vnfd_ids:
231 if vnfd_id not in rift_vnfds:
232 raise VNFNotFoundError("VNF id %s not provided" % vnfd_id)
233
234 openmano = {}
235 openmano["name"] = rift_nsd.name
236 if rift_vnfd_id is not None:
237 for scaling_groups in rift_nsd.scaling_group_descriptor:
238 openmano["name"] += scaling_groups.name
239 openmano["description"] = rift_nsd.description
240 topology = {}
241 openmano["topology"] = topology
242
243 topology["nodes"] = {}
244 for vnfd in rift_nsd.constituent_vnfds:
245 vnfd_id = vnfd.vnfd_id_ref
246 if rift_vnfd_id is not None and rift_vnfd_id != vnfd_id:
247 continue
248 rift_vnfd = rift_vnfds[vnfd_id]
249 member_idx = vnfd.member_vnf_index
250 openmano_vnfd_id = openmano_vnfd_ids.get(vnfd_id,None)
251 if openmano_vnfd_id:
252 topology["nodes"][rift_vnfd.name + "__" + str(member_idx)] = {
253 "type": "VNF",
254 "vnf_id": openmano_vnfd_id
255 }
256 else:
257 topology["nodes"][rift_vnfd.name + "__" + str(member_idx)] = {
258 "type": "VNF",
259 "VNF model": rift_vnfd.name
260 }
261
262 for vld in rift_nsd.vlds:
263 # Openmano has both bridge_net and dataplane_net models for network types
264 # For now, since we are using openmano in developer mode lets just hardcode
265 # to bridge_net since it won't matter anyways.
266 # topology["nodes"][vld.name] = {"type": "network", "model": "bridge_net"}
267 pass
268
269 topology["connections"] = {}
270 for vld in rift_nsd.vlds:
271
272 # Create a connections entry for each external VLD
273 topology["connections"][vld.name] = {}
274 topology["connections"][vld.name]["nodes"] = []
275
276 #if vld.vim_network_name:
277 if True:
278 if vld.name not in topology["nodes"]:
279 topology["nodes"][vld.name] = {
280 "type": "external_network",
281 "model": vld.name,
282 }
283
284 # Add the external network to the list of connection points
285 topology["connections"][vld.name]["nodes"].append(
286 {vld.name: "0"}
287 )
288 elif vld.provider_network.has_field("physical_network"):
289 # Add the external datacenter network to the topology
290 # node list if it isn't already added
291 ext_net_name = vld.provider_network.physical_network
292 ext_net_name_with_seg = ext_net_name
293 if vld.provider_network.has_field("segmentation_id"):
294 ext_net_name_with_seg += ":{}".format(vld.provider_network.segmentation_id)
295
296 if ext_net_name not in topology["nodes"]:
297 topology["nodes"][ext_net_name] = {
298 "type": "external_network",
299 "model": ext_net_name_with_seg,
300 }
301
302 # Add the external network to the list of connection points
303 topology["connections"][vld.name]["nodes"].append(
304 {ext_net_name: "0"}
305 )
306
307
308 for vnfd_cp in vld.vnfd_connection_point_ref:
309
310 # Get the RIFT VNF for this external VLD connection point
311 vnfd = rift_vnfds[vnfd_cp.vnfd_id_ref]
312
313 # For each VNF in this connection, use the same interface name
314 topology["connections"][vld.name]["type"] = "link"
315 # Vnf ref is the vnf name with the member_vnf_idx appended
316 member_idx = vnfd_cp.member_vnf_index_ref
317 vnf_ref = vnfd.name + "__" + str(member_idx)
318 topology["connections"][vld.name]["nodes"].append(
319 {
320 vnf_ref: vnfd_cp.vnfd_connection_point_ref
321 }
322 )
323 return openmano
324
325 def rift2openmano_vnfd_nsd(rift_nsd, rift_vnfds, openmano_vnfd_ids,rift_vnfd_id=None):
326
327 if rift_vnfd_id not in rift_vnfds:
328 raise VNFNotFoundError("VNF id %s not provided" % rift_vnfd_id)
329
330 openmano_vnfd_nsd = {}
331 for groups in rift_nsd.scaling_group_descriptor:
332 openmano_vnfd_nsd["name"] = rift_vnfd_id+'__'+'scaling_group'+'__'+groups.name
333 openmano_vnfd_nsd["description"] = "Scaling Group"
334 topology = {}
335 openmano_vnfd_nsd["topology"] = topology
336 topology["connections"] = {}
337 topology["nodes"] = {}
338 tst_index = []
339 openmano_vnfd_id = openmano_vnfd_ids.get(rift_vnfd_id,None)
340 for rvnfd_id in rift_nsd.constituent_vnfds:
341 if rvnfd_id.vnfd_id_ref == rift_vnfd_id:
342 topology["nodes"][rift_vnfd_id+'__'+str(rvnfd_id.member_vnf_index)] = {
343 "type": "VNF",
344 "vnf_id": openmano_vnfd_id
345 }
346
347 for vld in rift_nsd.vlds:
348
349 # Create a connections entry for each external VLD
350 topology["connections"][vld.name] = {}
351 topology["connections"][vld.name]["nodes"] = []
352 if True:
353 if vld.name not in topology["nodes"]:
354 topology["nodes"][vld.name] = {
355 "type": "external_network",
356 "model": vld.name,
357 }
358 topology["connections"][vld.name]["nodes"].append(
359 {vld.name: "0"}
360 )
361
362
363
364 for vnfd_cp in vld.vnfd_connection_point_ref:
365 if not rift_vnfd_id in vnfd_cp.vnfd_id_ref:
366 continue
367 if rift_vnfd_id in vnfd_cp.vnfd_id_ref:
368
369 # Get the RIFT VNF for this external VLD connection point
370 vnfd = rift_vnfds[vnfd_cp.vnfd_id_ref]
371
372
373 # For each VNF in this connection, use the same interface name
374 topology["connections"][vld.name]["type"] = "link"
375 # Vnf ref is the vnf name with the member_vnf_idx appended
376 member_idx = vnfd_cp.member_vnf_index_ref
377 vnf_ref = rift_vnfd_id + "__" + str(member_idx)
378 topology["connections"][vld.name]["nodes"].append(
379 {
380 vnf_ref: vnfd_cp.vnfd_connection_point_ref
381 }
382 )
383 return openmano_vnfd_nsd
384
385
386 def cloud_init(rift_vnfd_id, vdu):
387 """ Populate cloud_init with script from
388 either the inline contents or from the file provided
389 """
390 vnfd_package_store = rift.package.store.VnfdPackageFilesystemStore(logger)
391
392 cloud_init_msg = None
393 if vdu.cloud_init is not None:
394 logger.debug("cloud_init script provided inline %s", vdu.cloud_init)
395 cloud_init_msg = vdu.cloud_init
396 elif vdu.cloud_init_file is not None:
397 # Get cloud-init script contents from the file provided in the cloud_init_file param
398 logger.debug("cloud_init script provided in file %s", vdu.cloud_init_file)
399 filename = vdu.cloud_init_file
400 vnfd_package_store.refresh()
401 stored_package = vnfd_package_store.get_package(rift_vnfd_id)
402 cloud_init_extractor = rift.package.cloud_init.PackageCloudInitExtractor(logger)
403 try:
404 cloud_init_msg = cloud_init_extractor.read_script(stored_package, filename)
405 except rift.package.cloud_init.CloudInitExtractionError as e:
406 raise ValueError(e)
407 else:
408 logger.debug("VDU translation: cloud-init script not provided")
409 return
410
411 logger.debug("Current cloud init msg is {}".format(cloud_init_msg))
412 return cloud_init_msg
413
414 def config_file_init(rift_vnfd_id, vdu, cfg_file):
415 """ Populate config file init with file provided
416 """
417 vnfd_package_store = rift.package.store.VnfdPackageFilesystemStore(logger)
418
419 # Get script contents from the file provided in the cloud_init directory
420 logger.debug("config file script provided in file {}".format(cfg_file))
421 filename = cfg_file
422 vnfd_package_store.refresh()
423 stored_package = vnfd_package_store.get_package(rift_vnfd_id)
424 cloud_init_extractor = rift.package.cloud_init.PackageCloudInitExtractor(logger)
425 try:
426 cfg_file_msg = cloud_init_extractor.read_script(stored_package, filename)
427 except rift.package.cloud_init.CloudInitExtractionError as e:
428 raise ValueError(e)
429
430 logger.debug("Current config file msg is {}".format(cfg_file_msg))
431 return cfg_file_msg
432
433 def rift2openmano_vnfd(rift_vnfd, rift_nsd):
434 openmano_vnf = {"vnf":{}}
435 vnf = openmano_vnf["vnf"]
436
437 vnf["name"] = rift_vnfd.name
438 vnf["description"] = rift_vnfd.description
439
440 vnf["external-connections"] = []
441
442 def find_vdu_and_ext_if_by_cp_ref(cp_ref_name):
443 for vdu in rift_vnfd.vdus:
444 for ext_if in vdu.external_interface:
445 if ext_if.vnfd_connection_point_ref == cp_ref_name:
446 return vdu, ext_if
447
448 raise ValueError("External connection point reference %s not found" % cp_ref_name)
449
450 def find_vdu_and_int_if_by_cp_ref(cp_ref_id):
451 for vdu in rift_vnfd.vdus:
452 for int_if in vdu.internal_interface:
453 if int_if.vdu_internal_connection_point_ref == cp_ref_id:
454 return vdu, int_if
455
456 raise ValueError("Internal connection point reference %s not found" % cp_ref_id)
457
458 def rift2openmano_if_type(ext_if):
459
460 cp_ref_name = ext_if.vnfd_connection_point_ref
461 for vld in rift_nsd.vlds:
462
463 # if it is an explicit mgmt_network then check if the given
464 # cp_ref is a part of it
465 if not vld.mgmt_network:
466 continue
467
468 for vld_cp in vld.vnfd_connection_point_ref:
469 if vld_cp.vnfd_connection_point_ref == cp_ref_name:
470 return "mgmt"
471
472
473 rift_type = ext_if.virtual_interface.type_yang
474 # Retaining it for backward compatibility!
475 if rift_type == "OM_MGMT":
476 return "mgmt"
477 elif rift_type == "VIRTIO" or rift_type == "E1000":
478 return "bridge"
479 else:
480 return "data"
481
482 def rift2openmano_vif(rift_type):
483 if rift_type == "VIRTIO":
484 return "virtio"
485 elif rift_type == "E1000":
486 return "e1000"
487 else:
488 raise ValueError("VDU Virtual Interface type {} not supported".format(rift_type))
489
490 # Add all external connections
491 for cp in rift_vnfd.cps:
492 # Find the VDU and and external interface for this connection point
493 vdu, ext_if = find_vdu_and_ext_if_by_cp_ref(cp.name)
494 connection = {
495 "name": cp.name,
496 "type": rift2openmano_if_type(ext_if),
497 "VNFC": vdu.name,
498 "local_iface_name": ext_if.name,
499 "description": "%s iface on VDU %s" % (ext_if.name, vdu.name),
500 }
501
502 vnf["external-connections"].append(connection)
503
504 # Add all internal networks
505 for vld in rift_vnfd.internal_vlds:
506 connection = {
507 "name": vld.name,
508 "description": vld.description,
509 "type": "bridge",
510 "elements": [],
511 }
512
513 # Add the specific VDU connection points
514 for int_cp in vld.internal_connection_point:
515 vdu, int_if = find_vdu_and_int_if_by_cp_ref(int_cp.id_ref)
516 connection["elements"].append({
517 "VNFC": vdu.name,
518 "local_iface_name": int_if.name,
519 })
520 if "internal-connections" not in vnf:
521 vnf["internal-connections"] = []
522
523 vnf["internal-connections"].append(connection)
524
525 # Add VDU's
526 vnf["VNFC"] = []
527 for vdu in rift_vnfd.vdus:
528 vnfc = {
529 "name": vdu.name,
530 "description": vdu.name,
531 "bridge-ifaces": [],
532 }
533
534 if vdu.vm_flavor.has_field("storage_gb") and vdu.vm_flavor.storage_gb:
535 vnfc["disk"] = vdu.vm_flavor.storage_gb
536
537 if vdu.has_field("image"):
538 if os.path.isabs(vdu.image):
539 vnfc["VNFC image"] = vdu.image
540 else:
541 vnfc["image name"] = vdu.image
542 if vdu.has_field("image_checksum"):
543 vnfc["image checksum"] = vdu.image_checksum
544
545 dedicated_int = False
546 for intf in list(vdu.internal_interface) + list(vdu.external_interface):
547 if intf.virtual_interface.type_yang in ["SR_IOV", "PCI_PASSTHROUGH"]:
548 dedicated_int = True
549 if vdu.guest_epa.has_field("numa_node_policy") or dedicated_int:
550 vnfc["numas"] = [{
551 "memory": max(int(vdu.vm_flavor.memory_mb/1024), 1),
552 "interfaces":[],
553 }]
554 numa_node_policy = vdu.guest_epa.numa_node_policy
555 if numa_node_policy.has_field("node"):
556 numa_node = numa_node_policy.node[0]
557
558 if numa_node.has_field("paired_threads"):
559 if numa_node.paired_threads.has_field("num_paired_threads"):
560 vnfc["numas"][0]["paired-threads"] = numa_node.paired_threads.num_paired_threads
561 if len(numa_node.paired_threads.paired_thread_ids) > 0:
562 vnfc["numas"][0]["paired-threads-id"] = []
563 for pair in numa_node.paired_threads.paired_thread_ids:
564 vnfc["numas"][0]["paired-threads-id"].append(
565 [pair.thread_a, pair.thread_b]
566 )
567
568 else:
569 if vdu.vm_flavor.has_field("vcpu_count"):
570 vnfc["numas"][0]["cores"] = max(vdu.vm_flavor.vcpu_count, 1)
571
572 if vdu.vm_flavor.has_field("vcpu_count") and vdu.vm_flavor.vcpu_count:
573 vnfc["vcpus"] = vdu.vm_flavor.vcpu_count
574
575 if vdu.vm_flavor.has_field("memory_mb") and vdu.vm_flavor.memory_mb:
576 vnfc["ram"] = vdu.vm_flavor.memory_mb
577
578
579 if vdu.has_field("hypervisor_epa"):
580 vnfc["hypervisor"] = {}
581 if vdu.hypervisor_epa.has_field("type"):
582 if vdu.hypervisor_epa.type_yang == "REQUIRE_KVM":
583 vnfc["hypervisor"]["type"] = "QEMU-kvm"
584
585 if vdu.hypervisor_epa.has_field("version"):
586 vnfc["hypervisor"]["version"] = vdu.hypervisor_epa.version
587
588 if vdu.has_field("host_epa"):
589 vnfc["processor"] = {}
590 if vdu.host_epa.has_field("om_cpu_model_string"):
591 vnfc["processor"]["model"] = vdu.host_epa.om_cpu_model_string
592 if vdu.host_epa.has_field("om_cpu_feature"):
593 vnfc["processor"]["features"] = []
594 for feature in vdu.host_epa.om_cpu_feature:
595 vnfc["processor"]["features"].append(feature.feature)
596
597 if vdu.has_field("volumes"):
598 vnfc["devices"] = []
599 # Sort volumes as device-list is implictly ordered by Openmano
600 newvollist = sorted(vdu.volumes, key=lambda k: k.name)
601 for iter_num, volume in enumerate(newvollist):
602 if iter_num == 0:
603 # Convert the first volume to vnfc.image
604 if os.path.isabs(volume.image):
605 vnfc["VNFC image"] = volume.image
606 else:
607 vnfc["image name"] = volume.image
608 if volume.has_field("image_checksum"):
609 vnfc["image checksum"] = volume.image_checksum
610 else:
611 # Add Openmano devices
612 device = {}
613 device["type"] = volume.device_type
614 device["image name"] = volume.image
615 if volume.has_field("image_checksum"):
616 device["image checksum"] = volume.image_checksum
617 vnfc["devices"].append(device)
618
619 vnfc_boot_data_init = False
620 if vdu.has_field("cloud_init") or vdu.has_field("cloud_init_file"):
621 vnfc['boot-data'] = dict()
622 vnfc_boot_data_init = True
623 vnfc['boot-data']['user-data'] = cloud_init(rift_vnfd.id, vdu)
624
625 if vdu.has_field("supplemental_boot_data"):
626 if vdu.supplemental_boot_data.has_field('boot_data_drive'):
627 if vdu.supplemental_boot_data.boot_data_drive is True:
628 if vnfc_boot_data_init is False:
629 vnfc['boot-data'] = dict()
630 vnfc_boot_data_init = True
631 vnfc['boot-data']['boot-data-drive'] = vdu.supplemental_boot_data.boot_data_drive
632
633 if vdu.supplemental_boot_data.has_field('config_file'):
634 om_cfgfile_list = list()
635 for custom_config_file in vdu.supplemental_boot_data.config_file:
636 cfg_source = config_file_init(rift_vnfd.id, vdu, custom_config_file.source)
637 om_cfgfile_list.append({"dest":custom_config_file.dest, "content": cfg_source})
638 vnfc['boot-data']['config-files'] = om_cfgfile_list
639
640
641 vnf["VNFC"].append(vnfc)
642
643 for int_if in list(vdu.internal_interface) + list(vdu.external_interface):
644 intf = {
645 "name": int_if.name,
646 }
647 if int_if.virtual_interface.has_field("vpci"):
648 intf["vpci"] = int_if.virtual_interface.vpci
649
650 if int_if.virtual_interface.type_yang in ["VIRTIO", "E1000"]:
651 intf["model"] = rift2openmano_vif(int_if.virtual_interface.type_yang)
652 vnfc["bridge-ifaces"].append(intf)
653
654 elif int_if.virtual_interface.type_yang in ["OM_MGMT"]:
655 vnfc["bridge-ifaces"].append(intf)
656
657 elif int_if.virtual_interface.type_yang == "SR_IOV":
658 intf["bandwidth"] = "10 Gbps"
659 intf["dedicated"] = "no"
660 vnfc["numas"][0]["interfaces"].append(intf)
661
662 elif int_if.virtual_interface.type_yang == "PCI_PASSTHROUGH":
663 intf["bandwidth"] = "10 Gbps"
664 intf["dedicated"] = "yes"
665 if "interfaces" not in vnfc["numas"][0]:
666 vnfc["numas"][0]["interfaces"] = []
667 vnfc["numas"][0]["interfaces"].append(intf)
668 else:
669 raise ValueError("Interface type %s not supported" % int_if.virtual_interface)
670
671 if int_if.virtual_interface.has_field("bandwidth"):
672 if int_if.virtual_interface.bandwidth != 0:
673 bps = int_if.virtual_interface.bandwidth
674
675 # Calculate the bits per second conversion
676 for x in [('M', 1000000), ('G', 1000000000)]:
677 if bps/x[1] >= 1:
678 intf["bandwidth"] = "{} {}bps".format(math.ceil(bps/x[1]), x[0])
679
680 # Sort bridge-ifaces-list TODO sort others
681 newlist = sorted(vnfc["bridge-ifaces"], key=lambda k: k['name'])
682 vnfc["bridge-ifaces"] = newlist
683
684 return openmano_vnf
685
686
687 def parse_args(argv=sys.argv[1:]):
688 """ Parse the command line arguments
689
690 Arguments:
691 arv - The list of arguments to parse
692
693 Returns:
694 Argparse Namespace instance
695 """
696 parser = argparse.ArgumentParser()
697 parser.add_argument(
698 '-o', '--outdir',
699 default='-',
700 help="Directory to output converted descriptors. Default is stdout",
701 )
702
703 parser.add_argument(
704 '-n', '--nsd-file-hdl',
705 metavar="nsd_file",
706 type=argparse.FileType('r'),
707 help="Rift NSD Descriptor File",
708 )
709
710 parser.add_argument(
711 '-v', '--vnfd-file-hdls',
712 metavar="vnfd_file",
713 action='append',
714 type=argparse.FileType('r'),
715 help="Rift VNFD Descriptor File",
716 )
717
718 args = parser.parse_args(argv)
719
720 if not os.path.exists(args.outdir):
721 os.makedirs(args.outdir)
722
723 if not is_writable_directory(args.outdir):
724 logging.error("Directory %s is not writable", args.outdir)
725 sys.exit(1)
726
727 return args
728
729
730 def write_yaml_to_file(name, outdir, desc_dict):
731 file_name = "%s.yaml" % name
732 yaml_str = yaml.dump(desc_dict)
733 if outdir == "-":
734 sys.stdout.write(yaml_str)
735 return
736
737 file_path = os.path.join(outdir, file_name)
738 dir_path = os.path.dirname(file_path)
739 if not os.path.exists(dir_path):
740 os.makedirs(dir_path)
741
742 with open(file_path, "w") as hdl:
743 hdl.write(yaml_str)
744
745 logger.info("Wrote descriptor to %s", file_path)
746
747
748 def main(argv=sys.argv[1:]):
749 args = parse_args(argv)
750 nsd = None
751 openmano_vnfr_ids = dict()
752 vnf_dict = None
753 if args.vnfd_file_hdls is not None:
754 vnf_dict = create_vnfd_from_files(args.vnfd_file_hdls)
755
756 for vnfd in vnf_dict:
757 openmano_vnfr_ids[vnfd] = vnfd
758
759 if args.nsd_file_hdl is not None:
760 nsd = create_nsd_from_file(args.nsd_file_hdl)
761
762 openmano_nsd = rift2openmano_nsd(nsd, vnf_dict, openmano_vnfr_ids)
763 vnfd_nsd = rift2openmano_vnfd_nsd(nsd, vnf_dict, openmano_vnfr_ids)
764 write_yaml_to_file(openmano_nsd["name"], args.outdir, openmano_nsd)
765 write_yaml_to_file(vnfd_nsd["name"], args.outdir, vnfd_nsd)
766 for vnf in vnf_dict.values():
767 openmano_vnf = rift2openmano_vnfd(vnf, nsd)
768 write_yaml_to_file(openmano_vnf["vnf"]["name"], args.outdir, openmano_vnf)
769
770
771 if __name__ == "__main__":
772 logging.basicConfig(level=logging.WARNING)
773 main()