pdu: list, create, show, delete
[osm/LW-UI.git] / instancehandler / views.py
index 45120e2..ad7ead7 100644 (file)
@@ -21,6 +21,7 @@ import yaml
 import json
 import logging
 from lib.osm.osmclient.clientv2 import Client
+from lib.osm.osm_rdcl_parser import OsmParser
 import authosm.utils as osmutils
 from sf_t3d.decorators import login_required
 
@@ -30,7 +31,6 @@ log = logging.getLogger('instancehandler/view.py')
 
 @login_required
 def list(request, type=None):
-
     user = osmutils.get_user(request)
     project_id = user.project_id
     client = Client()
@@ -46,57 +46,82 @@ def list(request, type=None):
         instance_list = client.ns_list(user.get_token())
     elif type == 'vnf':
         instance_list = client.vnf_list(user.get_token())
+    elif type == 'pdu':
+        instance_list = client.pdu_list(user.get_token())
 
     result['instances'] = instance_list['data'] if instance_list and instance_list['error'] is False else []
 
     return __response_handler(request, result, 'instance_list.html')
 
-
 @login_required
-def create(request):
+def create(request, type=None):
     result = {}
-    try:
-
-        ns_data = {
-            "nsName": request.POST.get('nsName', 'WithoutName'),
-            "nsDescription": request.POST.get('nsDescription', ''),
-            "nsdId": request.POST.get('nsdId', ''),
-            "vimAccountId": request.POST.get('vimAccountId', ''),
-        }
-        if 'ssh_key' in request.POST and request.POST.get('ssh_key') != '':
-            ns_data["ssh_keys"] = request.POST.get('ssh_key')
-
-        if 'config' in request.POST:
-            ns_config = yaml.load(request.POST.get('config'))
-            if isinstance(ns_config, dict):
-                if "vim-network-name" in ns_config:
-                    ns_config["vld"] = ns_config.pop("vim-network-name")
-                if "vld" in ns_config:
-                    print ns_config
-                    for vld in ns_config["vld"]:
-                        if vld.get("vim-network-name"):
-                            if isinstance(vld["vim-network-name"], dict):
-                                vim_network_name_dict = {}
-                                for vim_account, vim_net in vld["vim-network-name"].items():
-                                    vim_network_name_dict[ns_data["vimAccountId"]] = vim_net
-                                vld["vim-network-name"] = vim_network_name_dict
-                    ns_data["vld"] = ns_config["vld"]
-                if "vnf" in ns_config:
-                    for vnf in ns_config["vnf"]:
-                        if vnf.get("vim_account"):
-                            vnf["vimAccountId"] = ns_data["vimAccountId"]
-
-                    ns_data["vnf"] = ns_config["vnf"]
-    except Exception as e:
-        request.session["OSM_ERROR"] = "Error creating the NS; Invalid parameters provided."
-        return __response_handler(request, {}, 'instances:list', to_redirect=True, type='ns', )
-
-    print ns_data
     user = osmutils.get_user(request)
     client = Client()
-    result = client.ns_create(user.get_token(), ns_data)
-    return __response_handler(request, result, 'instances:list', to_redirect=True, type='ns',)
-
+    if type == 'ns':
+        try:
+
+            ns_data = {
+                "nsName": request.POST.get('nsName', 'WithoutName'),
+                "nsDescription": request.POST.get('nsDescription', ''),
+                "nsdId": request.POST.get('nsdId', ''),
+                "vimAccountId": request.POST.get('vimAccountId', ''),
+            }
+            if 'ssh_key' in request.POST and request.POST.get('ssh_key') != '':
+                ns_data["ssh_keys"] = [request.POST.get('ssh_key')]
+
+            if 'config' in request.POST:
+                ns_config = yaml.load(request.POST.get('config'))
+                if isinstance(ns_config, dict):
+                    if "vim-network-name" in ns_config:
+                        ns_config["vld"] = ns_config.pop("vim-network-name")
+                    if "vld" in ns_config:
+                        print ns_config
+                        for vld in ns_config["vld"]:
+                            if vld.get("vim-network-name"):
+                                if isinstance(vld["vim-network-name"], dict):
+                                    vim_network_name_dict = {}
+                                    for vim_account, vim_net in vld["vim-network-name"].items():
+                                        vim_network_name_dict[ns_data["vimAccountId"]] = vim_net
+                                    vld["vim-network-name"] = vim_network_name_dict
+                        ns_data["vld"] = ns_config["vld"]
+                    if "vnf" in ns_config:
+                        for vnf in ns_config["vnf"]:
+                            if vnf.get("vim_account"):
+                                vnf["vimAccountId"] = ns_data["vimAccountId"]
+
+                        ns_data["vnf"] = ns_config["vnf"]
+        except Exception as e:
+            request.session["OSM_ERROR"] = "Error creating the NS; Invalid parameters provided."
+            return __response_handler(request, {}, 'instances:list', to_redirect=True, type='ns', )
+        result = client.ns_create(user.get_token(), ns_data)
+        return __response_handler(request, result, 'instances:list', to_redirect=True, type='ns')
+    elif type == 'pdu':
+        interface_param_name = request.POST.getlist('interfaces_name')
+        interface_param_ip = request.POST.getlist('interfaces_ip')
+        interface_param_mgmt = request.POST.getlist('interfaces_mgmt')
+        interface_param_netname = request.POST.getlist('interfaces_vimnetname')
+
+        pdu_payload = {
+            "name": request.POST.get('name'),
+            "type": request.POST.get('pdu_type'),
+            "vim_accounts": request.POST.getlist('pdu_vim_accounts'),
+            "description": request.POST.get('description'),
+            "interfaces": []
+        }
+        for i in (0,len(interface_param_name)-1):
+            pdu_payload['interfaces'].append({
+                'name': interface_param_name[i],
+                'mgmt': True if interface_param_mgmt[i] == 'true' else False,
+                'ip-address': interface_param_ip[i],
+                'vim-network-name': interface_param_netname[i]
+            })
+        result = client.pdu_create(user.get_token(), pdu_payload)
+        if result['error']:
+            return __response_handler(request, result['data'], url=None,
+                                  status=result['data']['status'] if 'status' in result['data'] else 500)
+        else:
+            return __response_handler(request, {}, url=None, status=200)
 
 @login_required
 def ns_operations(request, instance_id=None, type=None):
@@ -150,160 +175,37 @@ def delete(request, instance_id=None, type=None):
     result = {}
     user = osmutils.get_user(request)
     client = Client()
-    result = client.ns_delete(user.get_token(), instance_id, force)
+    if type == 'ns':
+        result = client.ns_delete(user.get_token(), instance_id, force)
+    elif type == 'pdu':
+        result = client.pdu_delete(user.get_token(), instance_id)
     print result
     return __response_handler(request, result, 'instances:list', to_redirect=True, type='ns')
 
-
+@login_required
 def show_topology(request, instance_id=None, type=None):
     user = osmutils.get_user(request)
     project_id = user.project_id
     raw_content_types = request.META.get('HTTP_ACCEPT', '*/*').split(',')
     if 'application/json' in raw_content_types:
-        result = {'vertices': [
-            {"info": {"type": "vnf", "property": {"custom_label": ""},
-                      "group": []}, "id": "ping"},
-            {"info": {"type": "vnf", "property": {"custom_label": ""},
-                      "group": []}, "id": "pong"},
-            {"info": {"type": "vdu", "property": {"custom_label": ""},
-                      "group": ['pong']}, "id": "pong/ubuntu"},
-            {"info": {"type": "vdu", "property": {"custom_label": ""},
-                      "group": ['ping']}, "id": "ping/ubuntu"},
-            {"info": {"type": "cp", "property": {"custom_label": ""},
-                      "group": ['ping']}, "id": "ping/cp0"},
-            {"info": {"type": "cp", "property": {"custom_label": ""},
-                      "group": ['ping']}, "id": "ping/cp1"},
-            {"info": {"type": "cp", "property": {"custom_label": ""},
-                      "group": ['pong']}, "id": "pong/cp0"},
-            {"info": {"type": "cp", "property": {"custom_label": ""},
-                      "group": ['pong']}, "id": "pong/cp1"},
-            {"info": {"type": "ns_vl", "property": {"custom_label": ""},
-                      "group": []}, "id": "mgmt_vl"},
-        ],
-            'edges': [
-                # {"source": "ping", "group": [], "target": "ping/cp0", "view": "Data"},
-                {"source": "pong/ubuntu", "group": ['pong'], "target": "pong/cp0", "view": "vnf"},
-                {"source": "ping/ubuntu", "group": ['ping'], "target": "ping/cp0", "view": "vnf"},
-                {"source": "pong/ubuntu", "group": ['pong'], "target": "pong/cp1", "view": "vnf"},
-                {"source": "ping/ubuntu", "group": ['ping'], "target": "ping/cp1", "view": "vnf"},
-                {"source": "pong", "group": [], "target": "mgmt_vl", "view": "ns"},
-                {"source": "ping", "group": [], "target": "mgmt_vl", "view": "ns"},
-            ], 'graph_parameters': [],
-            'model': {
-                "layer": {
-
-                    "ns": {
-                        "nodes": {
-                            "vnf": {
-                                "addable": {
-                                    "callback": "addNode"
-                                },
-                                "removable": {
-                                    "callback": "removeNode"
-                                },
-                                "expands": "vnf"
-                            },
-                            "ns_vl": {
-                                "addable": {
-                                    "callback": "addNode"
-                                },
-                                "removable": {
-                                    "callback": "removeNode"
-                                }
-                            },
-
-                        },
-                        "allowed_edges": {
-                            "ns_vl": {
-                                "destination": {
-                                    "vnf": {
-                                        "callback": "addLink",
-                                        "direct_edge": False,
-                                        "removable": {
-                                            "callback": "removeLink"
-                                        }
-                                    }
-                                }
-                            },
-                            "vnf": {
-                                "destination": {
-                                    "ns_vl": {
-                                        "callback": "addLink",
-                                        "direct_edge": False,
-                                        "removable": {
-                                            "callback": "removeLink"
-                                        }
-                                    },
-
-                                }
-                            }
-
-                        }
-                    },
-                    "vnf": {
-                        "nodes": {
-                            "vdu": {
-                                "addable": {
-                                    "callback": "addNode"
-                                },
-                                "removable": {
-                                    "callback": "removeNode"
-                                }
-                            },
-                            "cp": {
-                                "addable": {
-                                    "callback": "addNode"
-                                },
-                                "removable": {
-                                    "callback": "removeNode"
-                                }
-                            },
-
-                        },
-                        "allowed_edges": {
-                            "vdu": {
-                                "destination": {
-                                    "cp": {
-                                        "callback": "addLink",
-                                        "direct_edge": False,
-                                        "removable": {
-                                            "callback": "removeLink"
-                                        }
-                                    }
-                                }
-                            },
-                            "cp": {
-                                "destination": {
-                                    "vdu": {
-                                        "callback": "addLink",
-                                        "direct_edge": False,
-                                        "removable": {
-                                            "callback": "removeLink"
-                                        }
-                                    }
-                                }
-                            }
-                        }
-                    },
-                    "name": "OSM",
-                    "version": 1,
-                    "nodes": {
-                        "vnf": {
-                            "label": "vnf"
-                        },
-                        "ns_vl": {
-                            "label": "vl"
-                        },
-                        "cp": {
-                            "label": "cp"
-                        },
-                        "vdu": {
-                            "label": "vdu"
-                        }
-                    },
-                    "description": "osm"
-                }
-            }}
+        client = Client()
+        nsr_object = {'nsr': {}, 'vnfr': {}, 'vnfd': {}}
+        if type == 'ns':
+
+            nsr_resp = client.ns_get(user.get_token(), instance_id)
+            nsr_object['nsr'] = nsr_resp['data']
+            if 'constituent-vnfr-ref' in nsr_object['nsr'] :
+                for vnfr_id in nsr_object['nsr']['constituent-vnfr-ref']:
+                    vnfr_resp = client.vnf_get(user.get_token(), vnfr_id)
+                    vnfr = vnfr_resp['data']
+                    nsr_object['vnfr'][vnfr['id']] = vnfr
+                    if vnfr['vnfd-id'] not in nsr_object['vnfd']:
+                        vnfd_resp = client.vnfd_get(user.get_token(), vnfr['vnfd-id'])
+                        nsr_object['vnfd'][vnfr['vnfd-id']] = vnfd_resp['vnfd:vnfd-catalog']['vnfd'][0]
+
+        test = OsmParser()
+
+        result = test.nsr_to_graph(nsr_object)
         return __response_handler(request, result)
     else:
         result = {'type': type, 'project_id': project_id, 'instance_id': instance_id}
@@ -320,6 +222,8 @@ def show(request, instance_id=None, type=None):
         result = client.ns_get(user.get_token(), instance_id)
     elif type == 'vnf':
         result = client.vnf_get(user.get_token(), instance_id)
+    elif type == 'pdu':
+        result = client.pdu_get(user.get_token(), instance_id)
     print result
     return __response_handler(request, result)
 
@@ -378,8 +282,8 @@ def create_alarm(request, instance_id=None, type=None):
 
 def __response_handler(request, data_res, url=None, to_redirect=None, *args, **kwargs):
     raw_content_types = request.META.get('HTTP_ACCEPT', '*/*').split(',')
-    if 'application/json' in raw_content_types or url is None:
-        return HttpResponse(json.dumps(data_res), content_type="application/json")
+    if not to_redirect and ('application/json' in raw_content_types or url is None):
+        return HttpResponse(json.dumps(data_res), content_type="application/json", *args, **kwargs)
     elif to_redirect:
         return redirect(url, *args, **kwargs)
     else: