horizon/openstack_dashboard/dashboards/admin/metadata_defs/forms.py
Travis Tripp 7e5f4d1594 Base Glance Metadata Definitions Admin UI
Provide a base admin UI for viewing, importing, and associating the
metadata definitions that can be used with various resource types
such as flavors, images, and host aggregates.

In Juno, Glance provided a metadata definitions catalog[1][2] where
users can register the available metadata definitions that can be used
on different types of resources (images, artifacts, volumes, flavors,
aggregates, etc). This includes key / value pairs such as
properties, extra specs, etc. Horizon landed several patches that
read these properties. You can view the functionality in the
"update metadata" action on Flavors, Images, and Host Aggregates.

This specific patch is to bring in the Admin UI for the basic coarse
grained actions on the definitions in the catalog. This includes creating
(importing) a namespace, viewing the overview details about
it, deleting the namespace, and associating the namespace for use with
specific resource types.

Future blueprints will be registered for:
 - CRUD on individual metadata definitions within the namespace
For example, editing the default value of an individual property.

[1] Approved Glance Juno Spec:
https://github.com/openstack/glance-specs/blob/master/specs/juno/metadata-schema-catalog.rst

[2] Glance PTL Juno Feature Overview:
https://www.youtube.com/watch?v=3ptriiw1wK8&t=14m27s

Co-Authored-By: Travis Tripp <travis.tripp@hp.com>
Co-Authored-By: Santiago Baldassin<santiago.b.baldassin@intel.com>
Co-Authored-By: Bartosz Fic <bartosz.fic@intel.com>
Co-Authored-By: Pawel Koniszewski <pawel.koniszewski@intel.com>
Co-Authored-By: Michal Dulko <michal.dulko@intel.com>
DocImpact: Concept awareness
Change-Id: Ie34007f73af7e0941631a52f03841068e509a72c
Implements: blueprint glance-metadata-definitions-base-admin-ui
2014-12-17 16:10:53 -07:00

152 lines
5.7 KiB
Python

#
# (c) Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# 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 "AS IS" 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.
"""
Forms for managing metadata.
"""
import json
import logging
from django.forms import ValidationError # noqa
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon import messages
from openstack_dashboard.api import glance
from openstack_dashboard.dashboards.admin.metadata_defs \
import constants
LOG = logging.getLogger(__name__)
class CreateNamespaceForm(forms.SelfHandlingForm):
source_type = forms.ChoiceField(
label=_('Namespace Definition Source'),
required=False,
choices=[('file', _('Metadata Definition File')),
('raw', _('Direct Input'))],
widget=forms.Select(
attrs={'class': 'switchable', 'data-slug': 'source'}))
metadef_file = forms.FileField(
label=_("Metadata Definition File"),
help_text=_("A local metadata definition file to upload."),
widget=forms.FileInput(
attrs={'class': 'switched', 'data-switch-on': 'source',
'data-source-file': _('Metadata Definition File')}),
required=False)
direct_input = forms.CharField(
label=_('Namespace JSON'),
help_text=_('The JSON formatted contents of a namespace.'),
widget=forms.widgets.Textarea(
attrs={'class': 'switched', 'data-switch-on': 'source',
'data-source-raw': _('Namespace JSON')}),
required=False)
public = forms.BooleanField(label=_("Public"), required=False)
protected = forms.BooleanField(label=_("Protected"), required=False)
def __init__(self, request, *args, **kwargs):
super(CreateNamespaceForm, self).__init__(request, *args, **kwargs)
def clean(self):
data = super(CreateNamespaceForm, self).clean()
# The key can be missing based on particular upload
# conditions. Code defensively for it here...
metadef_file = data.get('metadef_file', None)
metadata_raw = data.get('direct_input', None)
if metadata_raw and metadef_file:
raise ValidationError(
_("Cannot specify both file and direct input."))
if not metadata_raw and not metadef_file:
raise ValidationError(
_("No input was provided for the namespace content."))
try:
if metadef_file:
ns_str = self.files['metadef_file'].read()
else:
ns_str = data['direct_input']
namespace = json.loads(ns_str)
if data['public']:
namespace['visibility'] = 'public'
else:
namespace['visibility'] = 'private'
namespace['protected'] = data['protected']
for protected_prop in constants.METADEFS_PROTECTED_PROPS:
namespace.pop(protected_prop, None)
data['namespace'] = namespace
except Exception as e:
msg = _('There was a problem loading the namespace: %s.') % e
raise forms.ValidationError(msg)
return data
def handle(self, request, data):
try:
namespace = glance.metadefs_namespace_create(request,
data['namespace'])
messages.success(request,
_('Namespace %s has been created.') %
namespace['namespace'])
return namespace
except Exception as e:
msg = _('Unable to create new namespace. %s')
msg %= e.message.split('Failed validating', 1)[0]
exceptions.handle(request, message=msg)
return False
class ManageResourceTypesForm(forms.SelfHandlingForm):
def __init__(self, request, *args, **kwargs):
super(ManageResourceTypesForm, self).__init__(request, *args, **kwargs)
def handle(self, request, context):
namespace_name = self.initial['id']
current_names = self.get_names(self.initial['resource_types'])
try:
updated_types = json.loads(self.data['resource_types'])
selected_types = [updated_type for updated_type in updated_types
if updated_type.pop('selected', False)]
for current_name in current_names:
glance.metadefs_namespace_remove_resource_type(
self.request, namespace_name, current_name)
for selected_type in selected_types:
selected_type.pop('$$hashKey', None)
selected_type.pop('created_at', None)
selected_type.pop('updated_at', None)
glance.metadefs_namespace_add_resource_type(
self.request, namespace_name, selected_type)
msg = _('Resource types updated for namespace %s.')
msg %= namespace_name
messages.success(request, msg)
except Exception:
msg = _('Error updating resource types for namespace %s.')
msg %= namespace_name
exceptions.handle(request, msg)
return False
return True
def get_names(self, items):
return [item['name'] for item in items]