WIM handler 87/7287/1
authorlombardofr <lombardo@everyup.it>
Mon, 11 Mar 2019 09:26:08 +0000 (10:26 +0100)
committerlombardofr <lombardo@everyup.it>
Mon, 11 Mar 2019 09:26:08 +0000 (10:26 +0100)
Change-Id: I4e9f120d9dc8485db850461bb5eb2d0f66bea3d3
Signed-off-by: lombardofr <lombardo@everyup.it>
21 files changed:
.gitignore
build-debpkg.sh
lib/osm/osmclient/clientv2.py
projecthandler/management/__init__.py [deleted file]
projecthandler/management/commands/__init__.py [deleted file]
projecthandler/management/commands/delete_project_type.py [deleted file]
projecthandler/management/commands/new_project_type.py [deleted file]
projecthandler/template/project/osm/osm_project_left_sidebar.html
requirements.txt
sf_t3d/settings.py
sf_t3d/urls.py
vimhandler/admin.py [deleted file]
vimhandler/models.py [deleted file]
vimhandler/tests.py [deleted file]
wimhandler/__init__.py [new file with mode: 0644]
wimhandler/apps.py [new file with mode: 0644]
wimhandler/template/modal/wim_create.html [new file with mode: 0644]
wimhandler/template/modal/wim_details.html [new file with mode: 0644]
wimhandler/template/wim_list.html [new file with mode: 0644]
wimhandler/urls.py [new file with mode: 0644]
wimhandler/views.py [new file with mode: 0644]

index 5af1e6d..5e05014 100644 (file)
@@ -51,6 +51,10 @@ instancehandler/migrations
 sdnctrlhandler/migrations
 authosm/migrations
 userhandler/migrations
+packagehandler/migrations
+netslicehandler/migrations
+vimhandler/migrations
+wimhandler/migrations
 
 #Deb package
 deb_dist/
index d1becda..6f05b94 100755 (executable)
@@ -15,7 +15,7 @@
 #    under the License.
 
 
-PKG_DIRECTORIES="authosm descriptorhandler instancehandler lib projecthandler sdnctrlhandler sf_t3d static template userhandler vimhandler packagehandler netslicehandler"
+PKG_DIRECTORIES="authosm descriptorhandler instancehandler lib projecthandler sdnctrlhandler sf_t3d static template userhandler vimhandler packagehandler netslicehandler wimhandler"
 PKG_FILES="bower.json django.ini LICENSE manage.py nginx-app.conf README.md requirements.txt supervisor-app.conf .bowerrc"
 MDG_NAME=lightui
 DEB_INSTALL=debian/osm-${MDG_NAME}.install
index f82bf4d..0914fb3 100644 (file)
@@ -1210,6 +1210,23 @@ class Client(object):
         result['data'] = r.text
         return result
 
+    def wim_list(self, token):
+        result = {'error': True, 'data': ''}
+        headers = {"Content-Type": "application/yaml", "accept": "application/json",
+                   'Authorization': 'Bearer {}'.format(token['id'])}
+        _url = "{0}/admin/v1/wim_accounts".format(self._base_path)
+        try:
+            r = requests.get(_url, params=None, verify=False, stream=True, headers=headers)
+        except Exception as e:
+            log.exception(e)
+            result['data'] = str(e)
+            return result
+        if r.status_code == requests.codes.ok:
+            result['error'] = False
+        result['data'] = Util.json_loads_byteified(r.text)
+
+        return result
+
     def vim_list(self, token):
         result = {'error': True, 'data': ''}
         headers = {"Content-Type": "application/yaml", "accept": "application/json",
@@ -1227,6 +1244,23 @@ class Client(object):
 
         return result
 
+    def wim_delete(self, token, id):
+        result = {'error': True, 'data': ''}
+        headers = {"accept": "application/json",
+                   'Authorization': 'Bearer {}'.format(token['id'])}
+        _url = "{0}/admin/v1/wim_accounts/{1}".format(self._base_path, id)
+        try:
+            r = requests.delete(_url, params=None, verify=False, headers=headers)
+        except Exception as e:
+            log.exception(e)
+            result['data'] = str(e)
+            return result
+        if r.status_code == requests.codes.accepted:
+            result['error'] = False
+        else:
+            result['data'] = r.text
+        return result
+
     def vim_delete(self, token, id):
         result = {'error': True, 'data': ''}
         headers = {"accept": "application/json",
@@ -1244,6 +1278,24 @@ class Client(object):
             result['data'] = r.text
         return result
 
+    def wim_get(self, token, id):
+
+        result = {'error': True, 'data': ''}
+        headers = {"Content-Type": "application/json", "accept": "application/json",
+                   'Authorization': 'Bearer {}'.format(token['id'])}
+        _url = "{0}/admin/v1/wim_accounts/{1}".format(self._base_path, id)
+
+        try:
+            r = requests.get(_url, params=None, verify=False, stream=True, headers=headers)
+        except Exception as e:
+            log.exception(e)
+            result['data'] = str(e)
+            return result
+        if r.status_code == requests.codes.ok:
+            result['error'] = False
+        result['data'] = Util.json_loads_byteified(r.text)
+        return result
+
     def vim_get(self, token, id):
 
         result = {'error': True, 'data': ''}
@@ -1262,6 +1314,24 @@ class Client(object):
         result['data'] = Util.json_loads_byteified(r.text)
         return result
 
+    def wim_create(self, token, wim_data):
+        result = {'error': True, 'data': ''}
+        headers = {"Content-Type": "application/json", "accept": "application/json",
+                   'Authorization': 'Bearer {}'.format(token['id'])}
+
+        _url = "{0}/admin/v1/wim_accounts".format(self._base_path)
+
+        try:
+            r = requests.post(_url, json=wim_data, verify=False, headers=headers)
+        except Exception as e:
+            log.exception(e)
+            result['data'] = str(e)
+            return result
+        if r.status_code == requests.codes.created:
+            result['error'] = False
+        result['data'] = Util.json_loads_byteified(r.text)
+        return result
+
     def vim_create(self, token, vim_data):
 
         result = {'error': True, 'data': ''}
diff --git a/projecthandler/management/__init__.py b/projecthandler/management/__init__.py
deleted file mode 100644 (file)
index e69de29..0000000
diff --git a/projecthandler/management/commands/__init__.py b/projecthandler/management/commands/__init__.py
deleted file mode 100644 (file)
index e69de29..0000000
diff --git a/projecthandler/management/commands/delete_project_type.py b/projecthandler/management/commands/delete_project_type.py
deleted file mode 100644 (file)
index d750f9f..0000000
+++ /dev/null
@@ -1,14 +0,0 @@
-from django.core.management.base import BaseCommand, CommandError
-
-
-class Command(BaseCommand):
-    help = 'Delete a project type'
-
-    def handle(self, *args, **options):
-
-            try:
-                print 'delete project type'
-            except Exception:
-                raise CommandError('Error unable to delete a new project type')
-
-            self.stdout.write(self.style.SUCCESS('Project type successfully deleted'))
diff --git a/projecthandler/management/commands/new_project_type.py b/projecthandler/management/commands/new_project_type.py
deleted file mode 100644 (file)
index 7c9dce9..0000000
+++ /dev/null
@@ -1,14 +0,0 @@
-from django.core.management.base import BaseCommand, CommandError
-
-
-class Command(BaseCommand):
-    help = 'Create a new project type'
-
-    def handle(self, *args, **options):
-
-            try:
-                print 'new project type'
-            except Exception:
-                raise CommandError('Error unable to create a new project type')
-
-            self.stdout.write(self.style.SUCCESS('New project type successfully created'))
index d39a0c8..7067ca7 100644 (file)
                     <i class="fa fa-server fa-fw"></i> <span>VIM Accounts</span>
                 </a>
             </li>
+
+            {% url "wims:list"   as  wim_list_url %}
+            <li {% if request.get_full_path == wim_list_url %} class="active" {% endif %}>
+                <a href='{% url "wims:list"   %}'>
+                    <i class="fa fa-sitemap fa-rotate-180 fa-fw"></i> <span>WIM Accounts</span>
+                </a>
+            </li>
             {% if user.is_admin %}
                 <li class="header">ADMIN</li>
                 {% url "users:list"   as  user_list_url %}
index 99d35b5..d8f43b7 100644 (file)
@@ -1,12 +1,11 @@
 decorator==4.0.10
-Django==1.10.1
+Django==1.11.18
 django-model-utils==2.6
 functools32==3.2.3.post2
 jsonfield==1.0.3
 jsonschema==2.5.1
 pbr==1.10.0
 pyaml==15.8.2
-pymongo==3.4.0
 python-dateutil==2.6.0
 PyYAML==3.12
 requests==2.12.4
index 21563af..d000e65 100644 (file)
@@ -29,7 +29,7 @@ if os.getenv('DJANGO_ENV') == 'prod':
     DEBUG = False
 else:
     DEBUG = True
-    print DEBUG
+
 ALLOWED_HOSTS = ['*']
 
 AUTH_USER_MODEL = "authosm.OsmUser"
@@ -56,6 +56,7 @@ INSTALLED_APPS = [
     'packagehandler',
     'descriptorhandler',
     'vimhandler',
+    'wimhandler',
     'instancehandler',
     'sdnctrlhandler',
     'userhandler',
@@ -95,6 +96,7 @@ TEMPLATES = [
             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, 'wimhandler', 'template'),
             os.path.join(BASE_DIR, 'instancehandler', 'template'),
             os.path.join(BASE_DIR, 'sdnctrlhandler', 'template'),
             os.path.join(BASE_DIR, 'userhandler', 'templates'),
index 8333b5d..d13bd0f 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'^wims/', include('wimhandler.urls', namespace='wims'), name='wims_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'^netslices/', include('netslicehandler.urls', namespace='netslices'), name='netslices_base'),
diff --git a/vimhandler/admin.py b/vimhandler/admin.py
deleted file mode 100644 (file)
index 2e9690a..0000000
+++ /dev/null
@@ -1,19 +0,0 @@
-#
-#   Copyright 2018 CNIT - Consorzio Nazionale Interuniversitario per le Telecomunicazioni
-#
-#   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.contrib import admin
-
-# Register your models here.
diff --git a/vimhandler/models.py b/vimhandler/models.py
deleted file mode 100644 (file)
index 21d5735..0000000
+++ /dev/null
@@ -1,21 +0,0 @@
-#
-#   Copyright 2018 CNIT - Consorzio Nazionale Interuniversitario per le Telecomunicazioni
-#
-#   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.db import models
-
-# Create your models here.
diff --git a/vimhandler/tests.py b/vimhandler/tests.py
deleted file mode 100644 (file)
index 79947e6..0000000
+++ /dev/null
@@ -1,19 +0,0 @@
-#
-#   Copyright 2018 CNIT - Consorzio Nazionale Interuniversitario per le Telecomunicazioni
-#
-#   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.test import TestCase
-
-# Create your tests here.
diff --git a/wimhandler/__init__.py b/wimhandler/__init__.py
new file mode 100644 (file)
index 0000000..00de7ab
--- /dev/null
@@ -0,0 +1,13 @@
+#   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.
\ No newline at end of file
diff --git a/wimhandler/apps.py b/wimhandler/apps.py
new file mode 100644 (file)
index 0000000..8d17b0a
--- /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 WimhandlerConfig(AppConfig):
+    name = 'wimhandler'
diff --git a/wimhandler/template/modal/wim_create.html b/wimhandler/template/modal/wim_create.html
new file mode 100644 (file)
index 0000000..e7eb6a2
--- /dev/null
@@ -0,0 +1,74 @@
+<div class="modal" id="modal_new_wim" xmlns="http://www.w3.org/1999/html">
+    <div class="modal-dialog modal-lg">
+        <div class="modal-content">
+            <div class="modal-header">
+                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
+                    <span aria-hidden="true">×</span></button>
+                <h4 class="modal-title">New WIM</h4>
+            </div>
+            <form id="formCreateWIM" action='{% url "wims:create" %}'
+                  class="form-horizontal"
+                  method="post" enctype="multipart/form-data">
+                {% csrf_token %}
+                <div class="modal-body" id="modal_new_wim_body">
+                    <div class="form-group">
+                        <label for="wim_name" class="col-sm-2">Name *</label>
+                        <div class="col-sm-3">
+                            <input class="form-control" id="wim_name" name="name" placeholder="Name" required>
+                        </div>
+
+                        <label for="wim_type" class="col-sm-2">Type *</label>
+                        <div class="col-sm-3">
+                            <select id="wim_type" name="wim_type" class="form-control">
+                                <option value="onos">Onos</option>
+                                <option value="tapi">Tapi</option>
+                                <option value="odl">OpenDaylight</option>
+                                <option value="dynpac">DynPac</option>
+                            </select>
+                        </div>
+                    </div> 
+
+                    <div class="form-group">
+                        <label for="wim_url" class="col-sm-2">URL*</label>
+                        <div class="col-sm-3">
+                            <input type="url" class="form-control" id="wim_url" name="wim_url"
+                                           placeholder="WIM URL" required>
+                        </div>
+                        <label for="wim_user" class="col-sm-2">Username*</label>
+                        <div class="col-sm-3">
+                            <input class="form-control" id="wim_user" name="user"
+                                            placeholder="WIM Username" required>
+                        </div>
+                    </div>
+
+                    <div class="form-group">
+                        <label for="wim_password" class="col-sm-2">Password*</label>
+                        <div class="col-sm-3">
+                            <input type="password" class="form-control" id="wim_password"
+                                       name="password" placeholder="WIMPassword" required>
+                        </div>
+                        <label for="wim_description" class="col-sm-2">Description</label>
+                        <div class="col-sm-3">
+                            <input class="form-control" id="wim_description" name="description"
+                                        placeholder="Description" >
+                        </div>
+                    </div>
+
+                </div>
+                <div class="modal-footer">
+                    <button type="button" class="btn btn-default pull-left" data-dismiss="modal">Cancel</button>
+                    <button class="btn btn-primary"
+                            data-loading-text="<i class='fa fa-circle-o-notch fa-spin'></i> Creating..."
+                            id="create_new_wim">Create
+                    </button>
+
+                </div>
+            </form>
+        </div>
+        <!-- /.modal-content -->
+    </div>
+    <!-- /.modal-dialog -->
+</div>
+
+
+
diff --git a/wimhandler/template/modal/wim_details.html b/wimhandler/template/modal/wim_details.html
new file mode 100644 (file)
index 0000000..3e788ad
--- /dev/null
@@ -0,0 +1,51 @@
+<div class="modal" id="modal_show_wim" xmlns="http://www.w3.org/1999/html">
+    <div class="modal-dialog">
+        <div class="modal-content">
+            <div class="modal-header">
+                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
+                    <span aria-hidden="true">×</span></button>
+                <h4 class="modal-title" >WIM Details</h4>
+            </div>
+
+            <div class="modal-body" id="modal_show_wim_body">
+                <div class="row">
+                    <div class="col-lg-10">
+                        <ul class="nav nav-stacked">
+                            <li><a><b>ID:</b> <span id="_id" class="pull-right"></span></a></li>
+                        </ul>
+                    </div>
+                    <div class="col-lg-7">
+                        <ul class="nav nav-stacked">
+                            <li><a><b>Operational State:</b><span id="operationalState" class="pull-right badge"></span></a></li>
+                            <li><a><b> Name:</b><span id="name" class="pull-right"></span></a></li>
+                            <li><a><b>URL:</b><span id="wim_url" class="pull-right "></span></a></li>
+                            <li><a><b>Created:</b><span id="created" class="pull-right "></span></a></li>
+
+                        </ul>
+                    </div>
+                    <div class="col-lg-5">
+                        <ul class="nav nav-stacked">
+                            <li><a><b>Schema Version:</b><span id="schema_version" class="pull-right "></span></a></li>
+                            <li><a><b>Type:</b><span id="wim_type" class="pull-right"></span></a></li>
+                            <li><a><b>Description:</b><span id="description" class="pull-right "></span></a></li>
+                            <li><a><b>Modified:</b><span id="modified" class="pull-right "></span></a></li>
+                        </ul>
+                    </div>
+                    <div class="col-lg-12">
+                        <ul class="nav nav-stacked">
+                        
+                        <li><a><b>Deployed:</b><span id="deployed" class="pull-right "></span></a></li>
+                        <li><a><b>Detailed Status:</b><span id="detailed-status" class="pull-right "></span></a></li>
+                        </ul>
+
+                    </div>
+                </div>
+            </div>
+            <div class="modal-footer">
+                <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
+            </div>
+        </div>
+        <!-- /.modal-content -->
+    </div>
+    <!-- /.modal-dialog -->
+</div>
\ No newline at end of file
diff --git a/wimhandler/template/wim_list.html b/wimhandler/template/wim_list.html
new file mode 100644 (file)
index 0000000..9a07c0f
--- /dev/null
@@ -0,0 +1,231 @@
+{% extends "base.html" %}
+{% load get %}
+{% load staticfiles %}
+
+
+{% block head_block %}
+    {{ block.super }}
+    <link rel="stylesheet" href="/static/bower_components/datatables.net-bs/css/dataTables.bootstrap.min.css">
+{% endblock %}
+{% block title_header_big %}
+    {{ block.super }}
+{% endblock %}
+{% block left_sidebar %}
+
+   {% include 'osm/osm_project_left_sidebar.html' %}
+
+{% endblock %}
+
+
+{% block breadcrumb_body %}
+    {{ block.super }}
+    <li><a href="{% url "wims:list"   %}">VIMS</a></li>
+{% endblock %}
+
+{% block content_body %}
+    {{ block.super }}
+    {% include 'modal/wim_details.html' %}
+    {% include 'modal/wim_create.html' %}
+    {% csrf_token %}
+    <div class="row">
+        <div class="col-md-12">
+
+            <div class="box">
+                <div class="box-header with-border">
+                    <h3 class="box-title">Registered WIM</h3>
+                    <div class="box-tools">
+                        <button type="button" class="btn btn-default" data-container="body"
+                            data-toggle="tooltip" data-placement="top" title="New PDU"
+                            onclick="javascript:openModalCreateWIM()">
+                        <i class="fa fa-plus"></i> <span> New WIM</span>
+                        </button>
+                    </div>
+                </div>
+                <div class="box-body">
+                    <table id="wims_table" class="table table-bordered table-striped">
+                        <thead>
+                        <tr>
+                            <th>Name</th>
+                            <th>Identifier</th>
+                            <th>Type</th>
+                            <th>Operational State</th>
+                            <th>Description</th>
+                            <th>Actions</th>
+                        </tr>
+                        </thead>
+                        <tbody>
+
+                        </tbody>
+                    </table>
+                </div>
+            </div>
+        </div>
+
+    </div>
+{% endblock %}
+
+{% block resource_block %}
+    {{ block.super }}
+    <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>
+    $(document).ready( function () {
+        var table = $('#wims_table').DataTable({
+            responsive: true,
+            "ajax": {
+                "url": "/wims/list/",
+                "dataSrc": function (json) {
+                    return json['datacenters'];
+                },
+                statusCode: {
+                    401: function () {
+                        console.log("no auth");
+                        moveToLogin(window.location.pathname);
+                    }
+                },
+                "error": function (hxr, error, thrown) {
+                    console.log(hxr)
+                    console.log(thrown)
+                    console.log(error);
+                }
+
+            },
+            "columns": [
+                {
+                    "render": function (data, type, row) {
+                        return row["name"];
+                    },
+                    "targets": 0
+                },
+                {
+                    "render": function (data, type, row) {
+                        return row['_id'];
+                    },
+                    "targets": 1
+                },
+                {
+                    "render": function (data, type, row) {
+                        return row["wim_type"];
+                    },
+                    "targets": 2
+                },
+                {
+                    "render": function (data, type, row) {
+                        return row["_admin"]['operationalState'];
+                    },
+                    "targets": 3
+                },
+                {
+                    "render": function (data, type, row) {
+                        return row['description'] || '';
+                    },
+                    "targets": 4
+                },
+                {
+                    "render": function (data, type, row) {
+                        return '<div class="btn-group"><button type="button" class="btn btn-default" ' +
+                            'onclick="javascript:showWIM( \''+row['_id'] + '\', \''+row['name'] +'\')" data-toggle="tooltip" data-placement="top" data-container="body" title="Show Info">' +
+                        '<i class="fa fa-info"></i>' +
+                        '</button> ' +
+                        '<button type="button" class="btn btn-default"' +
+                        'onclick="javascript:deleteWim(\''+row['_id']+'\', \''+ row["name"] +'\')" data-toggle="tooltip" data-placement="top" data-container="body" title="Delete">' +
+                        '<i class="far fa-trash-alt" ></i></button></div>';
+                    },
+                    "targets": 5,
+                    "orderable": false
+                }
+            ]
+        });
+
+        setInterval(function () {
+                table.ajax.reload();
+            }, 10000);
+    });
+
+        function openModalCreateWIM(){
+            $('#modal_new_wim').modal('show');
+        }
+        function deleteWim(wim_id, wim_name) {
+            var url = "/wims/"+wim_id+"/delete";
+            bootbox.confirm("Are you sure want to delete " + wim_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: url,
+                        type: 'GET',
+                        dataType: "json",
+                        contentType: "application/json;charset=utf-8",
+                        success: function (result) {
+                            if (result['error'] == true) {
+                                dialog.modal('hide');
+                                bootbox.alert("An error occurred.");
+                            }
+                            else {
+                                dialog.modal('hide');
+                                location.reload();
+                            }
+                        },
+                        error: function (error) {
+                            dialog.modal('hide');
+                            bootbox.alert("An error occurred.");
+                        }
+                    });
+                }
+            })
+        }
+
+        function showWIM(wim_uuid) {
+            var dialog = bootbox.dialog({
+                message: '<div class="text-center"><i class="fa fa-spin fa-spinner"></i> Loading...</div>',
+                closeButton: true
+            });
+
+            $.ajax({
+                url: '/wims/' + wim_uuid ,
+                type: 'GET',
+                dataType: "json",
+                contentType: "application/json;charset=utf-8",
+                success: function (result) {
+                    //$('#modal_show_vim_body').empty();
+                    var wim = result.wim;
+                    
+                    if (wim) {
+                        $('#modal_show_wim_body').find('span').text('-');
+                        for (var k in wim) {
+                            $('#' + k).text(wim[k])
+                        }
+                        if (wim['_admin']) {
+                            for (var i in wim['_admin']) {
+                                if (i === 'modified' || i === 'created') {
+                                    //$('#' + i).text(new Date(wim['_admin'][i]* 1000).toUTCString());
+                                    $('#' + i).text(moment(wim['_admin'][i] * 1000).format('DD/MM/YY hh:mm:ss'));
+                                }
+                                else if (i === 'deployed') {
+                                    $('#' + i).text(JSON.stringify(wim['_admin'][i]))
+                                }
+                                else
+                                    $('#' + i).text(wim['_admin'][i])
+                            }
+                        }
+                        dialog.modal('hide');
+                        $('#modal_show_wim').modal('show');
+                    }
+                    else {
+                        dialog.modal('hide');
+                        bootbox.alert("An error occurred while retrieving the WIM info.");
+                    }
+
+                },
+                error: function (result) {
+                    dialog.modal('hide');
+                    bootbox.alert("An error occurred while retrieving the WIM info.");
+                }
+            });
+
+        }
+    </script>
+
+{% endblock %}
diff --git a/wimhandler/urls.py b/wimhandler/urls.py
new file mode 100644 (file)
index 0000000..94b9645
--- /dev/null
@@ -0,0 +1,24 @@
+#   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 wimhandler import views
+
+urlpatterns = [
+    url(r'^list/', views.list, name='list'),
+    url(r'^create/', views.create, name='create'),
+    url(r'^(?P<wim_id>[0-9a-z-]+)/delete$', views.delete, name='delete'),
+    url(r'^(?P<wim_id>[0-9a-z-]+)', views.show, name='show'),
+
+]
\ No newline at end of file
diff --git a/wimhandler/views.py b/wimhandler/views.py
new file mode 100644 (file)
index 0000000..c885b60
--- /dev/null
@@ -0,0 +1,109 @@
+#   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.shortcuts import render, redirect
+from sf_t3d.decorators import login_required
+from django.http import HttpResponse
+import json
+from lib.osm.osmclient.clientv2 import Client
+import authosm.utils as osmutils
+import yaml
+import logging
+
+logging.basicConfig(level=logging.DEBUG)
+log = logging.getLogger('wimhandler.py')
+
+
+@login_required
+def list(request):
+    user = osmutils.get_user(request)
+    project_id = user.project_id
+    result = {'type': 'ns', 'project_id': project_id}
+    raw_content_types = request.META.get('HTTP_ACCEPT', '*/*').split(',')
+    if 'application/json' not in raw_content_types:
+        return __response_handler(request, result, 'wim_list.html')
+    client = Client()
+    result_client = client.wim_list(user.get_token())
+    result["datacenters"] = result_client['data'] if result_client and result_client['error'] is False else []
+    return __response_handler(request, result, 'wim_list.html')
+
+@login_required
+def create(request):
+    user = osmutils.get_user(request)
+    project_id = user.project_id
+    result = {'project_id': project_id}
+    if request.method == 'GET':
+        return __response_handler(request, result, 'wim_create.html')
+    else:
+        new_wim_dict = request.POST.dict()
+        client = Client()
+        keys = ["schema_version",
+                "schema_type",
+                "name",
+                "description",
+                "wim_url",
+                "wim_type",
+                "user",
+                "password",
+                "wim",
+                "description"]
+        wim_data = dict(filter(lambda i: i[0] in keys and len(i[1]) > 0, new_wim_dict.items()))
+        wim_data['config'] = {}
+        for k, v in new_wim_dict.items():
+            if str(k).startswith('config_') and len(v) > 0:
+                config_key = k[7:]
+                wim_data['config'][config_key] = v
+        if 'additional_conf' in new_wim_dict:
+            try:
+                additional_conf_dict = yaml.safe_load(new_wim_dict['additional_conf'])
+                for k,v in additional_conf_dict.items():
+                    wim_data['config'][k] = v
+            except Exception as e:
+                # TODO return error on json.loads exception
+                print e
+        result = client.wim_create(user.get_token(), wim_data)
+        return __response_handler(request, result, 'wims:list', to_redirect=True, )
+
+@login_required
+def delete(request, wim_id=None):
+    user = osmutils.get_user(request)
+    try:
+        client = Client()
+        del_res = client.wim_delete(user.get_token(), wim_id)
+    except Exception as e:
+        log.exception(e)
+    return __response_handler(request, del_res, 'wims:list', to_redirect=True, )
+
+@login_required
+def show(request, wim_id=None):
+    user = osmutils.get_user(request)
+    project_id = user.project_id
+    client = Client()
+    result = client.wim_get(user.get_token(), wim_id)
+    if isinstance(result, dict) and 'error' in result and result['error']:
+        return render(request, 'error.html')
+
+    return __response_handler(request, {
+        "wim": result['data'],
+        "project_id": project_id
+    }, 'wim_show.html')
+
+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