Example #1
0
    def __init__(self, *args, **kwargs):
        super(LaunchForm, self).__init__(*args, **kwargs)
        flavorlist = kwargs.get('initial', {}).get('flavorlist', [])
        self.fields['flavor'] = forms.ChoiceField(
            choices=flavorlist,
            label=_("Flavor"),
            help_text="Size of Image to launch")

        keynamelist = kwargs.get('initial', {}).get('keynamelist', [])
        self.fields['key_name'] = forms.ChoiceField(
            choices=keynamelist,
            label=_("Key Name"),
            required=False,
            help_text="Which keypair to use for authentication")

        securitygrouplist = kwargs.get('initial',
                                       {}).get('securitygrouplist', [])
        self.fields['security_groups'] = forms.MultipleChoiceField(
            choices=securitygrouplist,
            label=_("Security Groups"),
            required=True,
            initial=['default'],
            widget=forms.SelectMultiple(attrs={
                'class': 'chzn-select',
                'style': "min-width: 200px"
            }),
            help_text="Launch instance in these Security Groups")
        # setting self.fields.keyOrder seems to break validation,
        # so ordering fields manually
        field_list = ('name', 'user_data', 'flavor', 'key_name')
        for field in field_list[::-1]:
            self.fields.insert(0, field, self.fields.pop(field))
Example #2
0
class ServiceActionForm(forms.SelfHandlingForm):

    uuid = forms.CharField(label=_("Plugin ID"), widget=forms.HiddenInput)

    name = forms.CharField(
        label=_('Service Name'),
        widget=forms.TextInput(attrs={'readonly': 'readonly'})
    )

    board_list = forms.MultipleChoiceField(
        label=_("Boards List"),
        widget=forms.SelectMultiple(
            attrs={'class': 'switchable', 'data-slug': 'slug-select-boards'}),
        help_text=_("Select boards in this pool")
    )

    action = forms.ChoiceField(
        label=_("Action"),
        choices=[('ServiceEnable', _('Enable')),
                 ('ServiceDisable', _('Disable')),
                 ('ServiceRestore', _('Restore'))],
        widget=forms.Select(
            attrs={'class': 'switchable', 'data-slug': 'slug-action'},
        )
    )

    def __init__(self, *args, **kwargs):

        super(ServiceActionForm, self).__init__(*args, **kwargs)
        # input=kwargs.get('initial',{})

        self.fields["board_list"].choices = kwargs["initial"]["board_list"]

    def handle(self, request, data):

        counter = 0

        for board in data["board_list"]:
            for key, value in self.fields["board_list"].choices:
                if key == board:

                    try:
                        action = iotronic.service_action(request, key,
                                                         data["uuid"],
                                                         data["action"])
                        message_text = action
                        messages.success(request, _(message_text))

                        if counter != len(data["board_list"]) - 1:
                            counter += 1
                        else:
                            return True

                    except Exception:
                        message_text = "Unable to execute action on board " \
                                       + str(value) + "."
                        exceptions.handle(request, _(message_text))

                    break
Example #3
0
class InjectPluginForm(forms.SelfHandlingForm):

    uuid = forms.CharField(label=_("Plugin ID"), widget=forms.HiddenInput)

    name = forms.CharField(
        label=_('Plugin Name'),
        widget=forms.TextInput(attrs={'readonly': 'readonly'})
    )

    onboot = forms.BooleanField(label=_("On Boot"), required=False)

    board_list = forms.MultipleChoiceField(
        label=_("Boards List"),
        widget=forms.SelectMultiple(
            attrs={'class': 'switchable', 'data-slug': 'slug-inject-boards'}),
        help_text=_("Select boards in this pool ")
    )

    def __init__(self, *args, **kwargs):

        super(InjectPluginForm, self).__init__(*args, **kwargs)
        # input=kwargs.get('initial',{})

        boardslist_length = len(kwargs["initial"]["board_list"])

        self.fields["board_list"].choices = kwargs["initial"]["board_list"]
        self.fields["board_list"].max_length = boardslist_length

    def handle(self, request, data):

        counter = 0

        for board in data["board_list"]:
            for key, value in self.fields["board_list"].choices:
                if key == board:

                    try:
                        plugin = None
                        plugin = iotronic.plugin_inject(request, key,
                                                        data["uuid"],
                                                        data["onboot"])
                        # LOG.debug("API: %s %s", plugin, request)
                        message_text = "Plugin injected successfully on " \
                                       "board " + str(value) + "."
                        messages.success(request, _(message_text))

                        if counter != len(data["board_list"]) - 1:
                            counter += 1
                        else:
                            return plugin
                    except Exception:
                        message_text = "Unable to inject plugin on board " \
                                       + str(value) + "."
                        exceptions.handle(request, _(message_text))

                    break
Example #4
0
def add_unit_combos(newprjform):

    unit_table = get_unit_table()
    org_table = settings.HORIZON_CONFIG.get('organization', {})

    if len(unit_table) > 0:

        avail_nets = get_avail_networks(newprjform.request)

        choices_u = list()
        for k, v in unit_table.items():
            if len(avail_nets[k]) > 0:
                choices_u.append((k,v['name']))

        
        newprjform.fields['unit'] = forms.ChoiceField(
            label=_('Available units'),
            required=True,
            choices=choices_u,
            widget=forms.Select(attrs={
                'class': 'switchable',
                'data-slug': 'unitselector'
            })
        )

        for unit_id, unit_data in unit_table.items():

            if len(avail_nets[unit_id]) == 0:
                continue

            newprjform.fields["%s-net" % unit_id] = forms.ChoiceField(
                label=_('Available networks'),
                required=False,
                choices=[ (k,k) for k in avail_nets[unit_id] ],
                widget=forms.Select(attrs={
                    'class': 'switched',
                    'data-switch-on': 'unitselector',
                    'data-unitselector-%s' % unit_id : _('Available networks')
                })
            )

            ou_list = org_table.get(unit_data.get('organization', ""), None)
            if not ou_list:
                continue

            newprjform.fields["%s-ou" % unit_id] = forms.MultipleChoiceField(
                label=_('Unit or department'),
                required=False,
                choices=[ x[:2] for x in ou_list ],
                widget=forms.SelectMultiple(attrs={
                    'class': 'switched',
                    'data-switch-on': 'unitselector',
                    'data-unitselector-%s' % unit_id : _('Unit or department')
                })
            )
Example #5
0
class RemovePluginsForm(forms.SelfHandlingForm):

    uuid = forms.CharField(label=_("Board ID"), widget=forms.HiddenInput)

    name = forms.CharField(
        label=_('Board Name'),
        widget=forms.TextInput(attrs={'readonly': 'readonly'}))

    plugin_list = forms.MultipleChoiceField(
        label=_("Plugins List"),
        widget=forms.SelectMultiple(attrs={
            'class': 'switchable',
            'data-slug': 'slug-remove-plugins'
        }),
        help_text=_("Select plugins in this pool "))

    def __init__(self, *args, **kwargs):

        super(RemovePluginsForm, self).__init__(*args, **kwargs)
        # input=kwargs.get('initial',{})
        self.fields["plugin_list"].choices = kwargs["initial"]["plugin_list"]

    def handle(self, request, data):

        counter = 0

        for plugin in data["plugin_list"]:
            for key, value in self.fields["plugin_list"].choices:
                if key == plugin:

                    try:
                        board = None

                        board = iotronic.plugin_remove(request, data["uuid"],
                                                       key)

                        message_text = "Plugin " + str(value) + \
                                       " removed successfully."
                        messages.success(request, _(message_text))

                        if counter != len(data["plugin_list"]) - 1:
                            counter += 1
                        else:
                            return board
                    except Exception:
                        message_text = "Unable to remove plugin " \
                                       + str(value) + "."
                        exceptions.handle(request, _(message_text))

                    break
Example #6
0
class RemoveServicesForm(forms.SelfHandlingForm):

    uuid = forms.CharField(label=_("Board ID"), widget=forms.HiddenInput)

    name = forms.CharField(
        label=_('Board Name'),
        widget=forms.TextInput(attrs={'readonly': 'readonly'}))

    service_list = forms.MultipleChoiceField(
        label=_("Services List"),
        widget=forms.SelectMultiple(attrs={
            'class': 'switchable',
            'data-slug': 'slug-remove-services'
        }),
        help_text=_("Select services in this pool"))

    def __init__(self, *args, **kwargs):

        super(RemoveServicesForm, self).__init__(*args, **kwargs)
        # input=kwargs.get('initial',{})
        self.fields["service_list"].choices = kwargs["initial"]["service_list"]

    def handle(self, request, data):

        counter = 0

        for service in data["service_list"]:
            for key, value in self.fields["service_list"].choices:
                if key == service:

                    try:
                        disable = iotronic.service_action(
                            request, data["uuid"], key, "ServiceDisable")

                        message_text = disable
                        messages.success(request, _(message_text))

                        if counter != len(data["service_list"]) - 1:
                            counter += 1
                        else:
                            return True

                    except Exception:
                        message_text = "Unable to disable service " \
                                       + str(value) + "."
                        exceptions.handle(request, _(message_text))

                    break
Example #7
0
class DetachPortForm(forms.SelfHandlingForm):

    uuid = forms.CharField(label=_("Board ID"), widget=forms.HiddenInput)

    name = forms.CharField(
        label=_('Board Name'),
        widget=forms.TextInput(attrs={'readonly': 'readonly'}))

    port_list = forms.MultipleChoiceField(
        label=_("Ports List"),
        widget=forms.SelectMultiple(attrs={
            'class': 'switchable',
            'data-slug': 'slug-detacj-ports'
        }),
        help_text=_("Select one or more of the following attached ports"))

    def __init__(self, *args, **kwargs):

        super(DetachPortForm, self).__init__(*args, **kwargs)
        self.fields["port_list"].choices = kwargs["initial"]["ports"]

    def handle(self, request, data):
        # LOG.debug("DATA: %s %s", data, len(data["port_list"]))

        counter = 0

        for port in data["port_list"]:
            try:
                iotronic.detach_port(request, data["uuid"], port)

                message_text = "Detach port " + str(port) + " from board " + \
                               str(data["name"]) + " completed successfully"
                messages.success(request, _(message_text))

                if counter != len(data["port_list"]) - 1:
                    counter += 1
                else:
                    return True

            except Exception:
                message_text = "Unable to detach port " + str(port) + \
                               " from board " + str(data["name"])

                exceptions.handle(request, _(message_text))
Example #8
0
class EnableServiceForm(forms.SelfHandlingForm):

    uuid = forms.CharField(label=_("Board ID"), widget=forms.HiddenInput)

    name = forms.CharField(
        label=_('Board Name'),
        widget=forms.TextInput(attrs={'readonly': 'readonly'}))

    service_list = forms.MultipleChoiceField(
        label=_("Services List"),
        widget=forms.SelectMultiple(attrs={
            'class': 'switchable',
            'data-slug': 'slug-select-services'
        }),
        help_text=_("Add available services from this pool"))

    def __init__(self, *args, **kwargs):
        super(EnableServiceForm, self).__init__(*args, **kwargs)
        self.fields["service_list"].choices = kwargs["initial"]["service_list"]

    def handle(self, request, data):

        counter = 0
        for service in data["service_list"]:
            try:
                action = iotronic.service_action(request, data["uuid"],
                                                 service, "ServiceEnable")

                # message_text = "Service(s) enabled successfully."
                message_text = action
                messages.success(request, _(message_text))

                if counter != len(data["service_list"]) - 1:
                    counter += 1
                else:
                    return True

            except Exception:
                message_text = "Unable to enable service."
                exceptions.handle(request, _(message_text))
Example #9
0
class UnexposeWebserviceForm(forms.SelfHandlingForm):

    uuid = forms.CharField(label=_("Board ID"), widget=forms.HiddenInput)

    name = forms.CharField(
        label=_('Board Name'),
        widget=forms.TextInput(attrs={'readonly': 'readonly'}))

    ws_onboard = forms.MultipleChoiceField(
        label=_("Web Services on board"),
        widget=forms.SelectMultiple(attrs={
            'class': 'switchable',
            'data-slug': 'slug-select-webservices'
        }),
        help_text=_("Select a webservice from the list"))

    def __init__(self, *args, **kwargs):

        super(UnexposeWebserviceForm, self).__init__(*args, **kwargs)
        self.fields["ws_onboard"].choices = kwargs["initial"]["ws_onboard"]

    def handle(self, request, data):

        counter = 0
        for ws in data["ws_onboard"]:
            try:
                iotronic.webservice_unexpose(request, ws)

                message_text = "Web Service(s) unexposed successfully."
                messages.success(request, _(message_text))

                if counter != len(data["ws_onboard"]) - 1:
                    counter += 1
                else:
                    return True

            except Exception:
                LOG.debug("HERE")
                message_text = "Unable to unexpose web service."
                exceptions.handle(request, _(message_text))
    def __init__(self, request, *args, **kwargs):
        super(ReactivateForm, self).__init__(request, *args, **kwargs)

        self.fields['userid'] = forms.CharField(
            label=_("User ID"),
            widget=HiddenInput
        )

        self.fields['expdate'] = forms.DateTimeField(
            label="Expiration date",
            widget=SelectDateWidget(None, get_year_list())
        )

        self.fields['projects'] = forms.MultipleChoiceField(
            label=_('Available projects'),
            required=True,
            widget=forms.SelectMultiple(attrs={'class': 'switched'})
        )

        avail_prjs = list()
        for prj_entry in Project.objects.all():
            avail_prjs.append((prj_entry.projectname, prj_entry.projectname))
        self.fields['projects'].choices = avail_prjs
Example #11
0
class ProjectRequestForm(forms.SelfHandlingForm):

    prjaction = forms.ChoiceField(
        label=_('Project action'),
        choices=[
            ('newprj', _('Create new project')),
        ],
        widget=forms.Select(attrs={
            'class': 'switchable',
            'data-slug': 'actsource'
        }))

    newprj = forms.CharField(label=_('Personal project'),
                             max_length=OS_SNAME_LEN,
                             required=False,
                             widget=forms.TextInput(
                                 attrs={
                                     'class': 'switched',
                                     'data-switch-on': 'actsource',
                                     'data-actsource-newprj': _('Project name')
                                 }))
    prjdescr = forms.CharField(
        label=_("Project description"),
        required=False,
        widget=forms.widgets.Textarea(
            attrs={
                'class': 'switched',
                'data-switch-on': 'actsource',
                'data-actsource-newprj': _('Project description')
            }))
    prjpriv = forms.BooleanField(
        label=_("Private project"),
        required=False,
        initial=False,
        widget=forms.widgets.CheckboxInput(
            attrs={
                'class': 'switched',
                'data-switch-on': 'actsource',
                'data-actsource-newprj': _('Private project')
            }))

    selprj = forms.MultipleChoiceField(
        label=_('Available projects'),
        required=False,
        widget=forms.SelectMultiple(
            attrs={
                'class': 'switched',
                'data-switch-on': 'actsource',
                'data-actsource-selprj': _('Select existing project')
            }),
    )

    notes = forms.CharField(label=_('Notes'),
                            required=False,
                            widget=forms.widgets.Textarea())

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

        auth_prjs = [
            pitem.name for pitem in self.request.user.authorized_tenants
        ]

        pendPReq = PrjRequest.objects.filter(
            registration__userid=self.request.user.id)
        self.pendingProjects = [
            prjreq.project.projectname for prjreq in pendPReq
        ]
        excl_prjs = auth_prjs + self.pendingProjects

        prj_list = Project.objects.exclude(projectname__in=excl_prjs)
        prj_list = prj_list.filter(status=PRJ_PUBLIC, projectid__isnull=False)

        prjEntries = [(prj_entry.projectname, prj_entry.projectname)
                      for prj_entry in prj_list]
        if len(prjEntries):
            self.fields['selprj'].choices = prjEntries
            self.fields['prjaction'].choices = [
                ('newprj', _('Create new project')),
                ('selprj', _('Select existing projects'))
            ]

    @sensitive_variables('data')
    def handle(self, request, data):

        with transaction.atomic():

            registration = Registration.objects.filter(
                userid=request.user.id)[0]

            prj_action = data['prjaction']
            prjlist = list()
            if prj_action == 'selprj':
                for project in data['selprj']:
                    prjlist.append((project, "", PRJ_PUBLIC, False))

            elif prj_action == 'newprj':
                prjlist.append(
                    (data['newprj'], data['prjdescr'],
                     PRJ_PRIVATE if data['prjpriv'] else PRJ_PUBLIC, True))

            newprjlist = list()
            exstprjlist = list()
            for prjitem in prjlist:

                if prjitem[3]:
                    try:

                        prjArgs = {
                            'projectname': prjitem[0],
                            'description': prjitem[1],
                            'status': prjitem[2]
                        }
                        project = Project.objects.create(**prjArgs)
                        newprjlist.append(project.projectname)

                    except IntegrityError:
                        messages.error(
                            request,
                            _("Project %s already exists") % prjitem[0])
                        LOG.error("Cannot create project %s" % prjitem[0])
                        return False

                elif prjitem[0] in self.pendingProjects:
                    continue
                else:
                    project = Project.objects.get(projectname=prjitem[0])
                    exstprjlist.append(project.projectid)

                reqArgs = {
                    'registration': registration,
                    'project': project,
                    'flowstatus': PSTATUS_PENDING,
                    'notes': data['notes']
                }
                reqPrj = PrjRequest(**reqArgs)
                reqPrj.save()

            #
            # Send notification to cloud admins for project creation
            #
            for prj_name in newprjlist:
                noti_params = {
                    'username': request.user.username,
                    'project': prj_name
                }
                noti_sbj, noti_body = notification_render(
                    NEWPRJ_REQ_TYPE, noti_params)
                notifyManagers(noti_sbj, noti_body)

            #
            # Schedule notifications for project managers
            #
            for prj_id in exstprjlist:
                bookNotification(request.user.username, prj_id, MEMBER_REQUEST)

        return True
Example #12
0
class AddMemberAction(workflows.Action):
    pool_id = forms.ChoiceField(label=_("Pool"))
    member_type = forms.ChoiceField(
        label=_("Member Source"),
        choices=[('server_list', _("Select from active instances")),
                 ('member_address', _("Specify member IP address"))],
        required=False,
        widget=forms.Select(attrs={
            'class': 'switchable',
            'data-slug': 'membertype'
        }))
    members = forms.MultipleChoiceField(
        label=_("Member(s)"),
        required=False,
        initial=["default"],
        widget=forms.SelectMultiple(
            attrs={
                'class': 'switched',
                'data-switch-on': 'membertype',
                'data-membertype-server_list': _("Member(s)"),
            }),
        help_text=_("Select members for this pool "))
    address = forms.IPField(
        required=False,
        label=_("Member address"),
        help_text=_("Specify member IP address"),
        widget=forms.TextInput(
            attrs={
                'class': 'switched',
                'data-switch-on': 'membertype',
                'data-membertype-member_address': _("Member address"),
            }),
        initial="",
        version=forms.IPv4 | forms.IPv6,
        mask=False)
    weight = forms.IntegerField(
        max_value=256,
        min_value=1,
        label=_("Weight"),
        required=False,
        help_text=_("Relative part of requests this pool member serves "
                    "compared to others. \nThe same weight will be applied to "
                    "all the selected members and can be modified later. "
                    "Weight must be in the range 1 to 256."))
    protocol_port = forms.IntegerField(
        label=_("Protocol Port"),
        min_value=1,
        help_text=_("Enter an integer value between 1 and 65535. "
                    "The same port will be used for all the selected "
                    "members and can be modified later."),
        validators=[validators.validate_port_range])
    admin_state_up = forms.ChoiceField(choices=[(True, _('UP')),
                                                (False, _('DOWN'))],
                                       label=_("Admin State"))

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

        pool_id_choices = [('', _("Select a Pool"))]
        try:
            tenant_id = self.request.user.tenant_id
            pools = api.lbaas.pool_list(request, tenant_id=tenant_id)
        except Exception:
            pools = []
            exceptions.handle(request, _('Unable to retrieve pools list.'))
        pools = sorted(pools, key=lambda pool: pool.name)
        for p in pools:
            pool_id_choices.append((p.id, p.name))
        self.fields['pool_id'].choices = pool_id_choices

        members_choices = []
        try:
            servers, has_more = api.nova.server_list(request)
        except Exception:
            servers = []
            exceptions.handle(request, _('Unable to retrieve instances list.'))

        if len(servers) == 0:
            self.fields['members'].label = _(
                "No servers available. To add a member, you "
                "need at least one running instance.")
            self.fields['pool_id'].required = False
            self.fields['protocol_port'].required = False
            return

        for m in servers:
            members_choices.append((m.id, m.name))
        self.fields['members'].choices = sorted(members_choices,
                                                key=lambda member: member[1])

    def clean(self):
        cleaned_data = super(AddMemberAction, self).clean()
        if (cleaned_data.get('member_type') == 'server_list'
                and not cleaned_data.get('members')):
            msg = _('At least one member must be specified')
            self._errors['members'] = self.error_class([msg])
        elif (cleaned_data.get('member_type') == 'member_address'
              and not cleaned_data.get('address')):
            msg = _('Member IP address must be specified')
            self._errors['address'] = self.error_class([msg])
        return cleaned_data

    class Meta(object):
        name = _("Add New Member")
        permissions = ('openstack.services.network', )
        help_text = _("Add member(s) to the selected pool.\n\n"
                      "Choose one or more listed instances to be "
                      "added to the pool as member(s). "
                      "Assign a numeric weight and port number for the "
                      "selected member(s) to operate(s) on; e.g., 80. \n\n"
                      "Only one port can be associated with "
                      "each instance.")
Example #13
0
class CreateShareGroupTypeForm(forms.SelfHandlingForm):
    name = forms.CharField(max_length="255", label=_("Name"), required=True)
    group_specs = forms.CharField(
        required=False, label=_("Group specs"),
        widget=forms.widgets.Textarea(attrs=SGT_GROUP_SPECS_FORM_ATTRS))
    share_types = forms.MultipleChoiceField(
        label=_("Share Types"),
        required=True,
        widget=forms.SelectMultiple(attrs={
            "style": "height: 155px;",
        }),
        error_messages={
            'required': _("At least one share type must be specified.")
        })
    is_public = forms.BooleanField(
        label=_("Public"), required=False, initial=True,
        help_text=("Defines whether this share group type is available for "
                   "all or not. List of allowed tenants should be set "
                   "separately."))

    def __init__(self, request, *args, **kwargs):
        super(self.__class__, self).__init__(request, *args, **kwargs)
        manila_features = getattr(settings, 'OPENSTACK_MANILA_FEATURES', {})
        self.enable_public_share_group_type_creation = manila_features.get(
            'enable_public_share_group_type_creation', True)
        if not self.enable_public_share_group_type_creation:
            self.fields.pop('is_public')
        share_type_choices = manila.share_type_list(request)
        self.fields['share_types'].choices = [
            (choice.id, choice.name) for choice in share_type_choices]

    def clean(self):
        cleaned_data = super(CreateShareGroupTypeForm, self).clean()
        return cleaned_data

    def handle(self, request, data):
        try:
            set_dict, unset_list = utils.parse_str_meta(data['group_specs'])
            if unset_list:
                msg = _("Expected only pairs of key=value.")
                raise ValidationError(message=msg)

            is_public = (
                self.enable_public_share_group_type_creation and
                data["is_public"])
            share_group_type = manila.share_group_type_create(
                request, data["name"], share_types=data['share_types'],
                is_public=is_public)
            if set_dict:
                manila.share_group_type_set_specs(
                    request, share_group_type.id, set_dict)

            msg = _("Successfully created share group type: "
                    "%s") % share_group_type.name
            messages.success(request, msg)
            return True
        except ValidationError as e:
            # handle error without losing dialog
            self.api_error(e.messages[0])
            return False
        except Exception:
            exceptions.handle(request, _('Unable to create share group type.'))
            return False
Example #14
0
    def __init__(self, request, *args, **kwargs):

        super(RegistrForm, self).__init__(request, *args, **kwargs)

        self.registr_err = None

        initial = kwargs['initial'] if 'initial' in kwargs else dict()

        self.fields['username'] = forms.CharField(
            label=_('User name'),
            max_length=OS_LNAME_LEN,
            widget=forms.HiddenInput
            if 'username' in initial else forms.TextInput)

        self.fields['federated'] = forms.CharField(max_length=OS_LNAME_LEN,
                                                   widget=forms.HiddenInput)

        self.fields['givenname'] = forms.CharField(
            label=_('First name'),
            max_length=OS_LNAME_LEN,
            widget=forms.HiddenInput
            if 'givenname' in initial else forms.TextInput)

        self.fields['sn'] = forms.CharField(
            label=_('Last name'),
            max_length=OS_LNAME_LEN,
            widget=forms.HiddenInput if 'sn' in initial else forms.TextInput)

        if initial['needpwd']:
            self.fields['pwd'] = forms.RegexField(
                label=_("Password"),
                max_length=PWD_LEN,
                widget=forms.PasswordInput(render_value=False),
                regex=validators.password_validator(),
                error_messages={
                    'invalid': validators.password_validator_msg()
                })

            self.fields['repwd'] = forms.CharField(
                label=_("Confirm Password"),
                max_length=PWD_LEN,
                widget=forms.PasswordInput(render_value=False))

        self.fields['email'] = forms.EmailField(
            label=_('Email Address'),
            max_length=EMAIL_LEN,
            widget=forms.HiddenInput
            if 'email' in initial else forms.TextInput)

        self.fields['prjaction'] = forms.ChoiceField(
            label=_('Project action'),
            #choices = <see later>
            widget=forms.Select(attrs={
                'class': 'switchable',
                'data-slug': 'actsource'
            }))

        self.fields['newprj'] = forms.CharField(
            label=_('Personal project'),
            max_length=OS_SNAME_LEN,
            required=False,
            widget=forms.TextInput(
                attrs={
                    'class': 'switched',
                    'data-switch-on': 'actsource',
                    'data-actsource-newprj': _('Project name')
                }))

        self.fields['prjdescr'] = forms.CharField(
            label=_("Project description"),
            required=False,
            widget=forms.widgets.Textarea(
                attrs={
                    'class': 'switched',
                    'data-switch-on': 'actsource',
                    'data-actsource-newprj': _('Project description')
                }))

        self.fields['prjpriv'] = forms.BooleanField(
            label=_("Private project"),
            required=False,
            initial=False,
            widget=forms.widgets.CheckboxInput(
                attrs={
                    'class': 'switched',
                    'data-switch-on': 'actsource',
                    'data-actsource-newprj': _('Private project')
                }))

        self.fields['selprj'] = forms.MultipleChoiceField(
            label=_('Available projects'),
            required=False,
            widget=forms.SelectMultiple(
                attrs={
                    'class': 'switched',
                    'data-switch-on': 'actsource',
                    'data-actsource-selprj': _('Select existing project')
                }),
        )

        self.fields['organization'] = forms.CharField(
            label=_('Organization'),
            required=True,
            widget=forms.HiddenInput
            if 'organization' in initial else forms.TextInput)

        phone_regex = settings.HORIZON_CONFIG.get(
            'phone_regex', '^\s*\+*[0-9]+[0-9\s.]+\s*$')
        self.fields['phone'] = forms.RegexField(
            label=_('Phone number'),
            required=True,
            regex=phone_regex,
            error_messages={'invalid': _("Wrong phone format")})

        self.fields['contactper'] = forms.CharField(label=_('Contact person'),
                                                    required=False)

        self.fields['notes'] = forms.CharField(label=_('Notes'),
                                               required=False,
                                               widget=forms.widgets.Textarea())

        self.fields['aupok'] = forms.CharField(widget=forms.HiddenInput,
                                               initial='reject')

        import_guest_project()

        missing_guest = True
        avail_prjs = list()
        for prj_entry in Project.objects.exclude(status=PRJ_PRIVATE):
            if prj_entry.status == PRJ_GUEST:
                missing_guest = False
            elif prj_entry.projectid:
                avail_prjs.append(
                    (prj_entry.projectname, prj_entry.projectname))

        self.fields['selprj'].choices = avail_prjs

        if missing_guest:
            p_choices = [('selprj', _('Select existing projects')),
                         ('newprj', _('Create new project'))]
        else:
            p_choices = [('selprj', _('Select existing projects')),
                         ('newprj', _('Create new project')),
                         ('guestprj', _('Use guest project'))]

        self.fields['prjaction'].choices = p_choices
Example #15
0
class CallPluginForm(forms.SelfHandlingForm):

    uuid = forms.CharField(label=_("Plugin ID"), widget=forms.HiddenInput)

    name = forms.CharField(
        label=_('Plugin Name'),
        widget=forms.TextInput(attrs={'readonly': 'readonly'})
    )

    board_list = forms.MultipleChoiceField(
        label=_("Boards List"),
        widget=forms.SelectMultiple(
            attrs={'class': 'switchable', 'data-slug': 'slug-call-boards'}),
        help_text=_("Select boards in this pool ")
    )

    parameters = forms.CharField(
        label=_("Parameters"),
        required=False,
        widget=forms.Textarea(
            attrs={'class': 'switchable',
                   'data-slug': 'slug-callplugin-json'}),
        help_text=_("Plugin parameters")
    )

    def __init__(self, *args, **kwargs):

        super(CallPluginForm, self).__init__(*args, **kwargs)
        # input=kwargs.get('initial',{})

        boardslist_length = len(kwargs["initial"]["board_list"])

        self.fields["board_list"].choices = kwargs["initial"]["board_list"]
        self.fields["board_list"].max_length = boardslist_length

    def handle(self, request, data):

        counter = 0

        if not data["parameters"]:
            data["parameters"] = {}
        else:
            data["parameters"] = json.loads(data["parameters"])

        for board in data["board_list"]:
            for key, value in self.fields["board_list"].choices:
                if key == board:

                    try:
                        plugin = None
                        plugin = iotronic.plugin_action(request, key,
                                                        data["uuid"],
                                                        "PluginCall",
                                                        data["parameters"])
                        # LOG.debug("API: %s %s", plugin, request)
                        message_text = "Plugin called successfully on board " \
                                       + str(value) + "."
                        messages.success(request, _(message_text))

                        if counter != len(data["board_list"]) - 1:
                            counter += 2
                        else:
                            return plugin
                    except Exception:
                        message_text = "Unable to call plugin on board " \
                                       + str(value) + "."
                        exceptions.handle(request, _(message_text))

                    break
Example #16
0
class StopPluginForm(forms.SelfHandlingForm):

    uuid = forms.CharField(label=_("Plugin ID"), widget=forms.HiddenInput)

    name = forms.CharField(
        label=_('Plugin Name'),
        widget=forms.TextInput(attrs={'readonly': 'readonly'})
    )

    delay = forms.IntegerField(
        label=_("Delay in secs"),
        required=False,
        help_text=_("OPTIONAL: seconds to wait before stopping the plugin")
    )

    board_list = forms.MultipleChoiceField(
        label=_("Boards List"),
        widget=forms.SelectMultiple(
            attrs={'class': 'switchable', 'data-slug': 'slug-stop-boards'}),
        help_text=_("Select boards in this pool ")
    )

    def __init__(self, *args, **kwargs):

        super(StopPluginForm, self).__init__(*args, **kwargs)
        # input=kwargs.get('initial',{})

        boardslist_length = len(kwargs["initial"]["board_list"])

        self.fields["board_list"].choices = kwargs["initial"]["board_list"]
        self.fields["board_list"].max_length = boardslist_length

    def handle(self, request, data):

        counter = 0

        if not data["delay"]:
            data["delay"] = {}
        else:
            data["delay"] = {"delay": data["delay"]}

        for board in data["board_list"]:
            for key, value in self.fields["board_list"].choices:
                if key == board:

                    try:
                        plugin = None
                        plugin = iotronic.plugin_action(request, key,
                                                        data["uuid"],
                                                        "PluginStop",
                                                        data["delay"])
                        # LOG.debug("API: %s %s", plugin, request)
                        message_text = "Plugin stopped successfully on board "\
                                       + str(value) + "."
                        messages.success(request, _(message_text))

                        if counter != len(data["board_list"]) - 1:
                            counter += 1
                        else:
                            return plugin
                    except Exception:
                        message_text = "Unable to stop plugin on board " \
                                       + str(value) + "."
                        exceptions.handle(request, _(message_text))

                    break