Ejemplo n.º 1
0
class CreateBoardForm(forms.SelfHandlingForm):
    name = forms.CharField(label=_("Board Name"))
    code = forms.CharField(label=_("Registration Code"),
                           help_text=_("Registration code"))

    # MODIFY ---> options: yun, server
    type = forms.ChoiceField(
        label=_("Type"),
        # choices=[('yun', _('YUN')), ('server', _('Server'))],
        choices=[('gateway', _('Gateway')), ('server', _('Server'))],
        widget=forms.Select(attrs={
            'class': 'switchable',
            'data-slug': 'slug-type'
        }, ))
    """
    mobile = forms.ChoiceField(
        label=_("Mobile"),
        choices =[('false', _('False')), ('true', _('True'))],
        widget=forms.Select(
            attrs={'class': 'switchable', 'data-slug': 'slug-mobile'},
        )
    )
    """
    mobile = forms.BooleanField(label=_("Mobile"), required=False)

    latitude = forms.FloatField(label=_("Latitude"))
    longitude = forms.FloatField(label=_("Longitude"))
    altitude = forms.FloatField(label=_("Altitude"))

    def handle(self, request, data):
        try:

            # Float
            # data["location"] = [{"latitude": data["latitude"],
            #                      "longitude": data["longitude"],
            #                      "altitude": data["altitude"]}]
            # String
            data["location"] = [{
                "latitude": str(data["latitude"]),
                "longitude": str(data["longitude"]),
                "altitude": str(data["altitude"])
            }]

            iotronic.board_create(request, data["code"], data["mobile"],
                                  data["location"], data["type"], data["name"])

            messages.success(request, _("Board created successfully."))
            return True

        except Exception:
            exceptions.handle(request, _('Unable to create board.'))
Ejemplo n.º 2
0
class ModifyDiscountForm(forms.SelfHandlingForm):

    id = forms.CharField(label=_("ID"), widget=forms.HiddenInput())
    name = forms.CharField(max_length=255, label=_("Name"))
    code = forms.CharField(max_length=32, label=_("Code"))
    discount_type_id = forms.ChoiceField(label = _('Discount Type'), choices=[])
    expiration_date = forms.DateField(label=_('Expiration Date'), required=False)
    amt = forms.FloatField(label=_('Amount'))
    notes = forms.CharField(max_length=255, label=_("Notes"), required=False)

    def __init__(self, request, *args, **kwargs):
        super(ModifyDiscountForm, self).__init__(request, *args, **kwargs)
        # set discount types
        self.fields['discount_type_id'].choices = gen_discount_types(request)

    def handle(self, request, data):
        data['expiration_date'] = str(data['expiration_date'])
        type_id = data.pop('id', None)
        if not type_id:
            exceptions.handle(request, _('Invalid request.'))
            return False
        try:
            modify_discount(request, type_id, data)
            return True

        except Exception:
            exceptions.handle(request, _('Unable to modify discount type.'))
Ejemplo n.º 3
0
class CreateBillForm(BaseBillForm):
    name = forms.CharField(label=_("Name"))
    region = forms.CharField(label=_("Region"))
    payment_type = forms.CharField(label=_("Payment Type"))
    order_unit = forms.CharField(label=_("Order Unit"))
    order_size = forms.IntegerField(label=_("Order Size"))
    price = forms.FloatField(label=_("Price"))

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

    # We have to protect the entire "data" dict because it contains the
    # password and confirm_password strings.
    @sensitive_variables('data')
    def handle(self, request, data):
        try:
            LOG.info('Creating bill with name "%s"' % data['name'])
            new_bill = bills(
                name=data['name'],
                region=data['region'],
                payment_type=data['payment_type'],
                order_unit=data['order_unit'],
                order_size=data['order_size'],
                price=data['price'],
            )
            new_bill.save()
            messages.success(
                request,
                _('Bill "%s" was successfully created.') % data['name'])
            return new_bill
        except:
            exceptions.handle(request, _('Unable to create bill.'))
Ejemplo n.º 4
0
class CreateDiscountForm(forms.SelfHandlingForm):

    name = forms.CharField(max_length=255, label=_("Name"))
    code = forms.CharField(max_length=32, label=_("Code"))
    discount_type_id = forms.ChoiceField(label=_('Discount Type'), choices=[])
    expiration_date = forms.DateField(label=_('Expiration Date (yyyy-mm-dd)'),
                                      required=False)
    amt = forms.FloatField(label=_('Amount'))
    notes = forms.CharField(max_length=255, label=_("Notes"), required=False)

    def __init__(self, request, *args, **kwargs):
        super(CreateDiscountForm, self).__init__(request, *args, **kwargs)
        # set discount types
        self.fields['discount_type_id'].choices = gen_discount_types(request)

    def handle(self, request, data):
        data['expiration_date'] = str(data['expiration_date'])

        # Check the expiration date
        if data['expiration_date'] == '' or data['expiration_date'] == 'None':
            data['expiration_date'] = None

        try:
            create_discount(request, data)
            return True

        except Exception:
            exceptions.handle(request, _('Unable to create discount type.'))
Ejemplo n.º 5
0
class MediaUpdateForm(forms.Form):
    id = forms.IntegerField(min_value=1)
    title = forms.CharField(max_length=128, required=False)
    subtitle = forms.CharField(max_length=128, required=False)
    description = forms.CharField(required=False)

    template_type = forms.ChoiceField(choices=((1, 1),
                                               (2, 2)),
                                      required=False)
    # 标签:数据格式为JSON字符串,如:[1, 2, 3]  (值为标签ID)
    tags = forms.CharField(required=False)
    # 资源热度
    temperature = forms.FloatField(min_value=0.1, max_value=10.0, required=False)
    # 票房预测
    box_office_forecast = forms.FloatField(min_value=0.1, max_value=5.0, required=False)
    # 口碑预测
    public_praise_forecast = forms.FloatField(min_value=0.1, max_value=5.0, required=False)
    # ROI 投资回报比 例如:1:5 (1比5)
    roi = forms.CharField(max_length=10, required=False)
    # 题材类别
    theme_type_id = forms.IntegerField(min_value=1, required=False)
    # 项目进度
    progress_id = forms.IntegerField(min_value=1, required=False)

    # 资源概述 数据格式为字典形式的JSON字符串,如:{"导演": "冯小刚, 吴宇森",
    #                                        "主演": "成龙, 李连杰",
    #                                        "出演": "巩俐, 章子怡", ......}
    media_outline = forms.CharField(required=False)
    # 预计上映/播出时间
    air_time = forms.DateTimeField(required=False)
    # 运营标记 0: 未设定 1:热门
    mark = forms.ChoiceField(choices=((0, 1),
                                      (1, 2)),
                             required=False)
    # 电影表现大数据分析 数据格式为字典形式的JSON字符串,如:{"导演号召力": 3.5,
    #                                                "男主角号召力": 4.0,
    #                                                "女主角号召力": 4.2,
    #                                                "类型关注度": 3.8,
    #                                                "片方指数": 3.7}
    film_performance = forms.CharField(max_length=512, required=False)
    picture = forms.ImageField(required=False)
Ejemplo n.º 6
0
class UpdateBillForm(BaseBillForm):
    id = forms.CharField(label=_("ID"), widget=forms.HiddenInput)
    name = forms.CharField(label=_("Name"))
    region = forms.CharField(label=_("Region"))
    payment_type = forms.CharField(label=_("Payment Type"))
    order_unit = forms.CharField(label=_("Order Unit"))
    order_size = forms.IntegerField(label=_("Order Size"))
    price = forms.FloatField(label=_("Price"))
    enabled = forms.BooleanField(label="Enabled", required=False)

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

        if api.keystone_can_edit_user() is False:
            for field in ('name', 'Region', 'payment_type', 'order_unit',
                          'order_size', 'price'):
                self.fields.pop(field)

    # We have to protect the entire "data" dict because it contains the
    # password and confirm_password strings.
    @sensitive_variables('data')
    def handle(self, request, data):
        failed, succeeded = [], []
        user_is_editable = api.keystone_can_edit_user()
        bill_id = data.pop('id')
        if user_is_editable:
            msg_bits = (_('name'), _('email'))
            try:
                new_bill = bills(id=bill_id,
                                 name=data['name'],
                                 region=data['region'],
                                 payment_type=data['payment_type'],
                                 order_unit=data['order_unit'],
                                 order_size=data['order_size'],
                                 price=data['price'],
                                 enabled=data['enabled'])
                new_bill.save()
                succeeded.extend(msg_bits)
            except:
                failed.append(msg_bits)
                exceptions.handle(request, _('Unable to create bill.'))

        if succeeded:
            messages.success(request, _('Bill has been updated successfully.'))
        if failed:
            failed = map(force_unicode, failed)
            messages.error(
                request,
                _('Unable to update %(attributes)s for the bill.') %
                {"attributes": ", ".join(failed)})
        return True
Ejemplo n.º 7
0
class UpdateAlarm(forms.SelfHandlingForm):
    id = forms.CharField(
        label=_("ID"), widget=forms.TextInput(attrs={'readonly': 'readonly'}))
    name = forms.CharField(label=_("Name"),
                           min_length=1,
                           max_length=255,
                           required=True)
    description = forms.CharField(label=_("Description"),
                                  min_length=1,
                                  max_length=255,
                                  required=False)
    aggregation = forms.ChoiceField(label=_("Aggregation"),
                                    choices=array_to_choices(
                                        scaling_resources.ALARM_AGGREGATIONS),
                                    required=True)
    measurement = forms.ChoiceField(label=_("Measurement"),
                                    choices=array_to_choices(
                                        scaling_resources.ALARM_MEASUREMENTS),
                                    required=True)
    operator = forms.ChoiceField(
        label=_("Operator"),
        choices=array_to_choices(scaling_resources.ALARM_OPERATORS),
        required=True,
    )
    threshold = forms.FloatField(label=_("Threshold"), required=True)
    unit = forms.DynamicChoiceField(label=_("Unit"),
                                    choices=array_to_choices(
                                        scaling_resources.ALARM_UNITS),
                                    required=True)
    period = forms.IntegerField(label=_("Period"), required=True)
    period_unit = forms.ChoiceField(label=_("Period Unit"),
                                    choices=array_to_choices(
                                        scaling_resources.ALARM_PERIOD_UNITS),
                                    required=True)

    failure_url = "horizon:project:a10scaling:index"
    success_url = "horizon:project:a10scaling:index"

    def handle(self, request, context):
        try:
            alarm = api.update_a10_scaling_alarm(request, **context)
            msg = _("Scaling Alarm {0} was successfully updated").format(
                context["name"])
            messages.success(request, msg)
            return alarm
        except Exception as ex:
            msg = _("Failed to update Scaling Action")
            LOG.exception(ex)
            redirect = reverse_lazy(self.failure_url)
            exceptions.handle(request, msg, redirect=redirect)
Ejemplo n.º 8
0
class ModifyBillingInvoiceForm(forms.SelfHandlingForm):

    id = forms.CharField(label=_("ID"), widget=forms.HiddenInput())
    balance_amt = forms.FloatField(label=_('Balance'))
    amt_paid = forms.FloatField(label=_('Paid'))
    notes = forms.CharField(label=_('Notes'))
    status = forms.ChoiceField(label=_('Account'), choices=status_choices)

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

    def handle(self, request, data):
        id = data.pop('id', None)
        if not id:
            exceptions.handle(request, _('Invalid request.'))
            return False

        try:
            modify_invoice(request, id, data)
            return True

        except Exception:
            exceptions.handle(request, _('Unable to modify invoice.'))
Ejemplo n.º 9
0
class AddAlarmAction(workflows.Action):
    name = forms.CharField(label=_("Name"),
                           min_length=1,
                           max_length=255,
                           required=True)
    description = forms.CharField(label=_("Description"),
                                  min_length=1,
                                  max_length=255,
                                  required=False)
    aggregation = forms.DynamicChoiceField(
        label=_("Aggregation"),
        choices=map(lambda x: (x, x), scaling_resources.ALARM_AGGREGATIONS),
        required=True)
    measurement = forms.ChoiceField(label=_("Measurement"),
                                    choices=map(
                                        lambda x: (x, x),
                                        scaling_resources.ALARM_MEASUREMENTS),
                                    required=True)
    operator = forms.ChoiceField(
        label=_("Operator"),
        choices=map(lambda x: (x, x), scaling_resources.ALARM_OPERATORS),
        required=True,
    )
    threshold = forms.FloatField(label=_("Threshold"), required=True)
    unit = forms.DynamicChoiceField(label=_("Unit"),
                                    choices=map(lambda x: (x, x),
                                                scaling_resources.ALARM_UNITS),
                                    required=True)
    period = forms.IntegerField(label=_("Period"), required=True)
    period_unit = forms.ChoiceField(label=_("Period Unit"),
                                    choices=map(
                                        lambda x: (x, x),
                                        scaling_resources.ALARM_PERIOD_UNITS),
                                    required=True)

    class Meta(object):
        name = _("Create New Scaling Alarm")
        # TODO(mdurrant) - Add a10-specific permissions
        permissions = ("openstack.services.network", )
        help_text = _("Specify the details for the scaling action below")
Ejemplo n.º 10
0
class UpdateInvoice(forms.SelfHandlingForm):

    #Defining the form fields
    invoice_id = forms.CharField(
        label=_("Invoice ID"),
        widget=forms.TextInput(attrs={'readonly': 'readonly'}),
        required=False)
    paid_cost = forms.FloatField(label=_("Paid  Cost"))
    paid_status = (('0', 'New'), ('1', 'Paid'), ('2', 'Declined'),
                   ('3', 'Refunded'))
    payment_status = forms.ChoiceField(choices=paid_status, required=True)

    def handle(self, request, data):
        """
        method : handle
        desc: To handle the update
        params:
            self - self
            request - request data
            data - update datas
        return: Update o/p
        """

        try:

            #Making the connection with the cloudkitty
            cloudkitty_conn = kittyapi.cloudkittyclient(self.request)

            #updating the invoice
            invoice = cloudkitty_conn.reports.update_invoice(
                invoice_id=data['invoice_id'],
                payment_status=data['payment_status'],
                paid_cost=data['paid_cost'])
            return invoice
        except Exception:
            exceptions.handle(request, _('Unable to update invoice.'))
Ejemplo n.º 11
0
class TagConfigureInputForm(forms.Form):
    tag_id = forms.IntegerField(min_value=1)
    attribute_id = forms.IntegerField(min_value=1)
    match_value = forms.FloatField(min_value=0.1, max_value=5.0)
Ejemplo n.º 12
0
class DecompositionAction(workflows.Action):
    xyz_validator = RegexValidator(regex='^([0-9]+) ([0-9]+) ([0-9]+)$',
                                   message='Number of subdomains in "x y z" format. Example "2 1 2"')

    subdomains = forms.IntegerField(
        label=_('Total number of subdomains'),
        required=False,
        min_value=1,
    )

    decomposition_method = forms.ChoiceField(
        label=_('Decomposition method'),
        required=False,
        help_text=_('OpenFOAM decomposition method')
    )

    n = forms.CharField(
        label=_('Number of subdomains in x, y, z'),
        required=False,
        help_text=_('Number of subdomains in x, y, z'),
        validators=[xyz_validator]
    )

    delta = forms.FloatField(
        label=_('Delta'),
        required=False,
        help_text=_('Cell skew factor'),
        min_value=0
    )

    order = forms.ChoiceField(
        label=_('Order'),
        required=False,
        help_text=_('Order of decomposition')
    )

    strategy = forms.CharField(
        label=_('Strategy'),
        required=False,
        help_text=_('Decomposition strategy: optional and complex')
    )

    processor_weights = forms.CharField(
        label=_('Processor weights'),
        required=False,
        help_text=_(
            'List of weighting factors for allocation of cells to processors; <wt1> is the weighting factor for '
            'processor 1, etc. ; weights are normalised so can take any range of values.')
    )

    datafile = forms.CharField(
        label=_('Data file'),
        required=False,
        help_text=_('Name of file containing data of allocation of cells to processors ')
    )

    class Meta:
        name = _('Decomposition method customization')

    def __init__(self, request, context, *args, **kwargs):
        self.request = request
        self.context = context

        super(DecompositionAction, self).__init__(
            request, context, *args, **kwargs)

    def populate_decomposition_method_choices(self, request, context):
        return [('', _("select"))] + \
               [('simple', _("Simple")),
                ('hierarchical', _("Hierarchical")),
                ('scotch', _("Scotch")),
                ('manual', _("Manual"))]

    def populate_order_choices(self, request, context):
        return [('xyz', _('xyz')),
                ('xzy', _('xzy')),
                ('yxz', _('yxz')),
                ('yzx', _('yzx')),
                ('zxy', _('zxy')),
                ('zyx', _('zyx'))]
Ejemplo n.º 13
0
class AdjustCoefficientActionForm(forms.Form):
    id = forms.IntegerField(min_value=1)
    value = forms.FloatField(min_value=0.01, max_value=1.50)
Ejemplo n.º 14
0
class MediaInputForm(forms.Form):
    title = forms.CharField(max_length=128)
    subtitle = forms.CharField(max_length=128)
    description = forms.CharField(required=False)

    template_type = forms.ChoiceField(choices=((1, 1),
                                               (2, 2)),
                                      error_messages={
                                          'required': 'Template type must in [1, 2]'
                                      },
                                      required=False)
    # 标签:数据格式为JSON字符串,如:[1, 2, 3]  (值为标签ID)
    tags = forms.CharField()

    # 资源热度
    temperature = forms.FloatField(min_value=0.1, max_value=10.0)
    # 票房预测
    box_office_forecast = forms.FloatField(min_value=0.1, max_value=5.0)
    # 口碑预测
    public_praise_forecast = forms.FloatField(min_value=0.1, max_value=5.0)
    # ROI 投资回报比 例如:1:5 (1比5)
    roi = forms.CharField(max_length=10)

    # # 资源类型
    # media_type_id = forms.IntegerField(min_value=1)
    # 题材类别
    theme_type_id = forms.IntegerField(min_value=1)
    # 项目进度
    progress_id = forms.IntegerField(min_value=1)

    # # 导演:数据格式为JSON字符串,如:['斯皮尔伯格', '冯小刚']
    # director = forms.CharField(max_length=256)
    # # 主演:数据格式为JSON字符串,如:['汤姆克鲁斯', '威尔史密斯', '皮尔斯布鲁斯南']
    # stars = forms.CharField(max_length=256)
    # # 演员:数据格式为JSON字符串,如:['王晓霞', '詹姆斯', '韦德']
    # actors = forms.CharField(max_length=256)
    # # 监制:数据格式为JSON字符串,如:['欧文']
    # producer = forms.CharField(max_length=256)
    # # 出品公司:数据格式为JSON字符串,如:['华文映像', '福星传媒']
    # production_company = forms.CharField(max_length=256)
    #
    # # 预计开机/录制时间
    # recorded_time = forms.DateTimeField()

    # 资源概述 数据格式为字典形式的JSON字符串,如:{"导演": "冯小刚, 吴宇森",
    #                                        "主演": "成龙, 李连杰",
    #                                        "出演": "巩俐, 章子怡", ......}
    media_outline = forms.CharField(required=False)

    # 预计上映/播出时间
    air_time = forms.DateTimeField()
    # # 预计播出平台:数据格式为JSON字符串,如:['一线卫视', '视频网络渠道']
    # play_platform = forms.CharField(max_length=256)

    # 运营标记 0: 未设定 1:热门
    mark = forms.ChoiceField(choices=((0, 1),
                                      (1, 2)),
                             error_messages={
                                 'required': 'mark must in [0, 1]'
                             })

    # 电影表现大数据分析 数据格式为字典形式的JSON字符串,如:{"导演号召力": 3.5,
    #                                                "男主角号召力": 4.0,
    #                                                "女主角号召力": 4.2,
    #                                                "类型关注度": 3.8,
    #                                                "片方指数": 3.7}
    film_performance = forms.CharField(max_length=512, required=False)

    picture = forms.ImageField(required=False)
Ejemplo n.º 15
0
class TagConfigureUpdateForm(forms.Form):
    id = forms.IntegerField(min_value=1)
    # attribute_id = forms.IntegerField(min_value=1, required=False)
    match_value = forms.FloatField(min_value=0.1, max_value=5.0, required=False)
Ejemplo n.º 16
0
class ModifyPlanForm(forms.SelfHandlingForm):

    id = forms.CharField(label=_("ID"), widget=forms.HiddenInput())
    name = forms.CharField(max_length=255, label=_("Name"))
    code = forms.CharField(max_length=32, label=_("Code"))
    service_type = forms.ChoiceField(label = _('Service Type'), choices=[])
    rate = forms.FloatField(label=_('Rate'))
    setup_fee = forms.FloatField(label=_('Setup Fee'), required=False)
    billing_type = forms.ChoiceField(
        label = _('Billing Type'),
        choices=[],
        required=False,
        widget=forms.Select(attrs={
            'class': 'switchable',
            'data-slug': 'billing_type'
        })
    )
    ref_id = forms.ChoiceField(
        label = _('Flavor'),
        choices=[],
        required=False,
        widget=forms.Select(attrs={
            'class': 'switched',
            'data-switch-on': 'billing_type',
            'data-billing_type-1': _('Flavor')
        })
    )
    attr_instances = forms.FloatField(
        label=_("Instances"),
        required=False,
        widget=forms.NumberInput(attrs={
            'step': 1,
            'class': 'switched',
            'data-switch-on': 'billing_type',
            'data-billing_type-2': _('Instances')
        })
    )
    attr_cpu = forms.FloatField(
        label=_("CPU"),
        required=False,
        widget=forms.NumberInput(attrs={
            'step': 1,
            'class': 'switched',
            'data-switch-on': 'billing_type',
            'data-billing_type-2': _('CPU')
        })
    )
    attr_ram = forms.FloatField(
        label=_("RAM (MB)"),
        required=False,
        widget=forms.NumberInput(attrs={
            'step': 1,
            'class': 'switched',
            'data-switch-on': 'billing_type',
            'data-billing_type-2': _('RAM (GB)')
        })
    )
    attr_storage = forms.FloatField(
        label=_("Storage (GB)"),
        required=False,
        widget=forms.NumberInput(attrs={
            'step': 1,
            'class': 'switched',
            'data-switch-on': 'billing_type',
            'data-billing_type-2': _('Storage (GB)')
        })
    )
    description = forms.CharField(label = _('Description'))
    metadata_mark = forms.CharField(max_length=255, label=_("Image Mark"), required=False)

    def __init__(self, request, *args, **kwargs):
        super(ModifyPlanForm, self).__init__(request, *args, **kwargs)
        # set discount types
        self.fields['service_type'].choices = gen_service_types(request)
        self.fields['billing_type'].choices = gen_billing_types(request)
        self.fields['billing_type'].choices.append((None, '-'))
        self.fields['ref_id'].choices = gen_flavors(request)

    def handle(self, request, data):
        type_id = data.pop('id', None)
        if not type_id:
            exceptions.handle(request, _('Invalid request.'))
            return False
        try:
            attr_instances =  data.pop('attr_instances')
            attr_cpu = data.pop('attr_cpu')
            attr_ram = data.pop('attr_ram')
            attr_storage = data.pop('attr_storage')
            if int(data['billing_type']) == RAB_BILLING_TYPE_ID:
                data['attrs'] = {}
                if attr_instances:
                    data['attrs']['instances'] = attr_instances
                if attr_cpu:
                    data['attrs']['cpu'] = attr_cpu
                if attr_ram:
                    data['attrs']['ram'] = attr_ram
                if attr_storage:
                    data['attrs']['storage'] = attr_storage
            modify_plan(request, type_id, data)
            return True

        except Exception:
            exceptions.handle(request, _('Unable to modify billing plan.'))
Ejemplo n.º 17
0
class CreateFlavorInfoAction(workflows.Action):
    _flavor_id_regex = (r'^[a-zA-Z0-9. _-]+$')
    _flavor_id_help_text = _("flavor id can only contain alphanumeric "
                             "characters, underscores, periods, hyphens, "
                             "spaces.")
    name = forms.CharField(label=_("Name"), max_length=255)
    flavor_id = forms.RegexField(label=_("ID"),
                                 regex=_flavor_id_regex,
                                 required=False,
                                 initial='auto',
                                 max_length=255,
                                 help_text=_flavor_id_help_text)
    vcpus = forms.IntegerField(label=_("VCPUs"),
                               min_value=1,
                               max_value=2147483647)
    memory_mb = forms.IntegerField(label=_("RAM (MB)"),
                                   min_value=1,
                                   max_value=2147483647)
    disk_gb = forms.IntegerField(label=_("Root Disk (GB)"),
                                 min_value=0,
                                 max_value=2147483647)
    eph_gb = forms.IntegerField(label=_("Ephemeral Disk (GB)"),
                                required=False,
                                initial=0,
                                min_value=0)
    swap_mb = forms.IntegerField(label=_("Swap Disk (MB)"),
                                 required=False,
                                 initial=0,
                                 min_value=0)
    rxtx_factor = forms.FloatField(label=_("RX/TX Factor"),
                                   required=False,
                                   initial=1,
                                   min_value=1)

    class Meta(object):
        name = _("Flavor Information")
        help_text = _("Flavors define the sizes for RAM, disk, number of "
                      "cores, and other resources and can be selected when "
                      "users deploy instances.")

    def clean_name(self):
        name = self.cleaned_data.get('name').strip()
        if not name:
            msg = _('Flavor name cannot be empty.')
            self._errors['name'] = self.error_class([msg])
        return name

    def clean(self):
        cleaned_data = super(CreateFlavorInfoAction, self).clean()
        name = cleaned_data.get('name')
        flavor_id = cleaned_data.get('flavor_id')

        try:
            flavors = api.nova.flavor_list(self.request, None)
        except Exception:
            flavors = []
            msg = _('Unable to get flavor list')
            exceptions.handle(self.request, msg)
            raise
        if flavors is not None and name is not None:
            for flavor in flavors:
                if flavor.name.lower() == name.lower():
                    error_msg = _('The name "%s" is already used by '
                                  'another flavor.') % name
                    self._errors['name'] = self.error_class([error_msg])
                if flavor.id == flavor_id:
                    error_msg = _('The ID "%s" is already used by '
                                  'another flavor.') % flavor_id
                    self._errors['flavor_id'] = self.error_class([error_msg])
        return cleaned_data
Ejemplo n.º 18
0
class CreateFlavorInfoAction(workflows.Action):
    _flavor_id_regex = (r'^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-'
                        r'[0-9a-fA-F]{4}-[0-9a-fA-F]{12}|[0-9]+|auto$')
    _flavor_id_help_text = _("Flavor ID should be UUID4 or integer. "
                             "Leave this field blank or use 'auto' to set "
                             "a random UUID4.")
    name = forms.CharField(label=_("Name"), max_length=255)
    flavor_id = forms.RegexField(label=_("ID"),
                                 regex=_flavor_id_regex,
                                 required=False,
                                 initial='auto',
                                 help_text=_flavor_id_help_text)
    vcpus = forms.IntegerField(label=_("VCPUs"), min_value=1)
    memory_mb = forms.IntegerField(label=_("RAM (MB)"), min_value=1)
    disk_gb = forms.IntegerField(label=_("Root Disk (GB)"), min_value=0)
    eph_gb = forms.IntegerField(label=_("Ephemeral Disk (GB)"),
                                required=False,
                                initial=0,
                                min_value=0)
    swap_mb = forms.IntegerField(label=_("Swap Disk (MB)"),
                                 required=False,
                                 initial=0,
                                 min_value=0)
    rxtx_factor = forms.FloatField(label=_("RX/TX Factor"),
                                   required=False,
                                   initial=1,
                                   min_value=1)

    class Meta(object):
        name = _("Flavor Information")
        help_text = _("Flavors define the sizes for RAM, disk, number of "
                      "cores, and other resources and can be selected when "
                      "users deploy instances.")

    def clean_name(self):
        name = self.cleaned_data.get('name').strip()
        if not name:
            msg = _('Flavor name cannot be empty.')
            self._errors['name'] = self.error_class([msg])
        return name

    def clean(self):
        cleaned_data = super(CreateFlavorInfoAction, self).clean()
        name = cleaned_data.get('name')
        flavor_id = cleaned_data.get('flavor_id')

        try:
            flavors = api.nova.flavor_list(self.request, None)
        except Exception:
            flavors = []
            msg = _('Unable to get flavor list')
            exceptions.check_message(["Connection", "refused"], msg)
            raise
        if flavors is not None and name is not None:
            for flavor in flavors:
                if flavor.name.lower() == name.lower():
                    error_msg = _('The name "%s" is already used by '
                                  'another flavor.') % name
                    self._errors['name'] = self.error_class([error_msg])
                if flavor.id == flavor_id:
                    error_msg = _('The ID "%s" is already used by '
                                  'another flavor.') % flavor_id
                    self._errors['flavor_id'] = self.error_class([error_msg])
        return cleaned_data
Ejemplo n.º 19
0
class AccountQuotaAction(workflows.Action):
    user_type = forms.ChoiceField(
        label=_("Account Type"),
        required=True,
        choices=[('normal', _("Normal User")), ('credit', _("Credit User"))],
        widget=forms.Select(
            attrs={
                'class': 'switchable',
                'data-slug': 'user_type'
            }
        )
    )
    credit_line = forms.FloatField(
        label=_("Credit Line"),
        required=False,
        min_value=0.0,
        initial=settings.GIFT_BANLANCE,
        widget=forms.TextInput(
            attrs={
                'class': 'switched',
                'data-switch-on': 'user_type',
                'data-user_type-credit': _('Credit Line'),
                'data-is-required': 'true',
            }))
    adjust_quota = forms.BooleanField(
        label=_("Adjust Quota"),
        required=False,
        initial=True,
        widget=forms.CheckboxInput(
            attrs={
                'class': 'switchable',
                'data-slug': 'adjust_quota',
                'data-hide-on-checked': 'false'
            }
        )
    )
    instances = forms.IntegerField(min_value=-1, initial=settings.QUOTA_DEFAULI['nova']['instances'],
                                   label=_("Instances"),
                                   required=True,
                                   widget=forms.TextInput(attrs={
                                       'class': 'switched',
                                       'data-switch-on': 'adjust_quota',
                                       'data-is-required': 'true',
                                       'style': 'width 10%'
                                   }))

    cores = forms.IntegerField(min_value=2, initial=settings.QUOTA_DEFAULI['nova']['cores'],
                               label=_("VCPUs"),
                               required=True,
                               widget=forms.TextInput(attrs={
                                   'class': 'switched',
                                   'data-switch-on': 'adjust_quota',
                                   'data-is-required': 'true'
                               }))
    ram = forms.IntegerField(min_value=-1, initial=settings.QUOTA_DEFAULI['nova']['ram'],
                             label=_("RAM (MB)"),
                             required=True,
                             widget=forms.TextInput(attrs={
                                 'class': 'switched',
                                 'data-switch-on': 'adjust_quota',
                                 'data-is-required': 'true'
                             }))
    volumes = forms.IntegerField(min_value=-1, initial=settings.QUOTA_DEFAULI['cinder']['volumes'],
                                 label=_("Volumes"),
                                 required=True,
                                 widget=forms.TextInput(attrs={
                                     'class': 'switched',
                                     'data-switch-on': 'adjust_quota',
                                     'data-is-required': 'true'
                                 }))
    snapshots = forms.IntegerField(min_value=-1, initial=settings.QUOTA_DEFAULI['cinder']['snapshots'],
                                   label=_("Volume Snapshots"),
                                   required=True,
                                   widget=forms.TextInput(attrs={
                                       'class': 'switched',
                                       'data-switch-on': 'adjust_quota',
                                       'data-is-required': 'true'
                                   }))
    volume_gigabytes = forms.IntegerField(
        min_value=-1, initial=settings.QUOTA_DEFAULI['cinder']['volume_gigabytes'],
        label=_("Size of Volumes(GB)"),
        required=True,
        widget=forms.TextInput(attrs={
            'class': 'switched',
            'data-switch-on': 'adjust_quota',
            'data-is-required': 'true'
        }))

    snapshot_gigabytes = forms.IntegerField(
        min_value=-1, initial=settings.QUOTA_DEFAULI['cinder']['snapshot_gigabytes'],
        label=_("Size of Snapshots (GB)"),
        required=True,
        widget=forms.TextInput(attrs={
            'class': 'switched',
            'data-switch-on': 'adjust_quota',
            'data-is-required': 'true'
        }))

    floatingip = forms.IntegerField(min_value=-1, initial=settings.QUOTA_DEFAULI['neutron']['floatingip'],
                                    label=_("Floating IPs"),
                                    required=True,
                                    widget=forms.TextInput(attrs={
                                        'class': 'switched',
                                        'data-switch-on': 'adjust_quota',
                                        'data-is-required': 'true'
                                    }))
    network = forms.IntegerField(min_value=-1, initial=settings.QUOTA_DEFAULI['neutron']['network'],
                                 label=_("Networks"),
                                 required=True,
                                 widget=forms.TextInput(attrs={
                                     'class': 'switched',
                                     'data-switch-on': 'adjust_quota',
                                     'data-is-required': 'true'
                                 }))
    router = forms.IntegerField(min_value=-1, initial=settings.QUOTA_DEFAULI['neutron']['router'],
                                label=_("Routers"),
                                required=True,
                                widget=forms.TextInput(attrs={
                                    'class': 'switched',
                                    'data-switch-on': 'adjust_quota',
                                    'data-is-required': 'true'
                                }))
    subnet = forms.IntegerField(min_value=-1, initial=settings.QUOTA_DEFAULI['neutron']['subnet'],
                                label=_("Subnets"),
                                required=True,
                                widget=forms.TextInput(attrs={
                                    'class': 'switched',
                                    'data-switch-on': 'adjust_quota',
                                    'data-is-required': 'true'
                                }))
    pool = forms.IntegerField(min_value=-1, initial=settings.QUOTA_DEFAULI['neutron']['pool'],
                              label=_("Loadbalancers"),
                              required=True,
                              widget=forms.TextInput(attrs={
                                  'class': 'switched',
                                  'data-switch-on': 'adjust_quota',
                                  'data-is-required': 'true'
                              }))
    bandwidth = forms.IntegerField(required=False, widget=forms.HiddenInput,
                                   initial=settings.QUOTA_DEFAULI['neutron']['bandwidth'], )

    def __init__(self, request, *args, **kwargs):
        super(AccountQuotaAction, self).__init__(request, *args, **kwargs)
        if policy.check((("identity", "project_admin_required"),), self.request):
            self.fields['credit_line'].validators.append(MaxValueValidator(settings.UPPER_CREDIT_LINE_FOR_PROJECT_ADMIN))
            self.fields['credit_line'].help_text = _('credit line is between 0~%s') % settings.UPPER_CREDIT_LINE_FOR_PROJECT_ADMIN

    class Meta(object):
        name = _("Account Quota")
Ejemplo n.º 20
0
class UpdateBoardForm(forms.SelfHandlingForm):
    uuid = forms.CharField(label=_("Board ID"), widget=forms.HiddenInput)
    name = forms.CharField(label=_("Board Name"))
    mobile = forms.BooleanField(label=_("Mobile"), required=False)

    latitude = forms.FloatField(label=_("Latitude"))
    longitude = forms.FloatField(label=_("Longitude"))
    altitude = forms.FloatField(label=_("Altitude"))

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

        super(UpdateBoardForm, self).__init__(*args, **kwargs)

        # LOG.debug("INITIAL: %s", kwargs["initial"])

        # LOG.debug("Manager: %s", policy.check((("iot", "iot_manager"),),
        #                                            self.request))
        # LOG.debug("Admin: %s", policy.check((("iot", "iot_admin"),),
        #                                          self.request))

        # Admin
        if policy.check((("iot", "iot:update_boards"), ), self.request):
            # LOG.debug("ADMIN")
            pass

        # Manager or Admin of the iot project
        elif (policy.check((("iot", "iot_manager"), ), self.request)
              or policy.check((("iot", "iot_admin"), ), self.request)):
            # LOG.debug("NO-edit IOT ADMIN")
            pass

        # Other users
        else:
            if self.request.user.id != kwargs["initial"]["owner"]:
                # LOG.debug("IMMUTABLE FIELDS")
                self.fields["name"].widget.attrs = {'readonly': 'readonly'}
                self.fields["mobile"].widget.attrs = {'disabled': 'disabled'}

                self.fields["latitude"].widget.attrs = {'readonly': 'readonly'}
                self.fields["longitude"].widget.attrs = {
                    'readonly': 'readonly'
                }
                self.fields["altitude"].widget.attrs = {'readonly': 'readonly'}

    def handle(self, request, data):
        try:

            data["location"] = [{
                "latitude": str(data["latitude"]),
                "longitude": str(data["longitude"]),
                "altitude": str(data["altitude"])
            }]
            iotronic.board_update(
                request, data["uuid"], {
                    "name": data["name"],
                    "mobile": data["mobile"],
                    "location": data["location"]
                })

            messages.success(request, _("Board updated successfully."))
            return True
        except Exception:
            exceptions.handle(request, _('Unable to update board.'))