new django app packagehandler 76/7076/2
authorlombardofr <lombardo@everyup.it>
Wed, 19 Dec 2018 16:27:24 +0000 (17:27 +0100)
committerlombardofr <lombardo@everyup.it>
Sun, 30 Dec 2018 11:42:01 +0000 (12:42 +0100)
Change-Id: Ia5014bd979a44cdd52829b9a074b70fe9a5ea101
Signed-off-by: lombardofr <lombardo@everyup.it>
29 files changed:
.gitignore
descriptorhandler/template/composer.html
descriptorhandler/template/descriptor_new.html [deleted file]
descriptorhandler/template/descriptor_view.html
descriptorhandler/template/descriptorlist.html [deleted file]
descriptorhandler/template/modal/choose_package_name.html
descriptorhandler/urls.py
descriptorhandler/views.py
instancehandler/template/instance_list_ns.html
lib/osm/osmclient/client.py [deleted file]
lib/osm/osmclient/clientv2.py
packagehandler/__init__.py [new file with mode: 0644]
packagehandler/apps.py [new file with mode: 0644]
packagehandler/migrations/__init__.py [new file with mode: 0644]
packagehandler/template/package_list.html [new file with mode: 0644]
packagehandler/template/package_list_ns.html [new file with mode: 0644]
packagehandler/template/package_list_vnf.html [new file with mode: 0644]
packagehandler/urls.py [new file with mode: 0644]
packagehandler/views.py [new file with mode: 0644]
projecthandler/template/project/osm/osm_project_descriptors.html [deleted file]
projecthandler/template/project/osm/osm_project_details.html
projecthandler/template/project/osm/osm_project_left_sidebar.html
projecthandler/template/project/project_descriptors.html
sf_t3d/settings.py
sf_t3d/urls.py
static/src/packagehandler/onboard_package.js [new file with mode: 0644]
static/src/packagehandler/packages_list.js [new file with mode: 0644]
static/src/projecthandler/descriptorslist.js [deleted file]
static/src/projecthandler/onboard_package.js [deleted file]

index 28635bf..5af1e6d 100644 (file)
@@ -9,7 +9,7 @@ __pycache__/
 env/
 .idea
 db.sqlite3
-.idea
+.vscode
 wheelhouse/
 
 .installed.cfg
index 7647151..f0c2e9a 100644 (file)
@@ -24,7 +24,6 @@
 
 {% block breadcrumb_body %}
     {{ block.super }}
-    <li><a href="{% url 'projects:descriptors:list_descriptors'  descriptor_type=type %}">{{ type|upper }} Descriptors</a></li>
     <li><a href="#"><i class="fa fa-sitemap"></i> {{ type|upper }} Composer</a></li>
 {% endblock %}
 
diff --git a/descriptorhandler/template/descriptor_new.html b/descriptorhandler/template/descriptor_new.html
deleted file mode 100644 (file)
index 2551f30..0000000
+++ /dev/null
@@ -1,67 +0,0 @@
-{% extends "/descriptor_view_base.html" %}
-
-{% load staticfiles %}
-
-
-{% block title_header_big %}
-{{ block.super }}
-Onboard new {{ descriptor_type }} package
-{% endblock %}
-
-{% block left_sidebar %}
-{% include 'osm/osm_project_left_sidebar.html' %}
-{% endblock %}
-
-{% block breadcrumb_body %}
-{{ block.super }}
-<li><a href="{% url 'projects:open_project'  %}">{{project_id}}</a></li>
-<li><a href="{% url 'projects:open_project'  %}descriptors/{{descriptor_type}}">{{ descriptor_type }}  Descriptors</a></li>
-<li>Create Descriptor</li>
-{% endblock %}
-
-{% block tab_pane_button_list %}
-{{ block.super }}
-<li id="file_li" class="active"><a href="#upload" data-toggle="tab"><i class="fa fa-upload"></i> Onboard Package</a></li>
-{% endblock %}
-
-{% block nav_buttons_list %}
-{{ block.super }}
-<li class="pull-right">
-    <button id="cancel" type="button" class="btn btn-block btn-primary btn-sm" onclick="cancel(this.id)"><i
-            class="fa fa-times"></i> Cancel
-    </button>
-</li>
-{% endblock %}
-
-{% block tab_pane_list %}
-{{ block.super }}
-
-<div class="tab-pane active" id="upload">
-
-    <h4>Drag and drop file below</h4>
-    <div class="upload-drop-zone" id="drop-zone">
-            Just drag and drop files here
-    </div>
-</div>
-{% endblock %}
-
-
-{% block resource_block %}
-{{ block.super }}
-
-<script>
-    var descr_list_url = '{% url "projects:descriptors:list_descriptors"   descriptor_type=descriptor_type%}';
-    var csrf_token = '{{csrf_token}}';
-    var new_desc_url ="{% url 'projects:descriptors:new_descriptor'  descriptor_type=descriptor_type %}"
-
-    function cancel(id) {
-        window.location.href = descr_list_url
-    }
-
-</script>
-    <script src="/static/src/projecthandler/onboard_package.js"></script>
-{% endblock %}
-
-{% block footer %}
-    {% include "footer.html" %}
-{% endblock %}
index 8a3fd3e..fec5168 100644 (file)
@@ -16,7 +16,6 @@ Edit {{ descriptor_type|upper }} Descriptor
 {% block breadcrumb_body %}
 {{ block.super }}
 <li><a href="{% url 'projects:open_project' %}">{{project_id}}</a></li>
-<li><a href="{% url 'projects:descriptors:list_descriptors' descriptor_type=descriptor_type %}">{{ descriptor_type }} Descriptors</a></li>
 <li><a>{{descriptor_id}}</a></li>
 {% endblock %}
 
diff --git a/descriptorhandler/template/descriptorlist.html b/descriptorhandler/template/descriptorlist.html
deleted file mode 100644 (file)
index bbe8f21..0000000
+++ /dev/null
@@ -1,48 +0,0 @@
-{% load staticfiles %}
-{% load get %}
-<div class="col-md-12">
-
-    <div class="box">
-        <div class="box-header with-border">
-            <h3 class="box-title">
-            </h3>
-            <div class="box-tools">
-                <div class="btn-group">
-                    <button type="button" class="btn btn-default" data-toggle="modal" data-target="#modal_new_package_name_chooser" >
-                <i class="fa fa-paint-brush"></i> <span> Compose a new {{ descriptor_type|upper }}</span></button>
-                </div>
-            </div>
-        </div>
-        <div class="box-body">
-            <table id="descriptors_table" class="table table-bordered table-striped dataTable"
-                   role="grid">
-                <thead>
-                <tr role="row">
-                    <th>Short Name</th>
-                    <th>Identified</th>
-                    <th>Description</th>
-                    <th style="width:10%">Vendor</th>
-                    <th style="width:5%">Version</th>
-                    <th style="width:35%">Actions</th>
-                </tr>
-                </thead>
-                <tbody>
-
-                </tbody>
-
-            </table>
-        </div>
-    </div>
-</div>
-
-<div class="col-sm-12">
-    <div class="box box-solid">
-        <div class="box-body">
-
-            <div class="upload-drop-zone" id="drop-zone">
-               <i class="fa fa-upload"></i> Just drag and drop files here
-            </div>
-        </div>
-    </div>
-</div>
-
index 2211026..fcad340 100644 (file)
@@ -6,7 +6,7 @@
                     <span aria-hidden="true">×</span></button>
                 <h4 class="modal-title">Create new Package</h4>
             </div>
-            <form id="formCreatePackage" action='{% url "projects:descriptors:create_package_empty" descriptor_type=descriptor_type %}'
+            <form id="formCreatePackage" action='{% url "packages:create_package_empty" package_type=package_type %}'
                   class="form-horizontal"
                   method="post" enctype="multipart/form-data">
                 {% csrf_token %}
index 481211a..893514a 100644 (file)
@@ -1,4 +1,3 @@
-#
 #   Copyright 2018 EveryUP Srl
 #
 #   Licensed under the Apache License, Version 2.0 (the "License");
 #   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 #   See the License for the specific language governing permissions and
 #   limitations under the License.
-#
+
 
 from django.conf.urls import url
 from descriptorhandler import views
 
 urlpatterns = [
-    url(r'(?P<descriptor_type>\w+)/list$', views.show_descriptors, name='list_descriptors'),
-    url(r'(?P<descriptor_type>\w+)/create', views.create_package_empty, name='create_package_empty'),
     url(r'(?P<descriptor_type>\w+)/(?P<descriptor_id>[-\w]+)(/$)', views.edit_descriptor, name='edit_descriptor'),
-    url(r'(?P<descriptor_type>\w+)/(?P<descriptor_id>[-\w]+)/delete$', views.delete_descriptor, name='delete_descriptor'),
-    url(r'(?P<descriptor_type>\w+)/(?P<descriptor_id>[-\w]+)/clone', views.clone_descriptor, name='clone_descriptor'),
     url(r'(?P<descriptor_type>\w+)/(?P<descriptor_id>[-\w]+)/addElement/(?P<element_type>\w+)', views.addElement,
         name='addElement'),
     url(r'(?P<descriptor_type>\w+)/(?P<descriptor_id>[-\w]+)/removeElement/(?P<element_type>\w+)', views.removeElement,
@@ -31,7 +26,6 @@ urlpatterns = [
         name='updateElement'),
     url(r'(?P<descriptor_type>\w+)/(?P<descriptor_id>[-\w]+)/action/(?P<action_name>[-\w]+)', views.custom_action,
         name='custom_action'),
-    url(r'(?P<descriptor_type>\w+)/new$', views.new_descriptor, name='new_descriptor'),
     url(r'composer$', views.open_composer, name='open_composer'),
     url(r'availablenodes', views.get_available_nodes, name='get_available_nodes'),
 ]
index 5824e57..e5728fb 100644 (file)
@@ -22,7 +22,6 @@ from sf_t3d.decorators import login_required
 from django.http import HttpResponse
 from django.shortcuts import render, redirect
 
-
 from lib.util import Util
 from lib.osm.osmclient.clientv2 import Client
 from lib.osm.osm_rdcl_parser import OsmParser
@@ -33,114 +32,9 @@ logging.basicConfig(level=logging.DEBUG)
 log = logging.getLogger('descriptorhandler/view.py')
 
 
-@login_required
-def show_descriptors(request, descriptor_type=None):
-    user = osmutils.get_user(request)
-    project_id = user.project_id
-    client = Client()
-    try:
-        if descriptor_type == 'nsd':
-            descriptors = client.nsd_list(user.get_token())
-        elif descriptor_type == 'vnfd':
-            descriptors = client.vnfd_list(user.get_token())
-    except Exception as e:
-        log.exception(e)
-        descriptors = []
-
-    url = 'osm/osm_project_descriptors.html'
-    return __response_handler(request, {
-        'descriptors': descriptors['data'] if descriptors and descriptors['error'] is False else [],
-        'project_id': project_id,
-        'project_type': 'osm',
-        'descriptor_type': descriptor_type
-    }, url)
-
-
-@login_required
-def delete_descriptor(request, descriptor_type=None, descriptor_id=None):
-    user = osmutils.get_user(request)
-    project_id = user.project_id
-    try:
-        client = Client()
-        if descriptor_type == 'nsd':
-            result = client.nsd_delete(user.get_token(), descriptor_id)
-        elif descriptor_type == 'vnfd':
-            result = client.vnfd_delete(user.get_token(), descriptor_id)
-    except Exception as e:
-        log.exception(e)
-        result = {'error': True, 'data': str(e)}
-
-    url = 'osm/osm_project_descriptors.html'
-    descriptors = {}
-    try:
-        if descriptor_type == 'nsd':
-            descriptors = client.nsd_list(user.get_token())
-        elif descriptor_type == 'vnfd':
-            descriptors = client.vnfd_list(user.get_token())
-    except Exception as e:
-        log.exception(e)
-
-    return __response_handler(request, {
-        'descriptors': descriptors['data'] if descriptors and descriptors['error'] is False else [],
-        'project_id': project_id,
-        'project_type': 'osm',
-        'descriptor_type': descriptor_type,
-        'alert_message': {
-            'success': False if result['error'] is True else True,
-            'message': 'An error occurred while processing your request.' if result and result['error'] is True else "Record deleted successfully"}
-    }, url)
-
-@login_required
-def create_package_empty(request, descriptor_type=None):
-    user = osmutils.get_user(request)
-    pkg_name = request.POST.get('name', '')
-    try:
-        client = Client()
-        if descriptor_type == 'nsd':
-            result = client.nsd_create_pkg_base(user.get_token(), pkg_name)
-        elif descriptor_type == 'vnfd':
-            result = client.vnfd_create_pkg_base(user.get_token(), pkg_name)
-        else:
-            log.debug('Update descriptor: Unknown data type')
-            result = {'error': True, 'data': 'Update descriptor: Unknown data type'}
-    except Exception as e:
-        log.exception(e)
-        result = {'error': True, 'data': str(e)}
-
-    if result['error'] == True:
-        return __response_handler(request, result['data'], url=None,
-                                  status=result['data']['status'] if 'status' in result['data'] else 500)
-    else:
-        result['data']['type'] = descriptor_type
-        return __response_handler(request, result, url=None, status=200)
-
-
-@login_required
-def clone_descriptor(request, descriptor_type=None, descriptor_id=None):
-    user = osmutils.get_user(request)
-    project_id = user.project_id
-    try:
-        client = Client()
-        if descriptor_type == 'nsd':
-            result = client.nsd_clone(user.get_token(), descriptor_id)
-        elif descriptor_type == 'vnfd':
-            result = client.vnfd_clone(user.get_token(), descriptor_id)
-        else:
-            log.debug('Update descriptor: Unknown data type')
-            result = {'error': True, 'data': 'Update descriptor: Unknown data type'}
-    except Exception as e:
-        log.exception(e)
-        result = {'error': True, 'data': str(e)}
-    if result['error'] == True:
-        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 addElement(request, descriptor_type=None, descriptor_id=None, element_type=None):
     user = osmutils.get_user(request)
-    project_id = user.project_id
     client = Client()
     if descriptor_type == 'nsd':
         descriptor_result = client.nsd_get(user.get_token(), descriptor_id)
@@ -180,7 +74,6 @@ def addElement(request, descriptor_type=None, descriptor_id=None, element_type=N
 @login_required
 def removeElement(request, descriptor_type=None, descriptor_id=None, element_type=None):
     user = osmutils.get_user(request)
-    project_id = user.project_id
     client = Client()
     if descriptor_type == 'nsd':
         descriptor_result = client.nsd_get(user.get_token(), descriptor_id)
@@ -220,7 +113,6 @@ def removeElement(request, descriptor_type=None, descriptor_id=None, element_typ
 @login_required
 def updateElement(request, descriptor_type=None, descriptor_id=None, element_type=None):
     user = osmutils.get_user(request)
-    project_id = user.project_id
     client = Client()
     if descriptor_type == 'nsd':
         descriptor_result = client.nsd_get(user.get_token(), descriptor_id)
@@ -258,45 +150,6 @@ def updateElement(request, descriptor_type=None, descriptor_id=None, element_typ
 
         return __response_handler(request, result_graph, url=None, status=200)
 
-@login_required
-def new_descriptor(request, descriptor_type=None):
-    user = osmutils.get_user(request)
-    project_id = user.project_id
-    page = 'descriptor_new.html'
-    if request.method == 'GET':
-        request_id = request.GET.get('id', '')
-
-        return __response_handler(request,  {
-            'project_id': project_id,
-            'descriptor_type': descriptor_type,
-            'descriptor_id': request_id,
-        }, page)
-    elif request.method == 'POST':
-        data_type = request.POST.get('type')
-        if data_type == "file":
-            file_uploaded = request.FILES['file']
-
-            try:
-                client = Client()
-                if descriptor_type == 'nsd':
-                    result = client.nsd_onboard(user.get_token(), file_uploaded)
-                elif descriptor_type == 'vnfd':
-                    result = client.vnfd_onboard(user.get_token(), file_uploaded)
-                else:
-                    log.debug('Create descriptor: Unknown data type')
-                    result = {'error': True, 'data': 'Create descriptor: Unknown data type'}
-
-            except Exception as e:
-                log.exception(e)
-                result = {'error': True, 'data': str(e)}
-        else:
-            result = {'error': True, 'data': 'Create descriptor: Unknown data type'}
-
-        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 edit_descriptor(request, descriptor_id=None, descriptor_type=None):
@@ -359,52 +212,9 @@ def edit_descriptor(request, descriptor_id=None, descriptor_type=None):
             'descriptor_strings': {'descriptor_string_yaml': descriptor_string_yaml,
                                    'descriptor_string_json': descriptor_string_json}})
 
-
-@login_required
-def get_package_files_list(request, descriptor_id, descriptor_type):
-    user = osmutils.get_user(request)
-    try:
-        client = Client()
-        if descriptor_type == 'nsd':
-            artifacts_res = client.nsd_artifacts(user.get_token(), descriptor_id)
-        elif descriptor_type == 'vnfd':
-            artifacts_res = client.vnf_packages_artifacts(user.get_token(), descriptor_id)
-        else:
-            return False
-
-        files_list = yaml.load(artifacts_res['data'] if artifacts_res and artifacts_res['error'] is False else [])
-        result = {'files': files_list}
-    except Exception as e:
-        log.exception(e)
-        url = 'error.html'
-        result = {'error_msg': 'Unknown error.'}
-    return __response_handler(request, result)
-
-
-@login_required
-def download_pkg(request, descriptor_id, descriptor_type):
-    user = osmutils.get_user(request)
-    file_name = "osm_export.tar.gz"
-    tar_pkg = None
-    try:
-        client = Client()
-        if descriptor_type == 'nsd':
-            tar_pkg = client.get_nsd_pkg(user.get_token(), descriptor_id)
-        elif descriptor_type == 'vnfd':
-            tar_pkg = client.get_vnfd_pkg(user.get_token(), descriptor_id)
-
-    except Exception as e:
-        log.exception(e)
-
-    response = HttpResponse(content_type="application/tgz")
-    response["Content-Disposition"] = "attachment; filename="+ file_name
-    response.write(tar_pkg.getvalue())
-    return response
-
 @login_required
 def open_composer(request):
     user = osmutils.get_user(request)
-    project_id = user.project_id
     descriptor_id = request.GET.get('id')
     descriptor_type = request.GET.get('type')
     result = {}
@@ -435,7 +245,6 @@ def open_composer(request):
 
     return __response_handler(request, result, 'composer.html')
 
-
 def get_available_nodes(request):
     user = osmutils.get_user(request)
     params = request.GET.dict()
@@ -454,13 +263,11 @@ def get_available_nodes(request):
 
     return __response_handler(request, {'descriptors': result})
 
-
 @login_required
 def custom_action(request, descriptor_id=None, descriptor_type=None, action_name=None):
     if request.method == 'GET':
         return globals()[action_name](request, descriptor_id, descriptor_type)
 
-
 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:
index e532076..78245d0 100644 (file)
@@ -7,7 +7,7 @@
 
             <button type="button" class="btn btn-default" data-container="body"
                     data-toggle="tooltip" data-placement="top" title="Instantiate NS"
-                    onclick="javascript:openModalCreateNS({ 'project_id':'{{ project_id }}','vim_list_url': '{% url "vims:list"  %}', 'nsd_list_url': '{% url "projects:descriptors:list_descriptors" descriptor_type='nsd' %}'})">
+                    onclick="javascript:openModalCreateNS({ 'project_id':'{{ project_id }}','vim_list_url': '{% url "vims:list"  %}', 'nsd_list_url': '{% url "packages:list_packages" package_type='ns' %}'})">
                 <i class="fa fa-paper-plane"></i> <span> New NS</span></button>
 
         </div>
diff --git a/lib/osm/osmclient/client.py b/lib/osm/osmclient/client.py
deleted file mode 100644 (file)
index 87e712b..0000000
+++ /dev/null
@@ -1,548 +0,0 @@
-import requests
-import logging
-import json
-import tarfile
-import yaml
-import pyaml
-import StringIO
-from lib.util import Util
-import hashlib
-import os
-
-logging.basicConfig(level=logging.DEBUG)
-log = logging.getLogger('helper.py')
-
-
-class Client(object):
-    def __init__(self, host=os.getenv('OSM_SERVER', "192.168.1.73"), so_port=9999, so_project='admin', ro_host=None, ro_port=9090, **kwargs):
-
-        self._user = 'admin'
-        self._password = 'admin'
-        # self._project = so_project
-        self._project = so_project
-        self._token_endpoint = 'admin/v1/tokens'
-        self._user_endpoint = 'admin/v1/users'
-
-        self._headers = {}
-        self._host = host
-
-        self._base_path = "https://{0}:{1}/osm".format(self._host, so_port)
-
-    def get_token(self):
-        postfields_dict = {'username': self._user,
-                           'password': self._password,
-                           'project-id': self._project}
-        token_url = "{0}/{1}".format(self._base_path, self._token_endpoint)
-        token = self._send_post(token_url, None, postfields_dict, headers={"Content-Type": "application/yaml", "accept": "application/json"})
-        if token is not None:
-            return token['id']
-        return None
-
-    def vim_list(self):
-        token = self.get_token()
-        if token:
-            self._headers['Authorization'] = 'Bearer {}'.format(token)
-            self._headers['accept'] = 'application/json'
-            _url = "{0}/admin/v1/vims".format(self._base_path)
-            return self._send_get(_url, headers=self._headers)
-
-    def vim_delete(self, id):
-        token = self.get_token()
-        if token:
-            self._headers['Authorization'] = 'Bearer {}'.format(token)
-            self._headers['accept'] = 'application/json'
-            _url = "{0}/admin/v1/vims/{1}".format(self._base_path, id)
-            return self._send_delete(_url, headers=self._headers)
-        return None
-
-    def vim_get(self, id):
-        token = self.get_token()
-        if token:
-            self._headers['Authorization'] = 'Bearer {}'.format(token)
-            self._headers['accept'] = 'application/json'
-            _url = "{0}/admin/v1/vims/{1}".format(self._base_path, id)
-            return self._send_get(_url, headers=self._headers)
-        return None
-
-    def vim_create(self, vim_data):
-        token = self.get_token()
-        headers = {}
-        if token:
-            headers['Authorization'] = 'Bearer {}'.format(token)
-            headers['Content-Type'] = 'application/json'
-            headers['accept'] = 'application/json'
-
-            _url = "{0}/admin/v1/vims".format(self._base_path)
-            return self._send_post(_url, headers=headers,
-                                  json=vim_data)
-        return None
-
-    def sdn_list(self):
-        token = self.get_token()
-        if token:
-            self._headers['Authorization'] = 'Bearer {}'.format(token)
-            self._headers['accept'] = 'application/json'
-            _url = "{0}/admin/v1/sdns".format(self._base_path)
-            return self._send_get(_url, headers=self._headers)
-
-    def sdn_delete(self, id):
-        token = self.get_token()
-        if token:
-            self._headers['Authorization'] = 'Bearer {}'.format(token)
-            self._headers['accept'] = 'application/json'
-            _url = "{0}/admin/v1/sdns/{1}".format(self._base_path, id)
-            return self._send_delete(_url, headers=self._headers)
-        return None
-
-    def sdn_get(self, id):
-        token = self.get_token()
-        if token:
-            self._headers['Authorization'] = 'Bearer {}'.format(token)
-            self._headers['accept'] = 'application/json'
-            _url = "{0}/admin/v1/sdns/{1}".format(self._base_path, id)
-            return self._send_get(_url, headers=self._headers)
-        return None
-
-    def sdn_create(self, sdn_data):
-        token = self.get_token()
-        headers = {}
-        if token:
-            headers['Authorization'] = 'Bearer {}'.format(token)
-            headers['Content-Type'] = 'application/json'
-            headers['accept'] = 'application/json'
-
-            _url = "{0}/admin/v1/sdns".format(self._base_path)
-            return self._send_post(_url, headers=headers,
-                                  json=sdn_data)
-        return None
-
-    def nsd_list(self):
-        token = self.get_token()
-        if token:
-            self._headers['Authorization'] = 'Bearer {}'.format(token)
-            self._headers['Content-Type'] = 'application/yaml'
-            self._headers['accept'] = 'application/json'
-            _url = "{0}/nsd/v1/ns_descriptors_content".format(self._base_path)
-            return self._send_get(_url, headers=self._headers)
-        return None
-
-    def nsd_get(self, id):
-        token = self.get_token()
-        if token:
-            self._headers['Authorization'] = 'Bearer {}'.format(token)
-            self._headers['Content-Type'] = 'application/yaml'
-            #self._headers['accept'] = 'application/json'
-            _url = "{0}/nsd/v1/ns_descriptors/{1}/nsd".format(self._base_path,id)
-            return yaml.load(self._send_get(_url, headers=self._headers))
-        return None
-
-    def nsd_delete(self, id):
-        token = self.get_token()
-        if token:
-            self._headers['Authorization'] = 'Bearer {}'.format(token)
-            self._headers['Content-Type'] = 'application/yaml'
-            self._headers['accept'] = 'application/json'
-            _url = "{0}/nsd/v1/ns_descriptors_content/{1}".format(self._base_path, id)
-            return self._send_delete(_url, headers=self._headers)
-        return None
-
-    def _descriptor_update(self, tarf, data):
-        print tarf.getnames()
-        # extract the package on a tmp directory
-        tarf.extractall('/tmp')
-
-        for name in tarf.getnames():
-            if name.endswith(".yaml") or name.endswith(".yml"):
-                with open('/tmp/' + name, 'w') as outfile:
-                    yaml.safe_dump(data, outfile, default_flow_style=False)
-                break
-
-        tarf_temp = tarfile.open('/tmp/' + tarf.getnames()[0] + ".tar.gz", "w:gz")
-        # tarf_temp = tarfile.open("pippo.tar.gz", "w:gz")
-        print tarf_temp.getnames()
-        # tarf_temp.add('/tmp/'+tarf.getnames()[0])
-        for tarinfo in tarf:
-            # if tarinfo.name.startswith(tarf.getnames()[0]):
-            #    new_name = tarinfo.name[len(tarf.getnames()[0]):]
-            tarf_temp.add('/tmp/' + tarinfo.name, tarinfo.name, recursive=False)
-        print tarf_temp.getnames()
-        tarf_temp.close()
-        return tarf
-
-    def nsd_update(self, id, data):
-        token = self.get_token()
-        headers = {}
-        if token:
-            # get the package onboarded
-            tar_pkg = self.get_nsd_pkg(id)
-            tarf = tarfile.open(fileobj=tar_pkg)
-
-            tarf = self._descriptor_update(tarf, data)
-            headers['Authorization'] = 'Bearer {}'.format(token)
-            headers['Content-Type'] = 'application/gzip'
-            headers['accept'] = 'application/json'
-            headers['Content-File-MD5'] = self.md5(open('/tmp/' + tarf.getnames()[0] + ".tar.gz", 'rb'))
-            #headers['Content-File-MD5'] = self.md5(open("pippo.tar.gz", 'rb'))
-
-            _url = "{0}/nsd/v1/ns_descriptors/{1}/nsd_content".format(self._base_path, id)
-            return self._send_put(_url, headers=headers, data=open('/tmp/'+tarf.getnames()[0] + ".tar.gz", 'rb'))
-            #return self._send_put(_url, headers=headers, data=open("pippo.tar.gz", 'rb'))
-
-        return None
-
-    def nsd_onboard(self, package):
-        token = self.get_token()
-        headers = {}
-        if token:
-
-            headers['Authorization'] = 'Bearer {}'.format(token)
-            headers['Content-Type'] = 'application/gzip'
-            headers['accept'] = 'application/json'
-            with open('/tmp/'+package.name, 'wb+') as destination:
-                for chunk in package.chunks():
-                    destination.write(chunk)
-            headers['Content-File-MD5'] = self.md5(open('/tmp/'+package.name, 'rb'))
-
-            _url = "{0}/nsd/v1/ns_descriptors_content/".format(self._base_path)
-            return self._send_post(_url, headers=headers,
-                                  data=open('/tmp/'+package.name, 'rb'))
-        return None
-
-    def nsd_artifacts(self, id):
-        token = self.get_token()
-        if token:
-            self._headers['Authorization'] = 'Bearer {}'.format(token)
-            self._headers['Content-Type'] = 'application/yaml'
-            self._headers['accept'] = 'text/plain'
-            _url = "{0}/nsd/v1/ns_descriptors/{1}/artifacts".format(self._base_path, id)
-            return self._send_get(_url, headers=self._headers)
-        return None
-
-    def ns_list(self):
-        token = self.get_token()
-        if token:
-            self._headers['Authorization'] = 'Bearer {}'.format(token)
-            self._headers['Content-Type'] = 'application/yaml'
-            self._headers['accept'] = 'application/json'
-            _url = "{0}/nslcm/v1/ns_instances_content".format(self._base_path)
-            return self._send_get(_url, headers=self._headers)
-        return None
-
-    def ns_create(self, ns_data):
-        token = self.get_token()
-        headers = {}
-        if token:
-            headers['Authorization'] = 'Bearer {}'.format(token)
-            headers['Content-Type'] = 'application/yaml'
-            headers['accept'] = 'application/json'
-
-            _url = "{0}/nslcm/v1/ns_instances_content".format(self._base_path)
-            return self._send_post(_url, headers=headers,
-                                  json=ns_data)
-        return None
-
-    def ns_get(self, id):
-        token = self.get_token()
-        if token:
-            self._headers['Authorization'] = 'Bearer {}'.format(token)
-            self._headers['Content-Type'] = 'application/json'
-            self._headers['accept'] = 'application/json'
-            _url = "{0}/nslcm/v1/ns_instances_content/{1}".format(self._base_path, id)
-            return self._send_get(_url, headers=self._headers)
-        return None
-
-    def ns_delete(self, id, force=None):
-        token = self.get_token()
-        if token:
-            self._headers['Authorization'] = 'Bearer {}'.format(token)
-            self._headers['accept'] = 'application/json'
-            query_path = ''
-            if force:
-                query_path = '?FORCE=true'
-            _url = "{0}/nslcm/v1/ns_instances_content/{1}{2}".format(self._base_path, id, query_path)
-
-            return self._send_delete(_url, headers=self._headers)
-        return None
-
-    def ns_action(self, id, action_payload):
-        token = self.get_token()
-        headers = {}
-        if token:
-            headers['Authorization'] = 'Bearer {}'.format(token)
-            headers['Content-Type'] = 'application/json'
-            headers['accept'] = 'application/json'
-
-            _url = "{0}/nslcm/v1/ns_instances/{1}/action".format(self._base_path, id)
-            return self._send_post(_url, headers=headers,
-                                   json=action_payload)
-        return None
-
-    def ns_op_list(self, id):
-        token = self.get_token()
-        headers = {}
-        if token:
-            headers['Authorization'] = 'Bearer {}'.format(token)
-            headers['Content-Type'] = 'application/json'
-            headers['accept'] = 'application/json'
-
-            _url = "{0}/nslcm/v1/ns_lcm_op_occs/?nsInstanceId={1}".format(self._base_path, id)
-            return self._send_get(_url, headers=headers)
-        return None
-
-    def ns_op(self, id):
-        token = self.get_token()
-        headers = {}
-        if token:
-            headers['Authorization'] = 'Bearer {}'.format(token)
-            headers['Content-Type'] = 'application/json'
-            headers['accept'] = 'application/json'
-
-            _url = "{0}/nslcm/v1/ns_lcm_op_occs/{1}".format(self._base_path, id)
-            return self._send_get(_url, headers=headers)
-        return None
-
-    def ns_alarm_create(self, id, alarm_payload):
-        token = self.get_token()
-        headers = {}
-        if token:
-            headers['Authorization'] = 'Bearer {}'.format(token)
-            headers['Content-Type'] = 'application/json'
-#            headers['accept'] = 'application/json'
-
-            _url = "{0}/test/message/alarm_request".format(self._base_path)
-            return self._send_post(_url, headers=headers, json=alarm_payload)
-        return None
-
-    def ns_metric_export(self, id, metric_payload):
-
-        token = self.get_token()
-        headers = {}
-        if token:
-            headers['Authorization'] = 'Bearer {}'.format(token)
-            headers['Content-Type'] = 'application/json'
-            #headers['accept'] = 'application/json'
-            _url = "{0}/test/message/metric_request".format(self._base_path)
-            print _url
-            return self._send_post(_url, headers=headers, json=metric_payload)
-        return None
-
-
-    def vnfd_list(self):
-        token = self.get_token()
-        if token:
-            self._headers['Authorization'] = 'Bearer {}'.format(token)
-            self._headers['Content-Type'] = 'application/yaml'
-            self._headers['accept'] = 'application/json'
-            _url = "{0}/vnfpkgm/v1/vnf_packages_content".format(self._base_path)
-            return self._send_get(_url, headers=self._headers)
-        return None
-
-    def vnfd_get(self, id):
-        token = self.get_token()
-        if token:
-            self._headers['Authorization'] = 'Bearer {}'.format(token)
-            self._headers['Content-Type'] = 'application/yaml'
-            #self._headers['accept'] = 'application/yaml'
-            _url = "{0}/vnfpkgm/v1/vnf_packages/{1}/vnfd".format(self._base_path, id)
-            return yaml.load(self._send_get(_url, headers=self._headers))
-        return None
-
-    def vnfd_delete(self, id):
-        token = self.get_token()
-        if token:
-            self._headers['Authorization'] = 'Bearer {}'.format(token)
-            self._headers['Content-Type'] = 'application/yaml'
-            self._headers['accept'] = 'application/json'
-            _url = "{0}/vnfpkgm/v1/vnf_packages_content/{1}".format(self._base_path, id)
-            return self._send_delete(_url, headers=self._headers)
-        return None
-
-    def vnfd_update(self, id, data):
-        token = self.get_token()
-        headers = {}
-        if token:
-            # get the package onboarded
-            tar_pkg = self.get_vnfd_pkg(id)
-            tarf = tarfile.open(fileobj=tar_pkg)
-
-            tarf = self._descriptor_update(tarf, data)
-            headers['Authorization'] = 'Bearer {}'.format(token)
-            headers['Content-Type'] = 'application/gzip'
-            headers['accept'] = 'application/json'
-            headers['Content-File-MD5'] = self.md5(open('/tmp/' + tarf.getnames()[0] + ".tar.gz", 'rb'))
-            # headers['Content-File-MD5'] = self.md5(open("pippo.tar.gz", 'rb'))
-
-            _url = "{0}/vnfpkgm/v1/vnf_packages/{1}/package_content".format(self._base_path, id)
-            return self._send_put(_url, headers=headers, data=open('/tmp/' + tarf.getnames()[0] + ".tar.gz", 'rb'))
-            # return self._send_put(_url, headers=headers, data=open("pippo.tar.gz", 'rb'))
-
-        return None
-
-    def vnfd_onboard(self, package):
-        token = self.get_token()
-        headers = {}
-        if token:
-            headers['Authorization'] = 'Bearer {}'.format(token)
-            headers['Content-Type'] = 'application/gzip'
-            headers['accept'] = 'application/json'
-            with open('/tmp/'+package.name, 'wb+') as destination:
-                for chunk in package.chunks():
-                    destination.write(chunk)
-            headers['Content-File-MD5'] = self.md5(open('/tmp/'+package.name, 'rb'))
-            _url = "{0}/vnfpkgm/v1/vnf_packages_content".format(self._base_path)
-            return self._send_post(_url, headers=headers,
-                                   data=open('/tmp/' + package.name, 'rb'))
-        return None
-
-    def vnf_packages_artifacts(self, id):
-        token = self.get_token()
-        if token:
-            self._headers['Authorization'] = 'Bearer {}'.format(token)
-            self._headers['Content-Type'] = 'application/yaml'
-            _url = "{0}/vnfpkgm/v1/vnf_packages/{1}/artifacts".format(self._base_path, id)
-            return self._send_get(_url, headers=self._headers)
-        return None
-
-    def vnf_list(self):
-        token = self.get_token()
-        if token:
-            self._headers['Authorization'] = 'Bearer {}'.format(token)
-            self._headers['Content-Type'] = 'application/yaml'
-            self._headers['accept'] = 'application/json'
-            _url = "{0}/nslcm/v1/vnfrs".format(self._base_path)
-            return self._send_get(_url, headers=self._headers)
-        return None
-
-    def vnf_get(self, id):
-        token = self.get_token()
-        if token:
-            self._headers['Authorization'] = 'Bearer {}'.format(token)
-            self._headers['Content-Type'] = 'application/json'
-            self._headers['accept'] = 'application/json'
-            _url = "{0}/nslcm/v1/vnfrs/{1}".format(self._base_path, id)
-            return self._send_get(_url, headers=self._headers)
-        return None
-
-    def _upload_package(self, filename, package):
-        token = self.get_token()
-        headers = {}
-        if token:
-            headers['Authorization'] = 'Bearer {}'.format(token)
-            headers['Content-Type'] = 'application/gzip'
-            headers['Content-File-MD5'] = self.md5(package)
-            headers['accept'] = 'application/json'
-        return None
-
-    def _send_post(self, url, data=None, json=None, **kwargs):
-        try:
-            r = requests.post(url, data=data, json=json, verify=False, **kwargs)
-            #print r.text
-        except Exception as e:
-            log.exception(e)
-            #print "Exception during send POST"
-            return {'error': 'error during connection to agent'}
-        if 'accept' in kwargs['headers']:
-            accept = kwargs['headers']['accept']
-            if accept == 'application/json':
-                #print "json"
-                return Util.json_loads_byteified(r.text)
-        return r
-
-    def _send_put(self, url, data=None, json=None, **kwargs):
-        try:
-            r = requests.put(url, data=data, json=json, verify=False, **kwargs)
-            print r.text
-        except Exception as e:
-            log.exception(e)
-            #print "Exception during send PUT"
-            return {'error': 'error during connection to agent'}
-
-        return r.json
-
-    def _send_get(self, url, params=None, **kwargs):
-        try:
-            r = requests.get(url, params=None, verify=False, stream=True, **kwargs)
-            #print r.headers
-        except Exception as e:
-            log.exception(e)
-            #print "Exception during send GET"
-            return {'error': 'error during connection to agent'}
-        if 'accept' in kwargs['headers']:
-            accept = kwargs['headers']['accept']
-            if accept == 'application/json':
-                #print "json"
-                return Util.json_loads_byteified(r.text)
-            elif accept == 'application/zip':
-                tarf =StringIO.StringIO(r.content)
-                #tarf = tarfile.open(fileobj=StringIO.StringIO(r.content))
-                # for tarinfo in tarf:
-                #     #print(tarinfo.name, "is", tarinfo.size, "bytes in size and is")
-                #     if tarinfo.isreg():
-                #         #print("a regular file.")
-                #     elif tarinfo.isdir():
-                #         #print("a directory.")
-                #     else:
-                #         #print("something else.")
-                return tarf
-            else:
-                return r.text
-        else:
-            return r.text
-
-    def _send_delete(self, url, params=None, **kwargs):
-        try:
-            r = requests.delete(url, params=None, verify=False, **kwargs)
-            len(r.content)
-            print r.text
-        except Exception as e:
-            log.exception(e)
-            print "Exception during send DELETE"
-            return {'error': 'error during connection to agent'}
-        return r.json
-
-    def md5(self, f):
-        hash_md5 = hashlib.md5()
-        for chunk in iter(lambda: f.read(1024), b""):
-            hash_md5.update(chunk)
-        return hash_md5.hexdigest()
-
-    def get_nsd_pkg(self, id):
-        token = self.get_token()
-        if token:
-            self._headers['Authorization'] = 'Bearer {}'.format(token)
-            #self._headers['Content-Type'] = 'application/yaml'
-            self._headers['accept'] = 'application/zip'
-            _url = "{0}/nsd/v1/ns_descriptors/{1}/nsd_content".format(self._base_path, id)
-            return self._send_get(_url, headers=self._headers)
-        return None
-
-    def get_vnfd_pkg(self, id):
-        token = self.get_token()
-        if token:
-            self._headers['Authorization'] = 'Bearer {}'.format(token)
-            #self._headers['Content-Type'] = 'application/yaml'
-            self._headers['accept'] = 'application/zip'
-            _url = "{0}/vnfpkgm/v1/vnf_packages/{1}/package_content".format(self._base_path, id)
-            return self._send_get(_url, headers=self._headers)
-        return None
-
-
-
-if __name__ == '__main__':
-
-
-    client = Client()
-    package = client.get_nsd_pkg('be489dfb-5f15-48c1-b693-67d830c591e5')
-    tarf = tarfile.open(fileobj=package)
-    tarf.extractall('/tmp')
-    yaml_object = yaml.safe_dump({}, default_flow_style=False)
-    yaml_file = open('/tmp/cirros_2vnf_ns/cirros_2vnf_nsd.yaml', 'w')
-    yaml_object = pyaml.dump(yaml_object, yaml_file, safe=True)
-    tarf_temp = tarfile.open(tarf.getnames()[0]+".tar.gz", "w:gz")
-
-    for tarinfo in tarf:
-        tarf_temp.add('/tmp/'+tarinfo.name, tarinfo.name)
-    tarf_temp.close()
-
-
-
index 79092b7..6307198 100644 (file)
@@ -37,7 +37,7 @@ class Client(object):
         self._user_endpoint = 'admin/v1/users'
         self._host = os.getenv('OSM_SERVER', "localhost")
         self._so_port = 9999
-        self._base_path = "https://{0}:{1}/osm".format(self._host, self._so_port)
+        self._base_path = 'https://{0}:{1}/osm'.format(self._host, self._so_port)
 
     def auth(self, args):
         result = {'error': True, 'data': ''}
@@ -251,12 +251,14 @@ class Client(object):
             result['data'] = Util.json_loads_byteified(r.text)
         return result
 
-    def nsd_list(self, token):
+    def nsd_list(self, token, filter=None):
         result = {'error': True, 'data': ''}
         headers = {"Content-Type": "application/yaml", "accept": "application/json",
                    'Authorization': 'Bearer {}'.format(token['id'])}
-
-        _url = "{0}/nsd/v1/ns_descriptors_content".format(self._base_path)
+        query_path = ''
+        if filter:
+            query_path = '?_admin.type='+filter
+        _url = "{0}/nsd/v1/ns_descriptors_content{1}".format(self._base_path, query_path)
         try:
             r = requests.get(_url, params=None, verify=False, stream=True, headers=headers)
         except Exception as e:
@@ -269,12 +271,14 @@ class Client(object):
 
         return result
 
-    def vnfd_list(self, token):
+    def vnfd_list(self, token, filter=None):
         result = {'error': True, 'data': ''}
         headers = {"Content-Type": "application/yaml", "accept": "application/json",
                    'Authorization': 'Bearer {}'.format(token['id'])}
-
-        _url = "{0}/vnfpkgm/v1/vnf_packages_content".format(self._base_path)
+        query_path = ''
+        if filter:
+            query_path = '?_admin.type='+filter
+        _url = "{0}/vnfpkgm/v1/vnf_packages_content{1}".format(self._base_path, query_path)
         try:
             r = requests.get(_url, params=None, verify=False, stream=True, headers=headers)
         except Exception as e:
diff --git a/packagehandler/__init__.py b/packagehandler/__init__.py
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/packagehandler/apps.py b/packagehandler/apps.py
new file mode 100644 (file)
index 0000000..c795813
--- /dev/null
@@ -0,0 +1,21 @@
+#   Copyright 2018 EveryUP Srl
+#
+#   Licensed under the Apache License, Version 2.0 (the "License");
+#   you may not use this file except in compliance with the License.
+#   You may obtain a copy of the License at
+#
+#       http://www.apache.org/licenses/LICENSE-2.0
+#
+#   Unless required by applicable law or agreed to in writing, software
+#   distributed under the License is distributed on an  BASIS,
+#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#   See the License for the specific language governing permissions and
+#   limitations under the License.
+
+from __future__ import unicode_literals
+
+from django.apps import AppConfig
+
+
+class PackagehandlerConfig(AppConfig):
+    name = 'packagehandler'
diff --git a/packagehandler/migrations/__init__.py b/packagehandler/migrations/__init__.py
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/packagehandler/template/package_list.html b/packagehandler/template/package_list.html
new file mode 100644 (file)
index 0000000..9aebd12
--- /dev/null
@@ -0,0 +1,284 @@
+{% extends "project_descriptors.html" %}
+{% load staticfiles %}
+
+
+{% block head_block %}
+       {{ block.super }}
+<link rel="stylesheet" href="/static/bower_components/select2/dist/css/select2.min.css">
+{% endblock %}
+
+{% block title_header_big %}
+    {{ block.super }}
+  {% if package_type  %}
+     {{ package_type|upper }}
+  {% else%}
+    Undefined
+  {% endif %} Packages
+{% endblock %}
+
+{% block left_sidebar %}
+    {% include 'osm/osm_project_left_sidebar.html' %}
+{% endblock %}
+
+{% block breadcrumb_body %}
+       {{ block.super }}
+    <li><a href="{% url 'projects:open_project' %}">{{project_id}}</a></li>
+    <li><a> {% if package_type  %}
+     {{ package_type }}
+  {% else%}
+    Undefined
+  {% endif %} Packages</a></li>
+
+{% endblock %}
+
+{% block content_body %}
+       {{ block.super }}
+{% include 'osm/modal/files_list.html' %}
+{% include 'modal/instance_create.html' %}
+{% include 'modal/choose_package_name.html' %}
+<div class="row">
+    {% if package_type == 'ns' %}
+        {% include "package_list_ns.html" %}
+    {% elif package_type == 'vnf' %}
+        {% include "package_list_vnf.html" %}
+    {% endif %}
+    
+</div>
+{% endblock %}
+
+
+{% block resource_block %}
+       {{ block.super }}
+     <script src="/static/bower_components/select2/dist/js/select2.js"></script>
+    <script src="/static/src/instancehandler/instance_create.js"></script>
+    <script src="/static/src/packagehandler/packages_list.js"></script>
+    <script src="/static/src/packagehandler/onboard_package.js"></script>
+
+    <script>
+    var csrf_token = '{{csrf_token}}';
+    var descr_list_url = '{% url "packages:list_packages"   package_type=package_type%}';
+    var new_desc_url = '{% url "packages:onboard_package"   package_type=package_type%}'
+    var vim_list_url = '{% url "vims:list"  %}';
+    var package_type = '{{ package_type | safe }}';
+    var project_id = '{{ project_id }}';
+    var table;
+    var row_builder = {
+        'ns': [
+                {
+                    "render": function (data, type, row) {
+                       return row['short-name'] || '';
+                    },
+                    "targets": 0
+                },
+                {
+                    "render": function (data, type, row) {
+                       return row['_id'];
+                    },
+                    "targets": 1
+                },
+                {
+                    "render": function (data, type, row) {
+                       return row['description'] || '';
+                    },
+                    "targets": 2
+                },
+                {
+                    "render": function (data, type, row) {
+                       return row['vendor'] || '';
+                    },
+                    "targets": 3
+                },
+                {
+                    "render": function (data, type, row) {
+                       return row['version'] || '';
+                    },
+                    "targets": 4
+                },
+                {
+                    "render": function (data, type, row) {
+                       var result = '<div class="btn-group">\n' ;
+                       
+                           result += '    <button type="button" class="btn btn-default" data-container="body"\n' +
+                               'data-toggle="tooltip" data-placement="top" title="Instantiate NS"\n' +
+                               'onclick="javascript:openModalCreateNS({ \'project_id\':\'' + project_id +'\', \'package_type\': \''+ package_type +'\', \'descriptor_name\':\''+row["name"]+'\', \'descriptor_id\':\''+row["_id"]+'\',\'vim_list_url\': \''+vim_list_url+'\',  \'nsd_list_url\': \''+descr_list_url+'\' })">\n' +
+                               '<i class="fa fa-paper-plane"></i></button>\n';
+                        result += '<button type="button" class="btn btn-default" data-container="body"\n' +
+                           '        data-toggle="tooltip" data-placement="top" title="Edit"\n' +
+                           '        onclick="javascript:openDescriptorView(\'nsd\', \''+row["_id"]+'\')">\n' +
+                           '    <i class="fa fa-edit"></i></button>\n' +
+                           '<button type="button" class="btn btn-default" data-container="body"\n' +
+                           '        data-toggle="tooltip" data-placement="top" title="Show content"\n' +
+                           '        onclick="javascript:openPackageContentList(\''+ package_type +'\', \''+row["_id"]+'\')">\n' +
+                           '    <i class="fa fa-folder-open"></i></button>\n' +
+                            '<button type="button" class="btn btn-default" data-container="body"\n' +
+                           '        data-toggle="tooltip" data-placement="top" title="Clone"\n' +
+                           '        onclick="javascript:clonePackage(\''+ package_type +'\', \''+row["_id"]+'\')">\n' +
+                           '    <i class="fa fa-clone"></i></button>\n';
+                           result += '<button type="button" class="btn btn-default" data-container="body"\n' +
+                           '        data-toggle="tooltip" data-placement="top" title="Show Graph"\n' +
+                           '  onclick="location.href=\'/projects/descriptors/composer?type=nsd&id='+row["_id"] +'\'"\n' +
+                           '        ><i class="fa fa-sitemap fa-fw"></i></button>\n';
+                        result +=
+                           '<button type="button" class="btn btn-default" data-container="body"\n' +
+                           '        data-toggle="tooltip" data-placement="top" title="Download package"\n' +
+                           '        onclick="location.href=\'/packages/'+package_type+'/'+ row["_id"] +'/download\'">\n' +
+                           '    <i class="fa fa-download fa-fw"></i></button>\n' +
+                           '<button type="button" class="btn btn-default" data-container="body"\n' +
+                           '        data-toggle="tooltip" data-placement="top" title="Delete"\n' +
+                           '        onclick="javascript:deletePackage( \'' + package_type + '\', \''+row["_id"] + '\', \''+row["name"] + '\')">\n' +
+                           '    <i class="far fa-trash-alt"></i></button>\n' +
+                           '</div>';
+
+                               return result
+                    },
+                    "targets": 5
+                }],
+        'vnf': [
+                {
+                    "render": function (data, type, row) {
+                       return row['short-name'] || '';
+                    },
+                    "targets": 0
+                },
+                {
+                    "render": function (data, type, row) {
+                       return row['_id'];
+                    },
+                    "targets": 1
+                },
+                {
+                    "render": function (data, type, row) {
+                       return row['_admin']['type'] || '';
+                    },
+                    "targets": 2
+                },
+                {
+                    "render": function (data, type, row) {
+                       return row['description'] || '';
+                    },
+                    "targets": 3
+                },
+                {
+                    "render": function (data, type, row) {
+                       return row['vendor'] || '';
+                    },
+                    "targets": 4
+                },
+                {
+                    "render": function (data, type, row) {
+                       return row['version'] || '';
+                    },
+                    "targets": 5
+                },
+                {
+                    "render": function (data, type, row) {
+                       var result = '<div class="btn-group">\n' ;
+                        result += '<button type="button" class="btn btn-default" data-container="body"\n' +
+                           '        data-toggle="tooltip" data-placement="top" title="Edit"\n' +
+                           '        onclick="javascript:openDescriptorView(\'vnfd\', \''+row["_id"]+'\')">\n' +
+                           '    <i class="fa fa-edit"></i></button>\n' +
+                           '<button type="button" class="btn btn-default" data-container="body"\n' +
+                           '        data-toggle="tooltip" data-placement="top" title="Show content"\n' +
+                           '        onclick="javascript:openPackageContentList(\''+ package_type +'\', \''+row["_id"]+'\')">\n' +
+                           '    <i class="fa fa-folder-open"></i></button>\n' +
+                            '<button type="button" class="btn btn-default" data-container="body"\n' +
+                           '        data-toggle="tooltip" data-placement="top" title="Clone"\n' +
+                           '        onclick="javascript:clonePackage(\''+ package_type +'\', \''+row["_id"]+'\')">\n' +
+                           '    <i class="fa fa-clone"></i></button>\n';
+                           result += '<button type="button" class="btn btn-default" data-container="body"\n' +
+                           '        data-toggle="tooltip" data-placement="top" title="Show Graph"\n' +
+                           '  onclick="location.href=\'/projects/descriptors/composer?type=vnfd&id='+row["_id"] +'\'"\n' +
+                           '        ><i class="fa fa-sitemap fa-fw"></i></button>\n';
+                        result +=
+                           '<button type="button" class="btn btn-default" data-container="body"\n' +
+                           '        data-toggle="tooltip" data-placement="top" title="Download package"\n' +
+                           '        onclick="location.href=\'/packages/'+package_type+'/'+ row["_id"] +'/download\'">\n' +
+                           '    <i class="fa fa-download fa-fw"></i></button>\n' +
+                           '<button type="button" class="btn btn-default" data-container="body"\n' +
+                           '        data-toggle="tooltip" data-placement="top" title="Delete"\n' +
+                           '        onclick="javascript:deletePackage( \'' + package_type + '\', \''+row["_id"] + '\', \''+row["name"] + '\')">\n' +
+                           '    <i class="far fa-trash-alt"></i></button>\n' +
+                           '</div>';
+
+                               return result
+                    },
+                    "targets": 6
+                }]
+    };
+    function refreshTable() {
+        var type_vnf = $('#type_vnf').val()
+        var url = (type_vnf && type_vnf !== '') ? ("/packages/" +package_type+"/list?type="+type_vnf) : ("/packages/" +package_type+"/list")
+        table.ajax.url(url);
+        table.ajax.reload();
+    }
+
+    $(document).ready( function () {
+        table = $('#descriptors_table').DataTable({
+            responsive: true,
+            "ajax": {
+                "url": "/packages/" +package_type+"/list",
+                "dataSrc": function (json) {
+                    return json['descriptors'];
+                },
+                statusCode: {
+                    401: function () {
+                        console.log("no auth");
+                        moveToLogin(window.location.pathname);
+                    }
+                },
+                "error": function (hxr, error, thrown) {
+
+                }
+
+            },
+            "columns": row_builder[package_type]
+
+        });
+
+        setInterval(refreshTable, 10000);
+
+
+        $("#formCreatePackage").submit(function (event) {
+                event.preventDefault(); //prevent default action
+                var post_url = $(this).attr("action"); //get form action url
+                var request_method = $(this).attr("method");
+                var form_data = new FormData(this); //Encode form elements for submission
+
+                $.ajax({
+                    url: post_url,
+                    type: request_method,
+                    data: form_data,
+                    headers: {
+                        "Accept": 'application/json'
+                    },
+                    contentType: false,
+                    processData: false
+                }).done(function (response, textStatus, jqXHR) {
+                    var map = {
+                        ns: 'nsd',
+                        vnf: 'vnfd'
+                    };
+                    location.href='/projects/descriptors/composer?type=' + map[response['data']['type']]+'&id=' + response['data']['id'];
+                }).fail(function (result) {
+                    var data = result.responseJSON;
+                    var title = "Error " + (data.code ? data.code : 'unknown');
+                    var message = data.detail ? data.detail : 'No detail available.';
+                    bootbox.alert({
+                        title: title,
+                        message: message
+                    });
+                });
+            });
+    });
+
+    $(document).on('change', '#type_vnf', function(){
+        refreshTable();
+    });
+    </script>
+
+
+{% endblock %}
+
+{% block footer %}
+    {% include "footer.html"  %}
+{% endblock %}
diff --git a/packagehandler/template/package_list_ns.html b/packagehandler/template/package_list_ns.html
new file mode 100644 (file)
index 0000000..3fae096
--- /dev/null
@@ -0,0 +1,48 @@
+{% load staticfiles %}
+{% load get %}
+<div class="col-md-12">
+
+    <div class="box">
+        <div class="box-header with-border">
+            <h3 class="box-title">
+            </h3>
+            <div class="box-tools">
+                <div class="btn-group">
+                    <button type="button" class="btn btn-default" data-toggle="modal" data-target="#modal_new_package_name_chooser" >
+                <i class="fa fa-paint-brush"></i> <span> Compose a new {{ package_type|upper }}</span></button>
+                </div>
+            </div>
+        </div>
+        <div class="box-body">
+            <table id="descriptors_table" class="table table-bordered table-striped dataTable"
+                   role="grid">
+                <thead>
+                <tr role="row">
+                    <th>Short Name</th>
+                    <th>Identified</th>
+                    <th>Description</th>
+                    <th style="width:10%">Vendor</th>
+                    <th style="width:5%">Version</th>
+                    <th style="width:35%">Actions</th>
+                </tr>
+                </thead>
+                <tbody>
+
+                </tbody>
+
+            </table>
+        </div>
+    </div>
+</div>
+
+<div class="col-sm-12">
+    <div class="box box-solid">
+        <div class="box-body">
+
+            <div class="upload-drop-zone" id="drop-zone">
+               <i class="fa fa-upload"></i> Just drag and drop files here
+            </div>
+        </div>
+    </div>
+</div>
+
diff --git a/packagehandler/template/package_list_vnf.html b/packagehandler/template/package_list_vnf.html
new file mode 100644 (file)
index 0000000..ead7d94
--- /dev/null
@@ -0,0 +1,56 @@
+{% load staticfiles %}
+{% load get %}
+<div class="col-md-12">
+
+    <div class="box">
+        <div class="box-header with-border">
+            <h3 class="box-title">
+            </h3>
+            <div class="box-tools">
+                <div class="btn-group">
+                    <button type="button" class="btn btn-default" data-toggle="modal" data-target="#modal_new_package_name_chooser" >
+                <i class="fa fa-paint-brush"></i> <span> Compose a new {{ package_type|upper }}</span></button>
+                </div>
+            </div>
+        </div>
+        <div class="box-body">
+            <table id="descriptors_table" class="table table-bordered table-striped dataTable"
+                   role="grid">
+                <thead>
+                <tr role="row">
+                    <th>Short Name</th>
+                    <th>Identified</th>
+                    <th>
+                        <select name="type" id="type_vnf" class="form-control">
+                        <option value="">Type</option>
+                        <option value="vnfd">VNF</option>
+                        <option value="pnfd">PNF</option>
+                        <option value="hnfd">HNF</option>
+                        </select>
+                    </th>
+                    <th>Description</th>
+                    <th style="width:10%">Vendor</th>
+                    <th style="width:5%">Version</th>
+                    <th style="width:35%">Actions</th>
+                </tr>
+                </thead>
+                <tbody>
+
+                </tbody>
+
+            </table>
+        </div>
+    </div>
+</div>
+
+<div class="col-sm-12">
+    <div class="box box-solid">
+        <div class="box-body">
+
+            <div class="upload-drop-zone" id="drop-zone">
+               <i class="fa fa-upload"></i> Just drag and drop files here
+            </div>
+        </div>
+    </div>
+</div>
+
diff --git a/packagehandler/urls.py b/packagehandler/urls.py
new file mode 100644 (file)
index 0000000..2a0c513
--- /dev/null
@@ -0,0 +1,27 @@
+#   Copyright 2018 EveryUP Srl
+#
+#   Licensed under the Apache License, Version 2.0 (the "License");
+#   you may not use this file except in compliance with the License.
+#   You may obtain a copy of the License at
+#
+#       http://www.apache.org/licenses/LICENSE-2.0
+#
+#   Unless required by applicable law or agreed to in writing, software
+#   distributed under the License is distributed on an  BASIS,
+#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#   See the License for the specific language governing permissions and
+#   limitations under the License.
+
+from django.conf.urls import url
+from packagehandler import views
+
+urlpatterns = [
+    url(r'(?P<package_type>\w+)/list$', views.show_packages, name='list_packages'),
+    url(r'(?P<package_type>\w+)/create', views.create_package_empty, name='create_package_empty'),
+    url(r'(?P<package_type>\w+)/(?P<package_id>[-\w]+)/delete$', views.delete_package, name='delete_package'),
+    url(r'(?P<package_type>\w+)/(?P<package_id>[-\w]+)/clone', views.clone_package, name='clone_package'),
+    url(r'(?P<package_type>\w+)/(?P<package_id>[-\w]+)/download', views.download_pkg, name='download_package'),
+    url(r'(?P<package_type>\w+)/(?P<package_id>[-\w]+)/action/(?P<action_name>[-\w]+)', views.custom_action,
+        name='custom_action'),
+    url(r'(?P<package_type>\w+)/new$', views.onboard_package, name='onboard_package'),
+]
\ No newline at end of file
diff --git a/packagehandler/views.py b/packagehandler/views.py
new file mode 100644 (file)
index 0000000..9783348
--- /dev/null
@@ -0,0 +1,217 @@
+#   Copyright 2018 EveryUP Srl
+#
+#   Licensed under the Apache License, Version 2.0 (the "License");
+#   you may not use this file except in compliance with the License.
+#   You may obtain a copy of the License at
+#
+#       http://www.apache.org/licenses/LICENSE-2.0
+#
+#   Unless required by applicable law or agreed to in writing, software
+#   distributed under the License is distributed on an  BASIS,
+#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#   See the License for the specific language governing permissions and
+#   limitations under the License.
+
+import json
+import logging
+
+import yaml
+from sf_t3d.decorators import login_required
+from django.http import HttpResponse
+from django.shortcuts import render, redirect
+
+
+from lib.util import Util
+from lib.osm.osmclient.clientv2 import Client
+from lib.osm.osm_rdcl_parser import OsmParser
+from lib.osm.osm_util import OsmUtil
+import authosm.utils as osmutils
+
+logging.basicConfig(level=logging.DEBUG)
+log = logging.getLogger('packagehandler/view.py')
+
+
+@login_required
+def show_packages(request, package_type=None):
+    user = osmutils.get_user(request)
+    project_id = user.project_id
+    client = Client()
+    filter = request.GET.get('type')
+    try:
+        if package_type == 'ns':
+            descriptors = client.nsd_list(user.get_token(),filter)
+        elif package_type == 'vnf':
+            descriptors = client.vnfd_list(user.get_token(),filter)
+    except Exception as e:
+        log.exception(e)
+        descriptors = []
+
+    url = 'package_list.html'
+    return __response_handler(request, {
+        'descriptors': descriptors['data'] if descriptors and descriptors['error'] is False else [],
+        'project_id': project_id,
+        'project_type': 'osm',
+        'package_type': package_type
+    }, url)
+
+@login_required
+def create_package_empty(request, package_type=None):
+    user = osmutils.get_user(request)
+    pkg_name = request.POST.get('name', '')
+    try:
+        client = Client()
+        if package_type == 'ns':
+            result = client.nsd_create_pkg_base(user.get_token(), pkg_name)
+        elif package_type == 'vnf':
+            result = client.vnfd_create_pkg_base(user.get_token(), pkg_name)
+        else:
+            log.debug('Update descriptor: Unknown data type')
+            result = {'error': True, 'data': 'Update descriptor: Unknown data type'}
+    except Exception as e:
+        log.exception(e)
+        result = {'error': True, 'data': str(e)}
+
+    if result['error'] == True:
+        return __response_handler(request, result['data'], url=None,
+                                  status=result['data']['status'] if 'status' in result['data'] else 500)
+    else:
+        result['data']['type'] = package_type
+        return __response_handler(request, result, url=None, status=200)
+
+
+@login_required
+def delete_package(request, package_type=None, package_id=None):
+    user = osmutils.get_user(request)
+    project_id = user.project_id
+    try:
+        client = Client()
+        if package_type == 'ns':
+            result = client.nsd_delete(user.get_token(), package_id)
+        elif package_type == 'vnf':
+            result = client.vnfd_delete(user.get_token(), package_id)
+    except Exception as e:
+        log.exception(e)
+        result = {'error': True, 'data': str(e)}
+
+    url = 'package_list.html'
+    descriptors = {}
+    try:
+        if package_type == 'ns':
+            descriptors = client.nsd_list(user.get_token())
+        elif package_type == 'vnf':
+            descriptors = client.vnfd_list(user.get_token())
+    except Exception as e:
+        log.exception(e)
+
+    return __response_handler(request, {
+        'descriptors': descriptors['data'] if descriptors and descriptors['error'] is False else [],
+        'project_id': project_id,
+        'project_type': 'osm',
+        'package_type': package_type,
+        'alert_message': {
+            'success': False if result['error'] is True else True,
+            'message': 'An error occurred while processing your request.' if result and result['error'] is True else "Record deleted successfully"}
+    }, url)
+
+@login_required
+def clone_package(request, package_type=None, package_id=None):
+    user = osmutils.get_user(request)
+    try:
+        client = Client()
+        if package_type == 'ns':
+            result = client.nsd_clone(user.get_token(), package_id)
+        elif package_type == 'vnf':
+            result = client.vnfd_clone(user.get_token(), package_id)
+        else:
+            log.debug('Update descriptor: Unknown data type')
+            result = {'error': True, 'data': 'Update descriptor: Unknown data type'}
+    except Exception as e:
+        log.exception(e)
+        result = {'error': True, 'data': str(e)}
+    if result['error'] == True:
+        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 download_pkg(request, package_id, package_type):
+    user = osmutils.get_user(request)
+    file_name = "osm_export.tar.gz"
+    tar_pkg = None
+    try:
+        client = Client()
+        if package_type == 'ns':
+            tar_pkg = client.get_nsd_pkg(user.get_token(), package_id)
+        elif package_type == 'vnf':
+            tar_pkg = client.get_vnfd_pkg(user.get_token(), package_id)
+
+    except Exception as e:
+        log.exception(e)
+    
+    response = HttpResponse(content_type="application/tgz")
+    response["Content-Disposition"] = "attachment; filename="+ file_name
+    response.write(tar_pkg.getvalue())
+    return response
+
+@login_required
+def onboard_package(request, package_type=None):
+    user = osmutils.get_user(request)
+    if request.method == 'POST':
+        data_type = request.POST.get('type')
+        if data_type == "file":
+            file_uploaded = request.FILES['file']
+
+            try:
+                client = Client()
+                if package_type == 'ns':
+                    result = client.nsd_onboard(user.get_token(), file_uploaded)
+                elif package_type == 'vnf':
+                    result = client.vnfd_onboard(user.get_token(), file_uploaded)
+                else:
+                    log.debug('Create descriptor: Unknown data type')
+                    result = {'error': True, 'data': 'Create descriptor: Unknown data type'}
+
+            except Exception as e:
+                log.exception(e)
+                result = {'error': True, 'data': str(e)}
+        else:
+            result = {'error': True, 'data': 'Create descriptor: Unknown data type'}
+
+        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 get_package_files_list(request, package_id, package_type):
+    user = osmutils.get_user(request)
+    try:
+        client = Client()
+        if package_type == 'ns':
+            artifacts_res = client.nsd_artifacts(user.get_token(), package_id)
+        elif package_type == 'vnf':
+            artifacts_res = client.vnf_packages_artifacts(user.get_token(), package_id)
+        else:
+            return False
+
+        files_list = yaml.load(artifacts_res['data'] if artifacts_res and artifacts_res['error'] is False else [])
+        result = {'files': files_list}
+    except Exception as e:
+        log.exception(e)
+        result = {'error_msg': 'Unknown error.'}
+    return __response_handler(request, result)
+
+@login_required
+def custom_action(request, package_id=None, package_type=None, action_name=None):
+    if request.method == 'GET':
+        return globals()[action_name](request, package_id, package_type)
+
+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", *args, **kwargs)
+    elif to_redirect:
+        return redirect(url, *args, **kwargs)
+    else:
+        return render(request, url, data_res)
\ No newline at end of file
diff --git a/projecthandler/template/project/osm/osm_project_descriptors.html b/projecthandler/template/project/osm/osm_project_descriptors.html
deleted file mode 100644 (file)
index bf40773..0000000
+++ /dev/null
@@ -1,202 +0,0 @@
-{% extends "project_descriptors.html" %}
-{% load staticfiles %}
-
-
-{% block head_block %}
-       {{ block.super }}
-<link rel="stylesheet" href="/static/bower_components/select2/dist/css/select2.min.css">
-{% endblock %}
-
-{% block title_header_big %}
-    {{ block.super }}
-  {% if descriptor_type  %}
-     {{ descriptor_type|upper }}
-  {% else%}
-    Undefined
-  {% endif %} Packages
-{% endblock %}
-
-{% block left_sidebar %}
-    {% include 'osm/osm_project_left_sidebar.html' %}
-{% endblock %}
-
-{% block breadcrumb_body %}
-       {{ block.super }}
-    <li><a href="{% url 'projects:open_project' %}">{{project_id}}</a></li>
-    <li><a> {% if descriptor_type  %}
-     {{ descriptor_type }}
-  {% else%}
-    Undefined
-  {% endif %} Packages</a></li>
-
-{% endblock %}
-
-{% block content_body %}
-       {{ block.super }}
-{% include 'osm/modal/files_list.html' %}
-{% include 'modal/instance_create.html' %}
-{% include 'modal/choose_package_name.html' %}
-<div class="row">
-    {% include "descriptorlist.html" %}
-</div>
-{% endblock %}
-
-
-
-
-{% block resource_block %}
-       {{ block.super }}
-     <script src="/static/bower_components/select2/dist/js/select2.js"></script>
-    <script src="/static/src/instancehandler/instance_create.js"></script>
-    <script src="/static/src/projecthandler/descriptorslist.js"></script>
-    <script src="/static/src/projecthandler/onboard_package.js"></script>
-
-    <script>
-    var csrf_token = '{{csrf_token}}';
-    var descr_list_url = '{% url "projects:descriptors:list_descriptors"   descriptor_type=descriptor_type%}';
-    var vim_list_url = '{% url "vims:list"  %}';
-    var new_desc_url ="{% url 'projects:descriptors:new_descriptor'  descriptor_type=descriptor_type %}";
-    var descriptor_type = '{{ descriptor_type | safe }}';
-    var project_id = '{{ project_id }}';
-    var table;
-
-    function refreshTable() {
-        table.ajax.reload();
-    }
-
-    $(document).ready( function () {
-        table = $('#descriptors_table').DataTable({
-            responsive: true,
-            "ajax": {
-                "url": "/projects/descriptors/" +descriptor_type+"/list",
-                "dataSrc": function (json) {
-                    return json['descriptors'];
-                },
-                statusCode: {
-                    401: function () {
-                        console.log("no auth");
-                        moveToLogin(window.location.pathname);
-                    }
-                },
-                "error": function (hxr, error, thrown) {
-
-                }
-
-            },
-            "columns": [
-                {
-                    "render": function (data, type, row) {
-                       return row['short-name'] || '';
-                    },
-                    "targets": 0
-                },
-                {
-                    "render": function (data, type, row) {
-                       return row['_id'];
-                    },
-                    "targets": 1
-                },
-                {
-                    "render": function (data, type, row) {
-                       return row['description'] || '';
-                    },
-                    "targets": 2
-                },
-                {
-                    "render": function (data, type, row) {
-                       return row['vendor'] || '';
-                    },
-                    "targets": 3
-                },
-                {
-                    "render": function (data, type, row) {
-                       return row['version'] || '';
-                    },
-                    "targets": 4
-                },
-                {
-                    "render": function (data, type, row) {
-                       var result = '<div class="btn-group">\n' ;
-                       if(descriptor_type == "nsd")
-                           result += '    <button type="button" class="btn btn-default" data-container="body"\n' +
-                               'data-toggle="tooltip" data-placement="top" title="Instantiate NS"\n' +
-                               'onclick="javascript:openModalCreateNS({ \'project_id\':\'' + project_id +'\', \'descriptor_type\': \''+ descriptor_type +'\', \'descriptor_name\':\''+row["name"]+'\', \'descriptor_id\':\''+row["_id"]+'\',\'vim_list_url\': \''+vim_list_url+'\',  \'nsd_list_url\': \''+descr_list_url+'\' })">\n' +
-                               '<i class="fa fa-paper-plane"></i></button>\n';
-                        result += '<button type="button" class="btn btn-default" data-container="body"\n' +
-                           '        data-toggle="tooltip" data-placement="top" title="Edit"\n' +
-                           '        onclick="javascript:openDescriptorView(\''+descriptor_type+'\', \''+row["_id"]+'\')">\n' +
-                           '    <i class="fa fa-edit"></i></button>\n' +
-                           '<button type="button" class="btn btn-default" data-container="body"\n' +
-                           '        data-toggle="tooltip" data-placement="top" title="Show content"\n' +
-                           '        onclick="javascript:openPackageContentList(\''+ descriptor_type +'\', \''+row["_id"]+'\')">\n' +
-                           '    <i class="fa fa-folder-open"></i></button>\n' +
-                            '<button type="button" class="btn btn-default" data-container="body"\n' +
-                           '        data-toggle="tooltip" data-placement="top" title="Clone"\n' +
-                           '        onclick="javascript:clonePackage(\''+ descriptor_type +'\', \''+row["_id"]+'\')">\n' +
-                           '    <i class="fa fa-clone"></i></button>\n';
-                        //if(descriptor_type == "nsd")
-                           result += '<button type="button" class="btn btn-default" data-container="body"\n' +
-                           '        data-toggle="tooltip" data-placement="top" title="Show Graph"\n' +
-                           '  onclick="location.href=\'/projects/descriptors/composer?type='+descriptor_type+'&id='+row["_id"] +'\'"\n' +
-                           '        ><i class="fa fa-sitemap fa-fw"></i></button>\n';
-                        result +=
-                           '<button type="button" class="btn btn-default" data-container="body"\n' +
-                           '        data-toggle="tooltip" data-placement="top" title="Download package"\n' +
-                           '        onclick="location.href=\'/projects/descriptors/'+descriptor_type+'/'+ row["_id"] +'/action/download_pkg\'">\n' +
-                           '    <i class="fa fa-download fa-fw"></i></button>\n' +
-                           '<button type="button" class="btn btn-default" data-container="body"\n' +
-                           '        data-toggle="tooltip" data-placement="top" title="Delete"\n' +
-                           '        onclick="javascript:deletePackage( \'' + descriptor_type + '\', \''+row["_id"] + '\', \''+row["name"] + '\')">\n' +
-                           '    <i class="far fa-trash-alt"></i></button>\n' +
-                           '</div>';
-
-                               return result
-                    },
-                    "targets": 5
-                }]
-
-
-        });
-
-        setInterval(refreshTable, 10000);
-
-
-        $("#formCreatePackage").submit(function (event) {
-                event.preventDefault(); //prevent default action
-                var post_url = $(this).attr("action"); //get form action url
-                var request_method = $(this).attr("method");
-                var form_data = new FormData(this); //Encode form elements for submission
-
-                $.ajax({
-                    url: post_url,
-                    type: request_method,
-                    data: form_data,
-                    headers: {
-                        "Accept": 'application/json'
-                    },
-                    contentType: false,
-                    processData: false
-                }).done(function (response, textStatus, jqXHR) {
-
-                    location.href='/projects/descriptors/composer?type=' + response['data']['type']+'&id=' + response['data']['id'];
-                }).fail(function (result) {
-                    var data = result.responseJSON;
-                    var title = "Error " + (data.code ? data.code : 'unknown');
-                    var message = data.detail ? data.detail : 'No detail available.';
-                    bootbox.alert({
-                        title: title,
-                        message: message
-                    });
-                });
-            });
-    });
-
-
-    </script>
-
-
-{% endblock %}
-
-{% block footer %}
-    {% include "footer.html"  %}
-{% endblock %}
index d4b7eb5..79eb4c2 100644 (file)
                     <li><a><b>Modified:</b> <span
                         class="pull-right">{{project_overview.updated_date|get_date}}</span></a>
                     </li>
-
                 </ul>
-
             </div>
-
         </div>
     </div>
     <div class="col-md-6">
@@ -44,7 +41,7 @@
                     <div class="inner"><h3>{{ project_overview.nsd }}</h3>
                         <p>NS packages</p></div>
                     <div class="icon"><i class="fa fa-archive"></i></div>
-                    <a href='{% url "projects:descriptors:list_descriptors"   descriptor_type="nsd" %}' class="small-box-footer">Open list <i
+                    <a href='{% url "packages:list_packages"   package_type="ns" %}' class="small-box-footer">Open list <i
                             class="fa fa-arrow-circle-right"></i></a></div>
             </div>
             <div class="col-md-6 ">
@@ -52,7 +49,7 @@
                     <div class="inner"><h3>{{ project_overview.vnfd }}</h3>
                         <p>VNF packages</p></div>
                     <div class="icon"><i class="fa fa-archive"></i></div>
-                    <a href='{% url "projects:descriptors:list_descriptors"   descriptor_type="vnfd" %}' class="small-box-footer">Open list <i
+                    <a href='{% url "packages:list_packages"   package_type="vnf" %}' class="small-box-footer">Open list <i
                             class="fa fa-arrow-circle-right"></i></a></div>
             </div>
         </div>
@@ -74,9 +71,7 @@
                     <a href='{% url "instances:list"  type="vnf"  %}' class="small-box-footer">Open list <i
                             class="fa fa-arrow-circle-right"></i></a></div>
             </div>
-
         </div>
-
     </div>
 </div>
 
index 63f9854..85bedfe 100644 (file)
@@ -14,8 +14,8 @@
                     <i class="fa fa-file-text fa-fw"></i> <span>Overview</span>
                 </a>
             </li>
-            {% url "projects:descriptors:list_descriptors"   descriptor_type="nsd" as  nsd_list_url %}
-            {% url "projects:descriptors:list_descriptors"   descriptor_type='vnfd' as  vnfd_list_url %}
+            {% url "packages:list_packages"   package_type="ns" as  nsd_list_url %}
+            {% url "packages:list_packages"   package_type='vnf' as  vnfd_list_url %}
             <li {% if request.get_full_path == nsd_list_url or  request.get_full_path == vnfd_list_url %}
                 class="active treeview menu-open" {% else %} class="treeview  menu-open" {% endif %} >
                 <a href="#">
index 3759fcd..e427313 100644 (file)
@@ -48,7 +48,6 @@
 
     <script src="/static/bower_components/datatables.net/js/jquery.dataTables.min.js"></script>
     <script src="/static/bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js"></script>
-    <script src="/static/src/projecthandler/descriptorslist.js"></script>
 
 {% endblock %}
 
index 2b22ac1..aae8b5e 100644 (file)
@@ -53,6 +53,7 @@ INSTALLED_APPS = [
     'django.contrib.sessions',
     'authosm',
     'projecthandler',
+    'packagehandler',
     'descriptorhandler',
     'vimhandler',
     'instancehandler',
@@ -90,6 +91,7 @@ TEMPLATES = [
             os.path.join(BASE_DIR, 'projecthandler', 'template'),
             os.path.join(BASE_DIR, 'projecthandler', 'template', 'download'),
             os.path.join(BASE_DIR, 'projecthandler', 'template', 'project'),
+            os.path.join(BASE_DIR, 'packagehandler', 'template'),
             os.path.join(BASE_DIR, 'descriptorhandler', 'template'),
             os.path.join(BASE_DIR, 'vimhandler', 'template'),
             os.path.join(BASE_DIR, 'instancehandler', 'template'),
index 5d9d02a..c5b3ae0 100644 (file)
@@ -26,6 +26,7 @@ urlpatterns = [
     url(r'^projects/', include('projecthandler.urls.project', namespace='projects'), name='projects_base'),
     url(r'^sdn/', include('sdnctrlhandler.urls', namespace='sdns'), name='sdns_base'),
     url(r'^vims/', include('vimhandler.urls', namespace='vims'), name='vims_base'),
+    url(r'^packages/', include('packagehandler.urls', namespace='packages'), name='packages_base'),
     url(r'^instances/', include('instancehandler.urls', namespace='instances'), name='instances_base'),
     url(r'^admin/users/', include('userhandler.urls', namespace='users'), name='users_base'),
     url(r'^forbidden', views.forbidden, name='forbidden'),
diff --git a/static/src/packagehandler/onboard_package.js b/static/src/packagehandler/onboard_package.js
new file mode 100644 (file)
index 0000000..d18be5b
--- /dev/null
@@ -0,0 +1,91 @@
+/*
+   Copyright 2018 EveryUP srl
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an  BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+*/
+
+var dropZone = document.getElementById('drop-zone');
+dropZone.ondrop = function (e) {
+    e.preventDefault();
+    this.className = 'upload-drop-zone';
+    create(e.dataTransfer.files, true);
+};
+
+dropZone.ondragover = function () {
+    this.className = 'upload-drop-zone drop';
+    return false;
+};
+
+dropZone.ondragleave = function () {
+    this.className = 'upload-drop-zone';
+    return false;
+};
+
+
+function create(fs, dropzone) {
+    var id = $('.nav-tabs .active').attr('id');
+    if (dropzone) id = 'file_li';
+    var type, text;
+    var data = new FormData();
+    switch (id) {
+
+        case 'file_li':
+            type = 'file';
+
+            var files = dropzone ? fs : document.getElementById('js-upload-files').files;
+            if (!files || !files.length) {
+                files = document.getElementById('drop-zone').files;
+                if (!files || !files.length) {
+                    alert("Select a file");
+                    return
+                }
+            }
+            console.log(files[0])
+            var patt1 = /\.([0-9a-z]+)(?:[\?#]|$)/i;
+            console.log(files[0].name.match(patt1));
+            var extension = files[0].name.substr(files[0].name.lastIndexOf('.') + 1);
+            console.log(extension);
+            if (!(extension == 'gz' )) {
+                alert("The file must be .tar.gz");
+                return
+            }
+
+            data.append('file', files[0]);
+            break;
+    }
+    data.append('csrfmiddlewaretoken', csrf_token);
+    data.append('type', type);
+    data.append('text', text);
+    data.append('id', '{{descriptor_id}}');
+    console.log(text);
+    var dialog = bootbox.dialog({
+                message: '<div class="text-center"><i class="fa fa-spin fa-spinner"></i> Onboarding...</div>',
+                closeButton: true
+            });
+    $.ajax({
+        url: new_desc_url,
+        type: 'POST',
+        data: data,
+        cache: false,
+        contentType: false,
+        processData: false,
+        success: function (result) {
+            dialog.modal('hide');
+            refreshTable();
+        },
+        error: function (result) {
+            dialog.modal('hide');
+            showAlert(result);
+        }
+    });
+}
\ No newline at end of file
diff --git a/static/src/packagehandler/packages_list.js b/static/src/packagehandler/packages_list.js
new file mode 100644 (file)
index 0000000..20a2159
--- /dev/null
@@ -0,0 +1,102 @@
+/*
+   Copyright 2018 EveryUP srl
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an  BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+*/
+
+function deletePackage(package_type, package_id, package_name) {
+
+    bootbox.confirm("Are you sure want to delete " + package_name + "?", function (result) {
+        if (result) {
+            var dialog = bootbox.dialog({
+                message: '<div class="text-center"><i class="fa fa-spin fa-spinner"></i> Loading...</div>',
+                closeButton: true
+            });
+            $.ajax({
+                url: '/packages/' + package_type + '/' + package_id + '/delete',
+                type: 'GET',
+                dataType: "json",
+                contentType: "application/json;charset=utf-8",
+                success: function (result) {
+                    dialog.modal('hide');
+                    location.reload();
+                },
+                error: function (result) {
+                    dialog.modal('hide');
+                    bootbox.alert("An error occurred.");
+                }
+            });
+        }
+    })
+}
+
+function clonePackage(package_type, package_id) {
+
+    bootbox.confirm("Are you sure want to clone?", function (result) {
+        if (result) {
+            var dialog = bootbox.dialog({
+                message: '<div class="text-center"><i class="fa fa-spin fa-spinner"></i> Loading...</div>',
+                closeButton: true
+            });
+            $.ajax({
+                url: '/packages/' + package_type + '/' + package_id + '/clone',
+                type: 'GET',
+                dataType: "json",
+                contentType: "application/json;charset=utf-8",
+                success: function (result) {
+                    dialog.modal('hide');
+                    location.reload();
+                },
+                error: function (result) {
+                    dialog.modal('hide');
+                    bootbox.alert("An error occurred.");
+                }
+            });
+        }
+    })
+}
+
+
+function openPackageContentList(type, pkg_id) {
+    var dialog = bootbox.dialog({
+        message: '<div class="text-center"><i class="fa fa-spin fa-spinner"></i> Loading...</div>',
+        closeButton: true
+    });
+    $.ajax({
+        url: '/packages/' + type + '/' + pkg_id + '/action/get_package_files_list',
+        type: 'GET',
+        dataType: "json",
+        contentType: "application/json;charset=utf-8",
+        success: function (result) {
+            //$('#modal_show_vim_body').empty();
+            dialog.modal('hide');
+            build_file_list("Files in " + pkg_id, result.files);
+        },
+        error: function (result) {
+            dialog.modal('hide');
+            bootbox.alert("An error occurred while retrieving the package content.");
+        }
+    });
+}
+
+
+function build_file_list(title, list) {
+    $('#files_list_tbody').find('tr:gt(0)').remove();
+    $('#files_list_tbody_title').text(title)
+    for (var i in list) {
+        var template = '<tr><td>-</td><td>' + list[i] + '</td><td><button type="button" class="btn btn-default" onclick="" disabled><i class="fa fa-folder-open"></i></button></td></tr>'
+        $('#files_list_tbody').append(template)
+    }
+    $('#modal_files_list').modal('show');
+}
+
diff --git a/static/src/projecthandler/descriptorslist.js b/static/src/projecthandler/descriptorslist.js
deleted file mode 100644 (file)
index 5060041..0000000
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
-   Copyright 2018 EveryUP srl
-
-   Licensed under the Apache License, Version 2.0 (the "License");
-   you may not use this file except in compliance with the License.
-   You may obtain a copy of the License at
-
-       http://www.apache.org/licenses/LICENSE-2.0
-
-   Unless required by applicable law or agreed to in writing, software
-   distributed under the License is distributed on an  BASIS,
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-   See the License for the specific language governing permissions and
-   limitations under the License.
-*/
-
-function deletePackage(descriptor_type, package_id, package_name) {
-
-    bootbox.confirm("Are you sure want to delete " + package_name + "?", function (result) {
-        if (result) {
-            var dialog = bootbox.dialog({
-                message: '<div class="text-center"><i class="fa fa-spin fa-spinner"></i> Loading...</div>',
-                closeButton: true
-            });
-            $.ajax({
-                url: '/projects/descriptors/' + descriptor_type + '/' + package_id + '/delete',
-                type: 'GET',
-                dataType: "json",
-                contentType: "application/json;charset=utf-8",
-                success: function (result) {
-                    dialog.modal('hide');
-                    location.reload();
-                },
-                error: function (result) {
-                    dialog.modal('hide');
-                    bootbox.alert("An error occurred.");
-                }
-            });
-        }
-    })
-}
-
-function clonePackage(descriptor_type, package_id) {
-
-    bootbox.confirm("Are you sure want to clone?", function (result) {
-        if (result) {
-            var dialog = bootbox.dialog({
-                message: '<div class="text-center"><i class="fa fa-spin fa-spinner"></i> Loading...</div>',
-                closeButton: true
-            });
-            $.ajax({
-                url: '/projects/descriptors/' + descriptor_type + '/' + package_id + '/clone',
-                type: 'GET',
-                dataType: "json",
-                contentType: "application/json;charset=utf-8",
-                success: function (result) {
-                    dialog.modal('hide');
-                    location.reload();
-                },
-                error: function (result) {
-                    dialog.modal('hide');
-                    bootbox.alert("An error occurred.");
-                }
-            });
-        }
-    })
-}
-
-
-function openPackageContentList(type, pkg_id) {
-    var dialog = bootbox.dialog({
-        message: '<div class="text-center"><i class="fa fa-spin fa-spinner"></i> Loading...</div>',
-        closeButton: true
-    });
-    $.ajax({
-        url: '/projects/descriptors/' + type + '/' + pkg_id + '/action/get_package_files_list',
-        type: 'GET',
-        dataType: "json",
-        contentType: "application/json;charset=utf-8",
-        success: function (result) {
-            //$('#modal_show_vim_body').empty();
-            dialog.modal('hide');
-            build_file_list("Files in " + pkg_id, result.files);
-        },
-        error: function (result) {
-            dialog.modal('hide');
-            bootbox.alert("An error occurred while retrieving the package content.");
-        }
-    });
-}
-
-
-function build_file_list(title, list) {
-    $('#files_list_tbody').find('tr:gt(0)').remove();
-    $('#files_list_tbody_title').text(title)
-    for (var i in list) {
-        var template = '<tr><td>-</td><td>' + list[i] + '</td><td><button type="button" class="btn btn-default" onclick="" disabled><i class="fa fa-folder-open"></i></button></td></tr>'
-        $('#files_list_tbody').append(template)
-    }
-    $('#modal_files_list').modal('show');
-}
-
diff --git a/static/src/projecthandler/onboard_package.js b/static/src/projecthandler/onboard_package.js
deleted file mode 100644 (file)
index d18be5b..0000000
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
-   Copyright 2018 EveryUP srl
-
-   Licensed under the Apache License, Version 2.0 (the "License");
-   you may not use this file except in compliance with the License.
-   You may obtain a copy of the License at
-
-       http://www.apache.org/licenses/LICENSE-2.0
-
-   Unless required by applicable law or agreed to in writing, software
-   distributed under the License is distributed on an  BASIS,
-   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-   See the License for the specific language governing permissions and
-   limitations under the License.
-*/
-
-var dropZone = document.getElementById('drop-zone');
-dropZone.ondrop = function (e) {
-    e.preventDefault();
-    this.className = 'upload-drop-zone';
-    create(e.dataTransfer.files, true);
-};
-
-dropZone.ondragover = function () {
-    this.className = 'upload-drop-zone drop';
-    return false;
-};
-
-dropZone.ondragleave = function () {
-    this.className = 'upload-drop-zone';
-    return false;
-};
-
-
-function create(fs, dropzone) {
-    var id = $('.nav-tabs .active').attr('id');
-    if (dropzone) id = 'file_li';
-    var type, text;
-    var data = new FormData();
-    switch (id) {
-
-        case 'file_li':
-            type = 'file';
-
-            var files = dropzone ? fs : document.getElementById('js-upload-files').files;
-            if (!files || !files.length) {
-                files = document.getElementById('drop-zone').files;
-                if (!files || !files.length) {
-                    alert("Select a file");
-                    return
-                }
-            }
-            console.log(files[0])
-            var patt1 = /\.([0-9a-z]+)(?:[\?#]|$)/i;
-            console.log(files[0].name.match(patt1));
-            var extension = files[0].name.substr(files[0].name.lastIndexOf('.') + 1);
-            console.log(extension);
-            if (!(extension == 'gz' )) {
-                alert("The file must be .tar.gz");
-                return
-            }
-
-            data.append('file', files[0]);
-            break;
-    }
-    data.append('csrfmiddlewaretoken', csrf_token);
-    data.append('type', type);
-    data.append('text', text);
-    data.append('id', '{{descriptor_id}}');
-    console.log(text);
-    var dialog = bootbox.dialog({
-                message: '<div class="text-center"><i class="fa fa-spin fa-spinner"></i> Onboarding...</div>',
-                closeButton: true
-            });
-    $.ajax({
-        url: new_desc_url,
-        type: 'POST',
-        data: data,
-        cache: false,
-        contentType: false,
-        processData: false,
-        success: function (result) {
-            dialog.modal('hide');
-            refreshTable();
-        },
-        error: function (result) {
-            dialog.modal('hide');
-            showAlert(result);
-        }
-    });
-}
\ No newline at end of file