Allow ns-creation params: vim-network, multisite deployement
[osm/NBI.git] / osm_nbi / nbi.py
index 1cd61d5..a72fa58 100644 (file)
@@ -19,8 +19,11 @@ from codecs import getreader
 from os import environ
 
 __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
-__version__ = "0.3"
-version_date = "Mar 2018"
+
+# TODO consider to remove and provide version using the static version file
+__version__ = "0.1.3"
+version_date = "Apr 2018"
+database_version = '1.0'
 
 """
 North Bound Interface  (O: OSM specific; 5,X: SOL005 not implemented yet; O5: SOL005 implemented)
@@ -40,6 +43,8 @@ URL: /osm                                                       GET     POST
                 /<subscriptionId>                               5                       X
 
         /vnfpkgm/v1
+            /vnf_packages_content                               O       O
+                /<vnfPkgId>                                     O                       O     
             /vnf_packages                                       O5      O5
                 /<vnfPkgId>                                     O5                      O5      5
                     /package_content                            O5               O5
@@ -54,7 +59,11 @@ URL: /osm                                                       GET     POST
                 /<nsInstanceId>                                 O                       O     
             /ns_instances                                       5       5
                 /<nsInstanceId>                                 5                       5     
-                    TO BE COMPLETED                             
+                    instantiate                                         O5
+                    terminate                                           O5
+                    action                                              O
+                    scale                                               O5
+                    heal                                                5
             /ns_lcm_op_occs                                     5       5
                 /<nsLcmOpOccId>                                 5                       5       5
                     TO BE COMPLETED                             5               5
@@ -67,7 +76,7 @@ URL: /osm                                                       GET     POST
                 /<id>                                           O                       O     
             /projects                                           O       O
                 /<id>                                           O                       O     
-            /vims                                               O       O
+            /vims_accounts  (also vims for compatibility)       O       O
                 /<id>                                           O                       O       O     
             /sdns                                               O       O
                 /<id>                                           O                       O       O     
@@ -140,6 +149,9 @@ class Server(object):
                     "vims": {"METHODS": ("GET", "POST"),
                         "<ID>": {"METHODS": ("GET", "DELETE")}
                     },
+                    "vim_accounts": {"METHODS": ("GET", "POST"),
+                        "<ID>": {"METHODS": ("GET", "DELETE")}
+                    },
                     "sdns": {"METHODS": ("GET", "POST"),
                         "<ID>": {"METHODS": ("GET", "DELETE")}
                     },
@@ -193,8 +205,16 @@ class Server(object):
                     "ns_instances_content": {"METHODS": ("GET", "POST"),
                         "<ID>": {"METHODS": ("GET", "DELETE")}
                     },
-                    "ns_instances": {"TODO": ("GET", "POST"),
-                        "<ID>": {"TODO": ("GET", "DELETE")}
+                    "ns_instances": {"METHODS": ("GET", "POST"),
+                        "<ID>": {"TODO": ("GET", "DELETE"),
+                             "scale": {"TODO": "POST"},
+                             "terminate": {"METHODS": "POST"},
+                             "instantiate": {"METHODS": "POST"},
+                             "action": {"METHODS": "POST"},
+                        }
+                    },
+                    "ns_lcm_op_occs": {"METHODS": "GET",
+                        "<ID>": {"METHODS": "GET"},
                     }
                 }
             },
@@ -332,7 +352,7 @@ class Server(object):
         if data is None:
             if accept and "text/html" in accept:
                 return html.format(data, cherrypy.request, cherrypy.response, session)
-            cherrypy.response.status = HTTPStatus.NO_CONTENT.value
+            cherrypy.response.status = HTTPStatus.NO_CONTENT.value
             return
         elif hasattr(data, "read"):  # file object
             if _format:
@@ -379,6 +399,25 @@ class Server(object):
             cherrypy.response.status = e.http_code.value
             return self._format_out("Welcome to OSM!", session)
 
+    @cherrypy.expose
+    def version(self, *args, **kwargs):
+        # TODO consider to remove and provide version using the static version file
+        global __version__, version_date
+        try:
+            if cherrypy.request.method != "GET":
+                raise NbiException("Only method GET is allowed", HTTPStatus.METHOD_NOT_ALLOWED)
+            elif args or kwargs:
+                raise NbiException("Invalid URL or query string for version", HTTPStatus.METHOD_NOT_ALLOWED)
+            return __version__ + " " + version_date
+        except NbiException as e:
+            cherrypy.response.status = e.http_code.value
+            problem_details = {
+                "code": e.http_code.name,
+                "status": e.http_code.value,
+                "detail": str(e),
+            }
+            return self._format_out(problem_details, None)
+
     @cherrypy.expose
     def token(self, method, token_id=None, kwargs=None):
         session = None
@@ -431,19 +470,12 @@ class Server(object):
             }
             return self._format_out(problem_details, session)
 
-    @cherrypy.expose
-    def test2(self, args0=None, args1=None, args2=None, args3=None, *args, **kwargs):
-        return_text = (
-            "<html><pre>\n{} {} {} {} {} {} \n".format(args0, args1, args2, args3, args, kwargs))
-        return_text += "</pre></html>"
-        return return_text
-
     @cherrypy.expose
     def test(self, *args, **kwargs):
         thread_info = None
         if args and args[0] == "help":
             return "<html><pre>\ninit\nfile/<name>  download file\ndb-clear/table\nprune\nlogin\nlogin2\n"\
-                    "sleep/<time>\n</pre></html>"
+                    "sleep/<time>\nmessage/topic\n</pre></html>"
 
         elif args and args[0] == "init":
             try:
@@ -460,8 +492,8 @@ class Server(object):
             f_path = cherrypy.tree.apps['/osm'].config["storage"]["path"] + "/" + args[1]
             f = open(f_path, "r")
             cherrypy.response.headers["Content-type"] = "text/plain"
-
             return f
+
         elif len(args) == 2 and args[0] == "db-clear":
             return self.engine.del_item_list({"project_id": "admin"}, args[1], {})
         elif args and args[0] == "prune":
@@ -487,12 +519,21 @@ class Server(object):
             # thread_info
         elif len(args) >= 2 and args[0] == "message":
             topic = args[1]
+            return_text = "<html><pre>{} ->\n".format(topic)
             try:
-                for k, v in kwargs.items():
-                    self.engine.msg.write(topic, k, yaml.load(v))
-                return "ok"
+                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)
+                        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))
+                        return_text += "  {}: {}\n".format(k, yaml.load(v))
             except Exception as e:
-                return "Error: " + str(e)
+                return_text += "Error: " + str(e)
+            return_text += "</pre></html>\n"
+            return return_text
 
         return_text = (
             "<html><pre>\nheaders:\n  args: {}\n".format(args) +
@@ -595,6 +636,10 @@ class Server(object):
                 engine_item = "vnfds"
             elif topic == "nslcm":
                 engine_item = "nsrs"
+                if item == "ns_lcm_op_occs":
+                    engine_item = "nslcmops"
+            if engine_item == "vims":   # TODO this is for backward compatibility, it will remove in the future
+                engine_item = "vim_accounts"
 
             if method == "GET":
                 if item2 in ("nsd_content", "package_content", "artifacts", "vnfd", "nsd"):
@@ -624,23 +669,38 @@ class Server(object):
                     else:
                         cherrypy.response.headers["Transaction-Id"] = _id
                     outdata = {"id": _id}
-                elif item in ("ns_descriptors", "vnf_packages"):
-                    _id = self.engine.new_item(session, engine_item, indata, kwargs, cherrypy.request.headers)
+                elif item == "ns_instances_content":
+                    _id = self.engine.new_item(session, engine_item, indata, kwargs)
+                    self.engine.ns_action(session, _id, "instantiate", {}, None)
                     self._set_location_header(topic, version, item, _id)
-                    #TODO form NsdInfo
                     outdata = {"id": _id}
+                elif item == "ns_instances" and item2:
+                    _id = self.engine.ns_action(session, _id, item2, indata, kwargs)
+                    self._set_location_header(topic, version, "ns_lcm_op_occs", _id)
+                    outdata = {"id": _id}
+                    cherrypy.response.status = HTTPStatus.ACCEPTED.value
                 else:
                     _id = self.engine.new_item(session, engine_item, indata, kwargs, cherrypy.request.headers)
                     self._set_location_header(topic, version, item, _id)
                     outdata = {"id": _id}
+                    # TODO form NsdInfo when item 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)
+                    cherrypy.response.status = HTTPStatus.OK.value
                 else:  # len(args) > 1
-                    # TODO return 202 ACCEPTED for nsrs vims
-                    self.engine.del_item(session, engine_item, _id)
-                    outdata = None
+                    if item == "ns_instances_content":
+                        self.engine.ns_action(session, _id, "terminate", {"autoremove": True}, None)
+                        cherrypy.response.status = HTTPStatus.ACCEPTED.value
+                    else:
+                        force = kwargs.get("FORCE")
+                        self.engine.del_item(session, engine_item, _id, force)
+                        cherrypy.response.status = HTTPStatus.NO_CONTENT.value
+                if engine_item in ("vim_accounts", "sdns"):
+                    cherrypy.response.status = HTTPStatus.ACCEPTED.value
+
             elif method == "PUT":
                 if not indata and not kwargs:
                     raise NbiException("Nothing to update. Provide payload and/or query string",
@@ -649,6 +709,7 @@ class Server(object):
                     completed = self.engine.upload_content(session, engine_item, _id, indata, kwargs, cherrypy.request.headers)
                     if not completed:
                         cherrypy.response.headers["Transaction-Id"] = id
+                    cherrypy.response.status = HTTPStatus.NO_CONTENT.value
                     outdata = None
                 else:
                     outdata = {"id": self.engine.edit_item(session, engine_item, args[1], indata, kwargs)}
@@ -766,7 +827,7 @@ def _start_service():
     # TODO add more entries, e.g.: storage
     cherrypy.tree.apps['/osm'].root.engine.start(engine_config)
     try:
-        cherrypy.tree.apps['/osm'].root.engine.create_admin()
+        cherrypy.tree.apps['/osm'].root.engine.init_db(target_version=database_version)
     except EngineException:
         pass
     # getenv('OSMOPENMANO_TENANT', None)