5b56265d2f23cdbb56414fff8c08893091addf6b
6 # Licensed under the Apache License, Version 2.0 (the "License"); you may
7 # not use this file except in compliance with the License. You may obtain
8 # a copy of the License at
10 # http://www.apache.org/licenses/LICENSE-2.0
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 # License for the specific language governing permissions and limitations
27 from jinja2
import Environment
, PackageLoader
28 from osm_im
.validation
import Validation
as validation_im
29 from osm_im
.validation
import ValidationException
30 from osm_im
import im_translation
31 from osmclient
.common
.exceptions
import ClientException
35 class PackageTool(object):
36 def __init__(self
, client
=None):
38 self
._logger
= logging
.getLogger("osmclient")
39 self
._validator
= validation_im()
59 **Create a package descriptor**
62 - package_type: [vnf, ns, nst]
63 - base directory: path of destination folder
64 - package_name: is the name of the package to be created
65 - image: specify the image of the vdu
66 - vcpu: number of virtual cpus of the vdu
67 - memory: amount of memory in MB pf the vdu
68 - storage: amount of storage in GB of the vdu
69 - interfaces: number of interfaces besides management interface
70 - vendor: vendor name of the vnf/ns
71 - detailed: include all possible values for NSD, VNFD, NST
72 - netslice_subnets: number of netslice_subnets for the NST
73 - netslice_vlds: number of virtual link descriptors for the NST
77 self
._logger
.debug("")
78 # print("location: {}".format(osmclient.__path__))
79 file_loader
= PackageLoader("osmclient")
80 env
= Environment(loader
=file_loader
)
81 if package_type
== "ns":
82 template
= env
.get_template("nsd.yaml.j2")
88 "interfaces": interfaces
,
91 elif package_type
== "vnf":
92 template
= env
.get_template("vnfd.yaml.j2")
98 "interfaces": interfaces
,
103 "detailed": detailed
,
105 elif package_type
== "nst":
106 template
= env
.get_template("nst.yaml.j2")
108 "name": package_name
,
110 "interfaces": interfaces
,
111 "netslice_subnets": netslice_subnets
,
112 "netslice_vlds": netslice_vlds
,
113 "detailed": detailed
,
116 raise ClientException(
117 "Wrong descriptor type {}. Options: ns, vnf, nst".format(package_type
)
120 # print("To be rendered: {}".format(content))
121 output
= template
.render(content
)
124 structure
= self
.discover_folder_structure(
125 base_directory
, package_name
, override
127 if structure
.get("folders"):
128 self
.create_folders(structure
["folders"], package_type
)
129 if structure
.get("files"):
130 self
.create_files(structure
["files"], output
, package_type
)
133 def validate(self
, base_directory
, recursive
=True, old_format
=False):
135 **Validate OSM Descriptors given a path**
138 - base_directory is the root path for all descriptors
140 :return: List of dict of validated descriptors. keys: type, path, valid, error
142 self
._logger
.debug("")
145 descriptors_paths
= [
146 f
for f
in glob
.glob(base_directory
+ "/**/*.yaml", recursive
=recursive
)
149 descriptors_paths
= [
150 f
for f
in glob
.glob(base_directory
+ "/*.yaml", recursive
=recursive
)
152 print("Base directory: {}".format(base_directory
))
153 print("{} Descriptors found to validate".format(len(descriptors_paths
)))
154 for desc_path
in descriptors_paths
:
155 with
open(desc_path
) as descriptor_file
:
156 descriptor_data
= descriptor_file
.read()
159 desc_type
, descriptor_data
= validation_im
.yaml_validation(
160 self
, descriptor_data
163 if desc_type
== "vnfd" or desc_type
== "nsd":
165 "OSM descriptor '{}' written in an unsupported format. Please update to ETSI SOL006 format".format(
170 "Package validation skipped. It can still be done with 'osm package-validate --old'"
173 "Package build can still be done with 'osm package-build --skip-validation'"
175 raise Exception("Not SOL006 format")
176 validation_im
.pyangbind_validation(self
, desc_type
, descriptor_data
)
178 {"type": desc_type
, "path": desc_path
, "valid": "OK", "error": "-"}
180 except Exception as e
:
191 def translate(self
, base_directory
, recursive
=True, dryrun
=False):
193 **Translate OSM Packages given a path**
196 - base_directory is the root path for all packages
198 :return: List of dict of translated packages. keys: current type, new type, path, valid, translated, error
200 self
._logger
.debug("")
203 descriptors_paths
= [
204 f
for f
in glob
.glob(base_directory
+ "/**/*.yaml", recursive
=recursive
)
207 descriptors_paths
= [
208 f
for f
in glob
.glob(base_directory
+ "/*.yaml", recursive
=recursive
)
210 print("Base directory: {}".format(base_directory
))
211 print("{} Descriptors found to validate".format(len(descriptors_paths
)))
212 for desc_path
in descriptors_paths
:
213 with
open(desc_path
) as descriptor_file
:
214 descriptor_data
= descriptor_file
.read()
217 desc_type
, descriptor_data
= validation_im
.yaml_validation(
218 self
, descriptor_data
220 self
._logger
.debug("desc_type: {}".format(desc_type
))
221 self
._logger
.debug("descriptor_data:\n{}".format(descriptor_data
))
222 self
._validator
.pyangbind_validation(desc_type
, descriptor_data
)
223 if not (desc_type
== "vnfd" or desc_type
== "nsd"):
226 "current type": desc_type
,
227 "new type": desc_type
,
235 new_desc_type
= desc_type
237 sol006_model
= yaml
.safe_dump(
238 im_translation
.translate_im_model_to_sol006(
242 default_flow_style
=False,
247 ) = self
._validator
.yaml_validation(sol006_model
)
248 self
._validator
.pyangbind_validation(
249 new_desc_type
, new_descriptor_data
252 with
open(desc_path
, "w") as descriptor_file
:
253 descriptor_file
.write(sol006_model
)
256 "current type": desc_type
,
257 "new type": new_desc_type
,
264 except ValidationException
as ve2
:
267 "current type": desc_type
,
268 "new type": new_desc_type
,
271 "translated": "ERROR",
272 "error": "Error in the post-validation: {}".format(
277 except Exception as e2
:
280 "current type": desc_type
,
281 "new type": new_desc_type
,
284 "translated": "ERROR",
285 "error": "Error in the translation: {}".format(str(e2
)),
288 except ValidationException
as ve
:
291 "current type": desc_type
,
296 "error": "Error in the pre-validation: {}".format(str(ve
)),
299 except Exception as e
:
302 "current type": desc_type
,
312 def descriptor_translate(self
, descriptor_file
):
314 **Translate input descriptor file from Rel EIGHT OSM to SOL006**
317 - base_directory is the root path for all packages
319 :return: YAML descriptor in the new format
321 self
._logger
.debug("")
322 with
open(descriptor_file
, "r") as df
:
323 im_model
= yaml
.safe_load(df
.read())
324 sol006_model
= im_translation
.translate_im_model_to_sol006(im_model
)
325 return yaml
.safe_dump(sol006_model
, indent
=4, default_flow_style
=False)
327 def build(self
, package_folder
, skip_validation
=False, skip_charm_build
=False):
329 **Creates a .tar.gz file given a package_folder**
332 - package_folder: is the name of the folder to be packaged
333 - skip_validation: is the flag to validate or not the descriptors on the folder before build
335 :returns: message result for the build process
337 self
._logger
.debug("")
338 package_folder
= package_folder
.rstrip("/")
339 if not os
.path
.exists("{}".format(package_folder
)):
340 return "Fail, package is not in the specified path"
341 if not skip_validation
:
342 print("Validating package {}".format(package_folder
))
343 results
= self
.validate(package_folder
, recursive
=False)
345 for result
in results
:
346 if result
["valid"] != "OK":
347 raise ClientException(
348 "There was an error validating the file {} with error: {}".format(
349 result
["path"], result
["error"]
352 print("Validation OK")
354 raise ClientException(
355 "No descriptor file found in: {}".format(package_folder
)
357 charm_list
= self
.build_all_charms(package_folder
, skip_charm_build
)
358 return self
.build_tarfile(package_folder
, charm_list
)
360 def calculate_checksum(self
, package_folder
):
362 **Function to calculate the checksum given a folder**
365 - package_folder: is the folder where we have the files to calculate the checksum
368 self
._logger
.debug("")
371 for f
in glob
.glob(package_folder
+ "/**/*.*", recursive
=True)
374 with
open("{}/checksums.txt".format(package_folder
), "w+") as checksum
:
375 for file_item
in files
:
376 if "checksums.txt" in file_item
:
378 # from https://www.quickprogrammingtips.com/python/how-to-calculate-md5-hash-of-a-file-in-python.html
379 md5_hash
= hashlib
.md5()
380 with
open(file_item
, "rb") as f
:
381 # Read and update hash in chunks of 4K
382 for byte_block
in iter(lambda: f
.read(4096), b
""):
383 md5_hash
.update(byte_block
)
384 checksum
.write("{}\t{}\n".format(md5_hash
.hexdigest(), file_item
))
386 def create_folders(self
, folders
, package_type
):
388 **Create folder given a list of folders**
391 - folders: [List] list of folders paths to be created
392 - package_type: is the type of package to be created
395 self
._logger
.debug("")
396 for folder
in folders
:
398 # print("Folder {} == package_type {}".format(folder[1], package_type))
399 if folder
[1] == package_type
:
400 print("Creating folder:\t{}".format(folder
[0]))
401 os
.makedirs(folder
[0])
402 except FileExistsError
:
405 def save_file(self
, file_name
, file_body
):
407 **Create a file given a name and the content**
410 - file_name: is the name of the file with the relative route
411 - file_body: is the content of the file
414 self
._logger
.debug("")
415 print("Creating file: \t{}".format(file_name
))
417 with
open(file_name
, "w+") as f
:
419 except Exception as e
:
420 raise ClientException(e
)
422 def generate_readme(self
):
424 **Creates the README content**
426 :returns: readme content
428 self
._logger
.debug("")
429 return """# Descriptor created by OSM descriptor package generated\n\n**Created on {} **""".format(
430 time
.strftime("%m/%d/%Y, %H:%M:%S", time
.localtime())
433 def generate_cloud_init(self
):
435 **Creates the cloud-init content**
437 :returns: cloud-init content
439 self
._logger
.debug("")
440 return "---\n#cloud-config"
442 def create_files(self
, files
, file_content
, package_type
):
444 **Creates the files given the file list and type**
447 - files: is the list of files structure
448 - file_content: is the content of the descriptor rendered by the template
449 - package_type: is the type of package to filter the creation structure
453 self
._logger
.debug("")
454 for file_item
, file_package
, file_type
in files
:
455 if package_type
== file_package
:
456 if file_type
== "descriptor":
457 self
.save_file(file_item
, file_content
)
458 elif file_type
== "readme":
459 self
.save_file(file_item
, self
.generate_readme())
460 elif file_type
== "cloud_init":
461 self
.save_file(file_item
, self
.generate_cloud_init())
463 def check_files_folders(self
, path_list
, override
):
465 **Find files and folders missing given a directory structure {"folders": [], "files": []}**
468 - path_list: is the list of files and folders to be created
469 - override: is the flag used to indicate the creation of the list even if the file exist to override it
471 :return: Missing paths Dict
473 self
._logger
.debug("")
477 for folder
in path_list
.get("folders"):
478 if not os
.path
.exists(folder
[0]):
479 folders
.append(folder
)
480 missing_paths
["folders"] = folders
482 for file_item
in path_list
.get("files"):
483 if not os
.path
.exists(file_item
[0]) or override
is True:
484 files
.append(file_item
)
485 missing_paths
["files"] = files
489 def build_all_charms(self
, package_folder
, skip_charm_build
):
491 **Read the descriptor file, check that the charms referenced are in the folder and compiles them**
494 - packet_folder: is the location of the package
495 :return: Files and Folders not found. In case of override, it will return all file list
497 self
._logger
.debug("")
499 descriptor_file
= False
500 descriptors_paths
= [f
for f
in glob
.glob(package_folder
+ "/*.yaml")]
501 for file in descriptors_paths
:
502 if file.endswith("nfd.yaml"):
503 descriptor_file
= True
504 charms_set
= self
.charms_search(file, "vnf")
505 if file.endswith("nsd.yaml"):
506 descriptor_file
= True
507 charms_set
= self
.charms_search(file, "ns")
508 print("List of charms in the descriptor: {}".format(charms_set
))
509 if not descriptor_file
:
510 raise ClientException(
511 'Descriptor filename is not correct in: {}. It should end with "nfd.yaml" or "nsd.yaml"'.format(
515 if charms_set
and not skip_charm_build
:
516 for charmName
in charms_set
:
518 "{}/charms/layers/{}".format(package_folder
, charmName
)
521 "Building charm {}/charms/layers/{}".format(
522 package_folder
, charmName
525 self
.charm_build(package_folder
, charmName
)
526 print("Charm built: {}".format(charmName
))
528 "{}/charms/ops/{}".format(package_folder
, charmName
)
530 self
.charmcraft_build(package_folder
, charmName
)
532 if not os
.path
.isdir(
533 "{}/charms/{}".format(package_folder
, charmName
)
535 raise ClientException(
536 "The charm: {} referenced in the descriptor file "
537 "is not present either in {}/charms or in {}/charms/layers".format(
538 charmName
, package_folder
, package_folder
541 self
._logger
.debug("Return list of charms: {}".format(charms_set
))
544 def discover_folder_structure(self
, base_directory
, name
, override
):
546 **Discover files and folders structure for OSM descriptors given a base_directory and name**
549 - base_directory: is the location of the package to be created
550 - name: is the name of the package
551 - override: is the flag used to indicate the creation of the list even if the file exist to override it
552 :return: Files and Folders not found. In case of override, it will return all file list
554 self
._logger
.debug("")
555 prefix
= "{}/{}".format(base_directory
, name
)
558 ("{}_ns".format(prefix
), "ns"),
559 ("{}_ns/icons".format(prefix
), "ns"),
560 ("{}_ns/charms".format(prefix
), "ns"),
561 ("{}_vnf".format(name
), "vnf"),
562 ("{}_vnf/charms".format(prefix
), "vnf"),
563 ("{}_vnf/cloud_init".format(prefix
), "vnf"),
564 ("{}_vnf/images".format(prefix
), "vnf"),
565 ("{}_vnf/icons".format(prefix
), "vnf"),
566 ("{}_vnf/scripts".format(prefix
), "vnf"),
567 ("{}_nst".format(prefix
), "nst"),
568 ("{}_nst/icons".format(prefix
), "nst"),
571 ("{}_ns/{}_nsd.yaml".format(prefix
, name
), "ns", "descriptor"),
572 ("{}_ns/README.md".format(prefix
), "ns", "readme"),
573 ("{}_vnf/{}_vnfd.yaml".format(prefix
, name
), "vnf", "descriptor"),
575 "{}_vnf/cloud_init/cloud-config.txt".format(prefix
),
579 ("{}_vnf/README.md".format(prefix
), "vnf", "readme"),
580 ("{}_nst/{}_nst.yaml".format(prefix
, name
), "nst", "descriptor"),
581 ("{}_nst/README.md".format(prefix
), "nst", "readme"),
584 missing_files_folders
= self
.check_files_folders(files_folders
, override
)
585 # print("Missing files and folders: {}".format(missing_files_folders))
586 return missing_files_folders
588 def charm_build(self
, charms_folder
, build_name
):
590 Build the charms inside the package.
591 params: package_folder is the name of the folder where is the charms to compile.
592 build_name is the name of the layer or interface
594 self
._logger
.debug("")
595 os
.environ
["JUJU_REPOSITORY"] = "{}/charms".format(charms_folder
)
596 os
.environ
["CHARM_LAYERS_DIR"] = "{}/layers".format(
597 os
.environ
["JUJU_REPOSITORY"]
599 os
.environ
["CHARM_INTERFACES_DIR"] = "{}/interfaces".format(
600 os
.environ
["JUJU_REPOSITORY"]
602 os
.environ
["CHARM_BUILD_DIR"] = "{}/charms/builds".format(charms_folder
)
603 if not os
.path
.exists(os
.environ
["CHARM_BUILD_DIR"]):
604 os
.makedirs(os
.environ
["CHARM_BUILD_DIR"])
605 src_folder
= "{}/{}".format(os
.environ
["CHARM_LAYERS_DIR"], build_name
)
606 result
= subprocess
.run(["charm", "build", "{}".format(src_folder
)])
607 if result
.returncode
== 1:
608 raise ClientException("failed to build the charm: {}".format(src_folder
))
609 self
._logger
.verbose("charm {} built".format(src_folder
))
611 def charmcraft_build(self
, package_folder
, charm_name
):
613 Build the charms inside the package (new operator framework charms)
614 params: package_folder is the name of the folder where is the charms to compile.
615 build_name is the name of the layer or interface
617 self
._logger
.debug("Building charm {}".format(charm_name
))
618 src_folder
= f
"{package_folder}/charms/ops/{charm_name}"
619 current_directory
= os
.getcwd()
622 result
= subprocess
.run(["charmcraft", "build"])
623 if result
.returncode
== 1:
624 raise ClientException(
625 "failed to build the charm: {}".format(src_folder
)
627 subprocess
.run(["rm", "-rf", f
"../../{charm_name}"])
628 subprocess
.run(["mv", "build", f
"../../{charm_name}"])
629 self
._logger
.verbose("charm {} built".format(src_folder
))
631 os
.chdir(current_directory
)
633 def build_tarfile(self
, package_folder
, charm_list
=None):
635 Creates a .tar.gz file given a package_folder
636 params: package_folder is the name of the folder to be packaged
637 returns: .tar.gz name
639 self
._logger
.debug("")
642 directory_name
, package_name
= self
.create_temp_dir(
643 package_folder
, charm_list
646 os
.chdir(directory_name
)
647 self
.calculate_checksum(package_name
)
648 with tarfile
.open("{}.tar.gz".format(package_name
), mode
="w:gz") as archive
:
649 print("Adding File: {}".format(package_name
))
650 archive
.add("{}".format(package_name
), recursive
=True)
651 # return "Created {}.tar.gz".format(package_folder)
652 # self.build("{}".format(os.path.basename(package_folder)))
655 created_package
= "{}/{}.tar.gz".format(
656 os
.path
.dirname(package_folder
) or ".", package_name
659 "{}/{}.tar.gz".format(directory_name
, package_name
), created_package
662 "{}/{}/checksums.txt".format(directory_name
, package_name
),
663 "{}/checksums.txt".format(package_folder
),
665 print("Package created: {}".format(created_package
))
666 return created_package
667 except Exception as exc
:
668 raise ClientException(
669 "failure during build of targz file (create temp dir, calculate checksum, "
670 "tar.gz file): {}".format(exc
)
675 shutil
.rmtree(os
.path
.join(package_folder
, "tmp"))
677 def create_temp_dir(self
, package_folder
, charm_list
=None):
679 Method to create a temporary folder where we can move the files in package_folder
681 self
._logger
.debug("")
682 ignore_patterns
= ".gitignore"
683 ignore
= shutil
.ignore_patterns(ignore_patterns
)
684 directory_name
= os
.path
.abspath(package_folder
)
685 package_name
= os
.path
.basename(directory_name
)
686 directory_name
+= "/tmp"
687 os
.makedirs("{}/{}".format(directory_name
, package_name
), exist_ok
=True)
688 self
._logger
.debug("Makedirs DONE: {}/{}".format(directory_name
, package_name
))
689 for item
in os
.listdir(package_folder
):
690 self
._logger
.debug("Item: {}".format(item
))
692 s
= os
.path
.join(package_folder
, item
)
693 d
= os
.path
.join(os
.path
.join(directory_name
, package_name
), item
)
696 os
.makedirs(d
, exist_ok
=True)
697 s_builds
= os
.path
.join(s
, "builds")
698 for charm
in charm_list
:
699 self
._logger
.debug("Copying charm {}".format(charm
))
700 if charm
in os
.listdir(s
):
701 s_charm
= os
.path
.join(s
, charm
)
702 elif charm
in os
.listdir(s_builds
):
703 s_charm
= os
.path
.join(s_builds
, charm
)
705 raise ClientException(
706 "The charm {} referenced in the descriptor file "
707 "could not be found in {}/charms or in {}/charms/builds".format(
708 charm
, package_folder
, package_folder
711 d_temp
= os
.path
.join(d
, charm
)
713 "Copying tree: {} -> {}".format(s_charm
, d_temp
)
716 s_charm
, d_temp
, symlinks
=True, ignore
=ignore
718 self
._logger
.debug("DONE")
720 self
._logger
.debug("Copying tree: {} -> {}".format(s
, d
))
721 shutil
.copytree(s
, d
, symlinks
=True, ignore
=ignore
)
722 self
._logger
.debug("DONE")
724 if item
in ignore_patterns
:
726 self
._logger
.debug("Copying file: {} -> {}".format(s
, d
))
728 self
._logger
.debug("DONE")
729 return directory_name
, package_name
731 def charms_search(self
, descriptor_file
, desc_type
):
733 "descriptor_file: {}, desc_type: {}".format(descriptor_file
, desc_type
)
736 with
open("{}".format(descriptor_file
)) as yaml_desc
:
737 descriptor_dict
= yaml
.safe_load(yaml_desc
)
738 # self._logger.debug("\n"+yaml.safe_dump(descriptor_dict, indent=4, default_flow_style=False))
743 "vnfd:vnfd-catalog" in descriptor_dict
744 or "vnfd-catalog" in descriptor_dict
749 "nsd:nsd-catalog" in descriptor_dict
750 or "nsd-catalog" in descriptor_dict
753 charms_set
= self
._charms
_search
_on
_osm
_im
_dict
(
754 descriptor_dict
, desc_type
757 if desc_type
== "ns":
758 get_charm_list
= self
._charms
_search
_on
_nsd
_sol
006_dict
759 elif desc_type
== "vnf":
760 get_charm_list
= self
._charms
_search
_on
_vnfd
_sol
006_dict
762 raise Exception("Bad descriptor type")
763 charms_set
= get_charm_list(descriptor_dict
)
766 def _charms_search_on_osm_im_dict(self
, osm_im_dict
, desc_type
):
767 self
._logger
.debug("")
769 for k1
, v1
in osm_im_dict
.items():
770 for k2
, v2
in v1
.items():
772 if "{}-configuration".format(desc_type
) in entry
:
773 vnf_config
= entry
["{}-configuration".format(desc_type
)]
774 for k3
, v3
in vnf_config
.items():
776 charms_set
.add((v3
["charm"]))
780 if "vdu-configuration" in vdu
:
781 for k4
, v4
in vdu
["vdu-configuration"].items():
783 charms_set
.add((v4
["charm"]))
786 def _charms_search_on_vnfd_sol006_dict(self
, sol006_dict
):
787 self
._logger
.debug("")
789 dfs
= sol006_dict
.get("vnfd", {}).get("df", [])
792 df
.get("lcm-operations-configuration", {})
793 .get("operate-vnf-op-config", {})
796 if day_1_2s
is not None:
797 for day_1_2
in day_1_2s
:
798 exec_env_list
= day_1_2
.get("execution-environment-list", [])
799 for exec_env
in exec_env_list
:
800 if "juju" in exec_env
and "charm" in exec_env
["juju"]:
801 charms_set
.add(exec_env
["juju"]["charm"])
804 def _charms_search_on_nsd_sol006_dict(self
, sol006_dict
):
805 self
._logger
.debug("")
807 nsd_list
= sol006_dict
.get("nsd", {}).get("nsd", [])
809 charm
= nsd
.get("ns-configuration", {}).get("juju", {}).get("charm")
811 charms_set
.add(charm
)