X-Git-Url: https://osm.etsi.org/gitweb/?p=osm%2FN2VC.git;a=blobdiff_plain;f=n2vc%2Futils.py;h=286f0fc05b135e7be53402b5472523b66d908d70;hp=16a47332cf284cba606dc27b5af3e281d902e15a;hb=d4cee8c1edd901a2922bb2593e5b643844f83b3a;hpb=475a7221e3598ad1c75ce802c5ad74ef7ecf72f1 diff --git a/n2vc/utils.py b/n2vc/utils.py index 16a4733..286f0fc 100644 --- a/n2vc/utils.py +++ b/n2vc/utils.py @@ -15,12 +15,16 @@ import base64 import re import binascii +import yaml +import string +import secrets from enum import Enum from juju.machine import Machine from juju.application import Application from juju.action import Action from juju.unit import Unit from n2vc.exceptions import N2VCInvalidCertificate +from typing import Tuple def base64_to_cacert(b64string): @@ -32,7 +36,11 @@ def base64_to_cacert(b64string): try: cacert = base64.b64decode(b64string).decode("utf-8") - cacert = re.sub(r"\\n", r"\n", cacert,) + cacert = re.sub( + r"\\n", + r"\n", + cacert, + ) except binascii.Error as e: raise N2VCInvalidCertificate(message="Invalid CA Certificate: {}".format(e)) @@ -113,10 +121,59 @@ JujuStatusToOSM = { }, } -DB_DATA = Dict( - { - "api_endpoints": Dict( - {"table": "admin", "filter": {"_id": "juju"}, "key": "api_endpoints"} - ) - } -) + +def obj_to_yaml(obj: object) -> str: + """ + Converts object to yaml format + :return: yaml data + """ + # dump to yaml + dump_text = yaml.dump(obj, default_flow_style=False, indent=2) + # split lines + lines = dump_text.splitlines() + # remove !!python/object tags + yaml_text = "" + for line in lines: + index = line.find("!!python/object") + if index >= 0: + line = line[:index] + yaml_text += line + "\n" + return yaml_text + + +def obj_to_dict(obj: object) -> dict: + """ + Converts object to dictionary format + :return: dict data + """ + # convert obj to yaml + yaml_text = obj_to_yaml(obj) + # parse to dict + return yaml.load(yaml_text, Loader=yaml.Loader) + + +def get_ee_id_components(ee_id: str) -> Tuple[str, str, str]: + """ + Get model, application and machine components from an execution environment id + :param ee_id: + :return: model_name, application_name, machine_id + """ + parts = ee_id.split(".") + if len(parts) != 3: + raise Exception("invalid ee id.") + model_name = parts[0] + application_name = parts[1] + machine_id = parts[2] + return model_name, application_name, machine_id + + +def generate_random_alfanum_string(size: int) -> str: + """ + Generate random alfa-numeric string with a size given by argument + :param size: + :return: random generated string + """ + + return "".join( + secrets.choice(string.ascii_letters + string.digits) for i in range(size) + )