Update from master
[osm/NBI.git] / osm_nbi / admin_topics.py
index daeb260..f70c497 100644 (file)
@@ -37,8 +37,6 @@ from osm_nbi.validation import (
     k8srepo_edit_schema,
     vca_new_schema,
     vca_edit_schema,
-    paas_new_schema,
-    paas_edit_schema,
     osmrepo_new_schema,
     osmrepo_edit_schema,
     validate_input,
@@ -49,6 +47,7 @@ from osm_nbi.base_topic import BaseTopic, EngineException
 from osm_nbi.authconn import AuthconnNotFoundException, AuthconnConflictException
 from osm_common.dbbase import deep_update_rfc7396
 import copy
+from osm_nbi.temporal.nbi_temporal import NbiTemporal
 
 __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
 
@@ -325,6 +324,18 @@ class CommonVimWimSdn(BaseTopic):
 
         return final_content
 
+    def _validate_input_edit(self, input, content, force=False):
+        """
+        Validates input user content for an edition. It uses jsonschema. Some overrides will use pyangbind
+        :param input: user input content for the new topic
+        :param force: may be used for being more tolerant
+        :return: The same input content, or a changed version of it.
+        """
+
+        if "vim_type" in content:
+            input["vim_type"] = content["vim_type"]
+        return super()._validate_input_edit(input, content, force)
+
     def format_on_edit(self, final_content, edit_content):
         """
         Modifies final_content inserting admin information upon edition
@@ -347,7 +358,6 @@ class CommonVimWimSdn(BaseTopic):
                 schema_version
             ) or self.config_to_encrypt.get("default")
             if edit_content.get("config") and config_to_encrypt_keys:
-
                 for p in config_to_encrypt_keys:
                     if edit_content["config"].get(p):
                         final_content["config"][p] = self.db.encrypt(
@@ -372,21 +382,14 @@ class CommonVimWimSdn(BaseTopic):
         """
         super().format_on_new(content, project_id=project_id, make_public=make_public)
         content["schema_version"] = schema_version = "1.11"
-        self._encrypt_password(content, schema_version)
-        self._encrypt_config_fields(content, schema_version)
-        content["_admin"]["operationalState"] = "PROCESSING"
-        self._insert_create_operation(content)
-        return "{}:0".format(content["_id"])
 
-    def _encrypt_password(self, content, schema_version):
+        # encrypt passwords
         if content.get(self.password_to_encrypt):
             content[self.password_to_encrypt] = self.db.encrypt(
                 content[self.password_to_encrypt],
                 schema_version=schema_version,
                 salt=content["_id"],
             )
-
-    def _encrypt_config_fields(self, content, schema_version):
         config_to_encrypt_keys = self.config_to_encrypt.get(
             schema_version
         ) or self.config_to_encrypt.get("default")
@@ -399,7 +402,8 @@ class CommonVimWimSdn(BaseTopic):
                         salt=content["_id"],
                     )
 
-    def _insert_create_operation(self, content):
+        content["_admin"]["operationalState"] = "PROCESSING"
+
         # create operation
         content["_admin"]["operations"] = [self._create_operation("create")]
         content["_admin"]["current_operation"] = None
@@ -427,6 +431,8 @@ class CommonVimWimSdn(BaseTopic):
                     "network": network,
                 }
 
+        return "{}:0".format(content["_id"])
+
     def delete(self, session, _id, dry_run=False, not_send_msg=None):
         """
         Delete item by its internal _id
@@ -487,8 +493,15 @@ class CommonVimWimSdn(BaseTopic):
         if session["force"]:
             self.db.del_one(self.topic, {"_id": _id})
             op_id = None
+            message = {"_id": _id, "op_id": op_id}
+            # The vim_type is a temporary hack to shim in temporal workflows in the create
+            if "vim_type" in db_content:
+                message["vim_type"] = db_content["vim_type"]
+
             self._send_msg(
-                "deleted", {"_id": _id, "op_id": op_id}, not_send_msg=not_send_msg
+                "deleted",
+                message,
+                not_send_msg=not_send_msg,
             )
         else:
             update_dict = {"_admin.to_delete": True}
@@ -503,8 +516,15 @@ class CommonVimWimSdn(BaseTopic):
             op_id = "{}:{}".format(
                 db_content["_id"], len(db_content["_admin"]["operations"])
             )
+            message = {"_id": _id, "op_id": op_id}
+            # The vim_type is a temporary hack to shim in temporal workflows in the create
+            if "vim_type" in db_content:
+                message["vim_type"] = db_content["vim_type"]
+
             self._send_msg(
-                "delete", {"_id": _id, "op_id": op_id}, not_send_msg=not_send_msg
+                "delete",
+                message,
+                not_send_msg=not_send_msg,
             )
         return op_id
 
@@ -525,6 +545,45 @@ class VimAccountTopic(CommonVimWimSdn):
             "vrops_password",
         ),
     }
+    valid_paas_providers = ["juju"]
+    temporal = NbiTemporal()
+
+    def check_conflict_on_new(self, session, indata):
+        super().check_conflict_on_new(session, indata)
+        self._check_paas_account(indata)
+
+    def _is_paas_vim_type(self, indata):
+        return indata.get("vim_type") and indata["vim_type"] == "paas"
+
+    def _check_paas_account(self, indata):
+        if not self._is_paas_vim_type(indata):
+            return
+        if not self._is_valid_paas_config(indata.get("config")):
+            raise EngineException(
+                "Invalid config for VIM account '{}'.".format(indata["name"]),
+                HTTPStatus.UNPROCESSABLE_ENTITY,
+            )
+
+    def _is_valid_paas_config(self, config) -> bool:
+        if not config:
+            return False
+        paas_provider = config.get("paas_provider")
+        is_valid_paas_provider = paas_provider in self.valid_paas_providers
+        if paas_provider == "juju":
+            return self._is_valid_juju_paas_config(config)
+        return is_valid_paas_provider
+
+    def _is_valid_juju_paas_config(self, config) -> bool:
+        if not config:
+            return False
+        config_keys = [
+            "paas_provider",
+            "ca_cert_content",
+            "cloud",
+            "cloud_credentials",
+            "authorized_keys",
+        ]
+        return all(key in config for key in config_keys)
 
     def check_conflict_on_del(self, session, _id, db_content):
         """
@@ -544,6 +603,13 @@ class VimAccountTopic(CommonVimWimSdn):
             )
         super().check_conflict_on_del(session, _id, db_content)
 
+    def _send_msg(self, action, content, not_send_msg=None):
+        if self._is_paas_vim_type(content):
+            self.temporal.start_vim_workflow(action, content)
+            return
+
+        super()._send_msg(action, content, not_send_msg)
+
 
 class WimAccountTopic(CommonVimWimSdn):
     topic = "wim_accounts"
@@ -729,39 +795,6 @@ class VcaTopic(CommonVimWimSdn):
         super().check_conflict_on_del(session, _id, db_content)
 
 
-class PaasTopic(CommonVimWimSdn):
-    topic = "paas"
-    topic_msg = "paas"
-    schema_new = paas_new_schema
-    schema_edit = paas_edit_schema
-    multiproject = True
-    password_to_encrypt = "secret"
-    config_to_encrypt = {}
-
-    def format_on_edit(self, final_content, edit_content):
-        oid = super().format_on_edit(final_content, edit_content)
-        final_content["_admin"]["operationalState"] = "PROCESSING"
-        final_content["_admin"]["detailed-status"] = "Editing"
-        return oid
-
-    def _check_if_used_by_ns(self):
-        pass
-
-    def check_conflict_on_del(self, session, _id, db_content):
-        """
-        Check if deletion can be done because of dependencies if it is not force.
-        :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
-        :param _id: internal _id
-        :param db_content: The database content of this item _id
-        :return: None if ok or raises EngineException with the conflict
-        """
-        if session["force"]:
-            return
-        self._check_if_used_by_ns()
-
-        super().check_conflict_on_del(session, _id, db_content)
-
-
 class K8sRepoTopic(CommonVimWimSdn):
     topic = "k8srepos"
     topic_msg = "k8srepo"
@@ -1109,8 +1142,10 @@ class UserTopicAuth(UserTopic):
                     if to_add["project"] in (
                         mapping["project"],
                         mapping["project_name"],
-                    ) and to_add["role"] in (mapping["role"], mapping["role_name"]):
-
+                    ) and to_add["role"] in (
+                        mapping["role"],
+                        mapping["role_name"],
+                    ):
                         if mapping in mappings_to_remove:  # do not remove
                             mappings_to_remove.remove(mapping)
                         break  # do not add, it is already at user
@@ -1126,7 +1161,10 @@ class UserTopicAuth(UserTopic):
                         if to_set["project"] in (
                             mapping["project"],
                             mapping["project_name"],
-                        ) and to_set["role"] in (mapping["role"], mapping["role_name"]):
+                        ) and to_set["role"] in (
+                            mapping["role"],
+                            mapping["role_name"],
+                        ):
                             if mapping in mappings_to_remove:  # do not remove
                                 mappings_to_remove.remove(mapping)
                             break  # do not add, it is already at user
@@ -1139,7 +1177,10 @@ class UserTopicAuth(UserTopic):
                         if to_set["project"] in (
                             mapping["project"],
                             mapping["project_name"],
-                        ) and to_set["role"] in (mapping["role"], mapping["role_name"]):
+                        ) and to_set["role"] in (
+                            mapping["role"],
+                            mapping["role_name"],
+                        ):
                             break
                     else:
                         # delete