From f7226f2b6597c929ea6ad04180a7c37ebbed9854 Mon Sep 17 00:00:00 2001 From: Janet Yu Date: Thu, 9 Apr 2015 01:23:57 -0700 Subject: [PATCH] Create rule in a policy via Horizon Add form to Policy Details page that lets user create a new rule in the policy. Update Horizon setup in devstack installation script to install JavaScript and CSS files used in Policies panel. * congress.py: Rename SERVICE_TABLE_SEPARATOR to more general TABLE_SEPARATOR. New API functions to create rule and more ways to get data source's schema. datasources/ * utils.py: Data source related helper functions. * views.py: Rename constant. policies/ * urls.py: New url for rule creation form. * views.py: Generate lists of all data source tables and columns and add them to the template context. policies/rules/ * tables.py: New button to show rule creation form. * views.py: New view for rule creation form. * workflows.py: Steps in rule creation form. Translate user inputs into Datalog and send off to the Congress server. policies/templates/policies/ * detail.html: Change to extend new base file, which includes new static files. Store lists of data source tables and columns here for use by child templates. policies/templates/policies/rules/ * _create_conditions.html: Rule creation step where user defines head column mapping, join, and negation conditions. * _create_output.html: Rule creation step where user defines rule metadata plus policy table name and columns. * _mapping_row.html: Template for a row of inputs that defines a head column mapping. * create.html: Rule creation modal window. static/admin/css/ * policies.css: Custom CSS used in Policies panel. static/admin/js/ * policies.js: Custom JavaScript used in Policies panel. templates/admin/ * _scripts.html: Custom JavaScript files used in Admin dashboard. * base.html: Custom CSS and JavaScript files used in Admin dashboard. Includes partial implementation of table aliases for self-joins. Does not include: usage of builtin tables, data preview before submitting rule, policy table name and column autocompletion in Output step, redisplay of rule creation form upon failure to create rule, robust input validation. Partially Implements: blueprint horizon-create-policies Change-Id: I6ef7e15c34d639f5eb09303077893dbf289347f9 --- contrib/devstack/lib/congress | 14 + contrib/horizon/congress.py | 23 +- contrib/horizon/datasources/utils.py | 187 ++++++++ contrib/horizon/datasources/views.py | 4 +- contrib/horizon/policies/rules/tables.py | 15 +- contrib/horizon/policies/rules/views.py | 36 ++ contrib/horizon/policies/rules/workflows.py | 439 ++++++++++++++++++ .../policies/templates/policies/detail.html | 5 +- .../policies/rules/_create_conditions.html | 174 +++++++ .../policies/rules/_create_output.html | 65 +++ .../policies/rules/_mapping_row.html | 21 + .../templates/policies/rules/create.html | 24 + contrib/horizon/policies/urls.py | 4 + contrib/horizon/policies/views.py | 41 +- contrib/horizon/static/admin/css/policies.css | 134 ++++++ contrib/horizon/static/admin/js/policies.js | 288 ++++++++++++ contrib/horizon/templates/admin/_scripts.html | 5 + contrib/horizon/templates/admin/base.html | 15 + 18 files changed, 1488 insertions(+), 6 deletions(-) create mode 100644 contrib/horizon/datasources/utils.py create mode 100644 contrib/horizon/policies/rules/views.py create mode 100644 contrib/horizon/policies/rules/workflows.py create mode 100644 contrib/horizon/policies/templates/policies/rules/_create_conditions.html create mode 100644 contrib/horizon/policies/templates/policies/rules/_create_output.html create mode 100644 contrib/horizon/policies/templates/policies/rules/_mapping_row.html create mode 100644 contrib/horizon/policies/templates/policies/rules/create.html create mode 100644 contrib/horizon/static/admin/css/policies.css create mode 100644 contrib/horizon/static/admin/js/policies.js create mode 100644 contrib/horizon/templates/admin/_scripts.html create mode 100644 contrib/horizon/templates/admin/base.html diff --git a/contrib/devstack/lib/congress b/contrib/devstack/lib/congress index 35e2383d2..3e4249ebd 100644 --- a/contrib/devstack/lib/congress +++ b/contrib/devstack/lib/congress @@ -271,6 +271,8 @@ function _congress_setup_horizon { # Dashboard panels cp -r $CONGRESS_HORIZON_DIR/datasources $HORIZON_DIR/openstack_dashboard/dashboards/admin/ cp -r $CONGRESS_HORIZON_DIR/policies $HORIZON_DIR/openstack_dashboard/dashboards/admin/ + cp -r $CONGRESS_HORIZON_DIR/static $HORIZON_DIR/openstack_dashboard/dashboards/admin/ + cp -r $CONGRESS_HORIZON_DIR/templates $HORIZON_DIR/openstack_dashboard/dashboards/admin/ cp $CONGRESS_HORIZON_DIR/congress.py $HORIZON_DIR/openstack_dashboard/api/ cp $CONGRESS_HORIZON_DIR/_50_policy.py $HORIZON_DIR/openstack_dashboard/local/enabled/ cp $CONGRESS_HORIZON_DIR/_60_policies.py $HORIZON_DIR/openstack_dashboard/local/enabled/ @@ -287,6 +289,18 @@ function _congress_setup_horizon { "\n openstack_dashboard.local.enabled,"\ "\n], HORIZON_CONFIG, INSTALLED_APPS)" >> $HORIZON_DIR/openstack_dashboard/test/settings.py + # Setup alias for django-admin which could be different depending on distro + local django_admin + if type -p django-admin > /dev/null; then + django_admin=django-admin + else + django_admin=django-admin.py + fi + + # Collect and compress static files (e.g., JavaScript, CSS) + DJANGO_SETTINGS_MODULE=openstack_dashboard.settings $django_admin collectstatic --noinput + DJANGO_SETTINGS_MODULE=openstack_dashboard.settings $django_admin compress --force + # Restart Horizon restart_apache_server } diff --git a/contrib/horizon/congress.py b/contrib/horizon/congress.py index 7083599ca..17671b578 100644 --- a/contrib/horizon/congress.py +++ b/contrib/horizon/congress.py @@ -18,9 +18,10 @@ from congressclient.v1 import client as congress_client import keystoneclient from openstack_dashboard.api import base + LITERALS_SEPARATOR = '),' RULE_SEPARATOR = ':-' -SERVICE_TABLE_SEPARATOR = ':' +TABLE_SEPARATOR = ':' LOG = logging.getLogger(__name__) @@ -128,6 +129,13 @@ def policy_get(request, policy_name): return p +def policy_rule_create(request, policy_name, body=None): + """Create a rule in the given policy, with the given properties.""" + client = congressclient(request) + rule = client.create_policy_rule(policy_name, body=body) + return rule + + def policy_rule_delete(request, policy_name, rule_id): """Delete a rule by id, from the given policy.""" client = congressclient(request) @@ -247,12 +255,25 @@ def datasource_rows_list(request, datasource_id, table_name): return datasource_rows +def datasource_schema_get(request, datasource_id): + """Get the schema for all tables in the given data source.""" + client = congressclient(request) + return client.show_datasource_schema(datasource_id) + + def datasource_table_schema_get(request, datasource_id, table_name): """Get the schema for a data source table.""" client = congressclient(request) return client.show_datasource_table_schema(datasource_id, table_name) +def datasource_table_schema_get_by_name(request, datasource_name, table_name): + """Get the schema for a data source table.""" + datasource = datasource_get_by_name(request, datasource_name) + client = congressclient(request) + return client.show_datasource_table_schema(datasource['id'], table_name) + + def datasource_statuses_list(request): client = congressclient(request) datasources_list = client.list_datasources() diff --git a/contrib/horizon/datasources/utils.py b/contrib/horizon/datasources/utils.py new file mode 100644 index 000000000..b748b1dd0 --- /dev/null +++ b/contrib/horizon/datasources/utils.py @@ -0,0 +1,187 @@ +# Copyright 2015 VMware. +# +# 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. + +import logging + +from openstack_dashboard.api import congress + + +LOG = logging.getLogger(__name__) + + +def _get_policy_tables(request): + # Return all policy tables. + all_tables = [] + try: + # Get all the policies. + policies = congress.policies_list(request) + except Exception as e: + LOG.error('Unable to get list of policies: %s' % e.message) + else: + try: + for policy in policies: + # Get all the tables in this policy. + policy_name = policy['name'] + policy_tables = congress.policy_tables_list(request, + policy_name) + # Get the names of the tables. + datasource_tables = [] + for table in policy_tables: + table.set_id_as_name_if_empty() + table_name = table['name'] + # Exclude service-derived tables. + if congress.TABLE_SEPARATOR not in table_name: + datasource_tables.append(table['name']) + + all_tables.append({'datasource': policy_name, + 'tables': datasource_tables}) + except Exception as e: + LOG.error('Unable to get tables for policy "%s": %s' % + (policy_name, e.message)) + return all_tables + + +def _get_service_tables(request): + # Return all service tables. + all_tables = [] + try: + # Get all the services. + services = congress.datasources_list(request) + except Exception as e: + LOG.error('Unable to get list of data sources: %s' % e.message) + else: + try: + for service in services: + # Get all the tables in this service. + service_id = service['id'] + service_tables = congress.datasource_tables_list(request, + service_id) + # Get the names of the tables. + datasource_tables = [] + for table in service_tables: + table.set_id_as_name_if_empty() + datasource_tables.append(table['name']) + + all_tables.append({'datasource': service['name'], + 'tables': datasource_tables}) + except Exception as e: + LOG.error('Unable to get tables for data source "%s": %s' % + (service_id, e.message)) + return all_tables + + +def get_datasource_tables(request): + """Get names of all data source tables. + + Example: + [ + { + 'datasource': 'classification', + 'tables': ['error'] + }, + { + 'datasource': 'neutronv2' + 'tables': ['networks', 'ports', ...] + }, + ... + ] + """ + tables = _get_policy_tables(request) + tables.extend(_get_service_tables(request)) + return tables + + +def get_datasource_columns(request): + """Get of names of columns from all data sources. + + Example: + [ + { + 'datasource': 'classification', + 'tables': [ + { + 'table': 'error', + 'columns': ['name'] + } + ] + }, + { + 'datasource': 'neutronv2', + 'tables': [ + { + 'table': 'networks', + 'columns': ['id', 'tenant_id', ...], + }, + ... + ], + ... + }, + ... + ] + """ + all_columns = [] + + # Get all the policy tables. + policy_tables = _get_policy_tables(request) + try: + for policy in policy_tables: + # Get all the columns in this policy. Unlike for the services, + # there's currently no congress client API to get the schema for + # all tables in a policy in a single call. + policy_name = policy['datasource'] + tables = policy['tables'] + + datasource_tables = [] + for table_name in tables: + # Get all the columns in this policy table. + schema = congress.policy_table_schema_get(request, policy_name, + table_name) + columns = [c['name'] for c in schema['columns']] + datasource_tables.append({'table': table_name, + 'columns': columns}) + + all_columns.append({'datasource': policy_name, + 'tables': datasource_tables}) + except Exception as e: + LOG.error('Unable to get schema for policy "%s" table "%s": %s' % + (policy_name, table_name, e.message)) + + try: + # Get all the services. + services = congress.datasources_list(request) + except Exception as e: + LOG.error('Unable to get list of data sources: %s' % e.message) + else: + try: + for service in services: + # Get the schema for this service. + service_id = service['id'] + service_name = service['name'] + schema = congress.datasource_schema_get(request, service_id) + + datasource_tables = [] + for table in schema['tables']: + # Get the columns for this table. + columns = [c['name'] for c in table['columns']] + datasource_table = {'table': table['table_id'], + 'columns': columns} + datasource_tables.append(datasource_table) + + all_columns.append({'datasource': service_name, + 'tables': datasource_tables}) + except Exception as e: + LOG.error('Unable to get schema for data source "%s": %s' % + (service_id, e.message)) + + return all_columns diff --git a/contrib/horizon/datasources/views.py b/contrib/horizon/datasources/views.py index f5a5ee226..b430aebbb 100644 --- a/contrib/horizon/datasources/views.py +++ b/contrib/horizon/datasources/views.py @@ -120,9 +120,9 @@ class DetailView(tables.DataTableView): # Policy data table. rows = congress.policy_rows_list(self.request, datasource_id, table_name) - if congress.SERVICE_TABLE_SEPARATOR in table_name: + if congress.TABLE_SEPARATOR in table_name: table_name_parts = table_name.split( - congress.SERVICE_TABLE_SEPARATOR) + congress.TABLE_SEPARATOR) maybe_datasource_name = table_name_parts[0] datasources = congress.datasources_list(self.request) for datasource in datasources: diff --git a/contrib/horizon/policies/rules/tables.py b/contrib/horizon/policies/rules/tables.py index 505eb71de..cbeb880ba 100644 --- a/contrib/horizon/policies/rules/tables.py +++ b/contrib/horizon/policies/rules/tables.py @@ -28,6 +28,19 @@ from openstack_dashboard import policy LOG = logging.getLogger(__name__) +class CreateRule(tables.LinkAction): + name = 'create_rule' + verbose_name = _('Create Rule') + url = 'horizon:admin:policies:create_rule' + classes = ('ajax-modal',) + icon = 'plus' + policy_rules = (('policy', 'create_rule'),) + + def get_link_url(self, datum=None): + policy_name = self.table.kwargs['policy_name'] + return reverse(self.url, args=(policy_name,)) + + class DeleteRule(policy.PolicyTargetMixin, tables.DeleteAction): @staticmethod def action_present(count): @@ -92,6 +105,6 @@ class PolicyRulesTable(tables.DataTable): class Meta(object): name = "policy_rules" verbose_name = _("Rules") - table_actions = (DeleteRule,) + table_actions = (CreateRule, DeleteRule,) row_actions = (DeleteRule,) hidden_title = False diff --git a/contrib/horizon/policies/rules/views.py b/contrib/horizon/policies/rules/views.py new file mode 100644 index 000000000..afc992f1f --- /dev/null +++ b/contrib/horizon/policies/rules/views.py @@ -0,0 +1,36 @@ +# Copyright 2015 VMware. +# +# 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. + +import logging + +from django.core.urlresolvers import reverse +from horizon import workflows +from openstack_dashboard.dashboards.admin.policies.rules import ( + workflows as rule_workflows) + + +LOG = logging.getLogger(__name__) + + +class CreateView(workflows.WorkflowView): + workflow_class = rule_workflows.CreateRule + ajax_template_name = 'admin/policies/rules/create.html' + success_url = 'horizon:admin:policies:detail' + + def get_success_url(self): + return reverse(self.success_url, + args=(self.kwargs['policy_name'],)) + + def get_initial(self): + return {'policy_name': self.kwargs['policy_name']} diff --git a/contrib/horizon/policies/rules/workflows.py b/contrib/horizon/policies/rules/workflows.py new file mode 100644 index 000000000..cf1aca320 --- /dev/null +++ b/contrib/horizon/policies/rules/workflows.py @@ -0,0 +1,439 @@ +# Copyright 2015 VMware. +# +# 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. + +import logging +import re + +from django.core.urlresolvers import reverse +from django import template +from django.utils.text import slugify +from django.utils.translation import ugettext_lazy as _ +from horizon import forms +from horizon import workflows +from openstack_dashboard.api import congress + + +COLUMN_FORMAT = '%s' % congress.TABLE_SEPARATOR +COLUMN_PATTERN = r'\s*[\w.]+%s[\w.]+\s+[\w.]+\s*$' % congress.TABLE_SEPARATOR +COLUMN_PATTERN_ERROR = 'Column name must be in "%s" format' % COLUMN_FORMAT + +TABLE_FORMAT = '%s
' % congress.TABLE_SEPARATOR +TABLE_PATTERN = r'\s*[\w.]+%s[\w.]+\s*$' % congress.TABLE_SEPARATOR +TABLE_PATTERN_ERROR = 'Table name must be in "%s" format' % TABLE_FORMAT + +LOG = logging.getLogger(__name__) + + +class CreateOutputAction(workflows.Action): + policy_name = forms.CharField(widget=forms.HiddenInput(), required=False) + rule_name = forms.CharField(label=_('Rule Name'), max_length=255, + initial='', required=False) + comment = forms.CharField(label=_('Rule Comment'), initial='', + required=False) + policy_table = forms.CharField(label=_("Policy Table Name"), initial='', + max_length=255) + policy_columns = forms.CharField( + label=_('Policy Table Columns'), initial='', + help_text=_('Name the columns in the output table, one per textbox.')) + failure_url = 'horizon:admin:policies:detail' + + def __init__(self, request, context, *args, **kwargs): + super(CreateOutputAction, self).__init__(request, context, *args, + **kwargs) + self.fields['policy_name'].initial = context['policy_name'] + + class Meta(object): + name = _('Output') + + +class CreateOutput(workflows.Step): + action_class = CreateOutputAction + contributes = ('policy_name', 'rule_name', 'comment', 'policy_table', + 'policy_columns') + template_name = 'admin/policies/rules/_create_output.html' + help_text = _('Information about the rule and the policy table ' + 'being created.') + + def render(self): + # Overriding parent method to add extra template context variables. + step_template = template.loader.get_template(self.template_name) + extra_context = {"form": self.action, + "step": self} + context = template.RequestContext(self.workflow.request, extra_context) + + # Data needed to re-create policy column inputs after an error occurs. + policy_columns = self.workflow.request.POST.get('policy_columns', '') + columns_list = policy_columns.split(', ') + context['policy_columns_list'] = columns_list + context['policy_columns_count'] = len(columns_list) + return step_template.render(context) + + +class CreateConditionsAction(workflows.Action): + mappings = forms.CharField(label=_('Policy table columns:'), initial='') + + class Meta(object): + name = _('Conditions') + + +class CreateConditions(workflows.Step): + action_class = CreateConditionsAction + contributes = ('mappings',) + template_name = 'admin/policies/rules/_create_conditions.html' + help_text = _('Sources from which the output policy table will get its ' + 'data, plus any constraints.') + + def _compare_mapping_columns(self, x, y): + # x = "mapping_column_", y = "mapping_column_" + return cmp(int(x.split('_')[-1]), int(y.split('_')[-1])) + + def render(self): + # Overriding parent method to add extra template context variables. + step_template = template.loader.get_template(self.template_name) + extra_context = {"form": self.action, + "step": self} + context = template.RequestContext(self.workflow.request, extra_context) + + # Data needed to re-create mapping column inputs after an error occurs. + post = self.workflow.request.POST + mappings = [] + policy_columns = post.get('policy_columns') + policy_columns_list = [] + # Policy column to data source mappings. + if policy_columns: + policy_columns_list = policy_columns.split(', ') + mapping_columns = [] + for param, value in post.items(): + if (param.startswith('mapping_column_') and + param != 'mapping_column_0'): + mapping_columns.append(param) + + # Mapping columns should be in the same order as the policy columns + # above to which they match. + sorted_mapping_columns = sorted(mapping_columns, + cmp=self._compare_mapping_columns) + mapping_columns_list = [post.get(c) + for c in sorted_mapping_columns] + mappings = zip(policy_columns_list, mapping_columns_list) + context['mappings'] = mappings + # Add one for the hidden template row. + context['mappings_count'] = len(mappings) + 1 + + # Data needed to re-create join, negation, and alias inputs. + joins = [] + negations = [] + aliases = [] + for param, value in post.items(): + if param.startswith('join_left_') and value: + join_num = param.split('_')[-1] + other_value = post.get('join_right_%s' % join_num) + join_op = post.get('join_op_%s' % join_num) + if other_value and join_op is not None: + joins.append((value, join_op, other_value)) + elif param.startswith('negation_value_') and value: + negation_num = param.split('_')[-1] + negation_column = post.get('negation_column_%s' % + negation_num) + if negation_column: + negations.append((value, negation_column)) + elif param.startswith('alias_column_') and value: + alias_num = param.split('_')[-1] + alias_name = post.get('alias_name_%s' % alias_num) + if alias_name: + aliases.append((value, alias_name)) + + # Make sure there's at least one empty row. + context['joins'] = joins or [('', '')] + context['joins_count'] = len(joins) or 1 + context['negations'] = negations or [('', '')] + context['negations_count'] = len(negations) or 1 + context['aliases'] = aliases or [('', '')] + context['aliases_count'] = len(aliases) or 1 + + # Input validation attributes. + context['column_pattern'] = COLUMN_PATTERN + context['column_pattern_error'] = COLUMN_PATTERN_ERROR + context['table_pattern'] = TABLE_PATTERN + context['table_pattern_error'] = TABLE_PATTERN_ERROR + return step_template.render(context) + + +def _underscore_slugify(name): + # Slugify given string, except using undesrscores instead of hyphens. + return slugify(name).replace('-', '_') + + +class CreateRule(workflows.Workflow): + slug = 'create_rule' + name = _('Create Rule') + finalize_button_name = _('Create') + success_message = _('Created rule%(rule_name)s.%(error)s') + failure_message = _('Unable to create rule%(rule_name)s: %(error)s') + default_steps = (CreateOutput, CreateConditions) + wizard = True + + def get_success_url(self): + policy_name = self.context.get('policy_name') + return reverse('horizon:admin:policies:detail', args=(policy_name,)) + + def get_failure_url(self): + policy_name = self.context.get('policy_name') + return reverse('horizon:admin:policies:detail', args=(policy_name,)) + + def format_status_message(self, message): + rule_name = self.context.get('rule_name') + name_str = '' + if rule_name: + name_str = ' "%s"' % rule_name + else: + rule_id = self.context.get('rule_id') + if rule_id: + name_str = ' %s' % rule_id + return message % {'rule_name': name_str, + 'error': self.context.get('error', '')} + + def _get_schema_columns(self, request, table): + table_parts = table.split(congress.TABLE_SEPARATOR) + datasource = table_parts[0] + table_name = table_parts[1] + try: + schema = congress.datasource_table_schema_get_by_name( + request, datasource, table_name) + except Exception: + # Maybe it's a policy table, not a service. + try: + schema = congress.policy_table_schema_get( + request, datasource, table_name) + except Exception as e: + # Nope. + LOG.error('Unable to get schema for table "%s", ' + 'datasource "%s": %s' % (table_name, datasource, + e.message)) + return e.message + return schema['columns'] + + def handle(self, request, data): + policy_name = data['policy_name'] + username = request.user.username + project_name = request.user.tenant_name + + # Output data. + rule_name = data.get('rule_name') + comment = data.get('comment') + policy_table = _underscore_slugify(data['policy_table']) + if not data['policy_columns']: + self.context['error'] = 'Missing policy table columns' + return False + policy_columns = data['policy_columns'].split(', ') + + # Conditions data. + if not data['mappings']: + self.context['error'] = ('Missing data source column mappings for ' + 'policy table columns') + return False + mapping_columns = [c.strip() for c in data['mappings'].split(', ')] + if len(policy_columns) != len(mapping_columns): + self.context['error'] = ('Missing data source column mappings for ' + 'some policy table columns') + return False + # Map columns used in rule's head. Every column in the head must also + # appear in the body. + head_columns = [_underscore_slugify(c).strip() for c in policy_columns] + column_variables = dict(zip(mapping_columns, head_columns)) + + # All tables needed in the body. + body_tables = set() + negation_tables = set() + + # Keep track of the tables from the head that need to be in the body. + for column in mapping_columns: + if re.match(COLUMN_PATTERN, column) is None: + self.context['error'] = '%s: %s' % (COLUMN_PATTERN_ERROR, + column) + return False + table = column.split()[0] + body_tables.add(table) + + # Make sure columns that are given a significant variable name are + # unique names by adding name_count as a suffix. + name_count = 0 + for param, value in request.POST.items(): + if param.startswith('join_left_') and value: + if re.match(COLUMN_PATTERN, value) is None: + self.context['error'] = '%s: %s' % (COLUMN_PATTERN_ERROR, + value) + return False + value = value.strip() + + # Get operator and other column used in join. + join_num = param.split('_')[-1] + join_op = request.POST.get('join_op_%s' % join_num) + other_value = request.POST.get('join_right_%s' % join_num) + other_value = other_value.strip() + + if join_op == '=': + try: + # Check if static value is a number, but keep it as a + # string, to be used later. + int(other_value) + column_variables[value] = other_value + except ValueError: + # Pass it along as a quoted string. + column_variables[value] = '"%s"' % other_value + else: + # Join between two columns. + if not other_value: + # Ignore incomplete pairing. + continue + if re.match(COLUMN_PATTERN, other_value) is None: + self.context['error'] = ('%s: %s' % + (COLUMN_PATTERN_ERROR, + other_value)) + return False + + # Tables used in the join need to be in the body. + value_parts = value.split() + body_tables.add(value_parts[0]) + body_tables.add(other_value.split()[0]) + + # Arbitrarily name the right column the same as the left. + column_name = value_parts[1] + # Use existing variable name if there is already one for + # either column in this join. + if other_value in column_variables: + column_variables[value] = column_variables[other_value] + elif value in column_variables: + column_variables[other_value] = column_variables[value] + else: + variable = '%s_%s' % (column_name, name_count) + name_count += 1 + column_variables[value] = variable + column_variables[other_value] = variable + + elif param.startswith('negation_value_') and value: + if re.match(COLUMN_PATTERN, value) is None: + self.context['error'] = '%s: %s' % (COLUMN_PATTERN_ERROR, + value) + return False + value = value.strip() + + # Get operator and other column used in negation. + negation_num = param.split('_')[-1] + negation_column = request.POST.get('negation_column_%s' % + negation_num) + if not negation_column: + # Ignore incomplete pairing. + continue + if re.match(COLUMN_PATTERN, negation_column) is None: + self.context['error'] = '%s: %s' % (COLUMN_PATTERN_ERROR, + negation_column) + return False + negation_column = negation_column.strip() + + # Tables for columns referenced by the negation table must + # appear in the body. + value_parts = value.split() + body_tables.add(value_parts[0]) + + negation_tables.add(negation_column.split()[0]) + # Use existing variable name if there is already one for either + # column in this negation. + if negation_column in column_variables: + column_variables[value] = column_variables[negation_column] + elif value in column_variables: + column_variables[negation_column] = column_variables[value] + else: + # Arbitrarily name the negated table's column the same as + # the value column. + column_name = value_parts[1] + variable = '%s_%s' % (column_name, name_count) + name_count += 1 + column_variables[value] = variable + column_variables[negation_column] = variable + + LOG.debug('column_variables for rule: %s' % column_variables) + + # Form the literals for all the tables needed in the body. Make sure + # column that have no relation to any other columns are given a unique + # variable name, using column_count. + column_count = 0 + literals = [] + for table in body_tables: + # Replace column names with variable names that join related + # columns together. + columns = self._get_schema_columns(request, table) + if isinstance(columns, basestring): + self.context['error'] = columns + return False + + literal_columns = [] + if columns: + for column in columns: + table_column = '%s %s' % (table, column['name']) + literal_columns.append( + column_variables.get(table_column, 'col_%s' % + column_count)) + column_count += 1 + literals.append('%s(%s)' % (table, ', '.join(literal_columns))) + else: + # Just the table name, such as for classification:true. + literals.append(table) + + # Form the negated tables. + for table in negation_tables: + columns = self._get_schema_columns(request, table) + if isinstance(columns, basestring): + self.context['error'] = columns + return False + + literal_columns = [] + num_variables = 0 + for column in columns: + table_column = '%s %s' % (table, column['name']) + if table_column in column_variables: + literal_columns.append(column_variables[table_column]) + num_variables += 1 + else: + literal_columns.append('col_%s' % column_count) + column_count += 1 + literal = 'not %s(%s)' % (table, ', '.join(literal_columns)) + literals.append(literal) + + # Every column in the negated table must appear in a non-negated + # literal in the body. If there are some variables that have not + # been used elsewhere, repeat the literal in its non-negated form. + if num_variables != len(columns) and table not in body_tables: + literals.append(literal.replace('not ', '')) + + # All together now. + rule = '%s(%s) %s %s' % (policy_table, ', '.join(head_columns), + congress.RULE_SEPARATOR, ', '.join(literals)) + LOG.info('User %s creating policy "%s" rule "%s" in tenant %s: %s' % + (username, policy_name, rule_name, project_name, rule)) + try: + params = { + 'name': rule_name, + 'comment': comment, + 'rule': rule, + } + rule = congress.policy_rule_create(request, policy_name, + body=params) + LOG.info('Created rule %s' % rule['id']) + self.context['rule_id'] = rule['id'] + except Exception as e: + LOG.error('Error creating policy "%s" rule "%s": %s' % + (policy_name, rule_name, e.message)) + self.context['error'] = e.message + return False + return True diff --git a/contrib/horizon/policies/templates/policies/detail.html b/contrib/horizon/policies/templates/policies/detail.html index d3746e1c2..c4c245c92 100644 --- a/contrib/horizon/policies/templates/policies/detail.html +++ b/contrib/horizon/policies/templates/policies/detail.html @@ -1,4 +1,4 @@ -{% extends 'base.html' %} +{% extends 'admin/base.html' %} {% load i18n %} {% block title %}{% trans "Policy Details" %}{% endblock %} @@ -8,7 +8,10 @@ {% block main %} {% include "admin/policies/_detail_overview.html" %} +
{{ policy_rules_table.render }}
+ + {% endblock %} diff --git a/contrib/horizon/policies/templates/policies/rules/_create_conditions.html b/contrib/horizon/policies/templates/policies/rules/_create_conditions.html new file mode 100644 index 000000000..997b55615 --- /dev/null +++ b/contrib/horizon/policies/templates/policies/rules/_create_conditions.html @@ -0,0 +1,174 @@ + +{{ step.get_help_text }} +{% include 'horizon/common/_form_errors.html' with form=form %} +
+
+
+ + + + {% include 'admin/policies/rules/_mapping_row.html' with form=form count=0 column='' value='' %} + {% for column, value in mappings %}{% include 'admin/policies/rules/_mapping_row.html' with form=form count=forloop.counter column=column value=value %}{% endfor %} + + + +
 
+ {% for error in form.mappings.errors %} + {{ error }} + {% endfor %} +
+ + + + + {% for left, op, right in joins %} + + + + {% endfor %} +
+
+ +
+
+
+ + +
+
+ + +
+ & + + + + + {% for value, column in negations %} + + + + + {% endfor %} +
+
+ + +
+ +
+
+ + +
+
value is in +
+ + +
+
+ +
+ & +{% comment %} + + + + + {% for column, name in aliases %} + + + + + + {% endfor %} +
+
+ +
+
+ {% if forloop.first %}
+ + +
{% endif %} +
+
+ + +
+
as + + + +
+ + +{% endcomment %} + + + + diff --git a/contrib/horizon/policies/templates/policies/rules/_create_output.html b/contrib/horizon/policies/templates/policies/rules/_create_output.html new file mode 100644 index 000000000..d4914c994 --- /dev/null +++ b/contrib/horizon/policies/templates/policies/rules/_create_output.html @@ -0,0 +1,65 @@ + +{{ step.get_help_text }} +{% include 'horizon/common/_form_errors.html' with form=form %} +
+
+
+ + {% if form.rule_name.help_text %} + + {% endif %} + + {% for error in form.rule_name.errors %} + {{ error }} + {% endfor %} +
+ +
+ + {% if form.comment.help_text %} + + {% endif %} + + {% for error in form.comment.errors %} + {{ error }} + {% endfor %} +
+ +
+ + {% if form.policy_table.help_text %} + + {% endif %} + + {% for error in form.policy_table.errors %} + {{ error }} + {% endfor %} +
+ +
+ + {% if form.policy_columns.help_text %} + + {% endif %} + + + {% for column in policy_columns_list %} + + + {% endfor %} + + + +
+ + + +
+ {% for error in form.policy_columns.errors %} + {{ error }} + {% endfor %} +
+ + +
+
+
diff --git a/contrib/horizon/policies/templates/policies/rules/_mapping_row.html b/contrib/horizon/policies/templates/policies/rules/_mapping_row.html new file mode 100644 index 000000000..ed7bea9f2 --- /dev/null +++ b/contrib/horizon/policies/templates/policies/rules/_mapping_row.html @@ -0,0 +1,21 @@ + + + {% if count <= 1 %}
+ + {% if form.mappings.help_text %} + + {% endif %} +
{% endif %} + + {{ column }} + maps to + +
+ + +
+ + + diff --git a/contrib/horizon/policies/templates/policies/rules/create.html b/contrib/horizon/policies/templates/policies/rules/create.html new file mode 100644 index 000000000..b2ffd822c --- /dev/null +++ b/contrib/horizon/policies/templates/policies/rules/create.html @@ -0,0 +1,24 @@ +{% extends 'horizon/common/_workflow.html' %} +{% load i18n %} + +{% block modal-footer %} + {% if workflow.wizard %} +
+ + +
+ +
+ + +
+ {% else %} + + {% if modal %}{% trans "Cancel" %}{% endif %} + {% endif %} +{% endblock %} diff --git a/contrib/horizon/policies/urls.py b/contrib/horizon/policies/urls.py index a08fb23f6..109c4173d 100644 --- a/contrib/horizon/policies/urls.py +++ b/contrib/horizon/policies/urls.py @@ -14,6 +14,8 @@ from django.conf.urls import patterns from django.conf.urls import url +from openstack_dashboard.dashboards.admin.policies.rules import ( + views as rule_views) from openstack_dashboard.dashboards.admin.policies import views @@ -25,4 +27,6 @@ urlpatterns = patterns( url(r'^$', views.IndexView.as_view(), name='index'), url(r'^create/$', views.CreateView.as_view(), name='create'), url(POLICY % 'detail', views.DetailView.as_view(), name='detail'), + url(POLICY % 'rules/create', + rule_views.CreateView.as_view(), name='create_rule'), ) diff --git a/contrib/horizon/policies/views.py b/contrib/horizon/policies/views.py index c9e5dd585..6a3b800f2 100644 --- a/contrib/horizon/policies/views.py +++ b/contrib/horizon/policies/views.py @@ -12,16 +12,19 @@ # License for the specific language governing permissions and limitations # under the License. +import json import logging from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse_lazy +from django.template.defaultfilters import dictsort from django.utils.translation import ugettext_lazy as _ from horizon import exceptions from horizon import forms from horizon import messages from horizon import tables from openstack_dashboard.api import congress +import openstack_dashboard.dashboards.admin.datasources.utils as ds_utils from openstack_dashboard.dashboards.admin.policies import ( forms as policies_forms) from openstack_dashboard.dashboards.admin.policies import ( @@ -91,6 +94,42 @@ class DetailView(tables.DataTableView): messages.error(self.request, msg) redirect = reverse('horizon:admin:policies:index') raise exceptions.Http302(redirect) - context['policy'] = policy + + # Alphabetize and convert list of data source tables and columns into + # JSON formatted string consumable by JavaScript. Do this here instead + # of in the Create Rule form so that the tables and columns lists + # appear in the HTML document before the JavaScript that uses them. + all_tables = ds_utils.get_datasource_tables(self.request) + sorted_datasources = dictsort(all_tables, 'datasource') + tables = [] + for ds in sorted_datasources: + datasource_tables = ds['tables'] + datasource_tables.sort() + for table in ds['tables']: + tables.append('%s%s%s' % (ds['datasource'], + congress.TABLE_SEPARATOR, table)) + context['tables'] = json.dumps(tables) + + datasource_columns = ds_utils.get_datasource_columns(self.request) + sorted_datasources = dictsort(datasource_columns, 'datasource') + columns = [] + for ds in sorted_datasources: + sorted_tables = dictsort(ds['tables'], 'table') + for tbl in sorted_tables: + # Ignore service-derived tables, which are already included. + if congress.TABLE_SEPARATOR in tbl['table']: + continue + table_columns = tbl['columns'] + if table_columns: + table_columns.sort() + else: + # Placeholder name for column when the table has none. + table_columns = ['_'] + + for column in table_columns: + columns.append('%s%s%s %s' % (ds['datasource'], + congress.TABLE_SEPARATOR, + tbl['table'], column)) + context['columns'] = json.dumps(columns) return context diff --git a/contrib/horizon/static/admin/css/policies.css b/contrib/horizon/static/admin/css/policies.css new file mode 100644 index 000000000..3c2ec64c4 --- /dev/null +++ b/contrib/horizon/static/admin/css/policies.css @@ -0,0 +1,134 @@ +/* tables */ +#policy_columns_table { + margin-bottom: 5px; +} +#policy_columns_table td.input-cell { + width: 94%; + padding-left: 0; +} +#policy_columns_table td.button-cell { + padding: 0; + text-align: right; +} + +#policy_columns_table td.input-errors, +#mappings_table td.input-errors { + padding: 0; +} +#policy_columns_table td.borderless, +#mappings_table td.borderless, +#joins_table td.borderless, +#negations_table td.borderless, +#aliases_table td.borderless { + border: none; +} +#mappings_table td.input-cell, +#joins_table td.input-cell, +#negations_table td.input-cell, +#aliases_table td.input-cell { + width: 36%; +} + +#mappings_table td.label-cell { + width: 22%; +} +#mappings_table td.policy-column-name { + width: 28%; + text-align: right; + font-style: italic; +} +#mappings_table td.mapping-text { + width: 10%; + text-align: center; +} + +#joins_table, +#negations_table, +#aliases_table { + margin-top: 30px; + margin-bottom: 5px; +} +#joins_table td.operator-cell, +#negations_table td.operator-cell { + width: 24%; + text-align: center; +} + +#aliases_table td.label-cell { + width: 19%; +} +#aliases_table td.alias-text { + width: 5%; + text-align: center; +} + +/* forms */ +#mappings_table div.form-group, +#joins_table div.form-group, +#negations_table div.form-group, +#aliases_table div.form-group { + margin-bottom: 0; +} +#mappings_table input.form-control, +#joins_table input.form-control, +#negations_table input.form-control, +#aliases_table input.form-control { + padding-right: 36px; +} +#mappings_table div.form-control-feedback, +#joins_table div.form-control-feedback, +#negations_table div.form-control-feedback, +#aliases_table div.form-control-feedback { + background-color: #DDDDDD; + width: 20px; + height: 24px; + top: 5px; + right: 5px; +} +#mappings_table span.caret, +#joins_table span.caret, +#negations_table span.caret, +#aliases_table span.caret { + border-width: 5px; + color: #333333; + margin-bottom: 10px; +} +#add_join_button, +#add_negation_button, +#add_alias_button { + margin-left: 5px; +} + + +/* autocompletion */ +.ui-autocomplete { + max-height: 200px; + overflow-y: auto; + /* prevent horizontal scrollbar */ + overflow-x: hidden; +} +/* IE 6 doesn't support max-height + * we use height instead, but this forces the menu to always be this tall + */ +* html .ui-autocomplete { + height: 200px; +} +.ui-widget { + font-family: inherit; + font-size: inherit; +} +.ui-state-hover, +.ui-widget-content .ui-state-hover, +.ui-widget-header .ui-state-hover, +.ui-state-focus, +.ui-widget-content .ui-state-focus, +.ui-widget-header .ui-state-focus, +.ui-state-active, +.ui-widget-content .ui-state-active, +.ui-widget-header .ui-state-active { + border: 1px solid #285e8e; + background: none; + background-color: #3276b1; + font-weight: normal; + color: #ffffff; +} diff --git a/contrib/horizon/static/admin/js/policies.js b/contrib/horizon/static/admin/js/policies.js new file mode 100644 index 000000000..c20807d10 --- /dev/null +++ b/contrib/horizon/static/admin/js/policies.js @@ -0,0 +1,288 @@ +horizon.policies = { + /* Update input attributes for column name autocompletion. */ + updateColumnAcInput: function($input) { + $input.attr({ + 'placeholder': $input.attr('data-column-example'), + 'pattern': $input.attr('data-pattern'), + 'title': $input.attr('data-pattern-error') + }); + /* form-control-feedback only hidden, so it still has autocompletion. */ + $input.closest('td').find('.form-control-feedback') + .removeClass('hidden'); + }, + + /* Get column names from conditions mappings. */ + getMappedColumns: function() { + var mappings = []; + $('#mappings_table').find('.policy-column-name').each(function() { + var $td = $(this); + var column = $td.text(); + if (column) { + mappings.push(column); + } + }); + return mappings; + }, + + /* Check if any columns need to be removed from conditions mappings. */ + scrubMappedColumns: function(columns) { + mappings = horizon.policies.getMappedColumns(); + if (!columns) { + columns = []; + var $inputs = $('#policy_columns_table').find('.policy-column-input'); + $inputs.each(function() { + var $input = $(this); + var name = $input.val(); + if (name) { + columns.push(name); + } + }); + } + + for (var i = 0; i < mappings.length; i++) { + var name = mappings[i]; + if ($.inArray(name, columns) == -1) { + $('#mappings_table').find('.policy-column-name:contains(' + + name + ')').closest('tr').remove(); + } + } + /* Put label back if there's only one row left without it. */ + var $rows = $('#mappings_table').find('.mapping-row'); + if ($rows.length == 1 && !$rows.find('.label-cell').text()) { + var label = $('#mapping_0').find('.label-cell').html(); + $rows.find('.label-cell').html(label); + } + }, +} + +horizon.addInitFunction(horizon.policies.init = function() { + /* Add another policy table column name. */ + $(document).on('click', '#add_policy_column_button', function(evt) { + evt.preventDefault(); + var $button = $(this); + var $tr = $('#policy_column_0').clone(); + + var count = $button.attr('data-count'); + var cid = parseInt(count); + $button.attr('data-count', cid + 1); + + /* Change ids and reset inputs. */ + $tr.attr('id', 'policy_column_' + cid); + $tr.find('input[name]').val('').each(function() { + this.name = this.name.replace(/^(.+_)\d+$/, '$1' + cid); + }); + $tr.find('.remove-policy-column-button').removeClass('hidden'); + /* Add row before the one reserved for errors. */ + $('#policy_columns_table').find('tr:last').before($tr); + }); + + /* Remove policy table column name input. */ + $(document).on('click', + '#policy_columns_table a.remove-policy-column-button', + function(evt) { + evt.preventDefault(); + var $a = $(this); + var $tr = $a.closest('tr'); + $tr.remove(); + horizon.policies.scrubMappedColumns(); + }); + + /* Add policy table columns to conditions and combine into single param. */ + $(document).on('change', + '#policy_columns_table input.policy-column-input', + function() { + var mappings = horizon.policies.getMappedColumns(); + var columns = []; + + var $inputs = $('#policy_columns_table').find('.policy-column-input'); + $inputs.each(function() { + var $input = $(this); + var name = $input.val(); + /* Does not make sense to have multiple of the same column. */ + if (name && $.inArray(name, columns) == -1) { + columns.push(name); + + if ($.inArray(name, mappings) == -1) { + /* Add mapping inputs for new policy column. */ + var $tr = $('#mapping_0').clone(); + var count = $('#mappings_table').attr('data-count'); + var cid = parseInt(count); + $('#mappings_table').attr('data-count', cid + 1); + + /* Change ids. */ + $tr.attr('id', 'mapping_' + cid).toggleClass('hidden mapping-row'); + $tr.find('.policy-column-name').text(name); + $tr.find('input[id]').each(function() { + this.id = this.id.replace(/^(.+_)\d+$/, '$1' + cid); + this.name = this.id; + }); + /* Remove label if there's already a row with it. */ + if ($('#mappings_table').find('.mapping-row').length) { + $tr.find('.label-cell').empty(); + } + $('#mappings_table').find('tr:last').before($tr); + + /* Add autocompletion. */ + $('#mapping_column_' + cid).autocomplete({ + minLength: 0, + source: JSON.parse($('#ds_columns').text()) + }); + $('#mapping_' + cid).find('.ac div.form-control-feedback') + .click(function() { + /* Focus on list now so that clicking outside of it closes it. */ + $('#mapping_column_' + cid).autocomplete('search', '').focus(); + }); + } + } + }); + + /* Workflow expects one policy_columns value. */ + $('#policy_columns').val(columns.join(', ')); + horizon.policies.scrubMappedColumns(columns); + }); + + /* Add another join. */ + $(document).on('click', '#add_join_button', function(evt) { + evt.preventDefault(); + var $button = $(this); + var $tr = $('#join_0').clone(); + + var count = $button.attr('data-count'); + var cid = parseInt(count); + $button.attr('data-count', cid + 1); + + /* Change ids and reset inputs. */ + $tr.attr('id', 'join_' + cid); + $tr.find('input[id], select[id]').val('').each(function() { + this.id = this.id.replace(/^(.+_)\d+$/, '$1' + cid); + this.name = this.id; + }); + $tr.find('select').val($tr.find('option:first').val()); + $tr.find('.remove-join-button').removeClass('hidden'); + $('#joins_table').append($tr); + + /* Add autocompletion. */ + $('#join_left_' + cid + ', #join_right_' + cid).autocomplete({ + minLength: 0, + source: JSON.parse($('#ds_columns').text()) + }); + horizon.policies.updateColumnAcInput($('#join_right_' + cid)); + $('#join_' + cid).find('.ac div.form-control-feedback').click(function() { + var $div = $(this); + /* Focus on list now so that clicking outside of it closes it. */ + $div.siblings('.ac-columns').autocomplete('search', '').focus(); + }); + }); + + /* Remove join input. */ + $(document).on('click', '#joins_table a.remove-join-button', + function(evt) { + evt.preventDefault(); + var $a = $(this); + var $tr = $a.closest('tr'); + $tr.remove(); + }); + + /* Update input attributes based on type selected. */ + $(document).on('change', '#joins_table select.join-op', function() { + var $select = $(this); + var $input = $select.closest('tr').find('.join-right').val(''); + + if (!$select.val()) { + $input.autocomplete({ + minLength: 0, + source: JSON.parse($('#ds_columns').text()) + }); + horizon.policies.updateColumnAcInput($input); + } else { + $input.closest('td').find('.form-control-feedback').addClass('hidden'); + $input.autocomplete('destroy'); + $input.attr('placeholder', $input.attr('data-static-example')); + $input.removeAttr('pattern').removeAttr('title'); + } + }); + + /* Add another negation. */ + $(document).on('click', '#add_negation_button', function(evt) { + evt.preventDefault(); + var $button = $(this); + var $tr = $('#negation_0').clone(); + + var count = $button.attr('data-count'); + var cid = parseInt(count); + $button.attr('data-count', cid + 1); + + /* Change ids and reset inputs. */ + $tr.attr('id', 'negation_' + cid); + $tr.find('input[id], select[id]').val('').each(function() { + this.id = this.id.replace(/^(.+_)\d+$/, '$1' + cid); + this.name = this.id; + }); + $tr.find('select').val($tr.find('option:first').val()); + $tr.find('.remove-negation-button').removeClass('hidden'); + $('#negations_table').append($tr); + + /* Add autocompletion. */ + $('#negation_value_' + cid + ', #negation_column_' + cid).autocomplete({ + minLength: 0, + source: JSON.parse($('#ds_columns').text()) + }); + $('#negation_' + cid).find('.ac div.form-control-feedback') + .click(function() { + var $div = $(this); + /* Focus on list now so that clicking outside of it closes it. */ + $div.siblings('.ac-columns').autocomplete('search', '').focus(); + }); + }); + + /* Remove negation input. */ + $(document).on('click', '#negations_table a.remove-negation-button', + function(evt) { + evt.preventDefault(); + var $a = $(this); + var $tr = $a.closest('tr'); + $tr.remove(); + }); + + /* Add another alias. */ + $(document).on('click', '#add_alias_button', function(evt) { + evt.preventDefault(); + var $button = $(this); + var $tr = $('#alias_0').clone(); + + var count = $button.attr('data-count'); + var cid = parseInt(count); + $button.attr('data-count', cid + 1); + + /* Change ids and reset inputs. */ + $tr.attr('id', 'alias_' + cid); + $tr.find('td:first').empty(); + $tr.find('input[id]').val('').each(function() { + this.id = this.id.replace(/^(.+_)\d+$/, '$1' + cid); + this.name = this.id; + }); + $tr.find('.remove-alias-button').removeClass('hidden'); + $('#aliases_table').append($tr); + + /* Add autocompletion. */ + $('#alias_column_' + cid).autocomplete({ + minLength: 0, + source: JSON.parse($('#ds_tables').text()) + }); + $('#alias_' + cid).find('.ac div.form-control-feedback') + .click(function() { + var $div = $(this); + /* Focus on list now so that clicking outside of it closes it. */ + $div.siblings('.ac-tables').autocomplete('search', '').focus(); + }); + }); + + /* Remove alias input. */ + $(document).on('click', '#aliases_table a.remove-alias-button', + function(evt) { + evt.preventDefault(); + var $a = $(this); + var $tr = $a.closest('tr'); + $tr.remove(); + }); +}); diff --git a/contrib/horizon/templates/admin/_scripts.html b/contrib/horizon/templates/admin/_scripts.html new file mode 100644 index 000000000..49e294ba6 --- /dev/null +++ b/contrib/horizon/templates/admin/_scripts.html @@ -0,0 +1,5 @@ +{% extends 'horizon/_scripts.html' %} + +{% block custom_js_files %} + +{% endblock %} diff --git a/contrib/horizon/templates/admin/base.html b/contrib/horizon/templates/admin/base.html new file mode 100644 index 000000000..650945fc9 --- /dev/null +++ b/contrib/horizon/templates/admin/base.html @@ -0,0 +1,15 @@ +{% extends 'base.html' %} + +{% block css %} + {% include "_stylesheets.html" %} + + {% load compress %} + {% compress css %} + + + {% endcompress %} +{% endblock %} + +{% block js %} + {% include "admin/_scripts.html" %} +{% endblock %}