Use of yaml.SafeLoader instead of yaml.Loader
[osm/N2VC.git] / n2vc / utils.py
index f0146a0..a4a6a23 100644 (file)
@@ -16,12 +16,15 @@ import base64
 import re
 import binascii
 import yaml
 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 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):
 
 
 def base64_to_cacert(b64string):
@@ -33,7 +36,11 @@ def base64_to_cacert(b64string):
     try:
         cacert = base64.b64decode(b64string).decode("utf-8")
 
     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))
 
     except binascii.Error as e:
         raise N2VCInvalidCertificate(message="Invalid CA Certificate: {}".format(e))
 
@@ -142,4 +149,31 @@ def obj_to_dict(obj: object) -> dict:
     # convert obj to yaml
     yaml_text = obj_to_yaml(obj)
     # parse to dict
     # convert obj to yaml
     yaml_text = obj_to_yaml(obj)
     # parse to dict
-    return yaml.load(yaml_text, Loader=yaml.Loader)
+    return yaml.load(yaml_text, Loader=yaml.SafeLoader)
+
+
+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)
+    )