<commit_before># Copyright 2015 HP Software, LLC
# All Rights Reserved.
#
# 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 django.utils.translation import ugettext_lazy as _
from django.views.decorators.debug import sensitive_variables  # noqa

from horizon import exceptions
from horizon import forms
from horizon import messages
from horizon.utils import memoized

from openstack_dashboard import api
from openstack_dashboard.contrib.trove import api as trove_api
from openstack_dashboard.contrib.trove.content.databases import db_capability

LOG = logging.getLogger(__name__)


class LaunchForm(forms.SelfHandlingForm):
    name = forms.CharField(label=_("Cluster Name"),
                           max_length=80)
    datastore = forms.ChoiceField(
        label=_("Datastore"),
        help_text=_("Type and version of datastore."),
        widget=forms.Select(attrs={
            'class': 'switchable',
            'data-slug': 'datastore'
        }))
    mongodb_flavor = forms.ChoiceField(
        label=_("Flavor"),
        help_text=_("Size of instance to launch."),
        required=False,
        widget=forms.Select(attrs={
            'class': 'switched',
            'data-switch-on': 'datastore',
        }))
    vertica_flavor = forms.ChoiceField(
        label=_("Flavor"),
        help_text=_("Size of instance to launch."),
        required=False,
        widget=forms.Select(attrs={
            'class': 'switched',
            'data-switch-on': 'datastore',
        }))
    network = forms.ChoiceField(
        label=_("Network"),
        help_text=_("Network attached to instance."),
        required=False)
    volume = forms.IntegerField(
        label=_("Volume Size"),
        min_value=0,
        initial=1,
        help_text=_("Size of the volume in GB."))
    root_password = forms.CharField(
        label=_("Root Password"),
        required=False,
        help_text=_("Password for root user."),
        widget=forms.PasswordInput(attrs={
            'class': 'switched',
            'data-switch-on': 'datastore',
        }))
    num_instances_vertica = forms.IntegerField(
        label=_("Number of Instances"),
        min_value=3,
        initial=3,
        required=False,
        help_text=_("Number of instances in the cluster. (Read only)"),
        widget=forms.TextInput(attrs={
            'readonly': 'readonly',
            'class': 'switched',
            'data-switch-on': 'datastore',
        }))
    num_shards = forms.IntegerField(
        label=_("Number of Shards"),
        min_value=1,
        initial=1,
        required=False,
        help_text=_("Number of shards. (Read only)"),
        widget=forms.TextInput(attrs={
            'readonly': 'readonly',
            'class': 'switched',
            'data-switch-on': 'datastore',
        }))
    num_instances_per_shards = forms.IntegerField(
        label=_("Instances Per Shard"),
        initial=3,
        required=False,
        help_text=_("Number of instances per shard. (Read only)"),
        widget=forms.TextInput(attrs={
            'readonly': 'readonly',
            'class': 'switched',
            'data-switch-on': 'datastore',
        }))

    # (name of field variable, label)
    mongodb_fields = [
        ('mongodb_flavor', _('Flavor')),
        ('num_shards', _('Number of Shards')),
        ('num_instances_per_shards', _('Instances Per Shard'))
    ]
    vertica_fields = [
        ('num_instances_vertica', ('Number of Instances')),
        ('vertica_flavor', _('Flavor')),
        ('root_password', _('<PASSWORD>')),
    ]

    def __init__(self, request, *args, **kwargs):
        super(LaunchForm, self).__init__(request, *args, **kwargs)

        self.fields['datastore'].choices = self.populate_datastore_choices(
            request)
        self.populate_flavor_choices(request)

        self.fields['network'].choices = self.populate_network_choices(
            request)

    def clean(self):
        datastore_field_value = self.data.get("datastore", None)
        if datastore_field_value:
            datastore = datastore_field_value.split(',')[0]

            if db_capability.is_mongodb_datastore(datastore):
                if self.data.get("num_shards", None) < 1:
                    msg = _("The number of shards must be greater than 1.")
                    self._errors["num_shards"] = self.error_class([msg])

            elif db_capability.is_vertica_datastore(datastore):
                if not self.data.get("vertica_flavor", None):
                    msg = _("The flavor must be specified.")
                    self._errors["vertica_flavor"] = self.error_class([msg])
                if not self.data.get("root_password", None):
                    msg = _("Password for root user must be specified.")
                    self._errors["root_password"] = self.error_class([msg])

        return self.cleaned_data

    @memoized.memoized_method
    def datastore_flavors(self, request, datastore_name, datastore_version):
        try:
            return trove_api.trove.datastore_flavors(
                request, datastore_name, datastore_version)
        except Exception:
            LOG.exception("Exception while obtaining flavors list")
            self._flavors = []
            redirect = reverse('horizon:project:database_clusters:index')
            exceptions.handle(request,
                              _('Unable to obtain flavors.'),
                              redirect=redirect)

    def populate_flavor_choices(self, request):
        valid_flavor = []
        for ds in self.datastores(request):
            # TODO(michayu): until capabilities lands
            if db_capability.is_mongodb_datastore(ds.name):<commit_msg>Fix TypeError on comparison on Python 3<commit_after># Copyright 2015 HP Software, LLC
# All Rights Reserved.
#
# 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 django.utils.translation import ugettext_lazy as _
from django.views.decorators.debug import sensitive_variables  # noqa

from horizon import exceptions
from horizon import forms
from horizon import messages
from horizon.utils import memoized

from openstack_dashboard import api
from openstack_dashboard.contrib.trove import api as trove_api
from openstack_dashboard.contrib.trove.content.databases import db_capability

LOG = logging.getLogger(__name__)


class LaunchForm(forms.SelfHandlingForm):
    name = forms.CharField(label=_("Cluster Name"),
                           max_length=80)
    datastore = forms.ChoiceField(
        label=_("Datastore"),
        help_text=_("Type and version of datastore."),
        widget=forms.Select(attrs={
            'class': 'switchable',
            'data-slug': 'datastore'
        }))
    mongodb_flavor = forms.ChoiceField(
        label=_("Flavor"),
        help_text=_("Size of instance to launch."),
        required=False,
        widget=forms.Select(attrs={
            'class': 'switched',
            'data-switch-on': 'datastore',
        }))
    vertica_flavor = forms.ChoiceField(
        label=_("Flavor"),
        help_text=_("Size of instance to launch."),
        required=False,
        widget=forms.Select(attrs={
            'class': 'switched',
            'data-switch-on': 'datastore',
        }))
    network = forms.ChoiceField(
        label=_("Network"),
        help_text=_("Network attached to instance."),
        required=False)
    volume = forms.IntegerField(
        label=_("Volume Size"),
        min_value=0,
        initial=1,
        help_text=_("Size of the volume in GB."))
    root_password = forms.CharField(
        label=_("Root Password"),
        required=False,
        help_text=_("Password for root user."),
        widget=forms.PasswordInput(attrs={
            'class': 'switched',
            'data-switch-on': 'datastore',
        }))
    num_instances_vertica = forms.IntegerField(
        label=_("Number of Instances"),
        min_value=3,
        initial=3,
        required=False,
        help_text=_("Number of instances in the cluster. (Read only)"),
        widget=forms.TextInput(attrs={
            'readonly': 'readonly',
            'class': 'switched',
            'data-switch-on': 'datastore',
        }))
    num_shards = forms.IntegerField(
        label=_("Number of Shards"),
        min_value=1,
        initial=1,
        required=False,
        help_text=_("Number of shards. (Read only)"),
        widget=forms.TextInput(attrs={
            'readonly': 'readonly',
            'class': 'switched',
            'data-switch-on': 'datastore',
        }))
    num_instances_per_shards = forms.IntegerField(
        label=_("Instances Per Shard"),
        initial=3,
        required=False,
        help_text=_("Number of instances per shard. (Read only)"),
        widget=forms.TextInput(attrs={
            'readonly': 'readonly',
            'class': 'switched',
            'data-switch-on': 'datastore',
        }))

    # (name of field variable, label)
    mongodb_fields = [
        ('mongodb_flavor', _('Flavor')),
        ('num_shards', _('Number of Shards')),
        ('num_instances_per_shards', _('Instances Per Shard'))
    ]
    vertica_fields = [
        ('num_instances_vertica', ('Number of Instances')),
        ('vertica_flavor', _('Flavor')),
        ('root_password', _('<PASSWORD>')),
    ]

    def __init__(self, request, *args, **kwargs):
        super(LaunchForm, self).__init__(request, *args, **kwargs)

        self.fields['datastore'].choices = self.populate_datastore_choices(
            request)
        self.populate_flavor_choices(request)

        self.fields['network'].choices = self.populate_network_choices(
            request)

    def clean(self):
        datastore_field_value = self.data.get("datastore", None)
        if datastore_field_value:
            datastore = datastore_field_value.split(',')[0]

            if db_capability.is_mongodb_datastore(datastore):
                if self.data.get("num_shards", 0) < 1:
                    msg = _("The number of shards must be greater than 1.")
                    self._errors["num_shards"] = self.error_class([msg])

            elif db_capability.is_vertica_datastore(datastore):
                if not self.data.get("vertica_flavor", None):
                    msg = _("The flavor must be specified.")
                    self._errors["vertica_flavor"] = self.error_class([msg])
                if not self.data.get("root_password", None):
                    msg = _("Password for root user must be specified.")
                    self._errors["root_password"] = self.error_class([msg])

        return self.cleaned_data

    @memoized.memoized_method
    def datastore_flavors(self, request, datastore_name, datastore_version):
        try:
            return trove_api.trove.datastore_flavors(
                request, datastore_name, datastore_version)
        except Exception:
            LOG.exception("Exception while obtaining flavors list")
            self._flavors = []
            redirect = reverse('horizon:project:database_clusters:index')
            exceptions.handle(request,
                              _('Unable to obtain flavors.'),
                              redirect=redirect)

    def populate_flavor_choices(self, request):
        valid_flavor = []
        for ds in self.datastores(request):
            # TODO(michayu): until capabilities lands
            if db_capability.is_mongodb_datastore(ds.name):
{'fraction_non_alphanumeric': 0.11305110420154668, 'fraction_numerical': 0.0033484812245874193, 'mean_word_length': 2.4699861687413556, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5452350', 'n_tokens_mistral': 3604, 'n_tokens_neox': 3545, 'n_words': 845}