Merge branch 'master' into netslice 99/6699/1
authorgarciadeblas <gerardo.garciadeblas@telefonica.com>
Mon, 15 Oct 2018 14:13:45 +0000 (16:13 +0200)
committergarciadeblas <gerardo.garciadeblas@telefonica.com>
Mon, 15 Oct 2018 14:13:45 +0000 (16:13 +0200)
20 files changed:
Dockerfile.local
keystone/Dockerfile [new file with mode: 0644]
keystone/scripts/start.sh [new file with mode: 0644]
osm_nbi/admin_topics.py [new file with mode: 0644]
osm_nbi/auth.py [new file with mode: 0644]
osm_nbi/authconn.py [new file with mode: 0644]
osm_nbi/authconn_keystone.py [new file with mode: 0644]
osm_nbi/base_topic.py [new file with mode: 0644]
osm_nbi/descriptor_topics.py [new file with mode: 0644]
osm_nbi/engine.py
osm_nbi/html_out.py
osm_nbi/html_public/version
osm_nbi/instance_topics.py [new file with mode: 0644]
osm_nbi/nbi.cfg
osm_nbi/nbi.py
osm_nbi/tests/clear-all.sh
osm_nbi/validation.py
setup.py
stdeb.cfg
tox.ini

index 1ec838a..f7dd01e 100644 (file)
@@ -9,14 +9,15 @@ WORKDIR /app/osm_nbi
 ADD . /app
 
 RUN apt-get update && apt-get install -y git python3 python3-jsonschema \
-    python3-pymongo python3-yaml python3-pip \
+    python3-pymongo python3-yaml python3-pip python3-keystoneclient \
     && pip3 install pip==9.0.3 \
-    && pip3 install aiokafka cherrypy \
+    && pip3 install aiokafka cherrypy==18.0.0 keystoneauth1 \
     && mkdir -p /app/storage/kafka && mkdir -p /app/log 
 
 # OSM_COMMON
 RUN git clone https://osm.etsi.org/gerrit/osm/common.git \
-    && cd common  && python3 setup.py develop && cd ..
+    && pip3 install -e common
+#    && cd common  && python3 setup.py develop && cd ..
 #    && pip3 install -U -r requirements.txt \
 #    && cd ..
 
@@ -43,26 +44,36 @@ VOLUME /app/log
 
 # The following ENV can be added with "docker run -e xxx' to configure
 # server
-ENV OSMNBI_SOCKET_HOST     0.0.0.0
-ENV OSMNBI_SOCKET_PORT     9999
+ENV OSMNBI_SOCKET_HOST                          0.0.0.0
+ENV OSMNBI_SOCKET_PORT                          9999
 # storage
-ENV OSMNBI_STORAGE_PATH    /app/storage
+ENV OSMNBI_STORAGE_PATH                         /app/storage
 # database
-ENV OSMNBI_DATABASE_DRIVER mongo
-ENV OSMNBI_DATABASE_HOST   mongo
-ENV OSMNBI_DATABASE_PORT   27017
+ENV OSMNBI_DATABASE_DRIVER                      mongo
+ENV OSMNBI_DATABASE_HOST                        mongo
+ENV OSMNBI_DATABASE_PORT                        27017
 # web
-ENV OSMNBI_STATIC_DIR      /app/osm_nbi/html_public
+ENV OSMNBI_STATIC_DIR                           /app/osm_nbi/html_public
 # logs
-ENV OSMNBI_LOG_FILE        /app/log
-ENV OSMNBI_LOG_LEVEL       DEBUG
+ENV OSMNBI_LOG_FILE                             /app/log
+ENV OSMNBI_LOG_LEVEL                            DEBUG
 # message
-ENV OSMNBI_MESSAGE_DRIVER  kafka
-ENV OSMNBI_MESSAGE_HOST    kafka
-ENV OSMNBI_MESSAGE_PORT    9092
+ENV OSMNBI_MESSAGE_DRIVER                       kafka
+ENV OSMNBI_MESSAGE_HOST                         kafka
+ENV OSMNBI_MESSAGE_PORT                         9092
 # logs
-ENV OSMNBI_LOG_FILE        /app/log/nbi.log
-ENV OSMNBI_LOG_LEVEL       DEBUG
+ENV OSMNBI_LOG_FILE                             /app/log/nbi.log
+ENV OSMNBI_LOG_LEVEL                            DEBUG
+# authentication
+ENV OSMNBI_AUTHENTICATION_BACKEND               internal
+#ENV OSMNBI_AUTHENTICATION_BACKEND               keystone
+#ENV OSMNBI_AUTHENTICATION_AUTH_URL              keystone
+#ENV OSMNBI_AUTHENTICATION_AUTH_PORT             5000
+#ENV OSMNBI_AUTHENTICATION_USER_DOMAIN_NAME      default
+#ENV OSMNBI_AUTHENTICATION_PROJECT_DOMAIN_NAME   default
+#ENV OSMNBI_AUTHENTICATION_SERVICE_USERNAME      nbi
+#ENV OSMNBI_AUTHENTICATION_SERVICE_PASSWORD      nbi
+#ENV OSMNBI_AUTHENTICATION_SERVICE_PROJECT       service
 
 # Run app.py when the container launches
 CMD ["python3", "nbi.py"]
diff --git a/keystone/Dockerfile b/keystone/Dockerfile
new file mode 100644 (file)
index 0000000..263716a
--- /dev/null
@@ -0,0 +1,32 @@
+FROM ubuntu:16.04
+
+LABEL Maintainer="esousa@whitestack.com" \
+      Description="Openstack Keystone Instance" \
+      Version="1.0" \
+      Author="Eduardo Sousa"
+
+EXPOSE 5000
+
+WORKDIR /keystone
+
+COPY scripts/start.sh /keystone/start.sh
+
+RUN apt-get update && \
+    apt-get upgrade -y && \
+    apt-get autoremove -y && \
+    apt-get install -y software-properties-common && \
+    add-apt-repository -y cloud-archive:queens && \
+    apt-get update && apt dist-upgrade -y && \
+    apt-get install -y python-openstackclient keystone apache2 libapache2-mod-wsgi net-tools mysql-client && \
+    rm -rf /var/lib/apt/lists/* && \
+    chmod +x start.sh
+
+ENV DB_HOST                 keystone-db     # DB Hostname
+ENV DB_PORT                 3306            # DB Port
+ENV ROOT_DB_USER            root            # DB Root User
+ENV ROOT_DB_PASSWORD        admin           # DB Root Password
+ENV KEYSTONE_DB_PASSWORD    admin           # Keystone user password
+ENV ADMIN_PASSWORD          admin           # Admin password
+ENV NBI_PASSWORD            nbi             # NBI password
+
+ENTRYPOINT ./start.sh
diff --git a/keystone/scripts/start.sh b/keystone/scripts/start.sh
new file mode 100644 (file)
index 0000000..1e3709e
--- /dev/null
@@ -0,0 +1,105 @@
+#!/bin/bash
+
+DB_EXISTS=""
+
+max_attempts=120
+function wait_db(){
+    db_host=$1
+    db_port=$2
+    attempt=0
+    echo "Wait until $max_attempts seconds for MySQL mano Server ${db_host}:${db_port} "
+    while ! mysqladmin ping -h"$db_host" -P"$db_port" --silent; do
+        #wait 120 sec
+        if [ $attempt -ge $max_attempts ]; then
+            echo
+            echo "Can not connect to database ${db_host}:${db_port} during $max_attempts sec"
+            return 1
+        fi
+        attempt=$[$attempt+1]
+        echo -n "."
+        sleep 1
+    done
+    return 0
+}
+
+function is_db_created() {
+    db_host=$1
+    db_port=$2
+    db_user=$3
+    db_pswd=$4
+    db_name=$5
+
+    if mysqlshow -h"$db_host" -P"$db_port" -u"$db_user" -p"$db_pswd" | grep -v Wildcard | grep -q $db_name; then
+        echo "DB $db_name exists"
+        return 0
+    else
+        echo "DB $db_name does not exist"
+        return 1
+    fi
+}
+
+wait_db "$DB_HOST" "$DB_PORT" || exit 1
+
+is_db_created "$DB_HOST" "$DB_PORT" "$ROOT_DB_USER" "$ROOT_DB_PASSWORD" "keystone" && DB_EXISTS="Y"
+
+if [ -z $DB_EXISTS ]; then
+    mysql -h"$DB_HOST" -P"$DB_PORT" -u"$ROOT_DB_USER" -p"$ROOT_DB_PASSWORD" --default_character_set utf8 -e "CREATE DATABASE keystone"
+    mysql -h"$DB_HOST" -P"$DB_PORT" -u"$ROOT_DB_USER" -p"$ROOT_DB_PASSWORD" --default_character_set utf8 -e "GRANT ALL PRIVILEGES ON keystone.* TO 'keystone'@'localhost' IDENTIFIED BY '$KEYSTONE_DB_PASSWORD'"
+    mysql -h"$DB_HOST" -P"$DB_PORT" -u"$ROOT_DB_USER" -p"$ROOT_DB_PASSWORD" --default_character_set utf8 -e "GRANT ALL PRIVILEGES ON keystone.* TO 'keystone'@'%' IDENTIFIED BY '$KEYSTONE_DB_PASSWORD'"
+fi
+
+# Setting Keystone database connection
+sed -i "721s%.*%connection = mysql+pymysql://keystone:$KEYSTONE_DB_PASSWORD@$DB_HOST:$DB_PORT/keystone%" /etc/keystone/keystone.conf
+
+# Setting Keystone tokens
+sed -i "2934s%.*%provider = fernet%" /etc/keystone/keystone.conf
+
+# Populate Keystone database
+if [ -z $DB_EXISTS ]; then
+    su -s /bin/sh -c "keystone-manage db_sync" keystone
+fi
+
+# Initialize Fernet key repositories
+keystone-manage fernet_setup --keystone-user keystone --keystone-group keystone
+keystone-manage credential_setup --keystone-user keystone --keystone-group keystone
+
+# Bootstrap Keystone service
+if [ -z $DB_EXISTS ]; then
+    keystone-manage bootstrap --bootstrap-password "$ADMIN_PASSWORD" \
+        --bootstrap-admin-url http://keystone:5000/v3/ \
+        --bootstrap-internal-url http://keystone:5000/v3/ \
+        --bootstrap-public-url http://keystone:5000/v3/ \
+        --bootstrap-region-id RegionOne
+fi
+
+# Restart Apache Service
+service apache2 restart
+
+cat << EOF >> setup_env
+export OS_PROJECT_DOMAIN_NAME=default
+export OS_USER_DOMAIN_NAME=default
+export OS_PROJECT_NAME=admin
+export OS_USERNAME=admin
+export OS_PASSWORD=$ADMIN_PASSWORD
+export OS_AUTH_URL=http://keystone:5000/v3
+export OS_IDENTITY_API_VERSION=3
+export OS_IMAGE_API_VERSION=2
+EOF
+
+source setup_env
+
+# Create NBI User
+if [ -z $DB_EXISTS ]; then
+    openstack user create --domain default --password "$NBI_PASSWORD" nbi
+    openstack project create --domain default --description "Service Project" service
+    openstack role add --project service --user nbi admin
+fi
+
+while ps -ef | grep -v grep | grep -q apache2
+do
+    sleep 60
+done
+
+# Only reaches this point if apache2 stops running
+# When this happens exits with error code
+exit 1
diff --git a/osm_nbi/admin_topics.py b/osm_nbi/admin_topics.py
new file mode 100644 (file)
index 0000000..3b5da53
--- /dev/null
@@ -0,0 +1,202 @@
+# -*- coding: utf-8 -*-
+
+# import logging
+from uuid import uuid4
+from hashlib import sha256
+from http import HTTPStatus
+from validation import user_new_schema, user_edit_schema, project_new_schema, project_edit_schema
+from validation import vim_account_new_schema, vim_account_edit_schema, sdn_new_schema, sdn_edit_schema
+from base_topic import BaseTopic, EngineException
+
+__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
+
+
+class UserTopic(BaseTopic):
+    topic = "users"
+    topic_msg = "users"
+    schema_new = user_new_schema
+    schema_edit = user_edit_schema
+
+    def __init__(self, db, fs, msg):
+        BaseTopic.__init__(self, db, fs, msg)
+
+    @staticmethod
+    def _get_project_filter(session, write=False, show_all=True):
+        """
+        Generates a filter dictionary for querying database users.
+        Current policy is admin can show all, non admin, only its own user.
+        :param session: contains "username", if user is "admin" and the working "project_id"
+        :param write: if operation is for reading (False) or writing (True)
+        :param show_all:  if True it will show public or
+        :return:
+        """
+        if session["admin"]:  # allows all
+            return {}
+        else:
+            return {"username": session["username"]}
+
+    def check_conflict_on_new(self, session, indata, force=False):
+        # check username not exists
+        if self.db.get_one(self.topic, {"username": indata.get("username")}, fail_on_empty=False, fail_on_more=False):
+            raise EngineException("username '{}' exists".format(indata["username"]), HTTPStatus.CONFLICT)
+        # check projects
+        if not force:
+            for p in indata["projects"]:
+                if p == "admin":
+                    continue
+                if not self.db.get_one("projects", {"_id": p}, fail_on_empty=False, fail_on_more=False):
+                    raise EngineException("project '{}' does not exists".format(p), HTTPStatus.CONFLICT)
+
+    def check_conflict_on_del(self, session, _id, force=False):
+        if _id == session["username"]:
+            raise EngineException("You cannot delete your own user", http_code=HTTPStatus.CONFLICT)
+
+    @staticmethod
+    def format_on_new(content, project_id=None, make_public=False):
+        BaseTopic.format_on_new(content, make_public=False)
+        content["_id"] = content["username"]
+        salt = uuid4().hex
+        content["_admin"]["salt"] = salt
+        if content.get("password"):
+            content["password"] = sha256(content["password"].encode('utf-8') + salt.encode('utf-8')).hexdigest()
+
+    @staticmethod
+    def format_on_edit(final_content, edit_content):
+        BaseTopic.format_on_edit(final_content, edit_content)
+        if edit_content.get("password"):
+            salt = uuid4().hex
+            final_content["_admin"]["salt"] = salt
+            final_content["password"] = sha256(edit_content["password"].encode('utf-8') +
+                                               salt.encode('utf-8')).hexdigest()
+
+    def edit(self, session, _id, indata=None, kwargs=None, force=False, content=None):
+        if not session["admin"]:
+            raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
+        return BaseTopic.edit(self, session, _id, indata=indata, kwargs=kwargs, force=force, content=content)
+
+    def new(self, rollback, session, indata=None, kwargs=None, headers=None, force=False, make_public=False):
+        if not session["admin"]:
+            raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
+        return BaseTopic.new(self, rollback, session, indata=indata, kwargs=kwargs, headers=headers, force=force,
+                             make_public=make_public)
+
+
+class ProjectTopic(BaseTopic):
+    topic = "projects"
+    topic_msg = "projects"
+    schema_new = project_new_schema
+    schema_edit = project_edit_schema
+
+    def __init__(self, db, fs, msg):
+        BaseTopic.__init__(self, db, fs, msg)
+
+    def check_conflict_on_new(self, session, indata, force=False):
+        if not indata.get("name"):
+            raise EngineException("missing 'name'")
+        # check name not exists
+        if self.db.get_one(self.topic, {"name": indata.get("name")}, fail_on_empty=False, fail_on_more=False):
+            raise EngineException("name '{}' exists".format(indata["name"]), HTTPStatus.CONFLICT)
+
+    @staticmethod
+    def format_on_new(content, project_id=None, make_public=False):
+        BaseTopic.format_on_new(content, None)
+        content["_id"] = content["name"]
+
+    def check_conflict_on_del(self, session, _id, force=False):
+        if _id == session["project_id"]:
+            raise EngineException("You cannot delete your own project", http_code=HTTPStatus.CONFLICT)
+        if force:
+            return
+        _filter = {"projects": _id}
+        if self.db.get_list("users", _filter):
+            raise EngineException("There is some USER that contains this project", http_code=HTTPStatus.CONFLICT)
+
+    def edit(self, session, _id, indata=None, kwargs=None, force=False, content=None):
+        if not session["admin"]:
+            raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
+        return BaseTopic.edit(self, session, _id, indata=indata, kwargs=kwargs, force=force, content=content)
+
+    def new(self, rollback, session, indata=None, kwargs=None, headers=None, force=False, make_public=False):
+        if not session["admin"]:
+            raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
+        return BaseTopic.new(self, rollback, session, indata=indata, kwargs=kwargs, headers=headers, force=force,
+                             make_public=make_public)
+
+
+class VimAccountTopic(BaseTopic):
+    topic = "vim_accounts"
+    topic_msg = "vim_account"
+    schema_new = vim_account_new_schema
+    schema_edit = vim_account_edit_schema
+
+    def __init__(self, db, fs, msg):
+        BaseTopic.__init__(self, db, fs, msg)
+
+    def check_conflict_on_new(self, session, indata, force=False):
+        self.check_unique_name(session, indata["name"], _id=None)
+
+    def check_conflict_on_edit(self, session, final_content, edit_content, _id, force=False):
+        if edit_content.get("name"):
+            self.check_unique_name(session, edit_content["name"], _id=_id)
+
+    @staticmethod
+    def format_on_new(content, project_id=None, make_public=False):
+        BaseTopic.format_on_new(content, project_id=project_id, make_public=False)
+        content["_admin"]["operationalState"] = "PROCESSING"
+
+    def delete(self, session, _id, force=False, dry_run=False):
+        """
+        Delete item by its internal _id
+        :param session: contains the used login username, working project, and admin rights
+        :param _id: server internal id
+        :param force: indicates if deletion must be forced in case of conflict
+        :param dry_run: make checking but do not delete
+        :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
+        """
+        # TODO add admin to filter, validate rights
+        if dry_run or force:    # delete completely
+            return BaseTopic.delete(self, session, _id, force, dry_run)
+        else:  # if not, sent to kafka
+            v = BaseTopic.delete(self, session, _id, force, dry_run=True)
+            self.db.set_one("vim_accounts", {"_id": _id}, {"_admin.to_delete": True})  # TODO change status
+            self._send_msg("delete", {"_id": _id})
+            return v  # TODO indicate an offline operation to return 202 ACCEPTED
+
+
+class SdnTopic(BaseTopic):
+    topic = "sdns"
+    topic_msg = "sdn"
+    schema_new = sdn_new_schema
+    schema_edit = sdn_edit_schema
+
+    def __init__(self, db, fs, msg):
+        BaseTopic.__init__(self, db, fs, msg)
+
+    def check_conflict_on_new(self, session, indata, force=False):
+        self.check_unique_name(session, indata["name"], _id=None)
+
+    def check_conflict_on_edit(self, session, final_content, edit_content, _id, force=False):
+        if edit_content.get("name"):
+            self.check_unique_name(session, edit_content["name"], _id=_id)
+
+    @staticmethod
+    def format_on_new(content, project_id=None, make_public=False):
+        BaseTopic.format_on_new(content, project_id=project_id, make_public=False)
+        content["_admin"]["operationalState"] = "PROCESSING"
+
+    def delete(self, session, _id, force=False, dry_run=False):
+        """
+        Delete item by its internal _id
+        :param session: contains the used login username, working project, and admin rights
+        :param _id: server internal id
+        :param force: indicates if deletion must be forced in case of conflict
+        :param dry_run: make checking but do not delete
+        :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
+        """
+        if dry_run or force:  # delete completely
+            return BaseTopic.delete(self, session, _id, force, dry_run)
+        else:  # if not sent to kafka
+            v = BaseTopic.delete(self, session, _id, force, dry_run=True)
+            self.db.set_one("sdns", {"_id": _id}, {"_admin.to_delete": True})  # TODO change status
+            self._send_msg("delete", {"_id": _id})
+            return v   # TODO indicate an offline operation to return 202 ACCEPTED
diff --git a/osm_nbi/auth.py b/osm_nbi/auth.py
new file mode 100644 (file)
index 0000000..90fc1e2
--- /dev/null
@@ -0,0 +1,311 @@
+# -*- coding: utf-8 -*-
+
+"""
+Authenticator is responsible for authenticating the users,
+create the tokens unscoped and scoped, retrieve the role
+list inside the projects that they are inserted
+"""
+
+__author__ = "Eduardo Sousa <esousa@whitestack.com>"
+__date__ = "$27-jul-2018 23:59:59$"
+
+import cherrypy
+import logging
+from base64 import standard_b64decode
+from copy import deepcopy
+from functools import reduce
+from hashlib import sha256
+from http import HTTPStatus
+from random import choice as random_choice
+from time import time
+
+from authconn import AuthException
+from authconn_keystone import AuthconnKeystone
+from osm_common import dbmongo
+from osm_common import dbmemory
+from osm_common.dbbase import DbException
+
+
+class Authenticator:
+    """
+    This class should hold all the mechanisms for User Authentication and
+    Authorization. Initially it should support Openstack Keystone as a
+    backend through a plugin model where more backends can be added and a
+    RBAC model to manage permissions on operations.
+    """
+
+    def __init__(self):
+        """
+        Authenticator initializer. Setup the initial state of the object,
+        while it waits for the config dictionary and database initialization.
+        """
+        self.backend = None
+        self.config = None
+        self.db = None
+        self.tokens = dict()
+        self.logger = logging.getLogger("nbi.authenticator")
+
+    def start(self, config):
+        """
+        Method to configure the Authenticator object. This method should be called
+        after object creation. It is responsible by initializing the selected backend,
+        as well as the initialization of the database connection.
+
+        :param config: dictionary containing the relevant parameters for this object.
+        """
+        self.config = config
+
+        try:
+            if not self.backend:
+                if config["authentication"]["backend"] == "keystone":
+                    self.backend = AuthconnKeystone(self.config["authentication"])
+                elif config["authentication"]["backend"] == "internal":
+                    pass
+                else:
+                    raise AuthException("Unknown authentication backend: {}"
+                                        .format(config["authentication"]["backend"]))
+            if not self.db:
+                if config["database"]["driver"] == "mongo":
+                    self.db = dbmongo.DbMongo()
+                    self.db.db_connect(config["database"])
+                elif config["database"]["driver"] == "memory":
+                    self.db = dbmemory.DbMemory()
+                    self.db.db_connect(config["database"])
+                else:
+                    raise AuthException("Invalid configuration param '{}' at '[database]':'driver'"
+                                        .format(config["database"]["driver"]))
+        except Exception as e:
+            raise AuthException(str(e))
+
+    def stop(self):
+        try:
+            if self.db:
+                self.db.db_disconnect()
+        except DbException as e:
+            raise AuthException(str(e), http_code=e.http_code)
+
+    def init_db(self, target_version='1.0'):
+        """
+        Check if the database has been initialized. If not, create the required tables
+        and insert the predefined mappings between roles and permissions.
+
+        :param target_version: schema version that should be present in the database.
+        :return: None if OK, exception if error or version is different.
+        """
+        pass
+
+    def authorize(self):
+        token = None
+        user_passwd64 = None
+        try:
+            # 1. Get token Authorization bearer
+            auth = cherrypy.request.headers.get("Authorization")
+            if auth:
+                auth_list = auth.split(" ")
+                if auth_list[0].lower() == "bearer":
+                    token = auth_list[-1]
+                elif auth_list[0].lower() == "basic":
+                    user_passwd64 = auth_list[-1]
+            if not token:
+                if cherrypy.session.get("Authorization"):
+                    # 2. Try using session before request a new token. If not, basic authentication will generate
+                    token = cherrypy.session.get("Authorization")
+                    if token == "logout":
+                        token = None  # force Unauthorized response to insert user pasword again
+                elif user_passwd64 and cherrypy.request.config.get("auth.allow_basic_authentication"):
+                    # 3. Get new token from user password
+                    user = None
+                    passwd = None
+                    try:
+                        user_passwd = standard_b64decode(user_passwd64).decode()
+                        user, _, passwd = user_passwd.partition(":")
+                    except Exception:
+                        pass
+                    outdata = self.new_token(None, {"username": user, "password": passwd})
+                    token = outdata["id"]
+                    cherrypy.session['Authorization'] = token
+            if self.config["authentication"]["backend"] == "internal":
+                return self._internal_authorize(token)
+            else:
+                try:
+                    self.backend.validate_token(token)
+                    return self.tokens[token]
+                except AuthException:
+                    self.del_token(token)
+                    raise
+        except AuthException as e:
+            if cherrypy.session.get('Authorization'):
+                del cherrypy.session['Authorization']
+            cherrypy.response.headers["WWW-Authenticate"] = 'Bearer realm="{}"'.format(e)
+            raise AuthException(str(e))
+
+    def new_token(self, session, indata, remote):
+        if self.config["authentication"]["backend"] == "internal":
+            return self._internal_new_token(session, indata, remote)
+        else:
+            if indata.get("username"):
+                token, projects = self.backend.authenticate_with_user_password(
+                    indata.get("username"), indata.get("password"))
+            elif session:
+                token, projects = self.backend.authenticate_with_token(
+                    session.get("id"), indata.get("project_id"))
+            else:
+                raise AuthException("Provide credentials: username/password or Authorization Bearer token",
+                                    http_code=HTTPStatus.UNAUTHORIZED)
+
+            if indata.get("project_id"):
+                project_id = indata.get("project_id")
+                if project_id not in projects:
+                    raise AuthException("Project {} not allowed for this user".format(project_id),
+                                        http_code=HTTPStatus.UNAUTHORIZED)
+            else:
+                project_id = projects[0]
+
+            if project_id == "admin":
+                session_admin = True
+            else:
+                session_admin = reduce(lambda x, y: x or (True if y == "admin" else False),
+                                       projects, False)
+
+            now = time()
+            new_session = {
+                "_id": token,
+                "id": token,
+                "issued_at": now,
+                "expires": now + 3600,
+                "project_id": project_id,
+                "username": indata.get("username") if not session else session.get("username"),
+                "remote_port": remote.port,
+                "admin": session_admin
+            }
+
+            if remote.name:
+                new_session["remote_host"] = remote.name
+            elif remote.ip:
+                new_session["remote_host"] = remote.ip
+
+            self.tokens[token] = new_session
+
+            return deepcopy(new_session)
+
+    def get_token_list(self, session):
+        if self.config["authentication"]["backend"] == "internal":
+            return self._internal_get_token_list(session)
+        else:
+            return [deepcopy(token) for token in self.tokens.values()
+                    if token["username"] == session["username"]]
+
+    def get_token(self, session, token):
+        if self.config["authentication"]["backend"] == "internal":
+            return self._internal_get_token(session, token)
+        else:
+            token_value = self.tokens.get(token)
+            if not token_value:
+                raise AuthException("token not found", http_code=HTTPStatus.NOT_FOUND)
+            if token_value["username"] != session["username"] and not session["admin"]:
+                raise AuthException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
+            return token_value
+
+    def del_token(self, token):
+        if self.config["authentication"]["backend"] == "internal":
+            return self._internal_del_token(token)
+        else:
+            try:
+                self.backend.revoke_token(token)
+                del self.tokens[token]
+                return "token '{}' deleted".format(token)
+            except KeyError:
+                raise AuthException("Token '{}' not found".format(token), http_code=HTTPStatus.NOT_FOUND)
+
+    def _internal_authorize(self, token):
+        try:
+            if not token:
+                raise AuthException("Needed a token or Authorization http header", http_code=HTTPStatus.UNAUTHORIZED)
+            if token not in self.tokens:
+                raise AuthException("Invalid token or Authorization http header", http_code=HTTPStatus.UNAUTHORIZED)
+            session = self.tokens[token]
+            now = time()
+            if session["expires"] < now:
+                del self.tokens[token]
+                raise AuthException("Expired Token or Authorization http header", http_code=HTTPStatus.UNAUTHORIZED)
+            return session
+        except AuthException:
+            if self.config["global"].get("test.user_not_authorized"):
+                return {"id": "fake-token-id-for-test",
+                        "project_id": self.config["global"].get("test.project_not_authorized", "admin"),
+                        "username": self.config["global"]["test.user_not_authorized"]}
+            else:
+                raise
+
+    def _internal_new_token(self, session, indata, remote):
+        now = time()
+        user_content = None
+
+        # Try using username/password
+        if indata.get("username"):
+            user_rows = self.db.get_list("users", {"username": indata.get("username")})
+            user_content = None
+            if user_rows:
+                user_content = user_rows[0]
+                salt = user_content["_admin"]["salt"]
+                shadow_password = sha256(indata.get("password", "").encode('utf-8') + salt.encode('utf-8')).hexdigest()
+                if shadow_password != user_content["password"]:
+                    user_content = None
+            if not user_content:
+                raise AuthException("Invalid username/password", http_code=HTTPStatus.UNAUTHORIZED)
+        elif session:
+            user_rows = self.db.get_list("users", {"username": session["username"]})
+            if user_rows:
+                user_content = user_rows[0]
+            else:
+                raise AuthException("Invalid token", http_code=HTTPStatus.UNAUTHORIZED)
+        else:
+            raise AuthException("Provide credentials: username/password or Authorization Bearer token",
+                                http_code=HTTPStatus.UNAUTHORIZED)
+
+        token_id = ''.join(random_choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
+                           for _ in range(0, 32))
+        if indata.get("project_id"):
+            project_id = indata.get("project_id")
+            if project_id not in user_content["projects"]:
+                raise AuthException("project {} not allowed for this user"
+                                    .format(project_id), http_code=HTTPStatus.UNAUTHORIZED)
+        else:
+            project_id = user_content["projects"][0]
+        if project_id == "admin":
+            session_admin = True
+        else:
+            project = self.db.get_one("projects", {"_id": project_id})
+            session_admin = project.get("admin", False)
+        new_session = {"issued_at": now, "expires": now + 3600,
+                       "_id": token_id, "id": token_id, "project_id": project_id, "username": user_content["username"],
+                       "remote_port": remote.port, "admin": session_admin}
+        if remote.name:
+            new_session["remote_host"] = remote.name
+        elif remote.ip:
+            new_session["remote_host"] = remote.ip
+
+        self.tokens[token_id] = new_session
+        return deepcopy(new_session)
+
+    def _internal_get_token_list(self, session):
+        token_list = []
+        for token_id, token_value in self.tokens.items():
+            if token_value["username"] == session["username"]:
+                token_list.append(deepcopy(token_value))
+        return token_list
+
+    def _internal_get_token(self, session, token_id):
+        token_value = self.tokens.get(token_id)
+        if not token_value:
+            raise AuthException("token not found", http_code=HTTPStatus.NOT_FOUND)
+        if token_value["username"] != session["username"] and not session["admin"]:
+            raise AuthException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
+        return token_value
+
+    def _internal_del_token(self, token_id):
+        try:
+            del self.tokens[token_id]
+            return "token '{}' deleted".format(token_id)
+        except KeyError:
+            raise AuthException("Token '{}' not found".format(token_id), http_code=HTTPStatus.NOT_FOUND)
diff --git a/osm_nbi/authconn.py b/osm_nbi/authconn.py
new file mode 100644 (file)
index 0000000..4d28bf8
--- /dev/null
@@ -0,0 +1,225 @@
+# -*- coding: utf-8 -*-
+
+"""
+Authconn implements an Abstract class for the Auth backend connector
+plugins with the definition of the methods to be implemented.
+"""
+
+__author__ = "Eduardo Sousa <esousa@whitestack.com>"
+__date__ = "$27-jul-2018 23:59:59$"
+
+from http import HTTPStatus
+
+
+class AuthException(Exception):
+    """
+    Authentication error.
+    """
+    def __init__(self, message, http_code=HTTPStatus.UNAUTHORIZED):
+        self.http_code = http_code
+        Exception.__init__(self, message)
+
+
+class AuthconnException(Exception):
+    """
+    Common and base class Exception for all authconn exceptions.
+    """
+    def __init__(self, message, http_code=HTTPStatus.UNAUTHORIZED):
+        Exception.__init__(message)
+        self.http_code = http_code
+
+
+class AuthconnConnectionException(AuthconnException):
+    """
+    Connectivity error with Auth backend.
+    """
+    def __init__(self, message, http_code=HTTPStatus.BAD_GATEWAY):
+        AuthconnException.__init__(self, message, http_code)
+
+
+class AuthconnNotSupportedException(AuthconnException):
+    """
+    The request is not supported by the Auth backend.
+    """
+    def __init__(self, message, http_code=HTTPStatus.NOT_IMPLEMENTED):
+        AuthconnException.__init__(self, message, http_code)
+
+
+class AuthconnNotImplementedException(AuthconnException):
+    """
+    The method is not implemented by the Auth backend.
+    """
+    def __init__(self, message, http_code=HTTPStatus.NOT_IMPLEMENTED):
+        AuthconnException.__init__(self, message, http_code)
+
+
+class AuthconnOperationException(AuthconnException):
+    """
+    The operation executed failed.
+    """
+    def __init__(self, message, http_code=HTTPStatus.INTERNAL_SERVER_ERROR):
+        AuthconnException.__init__(self, message, http_code)
+
+
+class Authconn:
+    """
+    Abstract base class for all the Auth backend connector plugins.
+    Each Auth backend connector plugin must be a subclass of
+    Authconn class.
+    """
+    def __init__(self, config):
+        """
+        Constructor of the Authconn class.
+
+        Note: each subclass
+
+        :param config: configuration dictionary containing all the
+        necessary configuration parameters.
+        """
+        self.config = config
+
+    def authenticate_with_user_password(self, user, password):
+        """
+        Authenticate a user using username and password.
+
+        :param user: username
+        :param password: password
+        :return: an unscoped token that grants access to project list
+        """
+        raise AuthconnNotImplementedException("Should have implemented this")
+
+    def authenticate_with_token(self, token, project=None):
+        """
+        Authenticate a user using a token. Can be used to revalidate the token
+        or to get a scoped token.
+
+        :param token: a valid token.
+        :param project: (optional) project for a scoped token.
+        :return: return a revalidated token, scoped if a project was passed or
+        the previous token was already scoped.
+        """
+        raise AuthconnNotImplementedException("Should have implemented this")
+
+    def validate_token(self, token):
+        """
+        Check if the token is valid.
+
+        :param token: token to validate
+        :return: dictionary with information associated with the token. If the
+        token is not valid, returns None.
+        """
+        raise AuthconnNotImplementedException("Should have implemented this")
+
+    def revoke_token(self, token):
+        """
+        Invalidate a token.
+
+        :param token: token to be revoked
+        """
+        raise AuthconnNotImplementedException("Should have implemented this")
+
+    def get_project_list(self, token):
+        """
+        Get all the projects associated with a user.
+
+        :param token: valid token
+        :return: list of projects
+        """
+        raise AuthconnNotImplementedException("Should have implemented this")
+
+    def get_role_list(self, token):
+        """
+        Get role list for a scoped project.
+
+        :param token: scoped token.
+        :return: returns the list of roles for the user in that project. If
+        the token is unscoped it returns None.
+        """
+        raise AuthconnNotImplementedException("Should have implemented this")
+
+    def create_user(self, user, password):
+        """
+        Create a user.
+
+        :param user: username.
+        :param password: password.
+        :raises AuthconnOperationException: if user creation failed.
+        """
+        raise AuthconnNotImplementedException("Should have implemented this")
+
+    def change_password(self, user, new_password):
+        """
+        Change the user password.
+
+        :param user: username.
+        :param new_password: new password.
+        :raises AuthconnOperationException: if user password change failed.
+        """
+        raise AuthconnNotImplementedException("Should have implemented this")
+
+    def delete_user(self, user):
+        """
+        Delete user.
+
+        :param user: username.
+        :raises AuthconnOperationException: if user deletion failed.
+        """
+        raise AuthconnNotImplementedException("Should have implemented this")
+
+    def create_role(self, role):
+        """
+        Create a role.
+
+        :param role: role name.
+        :raises AuthconnOperationException: if role creation failed.
+        """
+        raise AuthconnNotImplementedException("Should have implemented this")
+
+    def delete_role(self, role):
+        """
+        Delete a role.
+
+        :param role: role name.
+        :raises AuthconnOperationException: if user deletion failed.
+        """
+        raise AuthconnNotImplementedException("Should have implemented this")
+
+    def create_project(self, project):
+        """
+        Create a project.
+
+        :param project: project name.
+        :raises AuthconnOperationException: if project creation failed.
+        """
+        raise AuthconnNotImplementedException("Should have implemented this")
+
+    def delete_project(self, project):
+        """
+        Delete a project.
+
+        :param project: project name.
+        :raises AuthconnOperationException: if project deletion failed.
+        """
+        raise AuthconnNotImplementedException("Should have implemented this")
+
+    def assign_role_to_user(self, user, project, role):
+        """
+        Assigning a role to a user in a project.
+
+        :param user: username.
+        :param project: project name.
+        :param role: role name.
+        :raises AuthconnOperationException: if role assignment failed.
+        """
+        raise AuthconnNotImplementedException("Should have implemented this")
+
+    def remove_role_from_user(self, user, project, role):
+        """
+        Remove a role from a user in a project.
+
+        :param user: username.
+        :param project: project name.
+        :param role: role name.
+        :raises AuthconnOperationException: if role assignment revocation failed.
+        """
+        raise AuthconnNotImplementedException("Should have implemented this")
diff --git a/osm_nbi/authconn_keystone.py b/osm_nbi/authconn_keystone.py
new file mode 100644 (file)
index 0000000..6e33ed6
--- /dev/null
@@ -0,0 +1,310 @@
+# -*- coding: utf-8 -*-
+
+"""
+AuthconnKeystone implements implements the connector for
+Openstack Keystone and leverages the RBAC model, to bring
+it for OSM.
+"""
+
+__author__ = "Eduardo Sousa <esousa@whitestack.com>"
+__date__ = "$27-jul-2018 23:59:59$"
+
+from authconn import Authconn, AuthException, AuthconnOperationException
+
+import logging
+from keystoneauth1 import session
+from keystoneauth1.identity import v3
+from keystoneauth1.exceptions.base import ClientException
+from keystoneclient.v3 import client
+from http import HTTPStatus
+
+
+class AuthconnKeystone(Authconn):
+    def __init__(self, config):
+        Authconn.__init__(self, config)
+
+        self.logger = logging.getLogger("nbi.authenticator.keystone")
+
+        self.auth_url = "http://{0}:{1}/v3".format(config.get("auth_url", "keystone"), config.get("auth_port", "5000"))
+        self.user_domain_name = config.get("user_domain_name", "default")
+        self.admin_project = config.get("service_project", "service")
+        self.admin_username = config.get("service_username", "nbi")
+        self.admin_password = config.get("service_password", "nbi")
+        self.project_domain_name = config.get("project_domain_name", "default")
+
+        self.auth = v3.Password(user_domain_name=self.user_domain_name,
+                                username=self.admin_username,
+                                password=self.admin_password,
+                                project_domain_name=self.project_domain_name,
+                                project_name=self.admin_project,
+                                auth_url=self.auth_url)
+        self.sess = session.Session(auth=self.auth)
+        self.keystone = client.Client(session=self.sess)
+
+    def authenticate_with_user_password(self, user, password):
+        """
+        Authenticate a user using username and password.
+
+        :param user: username
+        :param password: password
+        :return: an unscoped token that grants access to project list
+        """
+        try:
+            user_id = list(filter(lambda x: x.name == user, self.keystone.users.list()))[0].id
+            project_names = [project.name for project in self.keystone.projects.list(user=user_id)]
+
+            token = self.keystone.get_raw_token_from_identity_service(
+                auth_url=self.auth_url,
+                username=user,
+                password=password,
+                user_domain_name=self.user_domain_name,
+                project_domain_name=self.project_domain_name)
+
+            return token["auth_token"], project_names
+        except ClientException:
+            self.logger.exception("Error during user authentication using keystone. Method: basic")
+            raise AuthException("Error during user authentication using Keystone", http_code=HTTPStatus.UNAUTHORIZED)
+
+    def authenticate_with_token(self, token, project=None):
+        """
+        Authenticate a user using a token. Can be used to revalidate the token
+        or to get a scoped token.
+
+        :param token: a valid token.
+        :param project: (optional) project for a scoped token.
+        :return: return a revalidated token, scoped if a project was passed or
+        the previous token was already scoped.
+        """
+        try:
+            token_info = self.keystone.tokens.validate(token=token)
+            projects = self.keystone.projects.list(user=token_info["user"]["id"])
+            project_names = [project.name for project in projects]
+
+            token = self.keystone.get_raw_token_from_identity_service(
+                auth_url=self.auth_url,
+                token=token,
+                project_name=project,
+                user_domain_name=self.user_domain_name,
+                project_domain_name=self.project_domain_name)
+
+            return token["auth_token"], project_names
+        except ClientException:
+            self.logger.exception("Error during user authentication using keystone. Method: bearer")
+            raise AuthException("Error during user authentication using Keystone", http_code=HTTPStatus.UNAUTHORIZED)
+
+    def validate_token(self, token):
+        """
+        Check if the token is valid.
+
+        :param token: token to validate
+        :return: dictionary with information associated with the token. If the
+        token is not valid, returns None.
+        """
+        if not token:
+            return
+
+        try:
+            token_info = self.keystone.tokens.validate(token=token)
+
+            return token_info
+        except ClientException:
+            self.logger.exception("Error during token validation using keystone")
+            raise AuthException("Error during token validation using Keystone", http_code=HTTPStatus.UNAUTHORIZED)
+
+    def revoke_token(self, token):
+        """
+        Invalidate a token.
+
+        :param token: token to be revoked
+        """
+        try:
+            self.keystone.tokens.revoke_token(token=token)
+
+            return True
+        except ClientException:
+            self.logger.exception("Error during token revocation using keystone")
+            raise AuthException("Error during token revocation using Keystone", http_code=HTTPStatus.UNAUTHORIZED)
+
+    def get_project_list(self, token):
+        """
+        Get all the projects associated with a user.
+
+        :param token: valid token
+        :return: list of projects
+        """
+        try:
+            token_info = self.keystone.tokens.validate(token=token)
+            projects = self.keystone.projects.list(user=token_info["user"]["id"])
+            project_names = [project.name for project in projects]
+
+            return project_names
+        except ClientException:
+            self.logger.exception("Error during user project listing using keystone")
+            raise AuthException("Error during user project listing using Keystone", http_code=HTTPStatus.UNAUTHORIZED)
+
+    def get_role_list(self, token):
+        """
+        Get role list for a scoped project.
+
+        :param token: scoped token.
+        :return: returns the list of roles for the user in that project. If
+        the token is unscoped it returns None.
+        """
+        try:
+            token_info = self.keystone.tokens.validate(token=token)
+            roles = self.keystone.roles.list(user=token_info["user"]["id"], project=token_info["project"]["id"])
+
+            return roles
+        except ClientException:
+            self.logger.exception("Error during user role listing using keystone")
+            raise AuthException("Error during user role listing using Keystone", http_code=HTTPStatus.UNAUTHORIZED)
+
+    def create_user(self, user, password):
+        """
+        Create a user.
+
+        :param user: username.
+        :param password: password.
+        :raises AuthconnOperationException: if user creation failed.
+        """
+        try:
+            result = self.keystone.users.create(user, password=password, domain=self.user_domain_name)
+
+            if not result:
+                raise ClientException()
+        except ClientException:
+            self.logger.exception("Error during user creation using keystone")
+            raise AuthconnOperationException("Error during user creation using Keystone")
+
+    def change_password(self, user, new_password):
+        """
+        Change the user password.
+
+        :param user: username.
+        :param new_password: new password.
+        :raises AuthconnOperationException: if user password change failed.
+        """
+        try:
+            result = self.keystone.users.update(user, password=new_password)
+
+            if not result:
+                raise ClientException()
+        except ClientException:
+            self.logger.exception("Error during user password update using keystone")
+            raise AuthconnOperationException("Error during user password update using Keystone")
+
+    def delete_user(self, user):
+        """
+        Delete user.
+
+        :param user: username.
+        :raises AuthconnOperationException: if user deletion failed.
+        """
+        try:
+            result = self.keystone.users.delete(user)
+
+            if not result:
+                raise ClientException()
+        except ClientException:
+            self.logger.exception("Error during user deletion using keystone")
+            raise AuthconnOperationException("Error during user deletion using Keystone")
+
+    def create_role(self, role):
+        """
+        Create a role.
+
+        :param role: role name.
+        :raises AuthconnOperationException: if role creation failed.
+        """
+        try:
+            result = self.keystone.roles.create(role, domain=self.user_domain_name)
+
+            if not result:
+                raise ClientException()
+        except ClientException:
+            self.logger.exception("Error during role creation using keystone")
+            raise AuthconnOperationException("Error during role creation using Keystone")
+
+    def delete_role(self, role):
+        """
+        Delete a role.
+
+        :param role: role name.
+        :raises AuthconnOperationException: if role deletion failed.
+        """
+        try:
+            result = self.keystone.roles.delete(role)
+
+            if not result:
+                raise ClientException()
+        except ClientException:
+            self.logger.exception("Error during role deletion using keystone")
+            raise AuthconnOperationException("Error during role deletion using Keystone")
+
+    def create_project(self, project):
+        """
+        Create a project.
+
+        :param project: project name.
+        :raises AuthconnOperationException: if project creation failed.
+        """
+        try:
+            result = self.keystone.project.create(project, self.project_domain_name)
+
+            if not result:
+                raise ClientException()
+        except ClientException:
+            self.logger.exception("Error during project creation using keystone")
+            raise AuthconnOperationException("Error during project creation using Keystone")
+
+    def delete_project(self, project):
+        """
+        Delete a project.
+
+        :param project: project name.
+        :raises AuthconnOperationException: if project deletion failed.
+        """
+        try:
+            result = self.keystone.project.delete(project)
+
+            if not result:
+                raise ClientException()
+        except ClientException:
+            self.logger.exception("Error during project deletion using keystone")
+            raise AuthconnOperationException("Error during project deletion using Keystone")
+
+    def assign_role_to_user(self, user, project, role):
+        """
+        Assigning a role to a user in a project.
+
+        :param user: username.
+        :param project: project name.
+        :param role: role name.
+        :raises AuthconnOperationException: if role assignment failed.
+        """
+        try:
+            result = self.keystone.roles.grant(role, user=user, project=project)
+
+            if not result:
+                raise ClientException()
+        except ClientException:
+            self.logger.exception("Error during user role assignment using keystone")
+            raise AuthconnOperationException("Error during user role assignment using Keystone")
+
+    def remove_role_from_user(self, user, project, role):
+        """
+        Remove a role from a user in a project.
+
+        :param user: username.
+        :param project: project name.
+        :param role: role name.
+        :raises AuthconnOperationException: if role assignment revocation failed.
+        """
+        try:
+            result = self.keystone.roles.revoke(role, user=user, project=project)
+
+            if not result:
+                raise ClientException()
+        except ClientException:
+            self.logger.exception("Error during user role revocation using keystone")
+            raise AuthconnOperationException("Error during user role revocation using Keystone")
diff --git a/osm_nbi/base_topic.py b/osm_nbi/base_topic.py
new file mode 100644 (file)
index 0000000..2060c4c
--- /dev/null
@@ -0,0 +1,358 @@
+# -*- coding: utf-8 -*-
+
+import logging
+from uuid import uuid4
+from http import HTTPStatus
+from time import time
+from osm_common.dbbase import deep_update_rfc7396
+from validation import validate_input, ValidationError
+
+__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
+
+
+class EngineException(Exception):
+
+    def __init__(self, message, http_code=HTTPStatus.BAD_REQUEST):
+        self.http_code = http_code
+        Exception.__init__(self, message)
+
+
+def get_iterable(input_var):
+    """
+    Returns an iterable, in case input_var is None it just returns an empty tuple
+    :param input_var: can be a list, tuple or None
+    :return: input_var or () if it is None
+    """
+    if input_var is None:
+        return ()
+    return input_var
+
+
+def versiontuple(v):
+    """utility for compare dot separate versions. Fills with zeros to proper number comparison"""
+    filled = []
+    for point in v.split("."):
+        filled.append(point.zfill(8))
+    return tuple(filled)
+
+
+class BaseTopic:
+    # static variables for all instance classes
+    topic = None        # to_override
+    topic_msg = None    # to_override
+    schema_new = None   # to_override
+    schema_edit = None  # to_override
+
+    def __init__(self, db, fs, msg):
+        self.db = db
+        self.fs = fs
+        self.msg = msg
+        self.logger = logging.getLogger("nbi.engine")
+
+    @staticmethod
+    def _remove_envelop(indata=None):
+        if not indata:
+            return {}
+        return indata
+
+    def _validate_input_new(self, input, force=False):
+        """
+        Validates input user content for a new entry. 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 self.schema_new:
+            validate_input(input, self.schema_new)
+        return input
+
+    def _validate_input_edit(self, input, 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 self.schema_edit:
+            validate_input(input, self.schema_edit)
+        return input
+
+    @staticmethod
+    def _get_project_filter(session, write=False, show_all=True):
+        """
+        Generates a filter dictionary for querying database, so that only allowed items for this project can be
+        addressed. Only propietary or public can be used. Allowed projects are at _admin.project_read/write. If it is
+        not present or contains ANY mean public.
+        :param session: contains "username", if user is "admin" and the working "project_id"
+        :param write: if operation is for reading (False) or writing (True)
+        :param show_all:  if True it will show public or
+        :return:
+        """
+        if write:
+            k = "_admin.projects_write.cont"
+        else:
+            k = "_admin.projects_read.cont"
+        if not show_all:
+            return {k: session["project_id"]}
+        elif session["admin"]:   # and show_all:  # allows all
+            return {}
+        else:
+            return {k: ["ANY", session["project_id"], None]}
+
+    def check_conflict_on_new(self, session, indata, force=False):
+        """
+        Check that the data to be inserted is valid
+        :param session: contains "username", if user is "admin" and the working "project_id"
+        :param indata: data to be inserted
+        :param force: boolean. With force it is more tolerant
+        :return: None or raises EngineException
+        """
+        pass
+
+    def check_conflict_on_edit(self, session, final_content, edit_content, _id, force=False):
+        """
+        Check that the data to be edited/uploaded is valid
+        :param session: contains "username", if user is "admin" and the working "project_id"
+        :param final_content: data once modified
+        :param edit_content: incremental data that contains the modifications to apply
+        :param _id: internal _id
+        :param force: boolean. With force it is more tolerant
+        :return: None or raises EngineException
+        """
+        pass
+
+    def check_unique_name(self, session, name, _id=None):
+        """
+        Check that the name is unique for this project
+        :param session: contains "username", if user is "admin" and the working "project_id"
+        :param name: name to be checked
+        :param _id: If not None, ignore this entry that are going to change
+        :return: None or raises EngineException
+        """
+        _filter = self._get_project_filter(session, write=False, show_all=False)
+        _filter["name"] = name
+        if _id:
+            _filter["_id.neq"] = _id
+        if self.db.get_one(self.topic, _filter, fail_on_empty=False, fail_on_more=False):
+            raise EngineException("name '{}' already exists for {}".format(name, self.topic), HTTPStatus.CONFLICT)
+
+    @staticmethod
+    def format_on_new(content, project_id=None, make_public=False):
+        """
+        Modifies content descriptor to include _admin
+        :param content: descriptor to be modified
+        :param project_id: if included, it add project read/write permissions
+        :param make_public: if included it is generated as public for reading.
+        :return: None, but content is modified
+        """
+        now = time()
+        if "_admin" not in content:
+            content["_admin"] = {}
+        if not content["_admin"].get("created"):
+            content["_admin"]["created"] = now
+        content["_admin"]["modified"] = now
+        if not content.get("_id"):
+            content["_id"] = str(uuid4())
+        if project_id:
+            if not content["_admin"].get("projects_read"):
+                content["_admin"]["projects_read"] = [project_id]
+                if make_public:
+                    content["_admin"]["projects_read"].append("ANY")
+            if not content["_admin"].get("projects_write"):
+                content["_admin"]["projects_write"] = [project_id]
+
+    @staticmethod
+    def format_on_edit(final_content, edit_content):
+        if final_content.get("_admin"):
+            now = time()
+            final_content["_admin"]["modified"] = now
+
+    def _send_msg(self, action, content):
+        if self.topic_msg:
+            content.pop("_admin", None)
+            self.msg.write(self.topic_msg, action, content)
+
+    def check_conflict_on_del(self, session, _id, force=False):
+        """
+        Check if deletion can be done because of dependencies if it is not force. To override
+        :param session: contains "username", if user is "admin" and the working "project_id"
+        :param _id: itnernal _id
+        :param force: Avoid this checking
+        :return: None if ok or raises EngineException with the conflict
+        """
+        pass
+
+    @staticmethod
+    def _update_input_with_kwargs(desc, kwargs):
+        """
+        Update descriptor with the kwargs. It contains dot separated keys
+        :param desc: dictionary to be updated
+        :param kwargs: plain dictionary to be used for updating.
+        :return: None, 'desc' is modified. It raises EngineException.  
+        """
+        if not kwargs:
+            return
+        try:
+            for k, v in kwargs.items():
+                update_content = desc
+                kitem_old = None
+                klist = k.split(".")
+                for kitem in klist:
+                    if kitem_old is not None:
+                        update_content = update_content[kitem_old]
+                    if isinstance(update_content, dict):
+                        kitem_old = kitem
+                    elif isinstance(update_content, list):
+                        kitem_old = int(kitem)
+                    else:
+                        raise EngineException(
+                            "Invalid query string '{}'. Descriptor is not a list nor dict at '{}'".format(k, kitem))
+                update_content[kitem_old] = v
+        except KeyError:
+            raise EngineException(
+                "Invalid query string '{}'. Descriptor does not contain '{}'".format(k, kitem_old))
+        except ValueError:
+            raise EngineException("Invalid query string '{}'. Expected integer index list instead of '{}'".format(
+                k, kitem))
+        except IndexError:
+            raise EngineException(
+                "Invalid query string '{}'. Index '{}' out of  range".format(k, kitem_old))
+
+    def show(self, session, _id):
+        """
+        Get complete information on an topic
+        :param session: contains the used login username and working project
+        :param _id: server internal id
+        :return: dictionary, raise exception if not found.
+        """
+        filter_db = self._get_project_filter(session, write=False, show_all=True)
+        filter_db["_id"] = _id
+        return self.db.get_one(self.topic, filter_db)
+        # TODO transform data for SOL005 URL requests
+        # TODO remove _admin if not admin
+
+    def get_file(self, session, _id, path=None, accept_header=None):
+        """
+        Only implemented for descriptor topics. Return the file content of a descriptor
+        :param session: contains the used login username and working project
+        :param _id: Identity of the item to get content
+        :param path: artifact path or "$DESCRIPTOR" or None
+        :param accept_header: Content of Accept header. Must contain applition/zip or/and text/plain
+        :return: opened file or raises an exception
+        """
+        raise EngineException("Method get_file not valid for this topic", HTTPStatus.INTERNAL_SERVER_ERROR)
+
+    def list(self, session, filter_q=None):
+        """
+        Get a list of the topic that matches a filter
+        :param session: contains the used login username and working project
+        :param filter_q: filter of data to be applied
+        :return: The list, it can be empty if no one match the filter.
+        """
+        if not filter_q:
+            filter_q = {}
+
+        filter_q.update(self._get_project_filter(session, write=False, show_all=True))
+
+        # TODO transform data for SOL005 URL requests. Transform filtering
+        # TODO implement "field-type" query string SOL005
+        return self.db.get_list(self.topic, filter_q)
+
+    def new(self, rollback, session, indata=None, kwargs=None, headers=None, force=False, make_public=False):
+        """
+        Creates a new entry into database.
+        :param rollback: list to append created items at database in case a rollback may to be done
+        :param session: contains the used login username and working project
+        :param indata: data to be inserted
+        :param kwargs: used to override the indata descriptor
+        :param headers: http request headers
+        :param force: If True avoid some dependence checks
+        :param make_public: Make the created item public to all projects
+        :return: _id: identity of the inserted data.
+        """
+        try:
+            content = self._remove_envelop(indata)
+
+            # Override descriptor with query string kwargs
+            self._update_input_with_kwargs(content, kwargs)
+            content = self._validate_input_new(content, force=force)
+            self.check_conflict_on_new(session, content, force=force)
+            self.format_on_new(content, project_id=session["project_id"], make_public=make_public)
+            _id = self.db.create(self.topic, content)
+            rollback.append({"topic": self.topic, "_id": _id})
+            self._send_msg("create", content)
+            return _id
+        except ValidationError as e:
+            raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
+
+    def upload_content(self, session, _id, indata, kwargs, headers, force=False):
+        """
+        Only implemented for descriptor topics.  Used for receiving content by chunks (with a transaction_id header
+        and/or gzip file. It will store and extract)
+        :param session: session
+        :param _id : the database id of entry to be updated
+        :param indata: http body request
+        :param kwargs: user query string to override parameters. NOT USED
+        :param headers:  http request headers
+        :param force: to be more tolerant with validation
+        :return: True package has is completely uploaded or False if partial content has been uplodaed.
+            Raise exception on error
+        """
+        raise EngineException("Method upload_content not valid for this topic", HTTPStatus.INTERNAL_SERVER_ERROR)
+
+    def delete_list(self, session, filter_q=None):
+        """
+        Delete a several entries of a topic. This is for internal usage and test only, not exposed to NBI API
+        :param session: contains the used login username and working project
+        :param filter_q: filter of data to be applied
+        :return: The deleted list, it can be empty if no one match the filter.
+        """
+        # TODO add admin to filter, validate rights
+        if not filter_q:
+            filter_q = {}
+        filter_q.update(self._get_project_filter(session, write=True, show_all=True))
+        return self.db.del_list(self.topic, filter_q)
+
+    def delete(self, session, _id, force=False, dry_run=False):
+        """
+        Delete item by its internal _id
+        :param session: contains the used login username, working project, and admin rights
+        :param _id: server internal id
+        :param force: indicates if deletion must be forced in case of conflict
+        :param dry_run: make checking but do not delete
+        :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
+        """
+        # TODO add admin to filter, validate rights
+        # data = self.get_item(topic, _id)
+        self.check_conflict_on_del(session, _id, force)
+        filter_q = self._get_project_filter(session, write=True, show_all=True)
+        filter_q["_id"] = _id
+        if not dry_run:
+            v = self.db.del_one(self.topic, filter_q)
+            self._send_msg("deleted", {"_id": _id})
+            return v
+        return None
+
+    def edit(self, session, _id, indata=None, kwargs=None, force=False, content=None):
+        indata = self._remove_envelop(indata)
+
+        # Override descriptor with query string kwargs
+        if kwargs:
+            self._update_input_with_kwargs(indata, kwargs)
+        try:
+            indata = self._validate_input_edit(indata, force=force)
+
+            # TODO self._check_edition(session, indata, _id, force)
+            if not content:
+                content = self.show(session, _id)
+            deep_update_rfc7396(content, indata)
+            self.check_conflict_on_edit(session, content, indata, _id=_id, force=force)
+            self.format_on_edit(content, indata)
+            self.db.replace(self.topic, _id, content)
+
+            indata.pop("_admin", None)
+            indata["_id"] = _id
+            self._send_msg("edit", indata)
+            return id
+        except ValidationError as e:
+            raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
diff --git a/osm_nbi/descriptor_topics.py b/osm_nbi/descriptor_topics.py
new file mode 100644 (file)
index 0000000..b59b4f8
--- /dev/null
@@ -0,0 +1,493 @@
+# -*- coding: utf-8 -*-
+
+import tarfile
+import yaml
+import json
+# import logging
+from hashlib import md5
+from osm_common.dbbase import DbException, deep_update_rfc7396
+from http import HTTPStatus
+from validation import ValidationError, pdu_new_schema, pdu_edit_schema
+from base_topic import BaseTopic, EngineException
+
+__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
+
+
+class DescriptorTopic(BaseTopic):
+
+    def __init__(self, db, fs, msg):
+        BaseTopic.__init__(self, db, fs, msg)
+
+    def check_conflict_on_edit(self, session, final_content, edit_content, _id, force=False):
+        # check that this id is not present
+        _filter = {"id": final_content["id"]}
+        if _id:
+            _filter["_id.neq"] = _id
+
+        _filter.update(self._get_project_filter(session, write=False, show_all=False))
+        if self.db.get_one(self.topic, _filter, fail_on_empty=False):
+            raise EngineException("{} with id '{}' already exists for this project".format(self.topic[:-1],
+                                                                                           final_content["id"]),
+                                  HTTPStatus.CONFLICT)
+        # TODO validate with pyangbind. Load and dumps to convert data types
+
+    @staticmethod
+    def format_on_new(content, project_id=None, make_public=False):
+        BaseTopic.format_on_new(content, project_id=project_id, make_public=make_public)
+        content["_admin"]["onboardingState"] = "CREATED"
+        content["_admin"]["operationalState"] = "DISABLED"
+        content["_admin"]["usageSate"] = "NOT_IN_USE"
+
+    def delete(self, session, _id, force=False, dry_run=False):
+        """
+        Delete item by its internal _id
+        :param session: contains the used login username, working project, and admin rights
+        :param _id: server internal id
+        :param force: indicates if deletion must be forced in case of conflict
+        :param dry_run: make checking but do not delete
+        :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
+        """
+        # TODO add admin to filter, validate rights
+        v = BaseTopic.delete(self, session, _id, force, dry_run=True)
+        if dry_run:
+            return
+        v = self.db.del_one(self.topic, {"_id": _id})
+        self.fs.file_delete(_id, ignore_non_exist=True)
+        self._send_msg("delete", {"_id": _id})
+        return v
+
+    @staticmethod
+    def get_one_by_id(db, session, topic, id):
+        # find owned by this project
+        _filter = BaseTopic._get_project_filter(session, write=False, show_all=False)
+        _filter["id"] = id
+        desc_list = db.get_list(topic, _filter)
+        if len(desc_list) == 1:
+            return desc_list[0]
+        elif len(desc_list) > 1:
+            raise DbException("Found more than one {} with id='{}' belonging to this project".format(topic[:-1], id),
+                              HTTPStatus.CONFLICT)
+
+        # not found any: try to find public
+        _filter = BaseTopic._get_project_filter(session, write=False, show_all=True)
+        _filter["id"] = id
+        desc_list = db.get_list(topic, _filter)
+        if not desc_list:
+            raise DbException("Not found any {} with id='{}'".format(topic[:-1], id), HTTPStatus.NOT_FOUND)
+        elif len(desc_list) == 1:
+            return desc_list[0]
+        else:
+            raise DbException("Found more than one public {} with id='{}'; and no one belonging to this project".format(
+                topic[:-1], id), HTTPStatus.CONFLICT)
+
+    def new(self, rollback, session, indata=None, kwargs=None, headers=None, force=False, make_public=False):
+        """
+        Creates a new almost empty DISABLED  entry into database. Due to SOL005, it does not follow normal procedure.
+        Creating a VNFD or NSD is done in two steps: 1. Creates an empty descriptor (this step) and 2) upload content
+        (self.upload_content)
+        :param rollback: list to append created items at database in case a rollback may to be done
+        :param session: contains the used login username and working project
+        :param indata: data to be inserted
+        :param kwargs: used to override the indata descriptor
+        :param headers: http request headers
+        :param force: If True avoid some dependence checks
+        :param make_public: Make the created descriptor public to all projects
+        :return: _id: identity of the inserted data.
+        """
+
+        try:
+            # _remove_envelop
+            if indata:
+                if "userDefinedData" in indata:
+                    indata = indata['userDefinedData']
+
+            # Override descriptor with query string kwargs
+            self._update_input_with_kwargs(indata, kwargs)
+            # uncomment when this method is implemented.
+            # Avoid override in this case as the target is userDefinedData, but not vnfd,nsd descriptors
+            # indata = DescriptorTopic._validate_input_new(self, indata, force=force)
+
+            content = {"_admin": {"userDefinedData": indata}}
+            self.format_on_new(content, session["project_id"], make_public=make_public)
+            _id = self.db.create(self.topic, content)
+            rollback.append({"topic": self.topic, "_id": _id})
+            return _id
+        except ValidationError as e:
+            raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
+
+    def upload_content(self, session, _id, indata, kwargs, headers, force=False):
+        """
+        Used for receiving content by chunks (with a transaction_id header and/or gzip file. It will store and extract)
+        :param session: session
+        :param _id : the nsd,vnfd is already created, this is the id
+        :param indata: http body request
+        :param kwargs: user query string to override parameters. NOT USED
+        :param headers:  http request headers
+        :param force: to be more tolerant with validation
+        :return: True package has is completely uploaded or False if partial content has been uplodaed.
+            Raise exception on error
+        """
+        # Check that _id exists and it is valid
+        current_desc = self.show(session, _id)
+
+        content_range_text = headers.get("Content-Range")
+        expected_md5 = headers.get("Content-File-MD5")
+        compressed = None
+        content_type = headers.get("Content-Type")
+        if content_type and "application/gzip" in content_type or "application/x-gzip" in content_type or \
+                "application/zip" in content_type:
+            compressed = "gzip"
+        filename = headers.get("Content-Filename")
+        if not filename:
+            filename = "package.tar.gz" if compressed else "package"
+        # TODO change to Content-Disposition filename https://tools.ietf.org/html/rfc6266
+        file_pkg = None
+        error_text = ""
+        try:
+            if content_range_text:
+                content_range = content_range_text.replace("-", " ").replace("/", " ").split()
+                if content_range[0] != "bytes":  # TODO check x<y not negative < total....
+                    raise IndexError()
+                start = int(content_range[1])
+                end = int(content_range[2]) + 1
+                total = int(content_range[3])
+            else:
+                start = 0
+
+            if start:
+                if not self.fs.file_exists(_id, 'dir'):
+                    raise EngineException("invalid Transaction-Id header", HTTPStatus.NOT_FOUND)
+            else:
+                self.fs.file_delete(_id, ignore_non_exist=True)
+                self.fs.mkdir(_id)
+
+            storage = self.fs.get_params()
+            storage["folder"] = _id
+
+            file_path = (_id, filename)
+            if self.fs.file_exists(file_path, 'file'):
+                file_size = self.fs.file_size(file_path)
+            else:
+                file_size = 0
+            if file_size != start:
+                raise EngineException("invalid Content-Range start sequence, expected '{}' but received '{}'".format(
+                    file_size, start), HTTPStatus.REQUESTED_RANGE_NOT_SATISFIABLE)
+            file_pkg = self.fs.file_open(file_path, 'a+b')
+            if isinstance(indata, dict):
+                indata_text = yaml.safe_dump(indata, indent=4, default_flow_style=False)
+                file_pkg.write(indata_text.encode(encoding="utf-8"))
+            else:
+                indata_len = 0
+                while True:
+                    indata_text = indata.read(4096)
+                    indata_len += len(indata_text)
+                    if not indata_text:
+                        break
+                    file_pkg.write(indata_text)
+            if content_range_text:
+                if indata_len != end-start:
+                    raise EngineException("Mismatch between Content-Range header {}-{} and body length of {}".format(
+                        start, end-1, indata_len), HTTPStatus.REQUESTED_RANGE_NOT_SATISFIABLE)
+                if end != total:
+                    # TODO update to UPLOADING
+                    return False
+
+            # PACKAGE UPLOADED
+            if expected_md5:
+                file_pkg.seek(0, 0)
+                file_md5 = md5()
+                chunk_data = file_pkg.read(1024)
+                while chunk_data:
+                    file_md5.update(chunk_data)
+                    chunk_data = file_pkg.read(1024)
+                if expected_md5 != file_md5.hexdigest():
+                    raise EngineException("Error, MD5 mismatch", HTTPStatus.CONFLICT)
+            file_pkg.seek(0, 0)
+            if compressed == "gzip":
+                tar = tarfile.open(mode='r', fileobj=file_pkg)
+                descriptor_file_name = None
+                for tarinfo in tar:
+                    tarname = tarinfo.name
+                    tarname_path = tarname.split("/")
+                    if not tarname_path[0] or ".." in tarname_path:  # if start with "/" means absolute path
+                        raise EngineException("Absolute path or '..' are not allowed for package descriptor tar.gz")
+                    if len(tarname_path) == 1 and not tarinfo.isdir():
+                        raise EngineException("All files must be inside a dir for package descriptor tar.gz")
+                    if tarname.endswith(".yaml") or tarname.endswith(".json") or tarname.endswith(".yml"):
+                        storage["pkg-dir"] = tarname_path[0]
+                        if len(tarname_path) == 2:
+                            if descriptor_file_name:
+                                raise EngineException(
+                                    "Found more than one descriptor file at package descriptor tar.gz")
+                            descriptor_file_name = tarname
+                if not descriptor_file_name:
+                    raise EngineException("Not found any descriptor file at package descriptor tar.gz")
+                storage["descriptor"] = descriptor_file_name
+                storage["zipfile"] = filename
+                self.fs.file_extract(tar, _id)
+                with self.fs.file_open((_id, descriptor_file_name), "r") as descriptor_file:
+                    content = descriptor_file.read()
+            else:
+                content = file_pkg.read()
+                storage["descriptor"] = descriptor_file_name = filename
+
+            if descriptor_file_name.endswith(".json"):
+                error_text = "Invalid json format "
+                indata = json.load(content)
+            else:
+                error_text = "Invalid yaml format "
+                indata = yaml.load(content)
+
+            current_desc["_admin"]["storage"] = storage
+            current_desc["_admin"]["onboardingState"] = "ONBOARDED"
+            current_desc["_admin"]["operationalState"] = "ENABLED"
+
+            indata = self._remove_envelop(indata)
+
+            # Override descriptor with query string kwargs
+            if kwargs:
+                self._update_input_with_kwargs(indata, kwargs)
+            # it will call overrides method at VnfdTopic or NsdTopic
+            indata = self._validate_input_new(indata, force=force)
+
+            deep_update_rfc7396(current_desc, indata)
+            self.check_conflict_on_edit(session, current_desc, indata, _id=_id, force=force)
+            self.db.replace(self.topic, _id, current_desc)
+
+            indata["_id"] = _id
+            self._send_msg("created", indata)
+
+            # TODO if descriptor has changed because kwargs update content and remove cached zip
+            # TODO if zip is not present creates one
+            return True
+
+        except EngineException:
+            raise
+        except IndexError:
+            raise EngineException("invalid Content-Range header format. Expected 'bytes start-end/total'",
+                                  HTTPStatus.REQUESTED_RANGE_NOT_SATISFIABLE)
+        except IOError as e:
+            raise EngineException("invalid upload transaction sequence: '{}'".format(e), HTTPStatus.BAD_REQUEST)
+        except tarfile.ReadError as e:
+            raise EngineException("invalid file content {}".format(e), HTTPStatus.BAD_REQUEST)
+        except (ValueError, yaml.YAMLError) as e:
+            raise EngineException(error_text + str(e))
+        except ValidationError as e:
+            raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
+        finally:
+            if file_pkg:
+                file_pkg.close()
+
+    def get_file(self, session, _id, path=None, accept_header=None):
+        """
+        Return the file content of a vnfd or nsd
+        :param session: contains the used login username and working project
+        :param _id: Identity of the vnfd, ndsd
+        :param path: artifact path or "$DESCRIPTOR" or None
+        :param accept_header: Content of Accept header. Must contain applition/zip or/and text/plain
+        :return: opened file or raises an exception
+        """
+        accept_text = accept_zip = False
+        if accept_header:
+            if 'text/plain' in accept_header or '*/*' in accept_header:
+                accept_text = True
+            if 'application/zip' in accept_header or '*/*' in accept_header:
+                accept_zip = True
+        if not accept_text and not accept_zip:
+            raise EngineException("provide request header 'Accept' with 'application/zip' or 'text/plain'",
+                                  http_code=HTTPStatus.NOT_ACCEPTABLE)
+
+        content = self.show(session, _id)
+        if content["_admin"]["onboardingState"] != "ONBOARDED":
+            raise EngineException("Cannot get content because this resource is not at 'ONBOARDED' state. "
+                                  "onboardingState is {}".format(content["_admin"]["onboardingState"]),
+                                  http_code=HTTPStatus.CONFLICT)
+        storage = content["_admin"]["storage"]
+        if path is not None and path != "$DESCRIPTOR":   # artifacts
+            if not storage.get('pkg-dir'):
+                raise EngineException("Packages does not contains artifacts", http_code=HTTPStatus.BAD_REQUEST)
+            if self.fs.file_exists((storage['folder'], storage['pkg-dir'], *path), 'dir'):
+                folder_content = self.fs.dir_ls((storage['folder'], storage['pkg-dir'], *path))
+                return folder_content, "text/plain"
+                # TODO manage folders in http
+            else:
+                return self.fs.file_open((storage['folder'], storage['pkg-dir'], *path), "rb"),\
+                    "application/octet-stream"
+
+        # pkgtype   accept  ZIP  TEXT    -> result
+        # manyfiles         yes  X       -> zip
+        #                   no   yes     -> error
+        # onefile           yes  no      -> zip
+        #                   X    yes     -> text
+
+        if accept_text and (not storage.get('pkg-dir') or path == "$DESCRIPTOR"):
+            return self.fs.file_open((storage['folder'], storage['descriptor']), "r"), "text/plain"
+        elif storage.get('pkg-dir') and not accept_zip:
+            raise EngineException("Packages that contains several files need to be retrieved with 'application/zip'"
+                                  "Accept header", http_code=HTTPStatus.NOT_ACCEPTABLE)
+        else:
+            if not storage.get('zipfile'):
+                # TODO generate zipfile if not present
+                raise EngineException("Only allowed 'text/plain' Accept header for this descriptor. To be solved in "
+                                      "future versions", http_code=HTTPStatus.NOT_ACCEPTABLE)
+            return self.fs.file_open((storage['folder'], storage['zipfile']), "rb"), "application/zip"
+
+
+class VnfdTopic(DescriptorTopic):
+    topic = "vnfds"
+    topic_msg = "vnfd"
+
+    def __init__(self, db, fs, msg):
+        DescriptorTopic.__init__(self, db, fs, msg)
+
+    @staticmethod
+    def _remove_envelop(indata=None):
+        if not indata:
+            return {}
+        clean_indata = indata
+        if clean_indata.get('vnfd:vnfd-catalog'):
+            clean_indata = clean_indata['vnfd:vnfd-catalog']
+        elif clean_indata.get('vnfd-catalog'):
+            clean_indata = clean_indata['vnfd-catalog']
+        if clean_indata.get('vnfd'):
+            if not isinstance(clean_indata['vnfd'], list) or len(clean_indata['vnfd']) != 1:
+                raise EngineException("'vnfd' must be a list only one element")
+            clean_indata = clean_indata['vnfd'][0]
+        return clean_indata
+
+    def check_conflict_on_del(self, session, _id, force=False):
+        """
+        Check that there is not any NSD that uses this VNFD. Only NSDs belonging to this project are considered. Note
+        that VNFD can be public and be used by NSD of other projects. Also check there are not deployments, or vnfr
+        that uses this vnfd
+        :param session:
+        :param _id: vnfd inernal id
+        :param force: Avoid this checking
+        :return: None or raises EngineException with the conflict
+        """
+        if force:
+            return
+        descriptor = self.db.get_one("vnfds", {"_id": _id})
+        descriptor_id = descriptor.get("id")
+        if not descriptor_id:  # empty vnfd not uploaded
+            return
+
+        _filter = self._get_project_filter(session, write=False, show_all=False)
+        # check vnfrs using this vnfd
+        _filter["vnfd-id"] = _id
+        if self.db.get_list("vnfrs", _filter):
+            raise EngineException("There is some VNFR that depends on this VNFD", http_code=HTTPStatus.CONFLICT)
+        del _filter["vnfd-id"]
+        # check NSD using this VNFD
+        _filter["constituent-vnfd.ANYINDEX.vnfd-id-ref"] = descriptor_id
+        if self.db.get_list("nsds", _filter):
+            raise EngineException("There is soame NSD that depends on this VNFD", http_code=HTTPStatus.CONFLICT)
+
+    def _validate_input_new(self, indata, force=False):
+        # TODO validate with pyangbind, serialize
+        return indata
+
+    def _validate_input_edit(self, indata, force=False):
+        # TODO validate with pyangbind, serialize
+        return indata
+
+
+class NsdTopic(DescriptorTopic):
+    topic = "nsds"
+    topic_msg = "nsd"
+
+    def __init__(self, db, fs, msg):
+        DescriptorTopic.__init__(self, db, fs, msg)
+
+    @staticmethod
+    def _remove_envelop(indata=None):
+        if not indata:
+            return {}
+        clean_indata = indata
+
+        if clean_indata.get('nsd:nsd-catalog'):
+            clean_indata = clean_indata['nsd:nsd-catalog']
+        elif clean_indata.get('nsd-catalog'):
+            clean_indata = clean_indata['nsd-catalog']
+        if clean_indata.get('nsd'):
+            if not isinstance(clean_indata['nsd'], list) or len(clean_indata['nsd']) != 1:
+                raise EngineException("'nsd' must be a list only one element")
+            clean_indata = clean_indata['nsd'][0]
+        return clean_indata
+
+    def _validate_input_new(self, indata, force=False):
+        # transform constituent-vnfd:member-vnf-index to string
+        if indata.get("constituent-vnfd"):
+            for constituent_vnfd in indata["constituent-vnfd"]:
+                if "member-vnf-index" in constituent_vnfd:
+                    constituent_vnfd["member-vnf-index"] = str(constituent_vnfd["member-vnf-index"])
+
+        # TODO validate with pyangbind, serialize
+        return indata
+
+    def _validate_input_edit(self, indata, force=False):
+        # TODO validate with pyangbind, serialize
+        return indata
+
+    def _check_descriptor_dependencies(self, session, descriptor):
+        """
+        Check that the dependent descriptors exist on a new descriptor or edition
+        :param session: client session information
+        :param descriptor: descriptor to be inserted or edit
+        :return: None or raises exception
+        """
+        if not descriptor.get("constituent-vnfd"):
+            return
+        for vnf in descriptor["constituent-vnfd"]:
+            vnfd_id = vnf["vnfd-id-ref"]
+            filter_q = self._get_project_filter(session, write=False, show_all=True)
+            filter_q["id"] = vnfd_id
+            if not self.db.get_list("vnfds", filter_q):
+                raise EngineException("Descriptor error at 'constituent-vnfd':'vnfd-id-ref'='{}' references a non "
+                                      "existing vnfd".format(vnfd_id), http_code=HTTPStatus.CONFLICT)
+
+    def check_conflict_on_edit(self, session, final_content, edit_content, _id, force=False):
+        super().check_conflict_on_edit(session, final_content, edit_content, _id, force=force)
+
+        self._check_descriptor_dependencies(session, final_content)
+
+    def check_conflict_on_del(self, session, _id, force=False):
+        """
+        Check that there is not any NSR that uses this NSD. Only NSRs belonging to this project are considered. Note
+        that NSD can be public and be used by other projects.
+        :param session:
+        :param _id: vnfd inernal id
+        :param force: Avoid this checking
+        :return: None or raises EngineException with the conflict
+        """
+        if force:
+            return
+        _filter = self._get_project_filter(session, write=False, show_all=False)
+        _filter["nsdId"] = _id
+        if self.db.get_list("nsrs", _filter):
+            raise EngineException("There is some NSR that depends on this NSD", http_code=HTTPStatus.CONFLICT)
+
+
+class PduTopic(BaseTopic):
+    topic = "pdus"
+    topic_msg = "pdu"
+    schema_new = pdu_new_schema
+    schema_edit = pdu_edit_schema
+
+    def __init__(self, db, fs, msg):
+        BaseTopic.__init__(self, db, fs, msg)
+
+    @staticmethod
+    def format_on_new(content, project_id=None, make_public=False):
+        BaseTopic.format_on_new(content, project_id=None, make_public=make_public)
+        content["_admin"]["onboardingState"] = "CREATED"
+        content["_admin"]["operationalState"] = "DISABLED"
+        content["_admin"]["usageSate"] = "NOT_IN_USE"
+
+    def check_conflict_on_del(self, session, _id, force=False):
+        if force:
+            return
+        # TODO Is it needed to check descriptors _admin.project_read/project_write??
+        _filter = {"vdur.pdu-id": _id}
+        if self.db.get_list("vnfrs", _filter):
+            raise EngineException("There is some NSR that uses this PDU", http_code=HTTPStatus.CONFLICT)
index 29bd4f1..ab7eec0 100644 (file)
@@ -1,55 +1,42 @@
 # -*- coding: utf-8 -*-
 
-from osm_common import dbmongo
-from osm_common import dbmemory
-from osm_common import fslocal
-from osm_common import msglocal
-from osm_common import msgkafka
-import tarfile
-import yaml
-import json
 import logging
-from random import choice as random_choice
-from uuid import uuid4
-from hashlib import sha256, md5
-from osm_common.dbbase import DbException, deep_update
+from osm_common import dbmongo, dbmemory, fslocal, msglocal, msgkafka, version as common_version
+from osm_common.dbbase import DbException
 from osm_common.fsbase import FsException
 from osm_common.msgbase import MsgException
 from http import HTTPStatus
-from time import time
-from copy import deepcopy, copy
-from validation import validate_input, ValidationError
+from base_topic import EngineException, versiontuple
+from admin_topics import UserTopic, ProjectTopic, VimAccountTopic, SdnTopic
+from descriptor_topics import VnfdTopic, NsdTopic, PduTopic
+from instance_topics import NsrTopic, VnfrTopic, NsLcmOpTopic
 
 __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
-
-
-class EngineException(Exception):
-
-    def __init__(self, message, http_code=HTTPStatus.BAD_REQUEST):
-        self.http_code = http_code
-        Exception.__init__(self, message)
-
-
-def get_iterable(input):
-    """
-    Returns an iterable, in case input is None it just returns an empty tuple
-    :param input:
-    :return: iterable
-    """
-    if input is None:
-        return ()
-    return input
+min_common_version = "0.1.8"
 
 
 class Engine(object):
+    map_from_topic_to_class = {
+        "vnfds": VnfdTopic,
+        "nsds": NsdTopic,
+        "pdus": PduTopic,
+        "nsrs": NsrTopic,
+        "vnfrs": VnfrTopic,
+        "nslcmops": NsLcmOpTopic,
+        "vim_accounts": VimAccountTopic,
+        "sdns": SdnTopic,
+        "users": UserTopic,
+        "projects": ProjectTopic,
+        # [NEW_TOPIC]: add an entry here
+    }
 
     def __init__(self):
-        self.tokens = {}
         self.db = None
         self.fs = None
         self.msg = None
         self.config = None
         self.logger = logging.getLogger("nbi.engine")
+        self.map_topic = {}
 
     def start(self, config):
         """
@@ -58,6 +45,11 @@ class Engine(object):
         :return: None
         """
         self.config = config
+        # check right version of common
+        if versiontuple(common_version) < versiontuple(min_common_version):
+            raise EngineException("Not compatible osm/common version '{}'. Needed '{}' or higher".format(
+                common_version, min_common_version))
+
         try:
             if not self.db:
                 if config["database"]["driver"] == "mongo":
@@ -86,6 +78,10 @@ class Engine(object):
                 else:
                     raise EngineException("Invalid configuration param '{}' at '[message]':'driver'".format(
                         config["storage"]["driver"]))
+
+            # create one class per topic
+            for topic, topic_class in self.map_from_topic_to_class.items():
+                self.map_topic[topic] = topic_class(self.db, self.fs, self.msg)
         except (DbException, FsException, MsgException) as e:
             raise EngineException(str(e), http_code=e.http_code)
 
@@ -100,994 +96,102 @@ class Engine(object):
         except (DbException, FsException, MsgException) as e:
             raise EngineException(str(e), http_code=e.http_code)
 
-    def authorize(self, token):
-        try:
-            if not token:
-                raise EngineException("Needed a token or Authorization http header",
-                                      http_code=HTTPStatus.UNAUTHORIZED)
-            if token not in self.tokens:
-                raise EngineException("Invalid token or Authorization http header",
-                                      http_code=HTTPStatus.UNAUTHORIZED)
-            session = self.tokens[token]
-            now = time()
-            if session["expires"] < now:
-                del self.tokens[token]
-                raise EngineException("Expired Token or Authorization http header",
-                                      http_code=HTTPStatus.UNAUTHORIZED)
-            return session
-        except EngineException:
-            if self.config["global"].get("test.user_not_authorized"):
-                return {"id": "fake-token-id-for-test",
-                        "project_id": self.config["global"].get("test.project_not_authorized", "admin"),
-                        "username": self.config["global"]["test.user_not_authorized"]}
-            else:
-                raise
-
-    def new_token(self, session, indata, remote):
-        now = time()
-        user_content = None
-
-        # Try using username/password
-        if indata.get("username"):
-            user_rows = self.db.get_list("users", {"username": indata.get("username")})
-            user_content = None
-            if user_rows:
-                user_content = user_rows[0]
-                salt = user_content["_admin"]["salt"]
-                shadow_password = sha256(indata.get("password", "").encode('utf-8') + salt.encode('utf-8')).hexdigest()
-                if shadow_password != user_content["password"]:
-                    user_content = None
-            if not user_content:
-                raise EngineException("Invalid username/password", http_code=HTTPStatus.UNAUTHORIZED)
-        elif session:
-            user_rows = self.db.get_list("users", {"username": session["username"]})
-            if user_rows:
-                user_content = user_rows[0]
-            else:
-                raise EngineException("Invalid token", http_code=HTTPStatus.UNAUTHORIZED)
-        else:
-            raise EngineException("Provide credentials: username/password or Authorization Bearer token",
-                                  http_code=HTTPStatus.UNAUTHORIZED)
-
-        token_id = ''.join(random_choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
-                           for _ in range(0, 32))
-        if indata.get("project_id"):
-            project_id = indata.get("project_id")
-            if project_id not in user_content["projects"]:
-                raise EngineException("project {} not allowed for this user".format(project_id),
-                                      http_code=HTTPStatus.UNAUTHORIZED)
-        else:
-            project_id = user_content["projects"][0]
-        if project_id == "admin":
-            session_admin = True
-        else:
-            project = self.db.get_one("projects", {"_id": project_id})
-            session_admin = project.get("admin", False)
-        new_session = {"issued_at": now, "expires": now+3600,
-                       "_id": token_id, "id": token_id, "project_id": project_id, "username": user_content["username"],
-                       "remote_port": remote.port, "admin": session_admin}
-        if remote.name:
-            new_session["remote_host"] = remote.name
-        elif remote.ip:
-            new_session["remote_host"] = remote.ip
-
-        self.tokens[token_id] = new_session
-        return deepcopy(new_session)
-
-    def get_token_list(self, session):
-        token_list = []
-        for token_id, token_value in self.tokens.items():
-            if token_value["username"] == session["username"]:
-                token_list.append(deepcopy(token_value))
-        return token_list
-
-    def get_token(self, session, token_id):
-        token_value = self.tokens.get(token_id)
-        if not token_value:
-            raise EngineException("token not found", http_code=HTTPStatus.NOT_FOUND)
-        if token_value["username"] != session["username"] and not session["admin"]:
-            raise EngineException("needed admin privileges", http_code=HTTPStatus.UNAUTHORIZED)
-        return token_value
-
-    def del_token(self, token_id):
-        try:
-            del self.tokens[token_id]
-            return "token '{}' deleted".format(token_id)
-        except KeyError:
-            raise EngineException("Token '{}' not found".format(token_id), http_code=HTTPStatus.NOT_FOUND)
-
-    @staticmethod
-    def _remove_envelop(item, indata=None):
-        """
-        Obtain the useful data removing the envelop. It goes throw the vnfd or nsd catalog and returns the
-        vnfd or nsd content
-        :param item: can be vnfds, nsds, users, projects, userDefinedData (initial content of a vnfds, nsds
-        :param indata: Content to be inspected
-        :return: the useful part of indata
-        """
-        clean_indata = indata
-        if not indata:
-            return {}
-        if item == "vnfds":
-            if clean_indata.get('vnfd:vnfd-catalog'):
-                clean_indata = clean_indata['vnfd:vnfd-catalog']
-            elif clean_indata.get('vnfd-catalog'):
-                clean_indata = clean_indata['vnfd-catalog']
-            if clean_indata.get('vnfd'):
-                if not isinstance(clean_indata['vnfd'], list) or len(clean_indata['vnfd']) != 1:
-                    raise EngineException("'vnfd' must be a list only one element")
-                clean_indata = clean_indata['vnfd'][0]
-        elif item == "nsds":
-            if clean_indata.get('nsd:nsd-catalog'):
-                clean_indata = clean_indata['nsd:nsd-catalog']
-            elif clean_indata.get('nsd-catalog'):
-                clean_indata = clean_indata['nsd-catalog']
-            if clean_indata.get('nsd'):
-                if not isinstance(clean_indata['nsd'], list) or len(clean_indata['nsd']) != 1:
-                    raise EngineException("'nsd' must be a list only one element")
-                clean_indata = clean_indata['nsd'][0]
-        elif item == "userDefinedData":
-            if "userDefinedData" in indata:
-                clean_indata = clean_indata['userDefinedData']
-        return clean_indata
-
-    def _check_project_dependencies(self, project_id):
-        """
-        Check if a project can be deleted
-        :param session:
-        :param _id:
-        :return:
-        """
-        # TODO Is it needed to check descriptors _admin.project_read/project_write??
-        _filter = {"projects": project_id}
-        if self.db.get_list("users", _filter):
-            raise EngineException("There are users that uses this project", http_code=HTTPStatus.CONFLICT)
-
-    def _check_dependencies_on_descriptor(self, session, item, descriptor_id, _id):
-        """
-        Check that the descriptor to be deleded is not a dependency of others
-        :param session: client session information
-        :param item: can be vnfds, nsds
-        :param descriptor_id: id (provided by client) of descriptor to be deleted
-        :param _id: internal id of descriptor to be deleted
-        :return: None or raises exception
-        """
-        if item == "vnfds":
-            _filter = {"constituent-vnfd.ANYINDEX.vnfd-id-ref": descriptor_id}
-            if self.get_item_list(session, "nsds", _filter):
-                raise EngineException("There are nsd that depends on this VNFD", http_code=HTTPStatus.CONFLICT)
-            if self.get_item_list(session, "vnfrs", {"vnfd-id": _id}):
-                raise EngineException("There are vnfr that depends on this VNFD", http_code=HTTPStatus.CONFLICT)
-        elif item == "nsds":
-            _filter = {"nsdId": _id}
-            if self.get_item_list(session, "nsrs", _filter):
-                raise EngineException("There are nsr that depends on this NSD", http_code=HTTPStatus.CONFLICT)
-
-    def _check_descriptor_dependencies(self, session, item, descriptor):
-        """
-        Check that the dependent descriptors exist on a new descriptor or edition
-        :param session: client session information
-        :param item: can be nsds, nsrs
-        :param descriptor: descriptor to be inserted or edit
-        :return: None or raises exception
-        """
-        if item == "nsds":
-            if not descriptor.get("constituent-vnfd"):
-                return
-            for vnf in descriptor["constituent-vnfd"]:
-                vnfd_id = vnf["vnfd-id-ref"]
-                if not self.get_item_list(session, "vnfds", {"id": vnfd_id}):
-                    raise EngineException("Descriptor error at 'constituent-vnfd':'vnfd-id-ref'='{}' references a non "
-                                          "existing vnfd".format(vnfd_id), http_code=HTTPStatus.CONFLICT)
-        elif item == "nsrs":
-            if not descriptor.get("nsdId"):
-                return
-            nsd_id = descriptor["nsdId"]
-            if not self.get_item_list(session, "nsds", {"id": nsd_id}):
-                raise EngineException("Descriptor error at nsdId='{}' references a non exist nsd".format(nsd_id),
-                                      http_code=HTTPStatus.CONFLICT)
-
-    def _check_edition(self, session, item, indata, id, force=False):
-        if item == "users":
-            if indata.get("projects"):
-                if not session["admin"]:
-                    raise EngineException("Needed admin privileges to edit user projects", HTTPStatus.UNAUTHORIZED)
-            if indata.get("password"):
-                # regenerate salt and encrypt password
-                salt = uuid4().hex
-                indata["_admin"] = {"salt": salt}
-                indata["password"] = sha256(indata["password"].encode('utf-8') + salt.encode('utf-8')).hexdigest()
-
-    def _validate_new_data(self, session, item, indata, id=None, force=False):
-        if item == "users":
-            # check username not exists
-            if not id and self.db.get_one(item, {"username": indata.get("username")}, fail_on_empty=False,
-                                          fail_on_more=False):
-                raise EngineException("username '{}' exists".format(indata["username"]), HTTPStatus.CONFLICT)
-            # check projects
-            if not force:
-                for p in indata["projects"]:
-                    if p == "admin":
-                        continue
-                    if not self.db.get_one("projects", {"_id": p}, fail_on_empty=False, fail_on_more=False):
-                        raise EngineException("project '{}' does not exists".format(p), HTTPStatus.CONFLICT)
-        elif item == "projects":
-            if not indata.get("name"):
-                raise EngineException("missing 'name'")
-            # check name not exists
-            if not id and self.db.get_one(item, {"name": indata.get("name")}, fail_on_empty=False, fail_on_more=False):
-                raise EngineException("name '{}' exists".format(indata["name"]), HTTPStatus.CONFLICT)
-        elif item in ("vnfds", "nsds"):
-            filter = {"id": indata["id"]}
-            if id:
-                filter["_id.neq"] = id
-            # TODO add admin to filter, validate rights
-            self._add_read_filter(session, item, filter)
-            if self.db.get_one(item, filter, fail_on_empty=False):
-                raise EngineException("{} with id '{}' already exists for this tenant".format(item[:-1], indata["id"]),
-                                      HTTPStatus.CONFLICT)
-            # TODO validate with pyangbind. Load and dumps to convert data types
-            if item == "nsds":
-                # transform constituent-vnfd:member-vnf-index to string
-                if indata.get("constituent-vnfd"):
-                    for constituent_vnfd in indata["constituent-vnfd"]:
-                        if "member-vnf-index" in constituent_vnfd:
-                            constituent_vnfd["member-vnf-index"] = str(constituent_vnfd["member-vnf-index"])
-
-            if item == "nsds" and not force:
-                self._check_descriptor_dependencies(session, "nsds", indata)
-        elif item == "userDefinedData":
-            # TODO validate userDefinedData is a keypair values
-            pass
-
-        elif item == "nsrs":
-            pass
-        elif item == "vim_accounts" or item == "sdns":
-            filter = {"name": indata.get("name")}
-            if id:
-                filter["_id.neq"] = id
-            if self.db.get_one(item, filter, fail_on_empty=False, fail_on_more=False):
-                raise EngineException("name '{}' already exists for {}".format(indata["name"], item),
-                                      HTTPStatus.CONFLICT)
-
-    def _check_ns_operation(self, session, nsr, operation, indata):
-        """
-        Check that user has enter right parameters for the operation
-        :param session:
-        :param operation: it can be: instantiate, terminate, action, TODO: update, heal
-        :param indata: descriptor with the parameters of the operation
-        :return: None
-        """
-        vnfds = {}
-        vim_accounts = []
-        nsd = nsr["nsd"]
-
-        def check_valid_vnf_member_index(member_vnf_index):
-            for vnf in nsd["constituent-vnfd"]:
-                if member_vnf_index == vnf["member-vnf-index"]:
-                    vnfd_id = vnf["vnfd-id-ref"]
-                    if vnfd_id not in vnfds:
-                        vnfds[vnfd_id] = self.db.get_one("vnfds", {"id": vnfd_id})
-                    return vnfds[vnfd_id]
-            else:
-                raise EngineException("Invalid parameter member_vnf_index='{}' is not one of the "
-                                      "nsd:constituent-vnfd".format(member_vnf_index))
-
-        def check_valid_vim_account(vim_account):
-            if vim_account in vim_accounts:
-                return
-            try:
-                self.db.get_one("vim_accounts", {"_id": vim_account})
-            except Exception:
-                raise EngineException("Invalid vimAccountId='{}' not present".format(vim_account))
-            vim_accounts.append(vim_account)
-
-        if operation == "action":
-            # check vnf_member_index
-            if indata.get("vnf_member_index"):
-                indata["member_vnf_index"] = indata.pop("vnf_member_index")    # for backward compatibility
-            if not indata.get("member_vnf_index"):
-                raise EngineException("Missing 'member_vnf_index' parameter")
-            vnfd = check_valid_vnf_member_index(indata["member_vnf_index"])
-            # check primitive
-            for config_primitive in get_iterable(vnfd.get("vnf-configuration", {}).get("config-primitive")):
-                if indata["primitive"] == config_primitive["name"]:
-                    # check needed primitive_params are provided
-                    if indata.get("primitive_params"):
-                        in_primitive_params_copy = copy(indata["primitive_params"])
-                    else:
-                        in_primitive_params_copy = {}
-                    for paramd in get_iterable(config_primitive.get("parameter")):
-                        if paramd["name"] in in_primitive_params_copy:
-                            del in_primitive_params_copy[paramd["name"]]
-                        elif not paramd.get("default-value"):
-                            raise EngineException("Needed parameter {} not provided for primitive '{}'".format(
-                                paramd["name"], indata["primitive"]))
-                    # check no extra primitive params are provided
-                    if in_primitive_params_copy:
-                        raise EngineException("parameter/s '{}' not present at vnfd for primitive '{}'".format(
-                            list(in_primitive_params_copy.keys()), indata["primitive"]))
-                    break
-            else:
-                raise EngineException("Invalid primitive '{}' is not present at vnfd".format(indata["primitive"]))
-        if operation == "scale":
-            vnfd = check_valid_vnf_member_index(indata["scaleVnfData"]["scaleByStepData"]["member-vnf-index"])
-            for scaling_group in get_iterable(vnfd.get("scaling-group-descriptor")):
-                if indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"] == scaling_group["name"]:
-                    break
-            else:
-                raise EngineException("Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
-                                      "present at vnfd:scaling-group-descriptor".format(
-                                          indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]))
-        if operation == "instantiate":
-            # check vim_account
-            check_valid_vim_account(indata["vimAccountId"])
-            for in_vnf in get_iterable(indata.get("vnf")):
-                vnfd = check_valid_vnf_member_index(in_vnf["member-vnf-index"])
-                if in_vnf.get("vimAccountId"):
-                    check_valid_vim_account(in_vnf["vimAccountId"])
-                for in_vdu in get_iterable(in_vnf.get("vdu")):
-                    for vdud in get_iterable(vnfd.get("vdu")):
-                        if vdud["id"] == in_vdu["id"]:
-                            for volume in get_iterable(in_vdu.get("volume")):
-                                for volumed in get_iterable(vdud.get("volumes")):
-                                    if volumed["name"] == volume["name"]:
-                                        break
-                                else:
-                                    raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
-                                                          "volume:name='{}' is not present at vnfd:vdu:volumes list".
-                                                          format(in_vnf["member-vnf-index"], in_vdu["id"],
-                                                                 volume["name"]))
-                            break
-                    else:
-                        raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu:id='{}' is not "
-                                              "present at vnfd".format(in_vnf["member-vnf-index"], in_vdu["id"]))
-
-                for in_internal_vld in get_iterable(in_vnf.get("internal-vld")):
-                    for internal_vldd in get_iterable(vnfd.get("internal-vld")):
-                        if in_internal_vld["name"] == internal_vldd["name"] or \
-                                in_internal_vld["name"] == internal_vldd["id"]:
-                            break
-                    else:
-                        raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
-                                              " is not present at vnfd '{}'".format(in_vnf["member-vnf-index"],
-                                                                                    in_internal_vld["name"],
-                                                                                    vnfd["id"]))
-            for in_vld in get_iterable(indata.get("vld")):
-                for vldd in get_iterable(nsd.get("vld")):
-                    if in_vld["name"] == vldd["name"] or in_vld["name"] == vldd["id"]:
-                        break
-                else:
-                    raise EngineException("Invalid parameter vld:name='{}' is not present at nsd:vld".format(
-                        in_vld["name"]))
-
-    def _format_new_data(self, session, item, indata):
-        now = time()
-        if "_admin" not in indata:
-            indata["_admin"] = {}
-        indata["_admin"]["created"] = now
-        indata["_admin"]["modified"] = now
-        if item == "users":
-            indata["_id"] = indata["username"]
-            salt = uuid4().hex
-            indata["_admin"]["salt"] = salt
-            indata["password"] = sha256(indata["password"].encode('utf-8') + salt.encode('utf-8')).hexdigest()
-        elif item == "projects":
-            indata["_id"] = indata["name"]
-        else:
-            if not indata.get("_id"):
-                indata["_id"] = str(uuid4())
-            if item in ("vnfds", "nsds", "nsrs", "vnfrs"):
-                if not indata["_admin"].get("projects_read"):
-                    indata["_admin"]["projects_read"] = [session["project_id"]]
-                if not indata["_admin"].get("projects_write"):
-                    indata["_admin"]["projects_write"] = [session["project_id"]]
-            if item in ("vnfds", "nsds"):
-                indata["_admin"]["onboardingState"] = "CREATED"
-                indata["_admin"]["operationalState"] = "DISABLED"
-                indata["_admin"]["usageSate"] = "NOT_IN_USE"
-            if item == "nsrs":
-                indata["_admin"]["nsState"] = "NOT_INSTANTIATED"
-            if item in ("vim_accounts", "sdns"):
-                indata["_admin"]["operationalState"] = "PROCESSING"
-
-    def upload_content(self, session, item, _id, indata, kwargs, headers):
-        """
-        Used for receiving content by chunks (with a transaction_id header and/or gzip file. It will store and extract)
-        :param session: session
-        :param item: can be nsds or vnfds
-        :param _id : the nsd,vnfd is already created, this is the id
-        :param indata: http body request
-        :param kwargs: user query string to override parameters. NOT USED
-        :param headers:  http request headers
-        :return: True package has is completely uploaded or False if partial content has been uplodaed.
-            Raise exception on error
-        """
-        # Check that _id exists and it is valid
-        current_desc = self.get_item(session, item, _id)
-
-        content_range_text = headers.get("Content-Range")
-        expected_md5 = headers.get("Content-File-MD5")
-        compressed = None
-        content_type = headers.get("Content-Type")
-        if content_type and "application/gzip" in content_type or "application/x-gzip" in content_type or \
-                "application/zip" in content_type:
-            compressed = "gzip"
-        filename = headers.get("Content-Filename")
-        if not filename:
-            filename = "package.tar.gz" if compressed else "package"
-        # TODO change to Content-Disposition filename https://tools.ietf.org/html/rfc6266
-        file_pkg = None
-        error_text = ""
-        try:
-            if content_range_text:
-                content_range = content_range_text.replace("-", " ").replace("/", " ").split()
-                if content_range[0] != "bytes":  # TODO check x<y not negative < total....
-                    raise IndexError()
-                start = int(content_range[1])
-                end = int(content_range[2]) + 1
-                total = int(content_range[3])
-            else:
-                start = 0
-
-            if start:
-                if not self.fs.file_exists(_id, 'dir'):
-                    raise EngineException("invalid Transaction-Id header", HTTPStatus.NOT_FOUND)
-            else:
-                self.fs.file_delete(_id, ignore_non_exist=True)
-                self.fs.mkdir(_id)
-
-            storage = self.fs.get_params()
-            storage["folder"] = _id
-
-            file_path = (_id, filename)
-            if self.fs.file_exists(file_path, 'file'):
-                file_size = self.fs.file_size(file_path)
-            else:
-                file_size = 0
-            if file_size != start:
-                raise EngineException("invalid Content-Range start sequence, expected '{}' but received '{}'".format(
-                    file_size, start), HTTPStatus.REQUESTED_RANGE_NOT_SATISFIABLE)
-            file_pkg = self.fs.file_open(file_path, 'a+b')
-            if isinstance(indata, dict):
-                indata_text = yaml.safe_dump(indata, indent=4, default_flow_style=False)
-                file_pkg.write(indata_text.encode(encoding="utf-8"))
-            else:
-                indata_len = 0
-                while True:
-                    indata_text = indata.read(4096)
-                    indata_len += len(indata_text)
-                    if not indata_text:
-                        break
-                    file_pkg.write(indata_text)
-            if content_range_text:
-                if indata_len != end-start:
-                    raise EngineException("Mismatch between Content-Range header {}-{} and body length of {}".format(
-                        start, end-1, indata_len), HTTPStatus.REQUESTED_RANGE_NOT_SATISFIABLE)
-                if end != total:
-                    # TODO update to UPLOADING
-                    return False
-
-            # PACKAGE UPLOADED
-            if expected_md5:
-                file_pkg.seek(0, 0)
-                file_md5 = md5()
-                chunk_data = file_pkg.read(1024)
-                while chunk_data:
-                    file_md5.update(chunk_data)
-                    chunk_data = file_pkg.read(1024)
-                if expected_md5 != file_md5.hexdigest():
-                    raise EngineException("Error, MD5 mismatch", HTTPStatus.CONFLICT)
-            file_pkg.seek(0, 0)
-            if compressed == "gzip":
-                tar = tarfile.open(mode='r', fileobj=file_pkg)
-                descriptor_file_name = None
-                for tarinfo in tar:
-                    tarname = tarinfo.name
-                    tarname_path = tarname.split("/")
-                    if not tarname_path[0] or ".." in tarname_path:  # if start with "/" means absolute path
-                        raise EngineException("Absolute path or '..' are not allowed for package descriptor tar.gz")
-                    if len(tarname_path) == 1 and not tarinfo.isdir():
-                        raise EngineException("All files must be inside a dir for package descriptor tar.gz")
-                    if tarname.endswith(".yaml") or tarname.endswith(".json") or tarname.endswith(".yml"):
-                        storage["pkg-dir"] = tarname_path[0]
-                        if len(tarname_path) == 2:
-                            if descriptor_file_name:
-                                raise EngineException(
-                                    "Found more than one descriptor file at package descriptor tar.gz")
-                            descriptor_file_name = tarname
-                if not descriptor_file_name:
-                    raise EngineException("Not found any descriptor file at package descriptor tar.gz")
-                storage["descriptor"] = descriptor_file_name
-                storage["zipfile"] = filename
-                self.fs.file_extract(tar, _id)
-                with self.fs.file_open((_id, descriptor_file_name), "r") as descriptor_file:
-                    content = descriptor_file.read()
-            else:
-                content = file_pkg.read()
-                storage["descriptor"] = descriptor_file_name = filename
-
-            if descriptor_file_name.endswith(".json"):
-                error_text = "Invalid json format "
-                indata = json.load(content)
-            else:
-                error_text = "Invalid yaml format "
-                indata = yaml.load(content)
-
-            current_desc["_admin"]["storage"] = storage
-            current_desc["_admin"]["onboardingState"] = "ONBOARDED"
-            current_desc["_admin"]["operationalState"] = "ENABLED"
-
-            self._edit_item(session, item, _id, current_desc, indata, kwargs)
-            # TODO if descriptor has changed because kwargs update content and remove cached zip
-            # TODO if zip is not present creates one
-            return True
-
-        except EngineException:
-            raise
-        except IndexError:
-            raise EngineException("invalid Content-Range header format. Expected 'bytes start-end/total'",
-                                  HTTPStatus.REQUESTED_RANGE_NOT_SATISFIABLE)
-        except IOError as e:
-            raise EngineException("invalid upload transaction sequence: '{}'".format(e), HTTPStatus.BAD_REQUEST)
-        except tarfile.ReadError as e:
-            raise EngineException("invalid file content {}".format(e), HTTPStatus.BAD_REQUEST)
-        except (ValueError, yaml.YAMLError) as e:
-            raise EngineException(error_text + str(e))
-        finally:
-            if file_pkg:
-                file_pkg.close()
-
-    def new_nsr(self, rollback, session, ns_request):
-        """
-        Creates a new nsr into database. It also creates needed vnfrs
-        :param rollback: list where this method appends created items at database in case a rollback may to be done
-        :param session: contains the used login username and working project
-        :param ns_request: params to be used for the nsr
-        :return: the _id of nsr descriptor stored at database
-        """
-        rollback_index = len(rollback)
-        step = ""
-        try:
-            # look for nsr
-            step = "getting nsd id='{}' from database".format(ns_request.get("nsdId"))
-            nsd = self.get_item(session, "nsds", ns_request["nsdId"])
-            nsr_id = str(uuid4())
-            now = time()
-            step = "filling nsr from input data"
-            nsr_descriptor = {
-                "name": ns_request["nsName"],
-                "name-ref": ns_request["nsName"],
-                "short-name": ns_request["nsName"],
-                "admin-status": "ENABLED",
-                "nsd": nsd,
-                "datacenter": ns_request["vimAccountId"],
-                "resource-orchestrator": "osmopenmano",
-                "description": ns_request.get("nsDescription", ""),
-                "constituent-vnfr-ref": [],
-
-                "operational-status": "init",    # typedef ns-operational-
-                "config-status": "init",         # typedef config-states
-                "detailed-status": "scheduled",
-
-                "orchestration-progress": {},
-                # {"networks": {"active": 0, "total": 0}, "vms": {"active": 0, "total": 0}},
-
-                "create-time": now,
-                "nsd-name-ref": nsd["name"],
-                "operational-events": [],   # "id", "timestamp", "description", "event",
-                "nsd-ref": nsd["id"],
-                "nsdId": nsd["_id"],
-                "instantiate_params": ns_request,
-                "ns-instance-config-ref": nsr_id,
-                "id": nsr_id,
-                "_id": nsr_id,
-                # "input-parameter": xpath, value,
-                "ssh-authorized-key": ns_request.get("key-pair-ref"),
-            }
-            ns_request["nsr_id"] = nsr_id
-
-            # Create VNFR
-            needed_vnfds = {}
-            for member_vnf in nsd["constituent-vnfd"]:
-                vnfd_id = member_vnf["vnfd-id-ref"]
-                step = "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
-                    member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
-                if vnfd_id not in needed_vnfds:
-                    # Obtain vnfd
-                    vnf_filter = {"id": vnfd_id}
-                    self._add_read_filter(session, "vnfds", vnf_filter)
-                    vnfd = self.db.get_one("vnfds", vnf_filter)
-                    vnfd.pop("_admin")
-                    needed_vnfds[vnfd_id] = vnfd
-                else:
-                    vnfd = needed_vnfds[vnfd_id]
-                step = "filling vnfr  vnfd-id='{}' constituent-vnfd='{}'".format(
-                    member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
-                vnfr_id = str(uuid4())
-                vnfr_descriptor = {
-                    "id": vnfr_id,
-                    "_id": vnfr_id,
-                    "nsr-id-ref": nsr_id,
-                    "member-vnf-index-ref": member_vnf["member-vnf-index"],
-                    "created-time": now,
-                    # "vnfd": vnfd,        # at OSM model.but removed to avoid data duplication TODO: revise
-                    "vnfd-ref": vnfd_id,
-                    "vnfd-id": vnfd["_id"],    # not at OSM model, but useful
-                    "vim-account-id": None,
-                    "vdur": [],
-                    "connection-point": [],
-                    "ip-address": None,  # mgmt-interface filled by LCM
-                }
-                for cp in vnfd.get("connection-point", ()):
-                    vnf_cp = {
-                        "name": cp["name"],
-                        "connection-point-id": cp.get("id"),
-                        "id": cp.get("id"),
-                        # "ip-address", "mac-address" # filled by LCM
-                        # vim-id  # TODO it would be nice having a vim port id
-                    }
-                    vnfr_descriptor["connection-point"].append(vnf_cp)
-                for vdu in vnfd["vdu"]:
-                    vdur_id = str(uuid4())
-                    vdur = {
-                        "id": vdur_id,
-                        "vdu-id-ref": vdu["id"],
-                        # TODO      "name": ""     Name of the VDU in the VIM
-                        "ip-address": None,  # mgmt-interface filled by LCM
-                        # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
-                        "internal-connection-point": [],
-                        "interfaces": [],
-                    }
-                    # TODO volumes: name, volume-id
-                    for icp in vdu.get("internal-connection-point", ()):
-                        vdu_icp = {
-                            "id": icp["id"],
-                            "connection-point-id": icp["id"],
-                            "name": icp.get("name"),
-                            # "ip-address", "mac-address" # filled by LCM
-                            # vim-id  # TODO it would be nice having a vim port id
-                        }
-                        vdur["internal-connection-point"].append(vdu_icp)
-                    for iface in vdu.get("interface", ()):
-                        vdu_iface = {
-                            "name": iface.get("name"),
-                            # "ip-address", "mac-address" # filled by LCM
-                            # vim-id  # TODO it would be nice having a vim port id
-                        }
-                        vdur["interfaces"].append(vdu_iface)
-                    vnfr_descriptor["vdur"].append(vdur)
-
-                step = "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
-                    member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
-                self._format_new_data(session, "vnfrs", vnfr_descriptor)
-                self.db.create("vnfrs", vnfr_descriptor)
-                rollback.insert(0, {"item": "vnfrs", "_id": vnfr_id})
-                nsr_descriptor["constituent-vnfr-ref"].append(vnfr_id)
-
-            step = "creating nsr at database"
-            self._format_new_data(session, "nsrs", nsr_descriptor)
-            self.db.create("nsrs", nsr_descriptor)
-            rollback.insert(rollback_index, {"item": "nsrs", "_id": nsr_id})
-            return nsr_id
-        except Exception as e:
-            raise EngineException("Error {}: {}".format(step, e))
-
-    @staticmethod
-    def _update_descriptor(desc, kwargs):
-        """
-        Update descriptor with the kwargs. It contains dot separated keys
-        :param desc: dictionary to be updated
-        :param kwargs: plain dictionary to be used for updating.
-        :return:
-        """
-        if not kwargs:
-            return
-        try:
-            for k, v in kwargs.items():
-                update_content = desc
-                kitem_old = None
-                klist = k.split(".")
-                for kitem in klist:
-                    if kitem_old is not None:
-                        update_content = update_content[kitem_old]
-                    if isinstance(update_content, dict):
-                        kitem_old = kitem
-                    elif isinstance(update_content, list):
-                        kitem_old = int(kitem)
-                    else:
-                        raise EngineException(
-                            "Invalid query string '{}'. Descriptor is not a list nor dict at '{}'".format(k, kitem))
-                update_content[kitem_old] = v
-        except KeyError:
-            raise EngineException(
-                "Invalid query string '{}'. Descriptor does not contain '{}'".format(k, kitem_old))
-        except ValueError:
-            raise EngineException("Invalid query string '{}'. Expected integer index list instead of '{}'".format(
-                k, kitem))
-        except IndexError:
-            raise EngineException(
-                "Invalid query string '{}'. Index '{}' out of  range".format(k, kitem_old))
-
-    def new_item(self, rollback, session, item, indata={}, kwargs=None, headers={}, force=False):
+    def new_item(self, rollback, session, topic, indata=None, kwargs=None, headers=None, force=False):
         """
         Creates a new entry into database. For nsds and vnfds it creates an almost empty DISABLED  entry,
         that must be completed with a call to method upload_content
-        :param rollback: list where this method appends created items at database in case a rollback may to be done
+        :param rollback: list to append created items at database in case a rollback must to be done
         :param session: contains the used login username and working project
-        :param item: it can be: users, projects, vim_accounts, sdns, nsrs, nsds, vnfds
+        :param topic: it can be: users, projects, vim_accounts, sdns, nsrs, nsds, vnfds
         :param indata: data to be inserted
         :param kwargs: used to override the indata descriptor
         :param headers: http request headers
         :param force: If True avoid some dependence checks
         :return: _id: identity of the inserted data.
         """
+        if topic not in self.map_topic:
+            raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
+        return self.map_topic[topic].new(rollback, session, indata, kwargs, headers, force)
 
-        if not session["admin"] and item in ("users", "projects"):
-            raise EngineException("Needed admin privileges to perform this operation", HTTPStatus.UNAUTHORIZED)
-
-        try:
-            item_envelop = item
-            if item in ("nsds", "vnfds"):
-                item_envelop = "userDefinedData"
-            content = self._remove_envelop(item_envelop, indata)
-
-            # Override descriptor with query string kwargs
-            self._update_descriptor(content, kwargs)
-            if not content and item not in ("nsds", "vnfds"):
-                raise EngineException("Empty payload")
-
-            validate_input(content, item, new=True)
-
-            if item == "nsrs":
-                # in this case the input descriptor is not the data to be stored
-                return self.new_nsr(rollback, session, ns_request=content)
-
-            self._validate_new_data(session, item_envelop, content, force=force)
-            if item in ("nsds", "vnfds"):
-                content = {"_admin": {"userDefinedData": content}}
-            self._format_new_data(session, item, content)
-            _id = self.db.create(item, content)
-            rollback.insert(0, {"item": item, "_id": _id})
-
-            if item == "vim_accounts":
-                msg_data = self.db.get_one(item, {"_id": _id})
-                msg_data.pop("_admin", None)
-                self.msg.write("vim_account", "create", msg_data)
-            elif item == "sdns":
-                msg_data = self.db.get_one(item, {"_id": _id})
-                msg_data.pop("_admin", None)
-                self.msg.write("sdn", "create", msg_data)
-            return _id
-        except ValidationError as e:
-            raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
-
-    def new_nslcmop(self, session, nsInstanceId, operation, params):
-        now = time()
-        _id = str(uuid4())
-        nslcmop = {
-            "id": _id,
-            "_id": _id,
-            "operationState": "PROCESSING",  # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
-            "statusEnteredTime": now,
-            "nsInstanceId": nsInstanceId,
-            "lcmOperationType": operation,
-            "startTime": now,
-            "isAutomaticInvocation": False,
-            "operationParams": params,
-            "isCancelPending": False,
-            "links": {
-                "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
-                "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsInstanceId,
-            }
-        }
-        return nslcmop
-
-    def ns_operation(self, rollback, session, nsInstanceId, operation, indata, kwargs=None):
+    def upload_content(self, session, topic, _id, indata, kwargs, headers, force=False):
         """
-        Performs a new operation over a ns
-        :param rollback: list where this method appends created items at database in case a rollback may to be done
+        Upload content for an already created entry (_id)
         :param session: contains the used login username and working project
-        :param nsInstanceId: _id of the nsr to perform the operation
-        :param operation: it can be: instantiate, terminate, action, TODO: update, heal
-        :param indata: descriptor with the parameters of the operation
+        :param topic: it can be: users, projects, vnfds, nsds,
+        :param _id: server id of the item
+        :param indata: data to be inserted
         :param kwargs: used to override the indata descriptor
-        :return: id of the nslcmops
-        """
-        try:
-            # Override descriptor with query string kwargs
-            self._update_descriptor(indata, kwargs)
-            validate_input(indata, "ns_" + operation, new=True)
-            # get ns from nsr_id
-            nsr = self.get_item(session, "nsrs", nsInstanceId)
-            if not nsr["_admin"].get("nsState") or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
-                if operation == "terminate" and indata.get("autoremove"):
-                    # NSR must be deleted
-                    return self.del_item(session, "nsrs", nsInstanceId)
-                if operation != "instantiate":
-                    raise EngineException("ns_instance '{}' cannot be '{}' because it is not instantiated".format(
-                        nsInstanceId, operation), HTTPStatus.CONFLICT)
-            else:
-                if operation == "instantiate" and not indata.get("force"):
-                    raise EngineException("ns_instance '{}' cannot be '{}' because it is already instantiated".format(
-                        nsInstanceId, operation), HTTPStatus.CONFLICT)
-            indata["nsInstanceId"] = nsInstanceId
-            self._check_ns_operation(session, nsr, operation, indata)
-            nslcmop = self.new_nslcmop(session, nsInstanceId, operation, indata)
-            self._format_new_data(session, "nslcmops", nslcmop)
-            _id = self.db.create("nslcmops", nslcmop)
-            rollback.insert(0, {"item": "nslcmops", "_id": _id})
-            indata["_id"] = _id
-            self.msg.write("ns", operation, nslcmop)
-            return _id
-        except ValidationError as e:
-            raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
-        # except DbException as e:
-        #     raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
-
-    def _add_read_filter(self, session, item, filter):
-        if session["admin"]:  # allows all
-            return filter
-        if item == "users":
-            filter["username"] = session["username"]
-        elif item in ("vnfds", "nsds", "nsrs", "vnfrs"):
-            filter["_admin.projects_read.cont"] = ["ANY", session["project_id"]]
-
-    def _add_delete_filter(self, session, item, filter):
-        if not session["admin"] and item in ("users", "projects"):
-            raise EngineException("Only admin users can perform this task", http_code=HTTPStatus.FORBIDDEN)
-        if item == "users":
-            if filter.get("_id") == session["username"] or filter.get("username") == session["username"]:
-                raise EngineException("You cannot delete your own user", http_code=HTTPStatus.CONFLICT)
-        elif item == "project":
-            if filter.get("_id") == session["project_id"]:
-                raise EngineException("You cannot delete your own project", http_code=HTTPStatus.CONFLICT)
-        elif item in ("vnfds", "nsds") and not session["admin"]:
-            filter["_admin.projects_write.cont"] = ["ANY", session["project_id"]]
-
-    def get_file(self, session, item, _id, path=None, accept_header=None):
-        """
-        Return the file content of a vnfd or nsd
-        :param session: contains the used login username and working project
-        :param item: it can be vnfds or nsds
-        :param _id: Identity of the vnfd, ndsd
-        :param path: artifact path or "$DESCRIPTOR" or None
-        :param accept_header: Content of Accept header. Must contain applition/zip or/and text/plain
-        :return: opened file or raises an exception
+        :param headers: http request headers
+        :param force: If True avoid some dependence checks
+        :return: _id: identity of the inserted data.
         """
-        accept_text = accept_zip = False
-        if accept_header:
-            if 'text/plain' in accept_header or '*/*' in accept_header:
-                accept_text = True
-            if 'application/zip' in accept_header or '*/*' in accept_header:
-                accept_zip = True
-        if not accept_text and not accept_zip:
-            raise EngineException("provide request header 'Accept' with 'application/zip' or 'text/plain'",
-                                  http_code=HTTPStatus.NOT_ACCEPTABLE)
-
-        content = self.get_item(session, item, _id)
-        if content["_admin"]["onboardingState"] != "ONBOARDED":
-            raise EngineException("Cannot get content because this resource is not at 'ONBOARDED' state. "
-                                  "onboardingState is {}".format(content["_admin"]["onboardingState"]),
-                                  http_code=HTTPStatus.CONFLICT)
-        storage = content["_admin"]["storage"]
-        if path is not None and path != "$DESCRIPTOR":   # artifacts
-            if not storage.get('pkg-dir'):
-                raise EngineException("Packages does not contains artifacts", http_code=HTTPStatus.BAD_REQUEST)
-            if self.fs.file_exists((storage['folder'], storage['pkg-dir'], *path), 'dir'):
-                folder_content = self.fs.dir_ls((storage['folder'], storage['pkg-dir'], *path))
-                return folder_content, "text/plain"
-                # TODO manage folders in http
-            else:
-                return self.fs.file_open((storage['folder'], storage['pkg-dir'], *path), "rb"),\
-                    "application/octet-stream"
-
-        # pkgtype   accept  ZIP  TEXT    -> result
-        # manyfiles         yes  X       -> zip
-        #                   no   yes     -> error
-        # onefile           yes  no      -> zip
-        #                   X    yes     -> text
+        if topic not in self.map_topic:
+            raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
+        return self.map_topic[topic].upload_content(session, _id, indata, kwargs, headers, force)
 
-        if accept_text and (not storage.get('pkg-dir') or path == "$DESCRIPTOR"):
-            return self.fs.file_open((storage['folder'], storage['descriptor']), "r"), "text/plain"
-        elif storage.get('pkg-dir') and not accept_zip:
-            raise EngineException("Packages that contains several files need to be retrieved with 'application/zip'"
-                                  "Accept header", http_code=HTTPStatus.NOT_ACCEPTABLE)
-        else:
-            if not storage.get('zipfile'):
-                # TODO generate zipfile if not present
-                raise EngineException("Only allowed 'text/plain' Accept header for this descriptor. To be solved in "
-                                      "future versions", http_code=HTTPStatus.NOT_ACCEPTABLE)
-            return self.fs.file_open((storage['folder'], storage['zipfile']), "rb"), "application/zip"
-
-    def get_item_list(self, session, item, filter={}):
+    def get_item_list(self, session, topic, filter_q=None):
         """
         Get a list of items
         :param session: contains the used login username and working project
-        :param item: it can be: users, projects, vnfds, nsds, ...
-        :param filter: filter of data to be applied
-        :return: The list, it can be empty if no one match the filter.
+        :param topic: it can be: users, projects, vnfds, nsds, ...
+        :param filter_q: filter of data to be applied
+        :return: The list, it can be empty if no one match the filter_q.
         """
-        # TODO add admin to filter, validate rights
-        # TODO transform data for SOL005 URL requests. Transform filtering
-        # TODO implement "field-type" query string SOL005
-
-        self._add_read_filter(session, item, filter)
-        return self.db.get_list(item, filter)
+        if topic not in self.map_topic:
+            raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
+        return self.map_topic[topic].list(session, filter_q)
 
-    def get_item(self, session, item, _id):
+    def get_item(self, session, topic, _id):
         """
-        Get complete information on an items
+        Get complete information on an item
         :param session: contains the used login username and working project
-        :param item: it can be: users, projects, vnfds, nsds,
+        :param topic: it can be: users, projects, vnfds, nsds,
         :param _id: server id of the item
         :return: dictionary, raise exception if not found.
         """
-        filter = {"_id": _id}
-        # TODO add admin to filter, validate rights
-        # TODO transform data for SOL005 URL requests
-        self._add_read_filter(session, item, filter)
-        return self.db.get_one(item, filter)
+        if topic not in self.map_topic:
+            raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
+        return self.map_topic[topic].show(session, _id)
 
-    def del_item_list(self, session, item, filter={}):
+    def del_item_list(self, session, topic, _filter=None):
         """
         Delete a list of items
         :param session: contains the used login username and working project
-        :param item: it can be: users, projects, vnfds, nsds, ...
-        :param filter: filter of data to be applied
-        :return: The deleted list, it can be empty if no one match the filter.
+        :param topic: it can be: users, projects, vnfds, nsds, ...
+        :param _filter: filter of data to be applied
+        :return: The deleted list, it can be empty if no one match the _filter.
         """
-        # TODO add admin to filter, validate rights
-        self._add_read_filter(session, item, filter)
-        return self.db.del_list(item, filter)
+        if topic not in self.map_topic:
+            raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
+        return self.map_topic[topic].delete_list(session, _filter)
 
-    def del_item(self, session, item, _id, force=False):
+    def del_item(self, session, topic, _id, force=False):
         """
         Delete item by its internal id
         :param session: contains the used login username and working project
-        :param item: it can be: users, projects, vnfds, nsds, ...
+        :param topic: it can be: users, projects, vnfds, nsds, ...
         :param _id: server id of the item
         :param force: indicates if deletion must be forced in case of conflict
         :return: dictionary with deleted item _id. It raises exception if not found.
         """
-        # TODO add admin to filter, validate rights
-        # data = self.get_item(item, _id)
-        filter = {"_id": _id}
-        self._add_delete_filter(session, item, filter)
-        if item in ("vnfds", "nsds") and not force:
-            descriptor = self.get_item(session, item, _id)
-            descriptor_id = descriptor.get("id")
-            if descriptor_id:
-                self._check_dependencies_on_descriptor(session, item, descriptor_id, _id)
-        elif item == "projects":
-            if not force:
-                self._check_project_dependencies(_id)
+        if topic not in self.map_topic:
+            raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
+        return self.map_topic[topic].delete(session, _id, force)
 
-        if item == "nsrs":
-            nsr = self.db.get_one(item, filter)
-            if nsr["_admin"].get("nsState") == "INSTANTIATED" and not force:
-                raise EngineException("nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
-                                      "Launch 'terminate' operation first; or force deletion".format(_id),
-                                      http_code=HTTPStatus.CONFLICT)
-            v = self.db.del_one(item, {"_id": _id})
-            self.db.del_list("nslcmops", {"nsInstanceId": _id})
-            self.db.del_list("vnfrs", {"nsr-id-ref": _id})
-            self.msg.write("ns", "deleted", {"_id": _id})
-            return v
-        if item in ("vim_accounts", "sdns") and not force:
-            self.db.set_one(item, {"_id": _id}, {"_admin.to_delete": True})   # TODO change status
-            if item == "vim_accounts":
-                self.msg.write("vim_account", "delete", {"_id": _id})
-            elif item == "sdns":
-                self.msg.write("sdn", "delete", {"_id": _id})
-            return {"deleted": 1}  # TODO indicate an offline operation to return 202 ACCEPTED
-
-        v = self.db.del_one(item, filter)
-        if item in ("vnfds", "nsds"):
-            self.fs.file_delete(_id, ignore_non_exist=True)
-        if item in ("vim_accounts", "sdns", "vnfds", "nsds"):
-            self.msg.write(item[:-1], "deleted", {"_id": _id})
-        return v
+    def edit_item(self, session, topic, _id, indata=None, kwargs=None, force=False):
+        """
+        Update an existing entry at database
+        :param session: contains the used login username and working project
+        :param topic: it can be: users, projects, vnfds, nsds, ...
+        :param _id: identifier to be updated
+        :param indata: data to be inserted
+        :param kwargs: used to override the indata descriptor
+        :param force: If True avoid some dependence checks
+        :return: dictionary, raise exception if not found.
+        """
+        if topic not in self.map_topic:
+            raise EngineException("Unknown topic {}!!!".format(topic), HTTPStatus.INTERNAL_SERVER_ERROR)
+        return self.map_topic[topic].edit(session, _id, indata, kwargs, force)
 
     def prune(self):
         """
@@ -1105,10 +209,10 @@ class Engine(object):
         if users:
             return None
             # raise EngineException("Unauthorized. Database users is not empty", HTTPStatus.UNAUTHORIZED)
-        indata = {"username": "admin", "password": "admin", "projects": ["admin"]}
-        fake_session = {"project_id": "admin", "username": "admin"}
-        self._format_new_data(fake_session, "users", indata)
-        _id = self.db.create("users", indata)
+        user_desc = {"username": "admin", "password": "admin", "projects": ["admin"]}
+        fake_session = {"project_id": "admin", "username": "admin", "admin": True}
+        roolback_list = []
+        _id = self.map_topic["users"].new(roolback_list, fake_session, user_desc, force=True)
         return _id
 
     def init_db(self, target_version='1.0'):
@@ -1138,70 +242,3 @@ class Engine(object):
             raise EngineException("Wrong database status '{}'".format(
                 version["status"]), HTTPStatus.INTERNAL_SERVER_ERROR)
         return
-
-    def _edit_item(self, session, item, id, content, indata={}, kwargs=None, force=False):
-        if indata:
-            indata = self._remove_envelop(item, indata)
-
-        # Override descriptor with query string kwargs
-        if kwargs:
-            try:
-                for k, v in kwargs.items():
-                    update_content = indata
-                    kitem_old = None
-                    klist = k.split(".")
-                    for kitem in klist:
-                        if kitem_old is not None:
-                            update_content = update_content[kitem_old]
-                        if isinstance(update_content, dict):
-                            kitem_old = kitem
-                        elif isinstance(update_content, list):
-                            kitem_old = int(kitem)
-                        else:
-                            raise EngineException(
-                                "Invalid query string '{}'. Descriptor is not a list nor dict at '{}'".format(k, kitem))
-                    update_content[kitem_old] = v
-            except KeyError:
-                raise EngineException(
-                    "Invalid query string '{}'. Descriptor does not contain '{}'".format(k, kitem_old))
-            except ValueError:
-                raise EngineException("Invalid query string '{}'. Expected integer index list instead of '{}'".format(
-                    k, kitem))
-            except IndexError:
-                raise EngineException(
-                    "Invalid query string '{}'. Index '{}' out of  range".format(k, kitem_old))
-        try:
-            validate_input(indata, item, new=False)
-        except ValidationError as e:
-            raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
-
-        self._check_edition(session, item, indata, id, force)
-        deep_update(content, indata)
-        self._validate_new_data(session, item, content, id=id, force=force)
-        # self._format_new_data(session, item, content)
-        self.db.replace(item, id, content)
-        if item in ("vim_accounts", "sdns"):
-            indata.pop("_admin", None)
-            indata["_id"] = id
-            if item == "vim_accounts":
-                self.msg.write("vim_account", "edit", indata)
-            elif item == "sdns":
-                self.msg.write("sdn", "edit", indata)
-        return id
-
-    def edit_item(self, session, item, _id, indata={}, kwargs=None, force=False):
-        """
-        Update an existing entry at database
-        :param session: contains the used login username and working project
-        :param item: it can be: users, projects, vnfds, nsds, ...
-        :param _id: identifier to be updated
-        :param indata: data to be inserted
-        :param kwargs: used to override the indata descriptor
-        :param force: If True avoid some dependence checks
-        :return: dictionary, raise exception if not found.
-        """
-        if not session["admin"] and item == "projects":
-            raise EngineException("Needed admin privileges to perform this operation", HTTPStatus.UNAUTHORIZED)
-
-        content = self.get_item(session, item, _id)
-        return self._edit_item(session, item, _id, content, indata, kwargs, force)
index 857d954..bfa13d4 100644 (file)
@@ -20,9 +20,9 @@ html_start = """
       <a href="https://osm.etsi.org"> <img src="/osm/static/OSM-logo.png" height="42" width="100"
         style="vertical-align:middle"> </a>
       <a>( {} )</a>
-      <a href="/osm/vnfpkgm/v1/vnf_packages_content">VNFDs </a>
-      <a href="/osm/nsd/v1/ns_descriptors_content">NSDs </a>
-      <a href="/osm/nslcm/v1/ns_instances_content">NSs </a>
+      <a href="/osm/vnfpkgm/v1/vnf_packages">VNFDs </a>
+      <a href="/osm/nsd/v1/ns_descriptors">NSDs </a>
+      <a href="/osm/nslcm/v1/ns_instances">NSs </a>
       <a href="/osm/admin/v1/users">USERs </a>
       <a href="/osm/admin/v1/projects">PROJECTs </a>
       <a href="/osm/admin/v1/tokens">TOKENs </a>
@@ -120,10 +120,10 @@ def format(data, request, response, session):
     if response.status and response.status > 202:
         body += html_body_error.format(yaml.safe_dump(data, explicit_start=True, indent=4, default_flow_style=False))
     elif isinstance(data, (list, tuple)):
-        if request.path_info == "/vnfpkgm/v1/vnf_packages_content":
+        if request.path_info == "/vnfpkgm/v1/vnf_packages":
             body += html_upload_body.format(request.path_info, "VNFD")
-        elif request.path_info == "/nsd/v1/ns_descriptors_content":
-            body += html_upload_body.format(request.path_info, "NSD")
+        elif request.path_info == "/nsd/v1/ns_descriptors":
+            body += html_upload_body.format(request.path_info + "_content", "NSD")
         for k in data:
             if isinstance(k, dict):
                 data_id = k.pop("_id", None)
index 03db56b..332aeb5 100644 (file)
@@ -1,3 +1,2 @@
-0.1.17
-2018-09-12
-
+0.1.21
+2018-10-09
diff --git a/osm_nbi/instance_topics.py b/osm_nbi/instance_topics.py
new file mode 100644 (file)
index 0000000..345e6a3
--- /dev/null
@@ -0,0 +1,456 @@
+# -*- coding: utf-8 -*-
+
+# import logging
+from uuid import uuid4
+from http import HTTPStatus
+from time import time
+from copy import copy
+from validation import validate_input, ValidationError, ns_instantiate, ns_action, ns_scale
+from base_topic import BaseTopic, EngineException, get_iterable
+from descriptor_topics import DescriptorTopic
+
+__author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
+
+
+class NsrTopic(BaseTopic):
+    topic = "nsrs"
+    topic_msg = "ns"
+
+    def __init__(self, db, fs, msg):
+        BaseTopic.__init__(self, db, fs, msg)
+
+    def _check_descriptor_dependencies(self, session, descriptor):
+        """
+        Check that the dependent descriptors exist on a new descriptor or edition
+        :param session: client session information
+        :param descriptor: descriptor to be inserted or edit
+        :return: None or raises exception
+        """
+        if not descriptor.get("nsdId"):
+            return
+        nsd_id = descriptor["nsdId"]
+        if not self.get_item_list(session, "nsds", {"id": nsd_id}):
+            raise EngineException("Descriptor error at nsdId='{}' references a non exist nsd".format(nsd_id),
+                                  http_code=HTTPStatus.CONFLICT)
+
+    @staticmethod
+    def format_on_new(content, project_id=None, make_public=False):
+        BaseTopic.format_on_new(content, project_id=project_id, make_public=make_public)
+        content["_admin"]["nsState"] = "NOT_INSTANTIATED"
+
+    def check_conflict_on_del(self, session, _id, force=False):
+        if force:
+            return
+        nsr = self.db.get_one("nsrs", {"_id": _id})
+        if nsr["_admin"].get("nsState") == "INSTANTIATED":
+            raise EngineException("nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
+                                  "Launch 'terminate' operation first; or force deletion".format(_id),
+                                  http_code=HTTPStatus.CONFLICT)
+
+    def delete(self, session, _id, force=False, dry_run=False):
+        """
+        Delete item by its internal _id
+        :param session: contains the used login username, working project, and admin rights
+        :param _id: server internal id
+        :param force: indicates if deletion must be forced in case of conflict
+        :param dry_run: make checking but do not delete
+        :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
+        """
+        # TODO add admin to filter, validate rights
+        BaseTopic.delete(self, session, _id, force, dry_run=True)
+        if dry_run:
+            return
+
+        v = self.db.del_one("nsrs", {"_id": _id})
+        self.db.del_list("nslcmops", {"nsInstanceId": _id})
+        self.db.del_list("vnfrs", {"nsr-id-ref": _id})
+        # set all used pdus as free
+        self.db.set_list("pdus", {"_admin.usage.nsr_id": _id},
+                         {"_admin.usageSate": "NOT_IN_USE", "_admin.usage": None})
+        self._send_msg("deleted", {"_id": _id})
+        return v
+
+    def new(self, rollback, session, indata=None, kwargs=None, headers=None, force=False, make_public=False):
+        """
+        Creates a new nsr into database. It also creates needed vnfrs
+        :param rollback: list to append the created items at database in case a rollback must be done
+        :param session: contains the used login username and working project
+        :param indata: params to be used for the nsr
+        :param kwargs: used to override the indata descriptor
+        :param headers: http request headers
+        :param force: If True avoid some dependence checks
+        :param make_public: Make the created item public to all projects
+        :return: the _id of nsr descriptor created at database
+        """
+
+        try:
+            ns_request = self._remove_envelop(indata)
+            # Override descriptor with query string kwargs
+            self._update_input_with_kwargs(ns_request, kwargs)
+            self._validate_input_new(ns_request, force)
+
+            step = ""
+            # look for nsr
+            step = "getting nsd id='{}' from database".format(ns_request.get("nsdId"))
+            _filter = {"_id": ns_request["nsdId"]}
+            _filter.update(BaseTopic._get_project_filter(session, write=False, show_all=True))
+            nsd = self.db.get_one("nsds", _filter)
+
+            nsr_id = str(uuid4())
+            now = time()
+            step = "filling nsr from input data"
+            nsr_descriptor = {
+                "name": ns_request["nsName"],
+                "name-ref": ns_request["nsName"],
+                "short-name": ns_request["nsName"],
+                "admin-status": "ENABLED",
+                "nsd": nsd,
+                "datacenter": ns_request["vimAccountId"],
+                "resource-orchestrator": "osmopenmano",
+                "description": ns_request.get("nsDescription", ""),
+                "constituent-vnfr-ref": [],
+
+                "operational-status": "init",    # typedef ns-operational-
+                "config-status": "init",         # typedef config-states
+                "detailed-status": "scheduled",
+
+                "orchestration-progress": {},
+                # {"networks": {"active": 0, "total": 0}, "vms": {"active": 0, "total": 0}},
+
+                "crete-time": now,
+                "nsd-name-ref": nsd["name"],
+                "operational-events": [],   # "id", "timestamp", "description", "event",
+                "nsd-ref": nsd["id"],
+                "instantiate_params": ns_request,
+                "ns-instance-config-ref": nsr_id,
+                "id": nsr_id,
+                "_id": nsr_id,
+                # "input-parameter": xpath, value,
+                "ssh-authorized-key": ns_request.get("key-pair-ref"),
+            }
+            ns_request["nsr_id"] = nsr_id
+
+            # Create VNFR
+            needed_vnfds = {}
+            for member_vnf in nsd["constituent-vnfd"]:
+                vnfd_id = member_vnf["vnfd-id-ref"]
+                step = "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
+                    member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
+                if vnfd_id not in needed_vnfds:
+                    # Obtain vnfd
+                    vnfd = DescriptorTopic.get_one_by_id(self.db, session, "vnfds", vnfd_id)
+                    vnfd.pop("_admin")
+                    needed_vnfds[vnfd_id] = vnfd
+                else:
+                    vnfd = needed_vnfds[vnfd_id]
+                step = "filling vnfr  vnfd-id='{}' constituent-vnfd='{}'".format(
+                    member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
+                vnfr_id = str(uuid4())
+                vnfr_descriptor = {
+                    "id": vnfr_id,
+                    "_id": vnfr_id,
+                    "nsr-id-ref": nsr_id,
+                    "member-vnf-index-ref": member_vnf["member-vnf-index"],
+                    "created-time": now,
+                    # "vnfd": vnfd,        # at OSM model.but removed to avoid data duplication TODO: revise
+                    "vnfd-ref": vnfd_id,
+                    "vnfd-id": vnfd["_id"],    # not at OSM model, but useful
+                    "vim-account-id": None,
+                    "vdur": [],
+                    "connection-point": [],
+                    "ip-address": None,  # mgmt-interface filled by LCM
+                }
+                for cp in vnfd.get("connection-point", ()):
+                    vnf_cp = {
+                        "name": cp["name"],
+                        "connection-point-id": cp.get("id"),
+                        "id": cp.get("id"),
+                        # "ip-address", "mac-address" # filled by LCM
+                        # vim-id  # TODO it would be nice having a vim port id
+                    }
+                    vnfr_descriptor["connection-point"].append(vnf_cp)
+                for vdu in vnfd["vdu"]:
+                    vdur_id = str(uuid4())
+                    vdur = {
+                        "id": vdur_id,
+                        "vdu-id-ref": vdu["id"],
+                        # TODO      "name": ""     Name of the VDU in the VIM
+                        "ip-address": None,  # mgmt-interface filled by LCM
+                        # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
+                        "internal-connection-point": [],
+                        "interfaces": [],
+                    }
+                    # TODO volumes: name, volume-id
+                    for icp in vdu.get("internal-connection-point", ()):
+                        vdu_icp = {
+                            "id": icp["id"],
+                            "connection-point-id": icp["id"],
+                            "name": icp.get("name"),
+                            # "ip-address", "mac-address" # filled by LCM
+                            # vim-id  # TODO it would be nice having a vim port id
+                        }
+                        vdur["internal-connection-point"].append(vdu_icp)
+                    for iface in vdu.get("interface", ()):
+                        vdu_iface = {
+                            "name": iface.get("name"),
+                            # "ip-address", "mac-address" # filled by LCM
+                            # vim-id  # TODO it would be nice having a vim port id
+                        }
+                        vdur["interfaces"].append(vdu_iface)
+                    vnfr_descriptor["vdur"].append(vdur)
+
+                step = "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
+                    member_vnf["vnfd-id-ref"], member_vnf["member-vnf-index"])
+
+                # add at database
+                BaseTopic.format_on_new(vnfr_descriptor, session["project_id"], make_public=make_public)
+                self.db.create("vnfrs", vnfr_descriptor)
+                rollback.append({"topic": "vnfrs", "_id": vnfr_id})
+                nsr_descriptor["constituent-vnfr-ref"].append(vnfr_id)
+
+            step = "creating nsr at database"
+            self.format_on_new(nsr_descriptor, session["project_id"], make_public=make_public)
+            self.db.create("nsrs", nsr_descriptor)
+            rollback.append({"topic": "nsrs", "_id": nsr_id})
+            return nsr_id
+        except Exception as e:
+            self.logger.exception("Exception {} at NsrTopic.new()".format(e), exc_info=True)
+            raise EngineException("Error {}: {}".format(step, e))
+        except ValidationError as e:
+            raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
+
+    def edit(self, session, _id, indata=None, kwargs=None, force=False, content=None):
+        raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
+
+
+class VnfrTopic(BaseTopic):
+    topic = "vnfrs"
+    topic_msg = None
+
+    def __init__(self, db, fs, msg):
+        BaseTopic.__init__(self, db, fs, msg)
+
+    def delete(self, session, _id, force=False, dry_run=False):
+        raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
+
+    def edit(self, session, _id, indata=None, kwargs=None, force=False, content=None):
+        raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
+
+    def new(self, rollback, session, indata=None, kwargs=None, headers=None, force=False, make_public=False):
+        # Not used because vnfrs are created and deleted by NsrTopic class directly
+        raise EngineException("Method new called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
+
+
+class NsLcmOpTopic(BaseTopic):
+    topic = "nslcmops"
+    topic_msg = "ns"
+    operation_schema = {    # mapping between operation and jsonschema to validate
+        "instantiate": ns_instantiate,
+        "action": ns_action,
+        "scale": ns_scale,
+        "terminate": None,
+    }
+
+    def __init__(self, db, fs, msg):
+        BaseTopic.__init__(self, db, fs, msg)
+
+    def _validate_input_new(self, input, force=False):
+        """
+        Validates input user content for a new entry. It uses jsonschema for each type or operation.
+        :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 self.schema_new:
+            validate_input(input, self.schema_new)
+        return input
+
+    def _check_ns_operation(self, session, nsr, operation, indata):
+        """
+        Check that user has enter right parameters for the operation
+        :param session:
+        :param operation: it can be: instantiate, terminate, action, TODO: update, heal
+        :param indata: descriptor with the parameters of the operation
+        :return: None
+        """
+        vnfds = {}
+        vim_accounts = []
+        nsd = nsr["nsd"]
+
+        def check_valid_vnf_member_index(member_vnf_index):
+            # TODO change to vnfR
+            for vnf in nsd["constituent-vnfd"]:
+                if member_vnf_index == vnf["member-vnf-index"]:
+                    vnfd_id = vnf["vnfd-id-ref"]
+                    if vnfd_id not in vnfds:
+                        vnfds[vnfd_id] = self.db.get_one("vnfds", {"id": vnfd_id})
+                    return vnfds[vnfd_id]
+            else:
+                raise EngineException("Invalid parameter member_vnf_index='{}' is not one of the "
+                                      "nsd:constituent-vnfd".format(member_vnf_index))
+
+        def check_valid_vim_account(vim_account):
+            if vim_account in vim_accounts:
+                return
+            try:
+                # TODO add _get_project_filter
+                self.db.get_one("vim_accounts", {"_id": vim_account})
+            except Exception:
+                raise EngineException("Invalid vimAccountId='{}' not present".format(vim_account))
+            vim_accounts.append(vim_account)
+
+        if operation == "action":
+            # check vnf_member_index
+            if indata.get("vnf_member_index"):
+                indata["member_vnf_index"] = indata.pop("vnf_member_index")    # for backward compatibility
+            if not indata.get("member_vnf_index"):
+                raise EngineException("Missing 'member_vnf_index' parameter")
+            vnfd = check_valid_vnf_member_index(indata["member_vnf_index"])
+            # check primitive
+            for config_primitive in get_iterable(vnfd.get("vnf-configuration", {}).get("config-primitive")):
+                if indata["primitive"] == config_primitive["name"]:
+                    # check needed primitive_params are provided
+                    if indata.get("primitive_params"):
+                        in_primitive_params_copy = copy(indata["primitive_params"])
+                    else:
+                        in_primitive_params_copy = {}
+                    for paramd in get_iterable(config_primitive.get("parameter")):
+                        if paramd["name"] in in_primitive_params_copy:
+                            del in_primitive_params_copy[paramd["name"]]
+                        elif not paramd.get("default-value"):
+                            raise EngineException("Needed parameter {} not provided for primitive '{}'".format(
+                                paramd["name"], indata["primitive"]))
+                    # check no extra primitive params are provided
+                    if in_primitive_params_copy:
+                        raise EngineException("parameter/s '{}' not present at vnfd for primitive '{}'".format(
+                            list(in_primitive_params_copy.keys()), indata["primitive"]))
+                    break
+            else:
+                raise EngineException("Invalid primitive '{}' is not present at vnfd".format(indata["primitive"]))
+        if operation == "scale":
+            vnfd = check_valid_vnf_member_index(indata["scaleVnfData"]["scaleByStepData"]["member-vnf-index"])
+            for scaling_group in get_iterable(vnfd.get("scaling-group-descriptor")):
+                if indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"] == scaling_group["name"]:
+                    break
+            else:
+                raise EngineException("Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
+                                      "present at vnfd:scaling-group-descriptor".format(
+                                          indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]))
+        if operation == "instantiate":
+            # check vim_account
+            check_valid_vim_account(indata["vimAccountId"])
+            for in_vnf in get_iterable(indata.get("vnf")):
+                vnfd = check_valid_vnf_member_index(in_vnf["member-vnf-index"])
+                if in_vnf.get("vimAccountId"):
+                    check_valid_vim_account(in_vnf["vimAccountId"])
+                for in_vdu in get_iterable(in_vnf.get("vdu")):
+                    for vdud in get_iterable(vnfd.get("vdu")):
+                        if vdud["id"] == in_vdu["id"]:
+                            for volume in get_iterable(in_vdu.get("volume")):
+                                for volumed in get_iterable(vdud.get("volumes")):
+                                    if volumed["name"] == volume["name"]:
+                                        break
+                                else:
+                                    raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
+                                                          "volume:name='{}' is not present at vnfd:vdu:volumes list".
+                                                          format(in_vnf["member-vnf-index"], in_vdu["id"],
+                                                                 volume["name"]))
+                            break
+                    else:
+                        raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu:id='{}' is not "
+                                              "present at vnfd".format(in_vnf["member-vnf-index"], in_vdu["id"]))
+
+                for in_internal_vld in get_iterable(in_vnf.get("internal-vld")):
+                    for internal_vldd in get_iterable(vnfd.get("internal-vld")):
+                        if in_internal_vld["name"] == internal_vldd["name"] or \
+                                in_internal_vld["name"] == internal_vldd["id"]:
+                            break
+                    else:
+                        raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
+                                              " is not present at vnfd '{}'".format(in_vnf["member-vnf-index"],
+                                                                                    in_internal_vld["name"],
+                                                                                    vnfd["id"]))
+            for in_vld in get_iterable(indata.get("vld")):
+                for vldd in get_iterable(nsd.get("vld")):
+                    if in_vld["name"] == vldd["name"] or in_vld["name"] == vldd["id"]:
+                        break
+                else:
+                    raise EngineException("Invalid parameter vld:name='{}' is not present at nsd:vld".format(
+                        in_vld["name"]))
+
+    def _create_nslcmop(self, session, nsInstanceId, operation, params):
+        now = time()
+        _id = str(uuid4())
+        nslcmop = {
+            "id": _id,
+            "_id": _id,
+            "operationState": "PROCESSING",  # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
+            "statusEnteredTime": now,
+            "nsInstanceId": nsInstanceId,
+            "lcmOperationType": operation,
+            "startTime": now,
+            "isAutomaticInvocation": False,
+            "operationParams": params,
+            "isCancelPending": False,
+            "links": {
+                "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
+                "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsInstanceId,
+            }
+        }
+        return nslcmop
+
+    def new(self, rollback, session, indata=None, kwargs=None, headers=None, force=False, make_public=False):
+        """
+        Performs a new operation over a ns
+        :param rollback: list to append created items at database in case a rollback must to be done
+        :param session: contains the used login username and working project
+        :param indata: descriptor with the parameters of the operation. It must contains among others
+            nsInstanceId: _id of the nsr to perform the operation
+            operation: it can be: instantiate, terminate, action, TODO: update, heal
+        :param kwargs: used to override the indata descriptor
+        :param headers: http request headers
+        :param force: If True avoid some dependence checks
+        :param make_public: Make the created item public to all projects
+        :return: id of the nslcmops
+        """
+        try:
+            # Override descriptor with query string kwargs
+            self._update_input_with_kwargs(indata, kwargs)
+            operation = indata["lcmOperationType"]
+            nsInstanceId = indata["nsInstanceId"]
+
+            validate_input(indata, self.operation_schema[operation])
+            # get ns from nsr_id
+            _filter = BaseTopic._get_project_filter(session, write=True, show_all=False)
+            _filter["_id"] = nsInstanceId
+            nsr = self.db.get_one("nsrs", _filter)
+
+            # initial checking
+            if not nsr["_admin"].get("nsState") or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
+                if operation == "terminate" and indata.get("autoremove"):
+                    # NSR must be deleted
+                    return self.delete(session, nsInstanceId)
+                if operation != "instantiate":
+                    raise EngineException("ns_instance '{}' cannot be '{}' because it is not instantiated".format(
+                        nsInstanceId, operation), HTTPStatus.CONFLICT)
+            else:
+                if operation == "instantiate" and not indata.get("force"):
+                    raise EngineException("ns_instance '{}' cannot be '{}' because it is already instantiated".format(
+                        nsInstanceId, operation), HTTPStatus.CONFLICT)
+            self._check_ns_operation(session, nsr, operation, indata)
+            nslcmop_desc = self._create_nslcmop(session, nsInstanceId, operation, indata)
+            self.format_on_new(nslcmop_desc, session["project_id"], make_public=make_public)
+            _id = self.db.create("nslcmops", nslcmop_desc)
+            rollback.append({"topic": "nslcmops", "_id": _id})
+            self.msg.write("ns", operation, nslcmop_desc)
+            return _id
+        except ValidationError as e:
+            raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
+        # except DbException as e:
+        #     raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
+
+    def delete(self, session, _id, force=False, dry_run=False):
+        raise EngineException("Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
+
+    def edit(self, session, _id, indata=None, kwargs=None, force=False, content=None):
+        raise EngineException("Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR)
index ffe407d..07956ed 100644 (file)
@@ -73,3 +73,5 @@ port: 9092
 loglevel:  "DEBUG"
 #logfile: /var/log/osm/nbi-message.log
 
+[authentication]
+backend: "internal"
index f8c564d..60a327e 100644 (file)
@@ -10,11 +10,13 @@ import logging
 import logging.handlers
 import getopt
 import sys
+
+from authconn import AuthException
+from auth import Authenticator
 from engine import Engine, EngineException
 from osm_common.dbbase import DbException
 from osm_common.fsbase import FsException
 from osm_common.msgbase import MsgException
-from base64 import standard_b64decode
 from http import HTTPStatus
 from codecs import getreader
 from os import environ, path
@@ -25,6 +27,7 @@ __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
 __version__ = "0.1.3"
 version_date = "Apr 2018"
 database_version = '1.0'
+auth_database_version = '1.0'
 
 """
 North Bound Interface  (O: OSM specific; 5,X: SOL005 not implemented yet; O5: SOL005 implemented)
@@ -72,6 +75,9 @@ URL: /osm                                                       GET     POST
                 /<vnfInstanceId>                                O
             /subscriptions                                      5       5
                 /<subscriptionId>                               5                       X
+        /pdu/v1
+            /pdu_descriptor                                     O       O
+                /<id>                                           O               O       O       O
         /admin/v1
             /tokens                                             O       O
                 /<id>                                           O                       O
@@ -145,6 +151,7 @@ class Server(object):
     def __init__(self):
         self.instance += 1
         self.engine = Engine()
+        self.authenticator = Authenticator()
         self.valid_methods = {   # contains allowed URL and methods
             "admin": {
                 "v1": {
@@ -168,6 +175,13 @@ class Server(object):
                              },
                 }
             },
+            "pdu": {
+                "v1": {
+                    "pdu_descriptors": {"METHODS": ("GET", "POST"),
+                                        "<ID>": {"METHODS": ("GET", "POST", "DELETE", "PATCH", "PUT")}
+                                        },
+                }
+            },
             "nsd": {
                 "v1": {
                     "ns_descriptors_content": {"METHODS": ("GET", "POST"),
@@ -235,48 +249,6 @@ class Server(object):
             },
         }
 
-    def _authorization(self):
-        token = None
-        user_passwd64 = None
-        try:
-            # 1. Get token Authorization bearer
-            auth = cherrypy.request.headers.get("Authorization")
-            if auth:
-                auth_list = auth.split(" ")
-                if auth_list[0].lower() == "bearer":
-                    token = auth_list[-1]
-                elif auth_list[0].lower() == "basic":
-                    user_passwd64 = auth_list[-1]
-            if not token:
-                if cherrypy.session.get("Authorization"):
-                    # 2. Try using session before request a new token. If not, basic authentication will generate
-                    token = cherrypy.session.get("Authorization")
-                    if token == "logout":
-                        token = None   # force Unauthorized response to insert user pasword again
-                elif user_passwd64 and cherrypy.request.config.get("auth.allow_basic_authentication"):
-                    # 3. Get new token from user password
-                    user = None
-                    passwd = None
-                    try:
-                        user_passwd = standard_b64decode(user_passwd64).decode()
-                        user, _, passwd = user_passwd.partition(":")
-                    except Exception:
-                        pass
-                    outdata = self.engine.new_token(None, {"username": user, "password": passwd})
-                    token = outdata["id"]
-                    cherrypy.session['Authorization'] = token
-            # 4. Get token from cookie
-            # if not token:
-            #     auth_cookie = cherrypy.request.cookie.get("Authorization")
-            #     if auth_cookie:
-            #         token = auth_cookie.value
-            return self.engine.authorize(token)
-        except EngineException as e:
-            if cherrypy.session.get('Authorization'):
-                del cherrypy.session['Authorization']
-            cherrypy.response.headers["WWW-Authenticate"] = 'Bearer realm="{}"'.format(e)
-            raise
-
     def _format_in(self, kwargs):
         try:
             indata = None
@@ -403,7 +375,7 @@ class Server(object):
         session = None
         try:
             if cherrypy.request.method == "GET":
-                session = self._authorization()
+                session = self.authenticator.authorize()
                 outdata = "Index page"
             else:
                 raise cherrypy.HTTPError(HTTPStatus.METHOD_NOT_ALLOWED.value,
@@ -411,7 +383,7 @@ class Server(object):
 
             return self._format_out(outdata, session)
 
-        except EngineException as e:
+        except (EngineException, AuthException) as e:
             cherrypy.log("index Exception {}".format(e))
             cherrypy.response.status = e.http_code.value
             return self._format_out("Welcome to OSM!", session)
@@ -444,19 +416,19 @@ class Server(object):
             raise NbiException("Expected application/yaml or application/json Content-Type", HTTPStatus.BAD_REQUEST)
         try:
             if method == "GET":
-                session = self._authorization()
+                session = self.authenticator.authorize()
                 if token_id:
-                    outdata = self.engine.get_token(session, token_id)
+                    outdata = self.authenticator.get_token(session, token_id)
                 else:
-                    outdata = self.engine.get_token_list(session)
+                    outdata = self.authenticator.get_token_list(session)
             elif method == "POST":
                 try:
-                    session = self._authorization()
+                    session = self.authenticator.authorize()
                 except Exception:
                     session = None
                 if kwargs:
                     indata.update(kwargs)
-                outdata = self.engine.new_token(session, indata, cherrypy.request.remote)
+                outdata = self.authenticator.new_token(session, indata, cherrypy.request.remote)
                 session = outdata
                 cherrypy.session['Authorization'] = outdata["_id"]
                 self._set_location_header("admin", "v1", "tokens", outdata["_id"])
@@ -466,9 +438,9 @@ class Server(object):
                 if not token_id and "id" in kwargs:
                     token_id = kwargs["id"]
                 elif not token_id:
-                    session = self._authorization()
+                    session = self.authenticator.authorize()
                     token_id = session["_id"]
-                outdata = self.engine.del_token(token_id)
+                outdata = self.authenticator.del_token(token_id)
                 session = None
                 cherrypy.session['Authorization'] = "logout"
                 # cherrypy.response.cookie["Authorization"] = token_id
@@ -476,7 +448,7 @@ class Server(object):
             else:
                 raise NbiException("Method {} not allowed for token".format(method), HTTPStatus.METHOD_NOT_ALLOWED)
             return self._format_out(outdata, session)
-        except (NbiException, EngineException, DbException) as e:
+        except (NbiException, EngineException, DbException, AuthException) as e:
             cherrypy.log("tokens Exception {}".format(e))
             cherrypy.response.status = e.http_code.value
             problem_details = {
@@ -511,7 +483,7 @@ class Server(object):
             return f
 
         elif len(args) == 2 and args[0] == "db-clear":
-            return self.engine.del_item_list({"project_id": "admin", "admin": True}, args[1], kwargs)
+            return self.engine.db.del_list(args[1], kwargs)
         elif args and args[0] == "prune":
             return self.engine.prune()
         elif args and args[0] == "login":
@@ -534,17 +506,17 @@ class Server(object):
             time.sleep(sleep_time)
             # thread_info
         elif len(args) >= 2 and args[0] == "message":
-            topic = args[1]
-            return_text = "<html><pre>{} ->\n".format(topic)
+            main_topic = args[1]
+            return_text = "<html><pre>{} ->\n".format(main_topic)
             try:
                 if cherrypy.request.method == 'POST':
                     to_send = yaml.load(cherrypy.request.body)
                     for k, v in to_send.items():
-                        self.engine.msg.write(topic, k, v)
+                        self.engine.msg.write(main_topic, k, v)
                         return_text += "  {}: {}\n".format(k, v)
                 elif cherrypy.request.method == 'GET':
                     for k, v in kwargs.items():
-                        self.engine.msg.write(topic, k, yaml.load(v))
+                        self.engine.msg.write(main_topic, k, yaml.load(v))
                         return_text += "  {}: {}\n".format(k, yaml.load(v))
             except Exception as e:
                 return_text += "Error: " + str(e)
@@ -573,7 +545,7 @@ class Server(object):
 
     def _check_valid_url_method(self, method, *args):
         if len(args) < 3:
-            raise NbiException("URL must contain at least 'topic/version/item'", HTTPStatus.METHOD_NOT_ALLOWED)
+            raise NbiException("URL must contain at least 'main_topic/version/topic'", HTTPStatus.METHOD_NOT_ALLOWED)
 
         reference = self.valid_methods
         for arg in args:
@@ -599,33 +571,35 @@ class Server(object):
         return
 
     @staticmethod
-    def _set_location_header(topic, version, item, id):
+    def _set_location_header(main_topic, version, topic, id):
         """
         Insert response header Location with the URL of created item base on URL params
-        :param topic:
+        :param main_topic:
         :param version:
-        :param item:
+        :param topic:
         :param id:
         :return: None
         """
         # Use cherrypy.request.base for absoluted path and make use of request.header HOST just in case behind aNAT
-        cherrypy.response.headers["Location"] = "/osm/{}/{}/{}/{}".format(topic, version, item, id)
+        cherrypy.response.headers["Location"] = "/osm/{}/{}/{}/{}".format(main_topic, version, topic, id)
         return
 
     @cherrypy.expose
-    def default(self, topic=None, version=None, item=None, _id=None, item2=None, *args, **kwargs):
+    def default(self, main_topic=None, version=None, topic=None, _id=None, item=None, *args, **kwargs):
         session = None
         outdata = None
         _format = None
         method = "DONE"
-        engine_item = None
+        engine_topic = None
         rollback = []
         session = None
         try:
-            if not topic or not version or not item:
-                raise NbiException("URL must contain at least 'topic/version/item'", HTTPStatus.METHOD_NOT_ALLOWED)
-            if topic not in ("admin", "vnfpkgm", "nsd", "nslcm"):
-                raise NbiException("URL topic '{}' not supported".format(topic), HTTPStatus.METHOD_NOT_ALLOWED)
+            if not main_topic or not version or not topic:
+                raise NbiException("URL must contain at least 'main_topic/version/topic'",
+                                   HTTPStatus.METHOD_NOT_ALLOWED)
+            if main_topic not in ("admin", "vnfpkgm", "nsd", "nslcm"):
+                raise NbiException("URL main_topic '{}' not supported".format(main_topic),
+                                   HTTPStatus.METHOD_NOT_ALLOWED)
             if version != 'v1':
                 raise NbiException("URL version '{}' not supported".format(version), HTTPStatus.METHOD_NOT_ALLOWED)
 
@@ -638,95 +612,107 @@ class Server(object):
             else:
                 force = False
 
-            self._check_valid_url_method(method, topic, version, item, _id, item2, *args)
+            self._check_valid_url_method(method, main_topic, version, topic, _id, item, *args)
 
-            if topic == "admin" and item == "tokens":
+            if main_topic == "admin" and topic == "tokens":
                 return self.token(method, _id, kwargs)
 
             # self.engine.load_dbase(cherrypy.request.app.config)
-            session = self._authorization()
+            session = self.authenticator.authorize()
             indata = self._format_in(kwargs)
-            engine_item = item
-            if item == "subscriptions":
-                engine_item = topic + "_" + item
-            if item2:
-                engine_item = item2
-
-            if topic == "nsd":
-                engine_item = "nsds"
-            elif topic == "vnfpkgm":
-                engine_item = "vnfds"
-            elif topic == "nslcm":
-                engine_item = "nsrs"
-                if item == "ns_lcm_op_occs":
-                    engine_item = "nslcmops"
-                if item == "vnfrs" or item == "vnf_instances":
-                    engine_item = "vnfrs"
-            if engine_item == "vims":   # TODO this is for backward compatibility, it will remove in the future
-                engine_item = "vim_accounts"
+            engine_topic = topic
+            if topic == "subscriptions":
+                engine_topic = main_topic + "_" + topic
+            if item:
+                engine_topic = item
+
+            if main_topic == "nsd":
+                engine_topic = "nsds"
+            elif main_topic == "vnfpkgm":
+                engine_topic = "vnfds"
+            elif main_topic == "nslcm":
+                engine_topic = "nsrs"
+                if topic == "ns_lcm_op_occs":
+                    engine_topic = "nslcmops"
+                if topic == "vnfrs" or topic == "vnf_instances":
+                    engine_topic = "vnfrs"
+            elif main_topic == "pdu":
+                engine_topic = "pdus"
+            if engine_topic == "vims":   # TODO this is for backward compatibility, it will remove in the future
+                engine_topic = "vim_accounts"
 
             if method == "GET":
-                if item2 in ("nsd_content", "package_content", "artifacts", "vnfd", "nsd"):
-                    if item2 in ("vnfd", "nsd"):
+                if item in ("nsd_content", "package_content", "artifacts", "vnfd", "nsd"):
+                    if item in ("vnfd", "nsd"):
                         path = "$DESCRIPTOR"
                     elif args:
                         path = args
-                    elif item2 == "artifacts":
+                    elif item == "artifacts":
                         path = ()
                     else:
                         path = None
-                    file, _format = self.engine.get_file(session, engine_item, _id, path,
+                    file, _format = self.engine.get_file(session, engine_topic, _id, path,
                                                          cherrypy.request.headers.get("Accept"))
                     outdata = file
                 elif not _id:
-                    outdata = self.engine.get_item_list(session, engine_item, kwargs)
+                    outdata = self.engine.get_item_list(session, engine_topic, kwargs)
                 else:
-                    outdata = self.engine.get_item(session, engine_item, _id)
+                    outdata = self.engine.get_item(session, engine_topic, _id)
             elif method == "POST":
-                if item in ("ns_descriptors_content", "vnf_packages_content"):
+                if topic in ("ns_descriptors_content", "vnf_packages_content"):
                     _id = cherrypy.request.headers.get("Transaction-Id")
                     if not _id:
-                        _id = self.engine.new_item(rollback, session, engine_item, {}, None, cherrypy.request.headers,
+                        _id = self.engine.new_item(rollback, session, engine_topic, {}, None, cherrypy.request.headers,
                                                    force=force)
-                    completed = self.engine.upload_content(session, engine_item, _id, indata, kwargs,
-                                                           cherrypy.request.headers)
+                    completed = self.engine.upload_content(session, engine_topic, _id, indata, kwargs,
+                                                           cherrypy.request.headers, force=force)
                     if completed:
-                        self._set_location_header(topic, version, item, _id)
+                        self._set_location_header(main_topic, version, topic, _id)
                     else:
                         cherrypy.response.headers["Transaction-Id"] = _id
                     outdata = {"id": _id}
-                elif item == "ns_instances_content":
-                    _id = self.engine.new_item(rollback, session, engine_item, indata, kwargs, force=force)
-                    self.engine.ns_operation(rollback, session, _id, "instantiate", indata, None)
-                    self._set_location_header(topic, version, item, _id)
+                elif topic == "ns_instances_content":
+                    # creates NSR
+                    _id = self.engine.new_item(rollback, session, engine_topic, indata, kwargs, force=force)
+                    # creates nslcmop
+                    indata["lcmOperationType"] = "instantiate"
+                    indata["nsInstanceId"] = _id
+                    self.engine.new_item(rollback, session, "nslcmops", indata, None)
+                    self._set_location_header(main_topic, version, topic, _id)
                     outdata = {"id": _id}
-                elif item == "ns_instances" and item2:
-                    _id = self.engine.ns_operation(rollback, session, _id, item2, indata, kwargs)
-                    self._set_location_header(topic, version, "ns_lcm_op_occs", _id)
+                elif topic == "ns_instances" and item:
+                    indata["lcmOperationType"] = item
+                    indata["nsInstanceId"] = _id
+                    _id = self.engine.new_item(rollback, session, "nslcmops", indata, kwargs)
+                    self._set_location_header(main_topic, version, "ns_lcm_op_occs", _id)
                     outdata = {"id": _id}
                     cherrypy.response.status = HTTPStatus.ACCEPTED.value
                 else:
-                    _id = self.engine.new_item(rollback, session, engine_item, indata, kwargs, cherrypy.request.headers,
-                                               force=force)
-                    self._set_location_header(topic, version, item, _id)
+                    _id = self.engine.new_item(rollback, session, engine_topic, indata, kwargs,
+                                               cherrypy.request.headers, force=force)
+                    self._set_location_header(main_topic, version, topic, _id)
                     outdata = {"id": _id}
-                    # TODO form NsdInfo when item in ("ns_descriptors", "vnf_packages")
+                    # TODO form NsdInfo when topic in ("ns_descriptors", "vnf_packages")
                 cherrypy.response.status = HTTPStatus.CREATED.value
 
             elif method == "DELETE":
                 if not _id:
-                    outdata = self.engine.del_item_list(session, engine_item, kwargs)
+                    outdata = self.engine.del_item_list(session, engine_topic, kwargs)
                     cherrypy.response.status = HTTPStatus.OK.value
                 else:  # len(args) > 1
-                    if item == "ns_instances_content" and not force:
-                        opp_id = self.engine.ns_operation(rollback, session, _id, "terminate", {"autoremove": True},
-                                                          None)
+                    if topic == "ns_instances_content" and not force:
+                        nslcmop_desc = {
+                            "lcmOperationType": "terminate",
+                            "nsInstanceId": _id,
+                            "autoremove": True
+                        }
+                        opp_id = self.engine.new_item(rollback, session, "nslcmops", nslcmop_desc, None)
                         outdata = {"_id": opp_id}
                         cherrypy.response.status = HTTPStatus.ACCEPTED.value
                     else:
-                        self.engine.del_item(session, engine_item, _id, force)
+                        self.engine.del_item(session, engine_topic, _id, force)
                         cherrypy.response.status = HTTPStatus.NO_CONTENT.value
-                if engine_item in ("vim_accounts", "sdns"):
+                if engine_topic in ("vim_accounts", "sdns"):
                     cherrypy.response.status = HTTPStatus.ACCEPTED.value
 
             elif method in ("PUT", "PATCH"):
@@ -734,35 +720,44 @@ class Server(object):
                 if not indata and not kwargs:
                     raise NbiException("Nothing to update. Provide payload and/or query string",
                                        HTTPStatus.BAD_REQUEST)
-                if item2 in ("nsd_content", "package_content") and method == "PUT":
-                    completed = self.engine.upload_content(session, engine_item, _id, indata, kwargs,
-                                                           cherrypy.request.headers)
+                if item in ("nsd_content", "package_content") and method == "PUT":
+                    completed = self.engine.upload_content(session, engine_topic, _id, indata, kwargs,
+                                                           cherrypy.request.headers, force=force)
                     if not completed:
                         cherrypy.response.headers["Transaction-Id"] = id
                 else:
-                    self.engine.edit_item(session, engine_item, _id, indata, kwargs, force=force)
+                    self.engine.edit_item(session, engine_topic, _id, indata, kwargs, force=force)
                 cherrypy.response.status = HTTPStatus.NO_CONTENT.value
             else:
                 raise NbiException("Method {} not allowed".format(method), HTTPStatus.METHOD_NOT_ALLOWED)
             return self._format_out(outdata, session, _format)
-        except (NbiException, EngineException, DbException, FsException, MsgException) as e:
-            cherrypy.log("Exception {}".format(e))
-            cherrypy.response.status = e.http_code.value
+        except Exception as e:
+            if isinstance(e, (NbiException, EngineException, DbException, FsException, MsgException, AuthException)):
+                http_code_value = cherrypy.response.status = e.http_code.value
+                http_code_name = e.http_code.name
+                cherrypy.log("Exception {}".format(e))
+            else:
+                http_code_value = cherrypy.response.status = HTTPStatus.BAD_REQUEST.value  # INTERNAL_SERVER_ERROR
+                cherrypy.log("CRITICAL: Exception {}".format(e))
+                http_code_name = HTTPStatus.BAD_REQUEST.name
             if hasattr(outdata, "close"):  # is an open file
                 outdata.close()
+            error_text = str(e)
+            rollback.reverse()
             for rollback_item in rollback:
                 try:
                     self.engine.del_item(**rollback_item, session=session, force=True)
                 except Exception as e2:
-                    cherrypy.log("Rollback Exception {}: {}".format(rollback_item, e2))
-            error_text = str(e)
-            if isinstance(e, MsgException):
-                error_text = "{} has been '{}' but other modules cannot be informed because an error on bus".format(
-                    engine_item[:-1], method, error_text)
+                    rollback_error_text = "Rollback Exception {}: {}".format(rollback_item, e2)
+                    cherrypy.log(rollback_error_text)
+                    error_text += ". " + rollback_error_text
+            # if isinstance(e, MsgException):
+            #     error_text = "{} has been '{}' but other modules cannot be informed because an error on bus".format(
+            #         engine_topic[:-1], method, error_text)
             problem_details = {
-                "code": e.http_code.name,
-                "status": e.http_code.value,
-                "detail": str(e),
+                "code": http_code_name,
+                "status": http_code_value,
+                "detail": error_text,
             }
             return self._format_out(problem_details, session)
             # raise cherrypy.HTTPError(e.http_code.value, str(e))
@@ -804,12 +799,13 @@ def _start_service():
                 update_dict['server.socket_host'] = v
             elif k1 in ("server", "test", "auth", "log"):
                 update_dict[k1 + '.' + k2] = v
-            elif k1 in ("message", "database", "storage"):
+            elif k1 in ("message", "database", "storage", "authentication"):
                 # k2 = k2.replace('_', '.')
-                if k2 == "port":
+                if k2 in ("port", "db_port"):
                     engine_config[k1][k2] = int(v)
                 else:
                     engine_config[k1][k2] = v
+
         except ValueError as e:
             cherrypy.log.error("Ignoring environ '{}': " + str(e))
         except Exception as e:
@@ -833,16 +829,16 @@ def _start_service():
         file_handler.setFormatter(log_formatter_simple)
         logger_cherry.addHandler(file_handler)
         logger_nbi.addHandler(file_handler)
-    else:
-        for format_, logger in {"nbi.server": logger_server,
-                                "nbi.access": logger_access,
-                                "%(name)s %(filename)s:%(lineno)s": logger_nbi
-                                }.items():
-            log_format_cherry = "%(asctime)s %(levelname)s {} %(message)s".format(format_)
-            log_formatter_cherry = logging.Formatter(log_format_cherry, datefmt='%Y-%m-%dT%H:%M:%S')
-            str_handler = logging.StreamHandler()
-            str_handler.setFormatter(log_formatter_cherry)
-            logger.addHandler(str_handler)
+    # log always to standard output
+    for format_, logger in {"nbi.server %(filename)s:%(lineno)s": logger_server,
+                            "nbi.access %(filename)s:%(lineno)s": logger_access,
+                            "%(name)s %(filename)s:%(lineno)s": logger_nbi
+                            }.items():
+        log_format_cherry = "%(asctime)s %(levelname)s {} %(message)s".format(format_)
+        log_formatter_cherry = logging.Formatter(log_format_cherry, datefmt='%Y-%m-%dT%H:%M:%S')
+        str_handler = logging.StreamHandler()
+        str_handler.setFormatter(log_formatter_cherry)
+        logger.addHandler(str_handler)
 
     if engine_config["global"].get("log.level"):
         logger_cherry.setLevel(engine_config["global"]["log.level"])
@@ -861,9 +857,11 @@ def _start_service():
             logger_module.setLevel(engine_config[k1]["loglevel"])
     # TODO add more entries, e.g.: storage
     cherrypy.tree.apps['/osm'].root.engine.start(engine_config)
+    cherrypy.tree.apps['/osm'].root.authenticator.start(engine_config)
     try:
         cherrypy.tree.apps['/osm'].root.engine.init_db(target_version=database_version)
-    except EngineException:
+        cherrypy.tree.apps['/osm'].root.authenticator.init_db(target_version=auth_database_version)
+    except (EngineException, AuthException):
         pass
     # getenv('OSMOPENMANO_TENANT', None)
 
index 5a9a9c6..e53df12 100755 (executable)
@@ -10,6 +10,7 @@ function usage(){
     echo -e "  OPTIONS"
     echo -e "     -h --help:   show this help"
     echo -e "     -f --force:  Do not ask for confirmation"
+    echo -e "     --completely:  It cleans also user admin. NBI will need to be restarted to init database"
     echo -e "     --clean-RO:  clean RO content. RO client (openmano) must be installed and configured"
     echo -e "     --clean-VCA: clean VCA content. juju  must be installed and configured"
     echo -e "  ENV variable 'OSMNBI_URL' is used for the URL of the NBI server. If missing, it uses" \
@@ -38,6 +39,7 @@ do
     shift
     ( [ "$option" == -h ] || [ "$option" == --help ] ) && usage && exit
     ( [ "$option" == -f ] || [ "$option" == --force ] ) && OSMNBI_CLEAN_FORCE=yes && continue
+    [ "$option" == --completely ] && OSMNBI_COMPLETELY=yes && continue
     [ "$option" == --clean-RO ] && OSMNBI_CLEAN_RO=yes && continue
     [ "$option" == --clean-VCA ] && OSMNBI_CLEAN_VCA=yes && continue
     echo "Unknown option '$option'. Type $0 --help" 2>&1 && exit 1
@@ -64,13 +66,18 @@ then
     done
 fi
 
-for item in vim_accounts vims sdns nsrs vnfrs nslcmops nsds vnfds projects
+for item in vim_accounts sdns nsrs vnfrs nslcmops nsds vnfds projects # vims
 do
     curl --insecure ${OSMNBI_URL}/test/db-clear/${item}
     echo " ${item}"
 done
-# delete all users except admin
-curl --insecure ${OSMNBI_URL}/test/db-clear/users?username.ne=admin
+if [ -n "$OSMNBI_COMPLETELY" ] ; then
+    curl --insecure ${OSMNBI_URL}/test/db-clear/users && echo " ${item}"
+    curl --insecure ${OSMNBI_URL}/test/db-clear/version && echo " ${item}"
+else
+    # delete all users except admin
+    curl --insecure ${OSMNBI_URL}/test/db-clear/users?username.ne=admin
+fi
 
 if [ -n "$OSMNBI_CLEAN_RO" ]
 then
index 4ffd0b7..fa812bf 100644 (file)
@@ -35,6 +35,7 @@ vlan_schema = {"type": "integer", "minimum": 1, "maximum": 4095}
 vlan1000_schema = {"type": "integer", "minimum": 1000, "maximum": 4095}
 mac_schema = {"type": "string",
               "pattern": "^[0-9a-fA-F][02468aceACE](:[0-9a-fA-F]{2}){5}$"}  # must be unicast: LSB bit of MSB byte ==0
+dpid_Schema = {"type": "string", "pattern": "^[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){7}$"}
 # mac_schema={"type":"string", "pattern":"^([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}$"}
 ip_schema = {"type": "string",
              "pattern": "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"}
@@ -56,6 +57,11 @@ array_edition_schema = {
     "additionalProperties": False,
     "minProperties": 1,
 }
+nameshort_list_schema = {
+    "type": "array",
+    "minItems": 1,
+    "items": nameshort_schema,
+}
 
 
 ns_instantiate_vdu = {
@@ -182,6 +188,8 @@ ns_instantiate = {
     "$schema": "http://json-schema.org/draft-04/schema#",
     "type": "object",
     "properties": {
+        "lcmOperationType": string_schema,
+        "nsInstanceId": id_schema,
         "nsName": name_schema,
         "nsDescription": {"oneOf": [description_schema, {"type": "null"}]},
         "nsdId": id_schema,
@@ -252,6 +260,8 @@ ns_action = {   # TODO for the moment it is only contemplated the vnfd primitive
     "$schema": "http://json-schema.org/draft-04/schema#",
     "type": "object",
     "properties": {
+        "lcmOperationType": string_schema,
+        "nsInstanceId": id_schema,
         "member_vnf_index": name_schema,
         "vnf_member_index": name_schema,  # TODO for backward compatibility. To remove in future
         "vdu_id": name_schema,
@@ -266,6 +276,8 @@ ns_scale = {   # TODO for the moment it is only VDU-scaling
     "$schema": "http://json-schema.org/draft-04/schema#",
     "type": "object",
     "properties": {
+        "lcmOperationType": string_schema,
+        "nsInstanceId": id_schema,
         "scaleType": {"enum": ["SCALE_VNF"]},
         "scaleVnfData": {
             "type": "object",
@@ -344,7 +356,7 @@ vim_account_new_schema = {
 sdn_properties = {
     "name": name_schema,
     "description": description_schema,
-    "dpid": {"type": "string", "pattern": "^[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){7}$"},
+    "dpid": dpid_Schema,
     "ip": ip_schema,
     "port": port_schema,
     "type": {"type": "string", "enum": ["opendaylight", "floodlight", "onos"]},
@@ -404,12 +416,73 @@ sdn_external_port_schema = {
     "required": ["port"]
 }
 
-# USERS
-user_project_schema = {
-    "type": "array",
-    "minItems": 1,
-    "items": nameshort_schema,
+# PDUs
+pdu_interface = {
+    "type": "object",
+    "properties": {
+        "name": nameshort_schema,
+        "mgmt": bool_schema,
+        "type": {"enum": ["overlay", 'underlay']},
+        "ip_address": ip_schema,
+        # TODO, add user, password, ssh-key
+        "mac_address": mac_schema,
+        "vim_network_name": nameshort_schema,  # interface is connected to one vim network, or switch port
+        "vim_network_id": nameshort_schema,
+        # provide this in case SDN assist must deal with this interface
+        "switch_dpid": dpid_Schema,
+        "switch_port": nameshort_schema,
+        "switch_mac": nameshort_schema,
+        "switch_vlan": vlan_schema,
+    },
+    "required": ["name", "mgmt", "ip_address"],
+    "additionalProperties": False
+}
+pdu_new_schema = {
+    "title": "pdu creation input schema",
+    "$schema": "http://json-schema.org/draft-04/schema#",
+    "type": "object",
+    "properties": {
+        "name": nameshort_schema,
+        "type": nameshort_schema,
+        "description": description_schema,
+        "shared": bool_schema,
+        "vims": nameshort_list_schema,
+        "vim_accounts": nameshort_list_schema,
+        "interfaces": {
+            "type": "array",
+            "items": {"type": pdu_interface},
+            "minItems": 1
+        }
+    },
+    "required": ["name", "type", "interfaces"],
+    "additionalProperties": False
 }
+
+pdu_edit_schema = {
+    "title": "pdu edit input schema",
+    "$schema": "http://json-schema.org/draft-04/schema#",
+    "type": "object",
+    "properties": {
+        "name": nameshort_schema,
+        "type": nameshort_schema,
+        "description": description_schema,
+        "shared": bool_schema,
+        "vims": {"oneOff": [array_edition_schema, nameshort_list_schema]},
+        "vim_accounts": {"oneOff": [array_edition_schema, nameshort_list_schema]},
+        "interfaces": {"oneOff": [
+            array_edition_schema,
+            {
+                "type": "array",
+                "items": {"type": pdu_interface},
+                "minItems": 1
+            }
+        ]}
+    },
+    "additionalProperties": False,
+    "minProperties": 1
+}
+
+# USERS
 user_new_schema = {
     "$schema": "http://json-schema.org/draft-04/schema#",
     "title": "New user schema",
@@ -417,7 +490,7 @@ user_new_schema = {
     "properties": {
         "username": nameshort_schema,
         "password": passwd_schema,
-        "projects": user_project_schema,
+        "projects": nameshort_list_schema,
     },
     "required": ["username", "password", "projects"],
     "additionalProperties": False
@@ -430,11 +503,13 @@ user_edit_schema = {
         "password": passwd_schema,
         "projects": {
             "oneOff": [
-                user_project_schema,
+                nameshort_list_schema,
                 array_edition_schema
             ]
         },
-    }
+    },
+    "minProperties": 1,
+    "additionalProperties": False
 }
 
 # PROJECTS
@@ -469,14 +544,16 @@ nbi_new_input_schemas = {
     "sdns": sdn_new_schema,
     "ns_instantiate": ns_instantiate,
     "ns_action": ns_action,
-    "ns_scale": ns_scale
+    "ns_scale": ns_scale,
+    "pdus": pdu_new_schema,
 }
 
 nbi_edit_input_schemas = {
     "users": user_edit_schema,
     "projects": project_edit_schema,
     "vim_accounts": vim_account_edit_schema,
-    "sdns": sdn_edit_schema
+    "sdns": sdn_edit_schema,
+    "pdus": pdu_edit_schema,
 }
 
 
@@ -484,19 +561,14 @@ class ValidationError(Exception):
     pass
 
 
-def validate_input(indata, item, new=True):
+def validate_input(indata, schema_to_use):
     """
     Validates input data against json schema
     :param indata: user input data. Should be a dictionary
-    :param item: can be users, projects, vims, sdns, ns_xxxxx
-    :param new: True if the validation is for creating or False if it is for editing
-    :return: None if ok, raises ValidationError exception otherwise
+    :param schema_to_use: jsonschema to test
+    :return: None if ok, raises ValidationError exception on error
     """
     try:
-        if new:
-            schema_to_use = nbi_new_input_schemas.get(item)
-        else:
-            schema_to_use = nbi_edit_input_schemas.get(item)
         if schema_to_use:
             js_v(indata, schema_to_use)
         return None
index f4c9f0d..8a293d5 100644 (file)
--- a/setup.py
+++ b/setup.py
@@ -6,8 +6,8 @@ from setuptools import setup
 _name = "osm_nbi"
 # version is at first line of osm_nbi/html_public/version
 here = os.path.abspath(os.path.dirname(__file__))
-with open(os.path.join(here, 'osm_nbi/html_public/version')) as version_file:
-    VERSION = version_file.readline().strip()
+with open(os.path.join(here, 'osm_nbi/html_public/version')) as version_file:
+    VERSION = version_file.readline().strip()
 with open(os.path.join(here, 'README.rst')) as readme_file:
     README = readme_file.read()
 
@@ -15,7 +15,7 @@ setup(
     name=_name,
     description='OSM North Bound Interface',
     long_description=README,
-    version_command=('git describe --match v* --tags --long --dirty', 'pep440-git'),
+    version_command=('git describe --match v* --tags --long --dirty', 'pep440-git-full'),
     # version=VERSION,
     # python_requires='>3.5.0',
     author='ETSI OSM',
@@ -34,7 +34,7 @@ setup(
         "git+https://osm.etsi.org/gerrit/osm/common.git@master#egg=osm-common-0.1.4"
     ],
     install_requires=[
-        'CherryPy', 'pymongo', 'jsonschema', 'PyYAML',
+        'CherryPy', 'pymongo', 'jsonschema', 'PyYAML', 'python-keystoneclient'
         # 'osm-common',
     ],
     setup_requires=['setuptools-version-command'],
index 72970ec..f7300ed 100644 (file)
--- a/stdeb.cfg
+++ b/stdeb.cfg
@@ -1,2 +1,2 @@
 [DEFAULT]
-Depends: python3-cherrypy3, python3-pymongo, python3-yaml, python3-jsonschema
+Depends: python3-cherrypy3, python3-pymongo, python3-yaml, python3-jsonschema, python3-keystoneclient
diff --git a/tox.ini b/tox.ini
index 0207a67..b864700 100644 (file)
--- a/tox.ini
+++ b/tox.ini
@@ -10,8 +10,8 @@ commands=nosetests
 [testenv:flake8]
 basepython = python3
 deps = flake8
-commands =
-    flake8 osm_nbi/ setup.py --max-line-length 120 --exclude .svn,CVS,.gz,.git,__pycache__,.tox,local,temp,vnfd_catalog.py,nsd_catalog.py --ignore W291,W293,E226
+commands = flake8 osm_nbi/ setup.py --max-line-length 120 \
+    --exclude .svn,CVS,.gz,.git,__pycache__,.tox,local,temp,vnfd_catalog.py,nsd_catalog.py --ignore W291,W293,E226,E402
 
 [testenv:build]
 basepython = python3