Пример #1
0
class KeyPairImportForm(BaseSecureForm):
    """Key Pair Import form
    """
    name_error_msg = _(u'Name is required')
    key_material_error_msg = _(u'Public Key Contents are required')
    name = wtforms.TextField(
        id=u'key-name',
        label=_(u'Name'),
        validators=[
            validators.InputRequired(message=name_error_msg),
            validators.Length(min=1, max=255)
        ],
    )
    key_material = wtforms.TextAreaField(
        id=u'key-import-contents',
        label=_(u'Public SSH Key Contents'),
        validators=[
            validators.InputRequired(message=key_material_error_msg),
            validators.Length(min=1)
        ],
    )

    def __init__(self, request, keypair=None, **kwargs):
        super(KeyPairImportForm, self).__init__(request, **kwargs)
        self.request = request
        self.name.error_msg = self.name_error_msg  # Used for Foundation Abide error message
        self.key_material.error_msg = self.key_material_error_msg
        if keypair is not None:
            self.name.data = keypair.name
Пример #2
0
    def volume_snapshot_create(self):
        if self.create_form.validate():
            name = self.request.params.get('name')
            description = self.request.params.get('description')
            tags_json = self.request.params.get('tags')
            with boto_error_handler(self.request, self.location):
                self.log_request(
                    _(u"Creating snapshot from volume {0}").format(
                        self.volume.id))
                params = {'VolumeId': self.volume.id}
                if description:
                    params['Description'] = description[0:255]
                snapshot = self.volume.connection.get_object('CreateSnapshot',
                                                             params,
                                                             Snapshot,
                                                             verb='POST')

                # Add name tag
                if name:
                    snapshot.add_tag('Name', name)
                if tags_json:
                    tags = json.loads(tags_json)
                    for tagname, tagvalue in tags.items():
                        snapshot.add_tag(tagname, tagvalue)
                msg = _(
                    u'Successfully sent create snapshot request.  It may take a moment to create the snapshot.'
                )
                self.request.session.flash(msg, queue=Notification.SUCCESS)
            location = self.request.route_path('volume_snapshots',
                                               id=self.volume.id)
            return HTTPFound(location=location)
        else:
            self.request.error_messages = self.create_form.get_errors_list()
        return self.render_dict
Пример #3
0
class GroupForm(BaseSecureForm):
    """Group form
    """
    group_name_error_msg = 'Group name is required'
    group_name = wtforms.TextField(
        id=u'group-name',
        label=_(u'Name'),
        validators=[
            validators.InputRequired(message=group_name_error_msg),
            validators.Length(min=1, max=255)
        ],
    )

    path_error_msg = ''
    path = wtforms.TextField(
        id=u'group-path',
        label=_(u'Path'),
        default="/",
        validators=[validators.Length(min=1, max=255)],
    )

    def __init__(self, request, group=None, **kwargs):
        super(GroupForm, self).__init__(request, **kwargs)
        self.request = request
        self.group_name.error_msg = self.group_name_error_msg  # Used for Foundation Abide error message
        self.path_error_msg = self.path_error_msg
        if group is not None:
            self.group_name.data = group.group_name
            self.path.data = group.path
Пример #4
0
 def __init__(self, context, request):
     self.context = context
     self.request = request
     self.version = __version__
     self.home_url = request.application_url
     self.help_url = request.registry.settings.get('help.url')
     self.support_url = request.registry.settings.get(
         'support.url') or "http://support.eucalyptus.com"
     self.aws_enabled = asbool(request.registry.settings.get('aws.enabled'))
     self.aws_regions = AWS_REGIONS
     self.default_region = request.registry.settings.get(
         'aws.default.region')
     self.browser_password_save = 'true' if asbool(
         request.registry.settings.get(
             'browser.password.save')) else 'false'
     self.cloud_type = request.session.get('cloud_type')
     self.selected_region = self.request.session.get(
         'region', self.default_region)
     self.selected_region_label = self.get_selected_region_label(
         self.selected_region)
     self.username = self.request.session.get('username')
     self.account = self.request.session.get('account')
     self.username_label = self.request.session.get('username_label')
     self.euca_logout_form = EucaLogoutForm(request=self.request)
     self.date_format = _(u'%I:%M:%S %p %b %d %Y')
     self.angular_date_format = _(u'hh:mm:ss a MMM d yyyy')
     self.tag_pattern_key = '^(?!aws:).{0,128}$'
     self.tag_pattern_value = '^(?!aws:).{0,256}$'
     self.integer_gt_zero_pattern = '^[1-9]\d*$'
     self.non_negative_pattern = '^[0-9]\d*$'
     self.cidr_pattern = '{0}{1}'.format(
         '^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}',
         '(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])(\/\d+)$')
     self.querystring = self.get_query_string()
     self.help_html_dir = 'eucaconsole:static/html/help/'
Пример #5
0
 def __init__(self, request):
     super(RoleView, self).__init__(request)
     self.title_parts = [
         _(u'Role'),
         request.matchdict.get('name') or _(u'Create')
     ]
     self.conn = self.get_connection(conn_type="iam")
     self.role = self.get_role()
     self.role_route_id = self.request.matchdict.get('name')
     self.all_users = self.get_all_users_array()
     self.role_form = RoleForm(self.request,
                               role=self.role,
                               formdata=self.request.params or None)
     self.delete_form = DeleteRoleForm(self.request,
                                       formdata=self.request.params)
     create_date = parser.parse(
         self.role.create_date) if self.role else datetime.now()
     self.role_name_validation_error_msg = _(
         u"Role names must be between 1 and 64 characters long, and may contain letters, numbers, '+', '=', ',', '.'. '@' and '-', and cannot contain spaces."
     )
     self.render_dict = dict(
         role=self.role,
         role_arn=self.role.arn if self.role else '',
         role_path=self.role.path if self.role else '',
         role_create_date=create_date,
         role_route_id=self.role_route_id,
         all_users=self.all_users,
         role_form=self.role_form,
         delete_form=self.delete_form,
         role_name_validation_error_msg=self.role_name_validation_error_msg,
     )
Пример #6
0
 def keypair_create(self):
     if self.keypair_form.validate():
         name = self.request.params.get('name')
         session = self.request.session
         new_keypair = None
         location = self.request.route_path('keypair_view', id=name)
         with boto_error_handler(self.request, location):
             self.log_request(_(u"Creating keypair ")+name)
             new_keypair = self.conn.create_key_pair(name)
             # Store the new keypair material information in the session
             self._store_file_(new_keypair.name+".pem",
                               'application/x-pem-file;charset=ISO-8859-1',
                               new_keypair.material)
             msg_template = _(u'Successfully created key pair {keypair}')
             msg = msg_template.format(keypair=name)
             self.request.session.flash(msg, queue=Notification.SUCCESS)
         if self.request.is_xhr:
             import logging; logging.info(">>>>>>>>> using create keypair xhr... fix this")
             keypair_material = new_keypair.material if new_keypair else None
             resp_body = json.dumps(dict(message=msg, payload=keypair_material))
             return Response(status=200, body=resp_body, content_type='application/x-pem-file;charset=ISO-8859-1')
         else:
             location = self.request.route_path('keypair_view', id=name)
             return HTTPFound(location=location)
     if self.request.is_xhr:
         form_errors = ', '.join(self.keypair_form.get_errors_list())
         return JSONResponse(status=400, message=form_errors)  # Validation failure = bad request
     else:
         self.request.error_messages = self.keypair_form.get_errors_list()
         return self.render_dict
Пример #7
0
class RoleForm(BaseSecureForm):
    """Role form
    """
    role_name_error_msg = 'Role name is required'
    role_name = wtforms.TextField(
        id=u'role-name',
        label=_(u'Name'),
        validators=[validators.InputRequired(message=role_name_error_msg), validators.Length(min=1, max=255)],
    )

    path_error_msg = ''
    path = wtforms.TextField(
        id=u'role-path',
        label=_(u'Path'),
        default="/",
        validators=[validators.Length(min=1, max=255)],
    )

    def __init__(self, request, role=None, **kwargs):
        super(RoleForm, self).__init__(request, **kwargs)
        self.request = request
        self.role_name.error_msg = self.role_name_error_msg  # Used for Foundation Abide error message
        self.path_error_msg = self.path_error_msg
        if role is not None:
            self.role_name.data = role.role_name
            self.path.data = role.path
Пример #8
0
 def securitygroup_create(self):
     if self.securitygroup_form.validate():
         name = self.request.params.get('name')
         description = self.request.params.get('description')
         tags_json = self.request.params.get('tags')
         with boto_error_handler(self.request, self.request.route_path('securitygroups')):
             self.log_request(_(u"Creating security group {0}").format(name))
             new_security_group = self.conn.create_security_group(name, description)
             self.add_rules(security_group=new_security_group)
             if tags_json:
                 tags = json.loads(tags_json)
                 for tagname, tagvalue in tags.items():
                     new_security_group.add_tag(tagname, tagvalue)
             msg = _(u'Successfully created security group')
             location = self.request.route_path('securitygroup_view', id=new_security_group.id)
             if self.request.is_xhr:
                 return JSONResponse(status=200, message=msg)
             else:
                 self.request.session.flash(msg, queue=Notification.SUCCESS)
                 return HTTPFound(location=location)
     if self.request.is_xhr:
         form_errors = ', '.join(self.securitygroup_form.get_errors_list())
         return JSONResponse(status=400, message=form_errors)  # Validation failure = bad request
     else:
         self.request.error_messages = self.securitygroup_form.get_errors_list()
         return self.render_dict
Пример #9
0
class ItemForm(Form):
    name = TextField(required_marker(u'Name'), [validators.Required()])
    type = SelectField(required_marker(u'Type'),
                       choices=[(u'TRADE', u'Trade'), (u'SALE', u'Sale')])
    price = DecimalField(required_marker(u'Price'))
    trade_with = TextField(required_marker(u'Trade with'))
    description = TextAreaField(required_marker(u'Description'),
                                [validators.Required()])
    reason = TextField(_(u'Reason'))
    quantity = TextField(required_marker(u'Quantity'), default=1)
    is_draft = BooleanField(_(u'Draft'))
    tags = TextField(_(u"Tags"))

    def validate_price(form, field):
        """
        Require the price field if this item is for SALE.
        """
        # if the item type is not SALE, just ignore the price field errors
        if form.type.data != 'SALE':
            field.errors = []
        elif form.type.data == 'SALE' and not field.data:
            raise validators.ValidationError(_(u"This field is required"))

    def validate_trade_with(form, field):
        """
        Require the trade_with field if this item is for TRADE.
        """
        # if the item type is not TRADE, just ignore the trade_with field errors
        if form.type.data != 'TRADE':
            field.errors = []
        elif form.type.data == 'TRADE' and not field.data:
            raise validators.ValidationError(_(u"This field is required"))
Пример #10
0
 def volume_create(self):
     if self.volume_form.validate():
         name = self.request.params.get('name', '')
         tags_json = self.request.params.get('tags')
         size = int(self.request.params.get('size', 1))
         zone = self.request.params.get('zone')
         snapshot_id = self.request.params.get('snapshot_id')
         kwargs = dict(size=size, zone=zone)
         if snapshot_id:
             snapshot = self.get_snapshot(snapshot_id)
             kwargs['snapshot'] = snapshot
         with boto_error_handler(self.request, self.request.route_path('volumes')):
             self.log_request(_(u"Creating volume (size={0}, zone={1}, snapshot_id={2})").format(size, zone, snapshot_id))
             volume = self.conn.create_volume(**kwargs)
             # Add name tag
             if name:
                 volume.add_tag('Name', name)
             if tags_json:
                 tags = json.loads(tags_json)
                 for tagname, tagvalue in tags.items():
                     volume.add_tag(tagname, tagvalue)
             msg = _(u'Successfully sent create volume request.  It may take a moment to create the volume.')
             self.request.session.flash(msg, queue=Notification.SUCCESS)
             location = self.request.route_path('volume_view', id=volume.id)
             return HTTPFound(location=location)
     else:
         self.request.error_messages = self.volume_form.get_errors_list()
     return self.render_dict
Пример #11
0
def reset_password(request):
    loginhash = request.matchdict['loginhash']
    users = User().queryObject().all()
    for user in users:
        if sha512(user.login).hexdigest() == loginhash:
            new_password = rand_string(10)
            logger.info('Password of user ' + user.login +
                        ' has been reset to ' + new_password)
            user.password = sha512(new_password).hexdigest()
            user.save()

            localizer = get_localizer(request)

            # Create the body of the message (a plain-text and an HTML version)
            url = request.route_url('login')
            text_ts = _('plain_password_reset_mail', mapping={
                        'name': user.name, 'password': new_password,
                        'url': url}, domain='Ondestan')
            html_ts = _('html_password_reset_mail', mapping={'name': user.name,
                        'password': new_password, 'url': url},
                        domain='Ondestan')
            subject_ts = _('subject_password_reset_mail', domain='Ondestan')

            text = localizer.translate(text_ts)
            html = localizer.translate(html_ts)
            subject = localizer.translate(subject_ts)

            send_mail(html, text, subject, user.email)
            break
Пример #12
0
 def __init__(self, context, request):
     self.context = context
     self.request = request
     self.version = __version__
     self.home_url = request.application_url
     self.help_url = request.registry.settings.get('help.url')
     self.support_url = request.registry.settings.get('support.url') or "http://support.eucalyptus.com"
     self.aws_enabled = asbool(request.registry.settings.get('aws.enabled'))
     self.aws_regions = AWS_REGIONS
     self.default_region = request.registry.settings.get('aws.default.region')
     self.browser_password_save = 'true' if asbool(request.registry.settings.get('browser.password.save')) else 'false'
     self.cloud_type = request.session.get('cloud_type')
     self.selected_region = self.request.session.get('region', self.default_region)
     self.selected_region_label = self.get_selected_region_label(self.selected_region)
     self.username = self.request.session.get('username')
     self.account = self.request.session.get('account')
     self.username_label = self.request.session.get('username_label')
     self.euca_logout_form = EucaLogoutForm(request=self.request)
     self.date_format = _(u'%I:%M:%S %p %b %d %Y')
     self.angular_date_format = _(u'hh:mm:ss a MMM d yyyy')
     self.tag_pattern_key = '^(?!aws:).{0,128}$'
     self.tag_pattern_value = '^(?!aws:).{0,256}$'
     self.integer_gt_zero_pattern = '^[1-9]\d*$'
     self.non_negative_pattern = '^[0-9]\d*$'
     self.cidr_pattern = '{0}{1}'.format(
         '^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}',
         '(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])(\/\d+)$'
     )
     self.querystring = self.get_query_string()
     self.help_html_dir = 'eucaconsole:static/html/help/'
Пример #13
0
 def volume_snapshot_create(self):
     if self.create_form.validate():
         name = self.request.params.get('name')
         description = self.request.params.get('description')
         tags_json = self.request.params.get('tags')
         with boto_error_handler(self.request, self.location):
             self.log_request(_(u"Creating snapshot from volume {0}").format(self.volume.id))
             params = {'VolumeId': self.volume.id}
             if description:
                 params['Description'] = description[0:255]
             snapshot = self.volume.connection.get_object('CreateSnapshot', params, Snapshot, verb='POST')
             
             # Add name tag
             if name:
                 snapshot.add_tag('Name', name)
             if tags_json:
                 tags = json.loads(tags_json)
                 for tagname, tagvalue in tags.items():
                     snapshot.add_tag(tagname, tagvalue)
             msg = _(u'Successfully sent create snapshot request.  It may take a moment to create the snapshot.')
             self.request.session.flash(msg, queue=Notification.SUCCESS)
         location = self.request.route_path('volume_snapshots', id=self.volume.id)
         return HTTPFound(location=location)
     else:
         self.request.error_messages = self.create_form.get_errors_list()
     return self.render_dict
Пример #14
0
 def __init__(self, request):
     super(UserView, self).__init__(request)
     self.conn = self.get_connection(conn_type="iam")
     with boto_error_handler(request, request.current_route_url()):
         self.user = self.get_user()
     if self.user is None:
         self.location = self.request.route_path('users')
     else:
         self.location = self.request.route_path('user_view',
                                                 name=self.user.user_name)
     self.prefix = '/users'
     self.user_form = None
     self.change_password_form = ChangePasswordForm(self.request)
     self.generate_form = GeneratePasswordForm(self.request)
     self.delete_form = DeleteUserForm(self.request)
     self.already_member_text = _(u"User already a member of all groups")
     self.no_groups_defined_text = _(u"There are no groups defined")
     self.render_dict = dict(
         user=self.user,
         prefix=self.prefix,
         user_create_date=getattr(self.user, 'create_date', None),
         change_password_form=self.change_password_form,
         generate_form=self.generate_form,
         delete_form=self.delete_form,
         disable_form=DisableUserForm(self.request),
         enable_form=EnableUserForm(self.request),
         quota_err=_(u"Requires non-negative integer (or may be empty)"),
     )
Пример #15
0
 def user_random_password(self):
     """ calls iam:UpdateLoginProfile """
     if not (self.is_csrf_valid()):
         return JSONResponse(status=400, message="missing CSRF token")
     with boto_error_handler(self.request):
         new_pass = PasswordGeneration.generate_password()
         self.log_request(
             _(u"Generating password for user {0}").format(
                 self.user.user_name))
         try:
             # try to fetch login profile.
             self.conn.get_login_profiles(user_name=self.user.user_name)
             # if that worked, update the profile
             result = self.conn.update_login_profile(
                 user_name=self.user.user_name, password=new_pass)
         except BotoServerError:
             # if that failed, create the profile
             result = self.conn.create_login_profile(
                 user_name=self.user.user_name, password=new_pass)
         # assemble file response
         account = self.request.session['account']
         string_output = StringIO.StringIO()
         csv_w = csv.writer(string_output)
         header = [_(u'Account'), _(u'User Name'), _(u'Password')]
         csv_w.writerow(header)
         row = [account, self.user.user_name, new_pass]
         csv_w.writerow(row)
         self._store_file_(
             "{acct}-{user}-login.csv".format(acct=account,
                                              user=self.user.user_name),
             'text/csv', string_output.getvalue())
         return dict(message=_(u"Successfully generated user password"),
                     results="true")
Пример #16
0
 def snapshots_delete(self):
     snapshot_id = self.request.params.get('snapshot_id')
     volume_id = self.request.params.get('volume_id')
     snapshot = self.get_snapshot(snapshot_id)
     # NOTE: could optimize by requiring snapshot name as param and avoid above CLC fetch
     snapshot_name = TaggedItemView.get_display_name(snapshot)
     location = self.get_redirect_location('snapshots')
     if volume_id:
         location = self.request.route_path('volume_snapshots', id=volume_id)
     if snapshot and self.delete_form.validate():
         with boto_error_handler(self.request, location):
             images_registered = self.get_images_registered(snapshot_id)
             if images_registered is not None:
                 for img in images_registered:
                     self.log_request(_(u"Deregistering image {0}").format(img.id))
                     img.deregister()
                 # Clear images cache
                 #ImagesView.invalidate_images_cache()
             self.log_request(_(u"Deleting snapshot {0}").format(snapshot_id))
             snapshot.delete()
             prefix = _(u'Successfully deleted snapshot')
             msg = '{prefix} {name}'.format(prefix=prefix, name=snapshot_name)
             self.request.session.flash(msg, queue=Notification.SUCCESS)
         return HTTPFound(location=location)
     else:
         msg = _(u'Unable to delete snapshot')
         self.request.session.flash(msg, queue=Notification.ERROR)
         return HTTPFound(location=location)
Пример #17
0
class ScalingGroupCreateForm(BaseScalingGroupForm):
    """Create Scaling Group form"""
    name_error_msg = _(u'Name is required')
    name = wtforms.TextField(
        label=_(u'Name'),
        validators=[
            validators.InputRequired(message=name_error_msg),
        ],
    )

    def __init__(self,
                 request,
                 scaling_group=None,
                 autoscale_conn=None,
                 ec2_conn=None,
                 launch_configs=None,
                 **kwargs):
        super(ScalingGroupCreateForm,
              self).__init__(request,
                             scaling_group=scaling_group,
                             autoscale_conn=autoscale_conn,
                             ec2_conn=ec2_conn,
                             launch_configs=launch_configs,
                             **kwargs)

        # Set error messages
        self.name.error_msg = self.name_error_msg

        # Set initial data
        self.availability_zones.data = [
            value for value, label in self.availability_zones.choices
        ]
Пример #18
0
 def ipaddresses_landing(self):
     # sort_keys are passed to sorting drop-down
     # Handle Allocate IP addresses form
     if self.request.method == 'POST':
         if self.allocate_form.validate():
             new_ips = []
             ipcount = int(self.request.params.get('ipcount', 0))
             with boto_error_handler(self.request, self.location):
                 self.log_request(_(u"Allocating {0} ElasticIPs").format(ipcount))
                 for i in xrange(ipcount):
                     new_ip = self.conn.allocate_address()
                     new_ips.append(new_ip.public_ip)
                 prefix = _(u'Successfully allocated IPs')
                 ips = ', '.join(new_ips)
                 msg = u'{prefix} {ips}'.format(prefix=prefix, ips=ips)
                 self.request.session.flash(msg, queue=Notification.SUCCESS)
             return HTTPFound(location=self.location)
     self.render_dict.update(
         initial_sort_key='public_ip',
         json_items_endpoint=self.get_json_endpoint('ipaddresses_json'),
         filter_fields=True,
         filters_form=IPAddressesFiltersForm(self.request, conn=self.conn, formdata=self.request.params or None),
         filter_keys=['public_ip', 'instance_id'],
         sort_keys=self.get_sort_keys(),
     )
     return self.render_dict
Пример #19
0
def notify_new_order_to_admin_by_email(order_state, request):
    admin_email = Config.get_string_value('config.admin_email')
    if admin_email != None and admin_email != '':
        localizer = get_localizer(request)

        # Create the body of the message (a plain-text and an HTML version).
        text_ts = _('plain_new_order_admin_mail',
            mapping={'name': order_state.order.user.name,
                     'login': order_state.order.user.login,
                     'units': order_state.order.units,
                     'address': order_state.order.address,
                     'url': request.route_url('orders'),
                     'state': _('order_state_0',
                                domain='Ondestán')},
            domain='Ondestan')
        html_ts = _('html_new_order_admin_mail',
            mapping={'name': order_state.order.user.name,
                     'login': order_state.order.user.login,
                     'units': order_state.order.units,
                     'address': order_state.order.address,
                     'url': request.route_url('orders'),
                     'state': _('order_state_0',
                                domain='Ondestán')},
            domain='Ondestan')
        subject_ts = _('subject_new_order_admin_mail', domain='Ondestan')

        text = localizer.translate(text_ts)
        html = localizer.translate(html_ts)
        subject = localizer.translate(subject_ts)

        send_mail(html, text, subject, admin_email)
Пример #20
0
def notify_order_update_to_user_by_email(order_state, request):
    localizer = get_localizer(request)

    # Create the body of the message (a plain-text and an HTML version).
    text_ts = _('plain_order_update_user_mail',
        mapping={'name': order_state.order.user.name,
                 'login': order_state.order.user.login,
                 'units': order_state.order.units,
                 'address': order_state.order.address,
                 'url': request.route_url('orders'),
                 'state': localizer.translate(_('order_state_' + str(order_state.state),
                            domain='Ondestan'))},
        domain='Ondestan')
    html_ts = _('html_order_update_user_mail',
        mapping={'name': order_state.order.user.name,
                 'login': order_state.order.user.login,
                 'units': order_state.order.units,
                 'address': order_state.order.address,
                 'url': request.route_url('orders'),
                 'state': localizer.translate(_('order_state_' + str(order_state.state),
                            domain='Ondestan'))},
        domain='Ondestan')
    subject_ts = _('subject_order_update_user_mail', domain='Ondestan')

    text = localizer.translate(text_ts)
    html = localizer.translate(html_ts)
    subject = localizer.translate(subject_ts)

    send_mail(html, text, subject, order_state.order.user.email)
Пример #21
0
def get_device_config_fancy_description(config, request=None, locale=None):

    if request != None:
        localizer = get_localizer(request)
    else:
        localizer = get_custom_localizer(locale)

    datatime = get_device_config_fancy_description_unit_value(config.datatime)
    sampletime = get_device_config_fancy_description_unit_value(config.sampletime)
    readtime = get_device_config_fancy_description_unit_value(config.readtime)
    parameters = {
        'datatime_val': datatime[0],
        'datatime_unit': localizer.translate(_(datatime[1],
            domain='Ondestan')),
        'sampletime_val': sampletime[0],
        'sampletime_unit': localizer.translate(_(sampletime[1],
            domain='Ondestan')),
        'readtime_val': readtime[0],
        'readtime_unit': localizer.translate(_(readtime[1],
            domain='Ondestan'))
    }

    return localizer.translate(_("fancy_config_description",
         domain='Ondestan',
         mapping=parameters))
Пример #22
0
 def user_random_password(self):
     """ calls iam:UpdateLoginProfile """
     if not(self.is_csrf_valid()):
         return JSONResponse(status=400, message="missing CSRF token")
     with boto_error_handler(self.request):
         new_pass = PasswordGeneration.generate_password()
         self.log_request(_(u"Generating password for user {0}").format(self.user.user_name))
         try:
             # try to fetch login profile.
             self.conn.get_login_profiles(user_name=self.user.user_name)
             # if that worked, update the profile
             result = self.conn.update_login_profile(user_name=self.user.user_name, password=new_pass)
         except BotoServerError:
             # if that failed, create the profile
             result = self.conn.create_login_profile(user_name=self.user.user_name, password=new_pass)
         # assemble file response
         account = self.request.session['account']
         string_output = StringIO.StringIO()
         csv_w = csv.writer(string_output)
         header = [_(u'Account'), _(u'User Name'), _(u'Password')]
         csv_w.writerow(header)
         row = [account, self.user.user_name, new_pass]
         csv_w.writerow(row)
         self._store_file_(
             "{acct}-{user}-login.csv".format(acct=account, user=self.user.user_name),
             'text/csv', string_output.getvalue())
         return dict(message=_(u"Successfully generated user password"), results="true")
Пример #23
0
    def role_create(self):
        if self.role_form.validate():
            new_role_name = self.request.params.get('role_name')
            role_type = self.request.params.get('roletype')
            acct_id = ''
            external_id = ''
            if role_type == 'xacct':
                acct_id = self.request.params.get('accountid')
                external_id = self.request.params.get('externalid')
            new_path = self.request.params.get('path')
            err_location = self.request.route_path('roles')
            with boto_error_handler(self.request, err_location):
                self.log_request(_(u"Creating role {0}").format(new_role_name))
                if role_type == 'xacct':
                    policy = {'Version': '2012-10-17'}
                    statement = {'Effect': 'Allow', 'Action': 'sts:AssumeRole',
                                 'Principal': {'AWS': "arn:aws:iam::%s:root" % acct_id}}
                    if len(external_id) > 0:
                        statement['Condition'] = {'StringEquals': {'sts:ExternalId': external_id}}
                    policy['Statement'] = [statement]
                    self.conn.create_role(role_name=new_role_name, path=new_path,
                                          assume_role_policy_document=json.dumps(policy))
                else:
                    self.conn.create_role(role_name=new_role_name, path=new_path)
                # now add instance profile
                RoleView.get_or_create_instance_profile(self.conn, new_role_name)
                msg_template = _(u'Successfully created role {role}')
                msg = msg_template.format(role=new_role_name)
                self.request.session.flash(msg, queue=Notification.SUCCESS)
            location = self.request.route_path('iam_policy_new') + '?type=role&id=' + quote(new_role_name)
            return HTTPFound(location=location)

        return self.render_dict
Пример #24
0
 def __init__(self, request):
     super(UserView, self).__init__(request)
     self.conn = self.get_connection(conn_type="iam")
     with boto_error_handler(request, request.current_route_url()):
         self.user = self.get_user()
     if self.user is None:
         self.location = self.request.route_path('users')
     else:
         self.location = self.request.route_path('user_view', name=self.user.user_name)
     self.prefix = '/users'
     self.user_form = None
     self.change_password_form = ChangePasswordForm(self.request)
     self.generate_form = GeneratePasswordForm(self.request)
     self.delete_form = DeleteUserForm(self.request)
     self.already_member_text = _(u"User already a member of all groups")
     self.no_groups_defined_text = _(u"There are no groups defined")
     self.render_dict = dict(
         user=self.user,
         prefix=self.prefix,
         user_create_date=getattr(self.user, 'create_date', None),
         change_password_form=self.change_password_form,
         generate_form=self.generate_form,
         delete_form=self.delete_form,
         disable_form=DisableUserForm(self.request),
         enable_form=EnableUserForm(self.request),
         quota_err=_(u"Requires non-negative integer (or may be empty)"),
     )
Пример #25
0
 def volume_create(self):
     if self.volume_form.validate():
         name = self.request.params.get('name', '')
         tags_json = self.request.params.get('tags')
         size = int(self.request.params.get('size', 1))
         zone = self.request.params.get('zone')
         snapshot_id = self.request.params.get('snapshot_id')
         kwargs = dict(size=size, zone=zone)
         if snapshot_id:
             snapshot = self.get_snapshot(snapshot_id)
             kwargs['snapshot'] = snapshot
         with boto_error_handler(self.request,
                                 self.request.route_path('volumes')):
             self.log_request(
                 _(u"Creating volume (size={0}, zone={1}, snapshot_id={2})"
                   ).format(size, zone, snapshot_id))
             volume = self.conn.create_volume(**kwargs)
             # Add name tag
             if name:
                 volume.add_tag('Name', name)
             if tags_json:
                 tags = json.loads(tags_json)
                 for tagname, tagvalue in tags.items():
                     volume.add_tag(tagname, tagvalue)
             msg = _(
                 u'Successfully sent create volume request.  It may take a moment to create the volume.'
             )
             self.request.session.flash(msg, queue=Notification.SUCCESS)
             location = self.request.route_path('volume_view', id=volume.id)
             return HTTPFound(location=location)
     else:
         self.request.error_messages = self.volume_form.get_errors_list()
     return self.render_dict
Пример #26
0
 def snapshot_register(self):
     snapshot_id = self.snapshot.id
     name = self.request.params.get('name')
     description = self.request.params.get('description')
     dot = self.request.params.get('dot')
     reg_as_windows = self.request.params.get('reg_as_windows')
     root_vol = BlockDeviceType(snapshot_id=snapshot_id)
     root_vol.delete_on_termination = dot
     bdm = BlockDeviceMapping()
     root_device_name = '/dev/sda' if self.cloud_type == 'euca' else '/dev/sda1'
     bdm[root_device_name] = root_vol
     location = self.request.route_path('snapshot_view', id=snapshot_id)
     if self.snapshot and self.register_form.validate():
         with boto_error_handler(self.request, location):
             self.log_request(_(u"Registering snapshot {0} as image {1}").format(snapshot_id, name))
             self.snapshot.connection.register_image(
                 name=name, description=description,
                 root_device_name=root_device_name,
                 kernel_id=('windows' if reg_as_windows else None),
                 block_device_map=bdm)
             prefix = _(u'Successfully registered snapshot')
             msg = '{prefix} {id}'.format(prefix=prefix, id=snapshot_id)
             # Clear images cache
             #ImagesView.invalidate_images_cache()
             self.request.session.flash(msg, queue=Notification.SUCCESS)
         return HTTPFound(location=location)
     return self.render_dict
Пример #27
0
 def ipaddresses_landing(self):
     # sort_keys are passed to sorting drop-down
     # Handle Allocate IP addresses form
     if self.request.method == 'POST':
         if self.allocate_form.validate():
             new_ips = []
             ipcount = int(self.request.params.get('ipcount', 0))
             with boto_error_handler(self.request, self.location):
                 self.log_request(
                     _(u"Allocating {0} ElasticIPs").format(ipcount))
                 for i in xrange(ipcount):
                     new_ip = self.conn.allocate_address()
                     new_ips.append(new_ip.public_ip)
                 prefix = _(u'Successfully allocated IPs')
                 ips = ', '.join(new_ips)
                 msg = u'{prefix} {ips}'.format(prefix=prefix, ips=ips)
                 self.request.session.flash(msg, queue=Notification.SUCCESS)
             return HTTPFound(location=self.location)
     self.render_dict.update(
         initial_sort_key='public_ip',
         json_items_endpoint=self.get_json_endpoint('ipaddresses_json'),
         filter_fields=True,
         filters_form=IPAddressesFiltersForm(self.request,
                                             conn=self.conn,
                                             formdata=self.request.params
                                             or None),
         filter_keys=['public_ip', 'instance_id'],
         sort_keys=self.get_sort_keys(),
     )
     return self.render_dict
Пример #28
0
class GroupUpdateForm(BaseSecureForm):
    """Group update form
    """
    group_name_error_msg = ''
    group_name = wtforms.TextField(
        id=u'group-name',
        label=_(u'Name'),
        validators=[validators.Length(min=1, max=255)],
    )

    path_error_msg = ''
    path = wtforms.TextField(
        id=u'group-path',
        label=_(u'Path'),
        validators=[validators.Length(min=1, max=255)],
    )

    users_error_msg = ''
    users = wtforms.TextField(
        id=u'group-users',
        label=(u''),
        validators=[],
    )

    def __init__(self, request, group=None, **kwargs):
        super(GroupUpdateForm, self).__init__(request, **kwargs)
        self.request = request
        self.group_name.error_msg = self.group_name_error_msg  # Used for Foundation Abide error message
        self.path_error_msg = self.path_error_msg
        if group is not None:
            self.group_name.data = group.group_name
            self.path.data = group.path
Пример #29
0
def update_user(request):
    localizer = get_localizer(request)

    user_id = int(request.params['id'])
    login = request.params['login']
    name = request.params['name']
    email = request.params['email']
    user = User().queryObject().filter(User.login == login).scalar()
    if ((user != None) and (user.id != user_id)):
        msg = _('login_already_use', domain='Ondestan')
        return localizer.translate(msg)
    user = User().queryObject().filter(User.email == email).scalar()
    if ((user != None) and (user.id != user_id)):
        msg = _('email_already_use', domain='Ondestan')
        return localizer.translate(msg)
    user = User().queryObject().filter(User.id == user_id).scalar()
    user.login = login
    user.name = name
    user.email = email
    user.phone = request.params['phone']
    user.password = sha512(request.params['password']).hexdigest()
    user.update()

    msg = _('user_profile_updated', domain='Ondestan')
    return localizer.translate(msg)
Пример #30
0
 def scalinggroup_create(self):
     """Handles the POST from the Create Scaling Group wizard"""
     if self.create_form.validate():
         with boto_error_handler(self.request, self.request.route_path('scalinggroups')):
             scaling_group_name = self.request.params.get('name')
             self.log_request(_(u"Creating scaling group {0}").format(scaling_group_name))
             scaling_group = AutoScalingGroup(
                 name=scaling_group_name,
                 launch_config=self.request.params.get('launch_config'),
                 availability_zones=self.request.params.getall('availability_zones'),
                 # load_balancers=self.request.params.getall('load_balancers'),
                 health_check_type=self.request.params.get('health_check_type'),
                 health_check_period=self.request.params.get('health_check_period'),
                 desired_capacity=self.request.params.get('desired_capacity'),
                 min_size=self.request.params.get('min_size'),
                 max_size=self.request.params.get('max_size'),
                 tags=self.parse_tags_param(scaling_group_name=scaling_group_name),
             )
             self.autoscale_conn.create_auto_scaling_group(scaling_group)
             msg = _(u'Successfully created scaling group')
             msg += ' {0}'.format(scaling_group.name)
             self.request.session.flash(msg, queue=Notification.SUCCESS)
             location = self.request.route_path('scalinggroup_view', id=scaling_group.name)
             return HTTPFound(location=location)
     else:
         self.request.error_messages = self.create_form.get_errors_list()
     return self.render_dict
Пример #31
0
 def user_delete_password(self):
     """ calls iam:DeleteLoginProfile """
     if not(self.is_csrf_valid()):
         return JSONResponse(status=400, message="missing CSRF token")
     with boto_error_handler(self.request):
         self.log_request(_(u"Deleting password for user {0}").format(self.user.user_name))
         self.conn.delete_login_profile(user_name=self.user.user_name)
         return dict(message=_(u"Successfully deleted user password"), results="true")
Пример #32
0
 def get_termination_policy_choices():
     return (
         (u'Default', _(u'Default')),
         (u'OldestInstance', _(u'Oldest instance')),
         (u'NewestInstance', _(u'Newest instance')),
         (u'OldestLaunchConfiguration', _(u'Oldest launch configuration')),
         (u'ClosestToNextInstanceHour', _(u'Closest to next instance hour')),
     )
Пример #33
0
 def get_termination_policy_choices():
     return (
         (u'Default', _(u'Default')),
         (u'OldestInstance', _(u'Oldest instance')),
         (u'NewestInstance', _(u'Newest instance')),
         (u'OldestLaunchConfiguration', _(u'Oldest launch configuration')),
         (u'ClosestToNextInstanceHour',
          _(u'Closest to next instance hour')),
     )
Пример #34
0
 def validate_user(self, request):
     try:
         user_id = int(request.matchdict['user_id'])
         try:
             DBSession.query(User).filter_by(id=user_id).one()
         except NoResultFound:
             request.errors.add('url', 'user_id', _(u"User doesn't exist"))
     except ValueError:
         request.errors.add('url', 'user_id', _(u'Invalid User ID'))
Пример #35
0
 def user_delete_policy(self):
     """ calls iam:DeleteUserPolicy """
     if not(self.is_csrf_valid()):
         return JSONResponse(status=400, message="missing CSRF token")
     policy = self.request.matchdict.get('policy')
     with boto_error_handler(self.request):
         self.log_request(_(u"Deleting policy {0} for user {1}").format(policy, self.user.user_name))
         result = self.conn.delete_user_policy(user_name=self.user.user_name, policy_name=policy)
         return dict(message=_(u"Successfully deleted user policy"), results=result)
Пример #36
0
 def user_activate_key(self):
     """ calls iam:UpdateAccessKey """
     if not(self.is_csrf_valid()):
         return JSONResponse(status=400, message="missing CSRF token")
     key_id = self.request.matchdict.get('key')
     with boto_error_handler(self.request):
         self.log_request(_(u"Activating access key {0} for user {1}").format(key_id, self.user.user_name))
         result = self.conn.update_access_key(user_name=self.user.user_name, access_key_id=key_id, status="Active")
         return dict(message=_(u"Successfully activated key"))
Пример #37
0
 def role_delete_policy(self):
     if not self.is_csrf_valid():
         return JSONResponse(status=400, message="missing CSRF token")
     # calls iam:DeleteRolePolicy
     policy = self.request.matchdict.get('policy')
     with boto_error_handler(self.request):
         self.log_request(_(u"Deleting policy {0} for role {1}").format(policy, self.role.role_name))
         result = self.conn.delete_role_policy(role_name=self.role.role_name, policy_name=policy)
         return dict(message=_(u"Successfully deleted role policy"), results=result)
Пример #38
0
 def instance_launch(self):
     """Handles the POST from the Launch instanced wizard"""
     if self.launch_form.validate():
         tags_json = self.request.params.get('tags')
         image_id = self.image.id
         key_name = self.request.params.get('keypair')
         if key_name and key_name == 'none':
             key_name = None  # Handle "None (advanced)" option
         num_instances = int(self.request.params.get('number', 1))
         securitygroup = self.request.params.get('securitygroup', 'default')
         security_groups = [securitygroup]  # Security group names
         instance_type = self.request.params.get('instance_type', 'm1.small')
         availability_zone = self.request.params.get('zone') or None
         kernel_id = self.request.params.get('kernel_id') or None
         ramdisk_id = self.request.params.get('ramdisk_id') or None
         monitoring_enabled = self.request.params.get('monitoring_enabled') == 'y'
         private_addressing = self.request.params.get('private_addressing') == 'y'
         addressing_type = 'private' if private_addressing else 'public'
         bdmapping_json = self.request.params.get('block_device_mapping')
         block_device_map = self.get_block_device_map(bdmapping_json)
         new_instance_ids = []
         with boto_error_handler(self.request, self.location):
             self.log_request(_(u"Running instance(s) (num={0}, image={1}, type={2})").format(
                 num_instances, image_id, instance_type))
             reservation = self.conn.run_instances(
                 image_id,
                 min_count=num_instances,
                 max_count=num_instances,
                 key_name=key_name,
                 user_data=self.get_user_data(),
                 addressing_type=addressing_type,
                 instance_type=instance_type,
                 placement=availability_zone,
                 kernel_id=kernel_id,
                 ramdisk_id=ramdisk_id,
                 monitoring_enabled=monitoring_enabled,
                 block_device_map=block_device_map,
                 security_group_ids=security_groups,
             )
             for idx, instance in enumerate(reservation.instances):
                 # Add tags for newly launched instance(s)
                 # Try adding name tag (from collection of name input fields)
                 input_field_name = 'name_{0}'.format(idx)
                 name = self.request.params.get(input_field_name, '').strip()
                 new_instance_ids.append(name or instance.id)
                 if name:
                     instance.add_tag('Name', name)
                 if tags_json:
                     tags = json.loads(tags_json)
                     for tagname, tagvalue in tags.items():
                         instance.add_tag(tagname, tagvalue)
             msg = _(u'Successfully sent launch instances request.  It may take a moment to launch instances ')
             msg += ', '.join(new_instance_ids)
             self.request.session.flash(msg, queue=Notification.SUCCESS)
         return HTTPFound(location=self.location)
     return self.render_dict
Пример #39
0
 def instance_more_launch(self):
     """Handles the POST from the Launch more instances like this form"""
     if self.launch_more_form.validate():
         image_id = self.image.id
         source_instance_tags = self.instance.tags
         key_name = self.instance.key_name
         num_instances = int(self.request.params.get('number', 1))
         security_groups = [group.name for group in self.instance.groups]
         instance_type = self.instance.instance_type
         availability_zone = self.instance.placement
         kernel_id = self.request.params.get('kernel_id') or None
         ramdisk_id = self.request.params.get('ramdisk_id') or None
         monitoring_enabled = self.request.params.get('monitoring_enabled') == 'y'
         private_addressing = self.request.params.get('private_addressing') == 'y'
         addressing_type = 'private' if private_addressing else 'public'
         bdmapping_json = self.request.params.get('block_device_mapping')
         block_device_map = self.get_block_device_map(bdmapping_json)
         new_instance_ids = []
         with boto_error_handler(self.request, self.location):
             self.log_request(_(u"Running instance(s) (num={0}, image={1}, type={2})").format(
                 num_instances, image_id, instance_type))
             reservation = self.conn.run_instances(
                 image_id,
                 min_count=num_instances,
                 max_count=num_instances,
                 key_name=key_name,
                 user_data=self.get_user_data(),
                 addressing_type=addressing_type,
                 instance_type=instance_type,
                 placement=availability_zone,
                 kernel_id=kernel_id,
                 ramdisk_id=ramdisk_id,
                 monitoring_enabled=monitoring_enabled,
                 block_device_map=block_device_map,
                 security_group_ids=security_groups,
             )
             for idx, instance in enumerate(reservation.instances):
                 # Add tags for newly launched instance(s)
                 # Try adding name tag (from collection of name input fields)
                 input_field_name = 'name_{0}'.format(idx)
                 name = self.request.params.get(input_field_name, '').strip()
                 new_instance_ids.append(name or instance.id)
                 if name:
                     instance.add_tag('Name', name)
                 if source_instance_tags:
                     for tagname, tagvalue in source_instance_tags.items():
                         # Don't copy 'Name' tag, and avoid tags that start with 'aws:' and 'euca:'
                         if all([tagname != 'Name', not tagname.startswith('aws:'), not tagname.startswith('euca:')]):
                             instance.add_tag(tagname, tagvalue)
             msg = _(u'Successfully sent launch instances request.  It may take a moment to launch instances ')
             msg += ', '.join(new_instance_ids)
             self.request.session.flash(msg, queue=Notification.SUCCESS)
         return HTTPFound(location=self.location)
     else:
         self.request.error_messages = self.launch_more_form.get_errors_list()
     return self.render_dict
Пример #40
0
class GeneratePasswordForm(BaseSecureForm):
    """CSRF-protected form to generate a random password"""
    password = wtforms.PasswordField(
        _(u'Your password'),
        validators=[
            validators.InputRequired(message=_(u'A password is required')),
            validators.Length(
                min=6, message=_(u'Password must be more than 6 characters'))
        ],
        widget=widgets.PasswordInput())
Пример #41
0
    def launchconfig_create(self):
        """Handles the POST from the Create Launch Configuration wizard"""
        if self.create_form.validate():
            autoscale_conn = self.get_connection(conn_type='autoscale')
            location = self.request.route_path('launchconfigs')
            image_id = self.image.id
            name = self.request.params.get('name')
            key_name = self.request.params.get('keypair')
            if key_name and key_name == 'none':
                key_name = None  # Handle "None (advanced)" option
            securitygroup = self.request.params.get('securitygroup', 'default')
            security_groups = [securitygroup]  # Security group names
            instance_type = self.request.params.get('instance_type',
                                                    'm1.small')
            kernel_id = self.request.params.get('kernel_id') or None
            ramdisk_id = self.request.params.get('ramdisk_id') or None
            monitoring_enabled = self.request.params.get(
                'monitoring_enabled') == 'y'
            bdmapping_json = self.request.params.get('block_device_mapping')
            block_device_mappings = [
                self.get_block_device_map(bdmapping_json)
            ] if bdmapping_json != '{}' else None
            with boto_error_handler(self.request, location):
                self.log_request(
                    _(u"Creating launch configuration {0}").format(name))
                launch_config = LaunchConfiguration(
                    name=name,
                    image_id=image_id,
                    key_name=key_name,
                    security_groups=security_groups,
                    user_data=self.get_user_data(),
                    instance_type=instance_type,
                    kernel_id=kernel_id,
                    ramdisk_id=ramdisk_id,
                    block_device_mappings=block_device_mappings,
                    instance_monitoring=monitoring_enabled,
                )
                autoscale_conn.create_launch_configuration(
                    launch_config=launch_config)
                msg = _(
                    u'Successfully sent create launch configuration request. '
                    u'It may take a moment to create the launch configuration.'
                )
                queue = Notification.SUCCESS
                self.request.session.flash(msg, queue=queue)

            if self.request.params.get('create_sg_from_lc') == 'y':
                escaped_name = quote(name)
                location = self.request.route_path('scalinggroup_new') + (
                    "?launch_config={0}".format(escaped_name))
            return HTTPFound(location=location)
        else:
            self.request.error_messages = self.create_form.get_errors_list()
        return self.render_dict
Пример #42
0
 def user_delete_password(self):
     """ calls iam:DeleteLoginProfile """
     if not (self.is_csrf_valid()):
         return JSONResponse(status=400, message="missing CSRF token")
     with boto_error_handler(self.request):
         self.log_request(
             _(u"Deleting password for user {0}").format(
                 self.user.user_name))
         self.conn.delete_login_profile(user_name=self.user.user_name)
         return dict(message=_(u"Successfully deleted user password"),
                     results="true")
Пример #43
0
 def validate_item(self, request):
     try:
         user_id = int(request.matchdict['user_id'])
         item_id = int(request.matchdict['item_id'])
         try:
             DBSession.query(Item).filter_by(id=item_id,
                                             user_id=user_id).one()
         except NoResultFound:
             request.errors.add('url', 'item_id', _(u"Item doesn't exist"))
     except ValueError:
         request.errors.add('url', 'item_id', _(u'Invalid Item ID'))
Пример #44
0
class LaunchMoreInstancesForm(BaseSecureForm):
    """Form class for launch more instances like this one"""
    number_error_msg = _(
        u'Number of instances must be a whole number greater than 0')
    number = wtforms.IntegerField(
        label=_(u'How many instances would you like to launch?'),
        validators=[
            validators.InputRequired(message=number_error_msg),
            validators.NumberRange(
                min=1, max=10
            ),  # Restrict num instances that can be launched in one go
        ],
    )
    userdata = wtforms.TextAreaField(label=_(u'User data'))
    userdata_file_helptext = _(u'User data file may not exceed 16 KB')
    userdata_file = wtforms.FileField(label=_(u''))
    kernel_id = wtforms.SelectField(label=_(u'Kernel ID'))
    ramdisk_id = wtforms.SelectField(label=_(u'RAM disk ID (RAMFS)'))
    monitoring_enabled = wtforms.BooleanField(
        label=_(u'Enable detailed monitoring'))
    private_addressing = wtforms.BooleanField(
        label=_(u'Use private addressing only'))

    def __init__(self,
                 request,
                 image=None,
                 instance=None,
                 conn=None,
                 **kwargs):
        super(LaunchMoreInstancesForm, self).__init__(request, **kwargs)
        self.image = image
        self.instance = instance
        self.conn = conn
        self.choices_manager = ChoicesManager(conn=conn)
        self.set_error_messages()
        self.set_help_text()
        self.set_choices()
        self.set_initial_data()

    def set_error_messages(self):
        self.number.error_msg = self.number_error_msg

    def set_help_text(self):
        self.userdata_file.help_text = self.userdata_file_helptext

    def set_choices(self):
        self.kernel_id.choices = self.choices_manager.kernels(image=self.image)
        self.ramdisk_id.choices = self.choices_manager.ramdisks(
            image=self.image)

    def set_initial_data(self):
        self.monitoring_enabled.data = self.instance.monitored
        self.private_addressing.data = self.enable_private_addressing()
        self.number.data = 1

    def enable_private_addressing(self):
        if self.instance.private_ip_address == self.instance.ip_address:
            return True
        return False
Пример #45
0
class AllocateIPsForm(BaseSecureForm):
    """Allocate IP Addresses form, used on IP Addresses landing page in modal dialog"""
    ipcount_error_msg = _(u'Please enter a whole number greater than zero')
    ipcount = wtforms.IntegerField(
        label=_(u'Number to allocate:'),
        validators=[validators.InputRequired(message=ipcount_error_msg)],
    )

    def __init__(self, request, **kwargs):
        super(AllocateIPsForm, self).__init__(request, **kwargs)
        self.ipcount.error_msg = self.ipcount_error_msg
Пример #46
0
 def securitygroup_delete(self):
     location = self.request.route_path('securitygroups')
     if self.security_group and self.delete_form.validate():
         name = self.security_group.name
         with boto_error_handler(self.request, location):
             self.log_request(_(u"Deleting security group {0}").format(name))
             self.security_group.delete()
             prefix = _(u'Successfully deleted security group')
             msg = '{0} {1}'.format(prefix, name)
             self.request.session.flash(msg, queue=Notification.SUCCESS)
         return HTTPFound(location=location)
     return self.render_dict
Пример #47
0
 def user_delete_key(self):
     """ calls iam:DeleteAccessKey """
     if not (self.is_csrf_valid()):
         return JSONResponse(status=400, message="missing CSRF token")
     key_id = self.request.matchdict.get('key')
     with boto_error_handler(self.request):
         self.log_request(
             _(u"Deleting access key {0} for user {1}").format(
                 key_id, self.user.user_name))
         result = self.conn.delete_access_key(user_name=self.user.user_name,
                                              access_key_id=key_id)
         return dict(message=_(u"Successfully deleted key"))
Пример #48
0
 def validate_image(self, request):
     try:
         item_id = int(request.matchdict['item_id'])
         image_id = int(request.matchdict['image_id'])
         try:
             DBSession.query(ItemImage).filter_by(id=image_id,
                                                  item_id=item_id).one()
         except NoResultFound:
             request.errors.add('url', 'image_id',
                                _(u"Image doesn't exist"))
     except ValueError:
         request.errors.add('url', 'image_id', _(u'Invalid Image ID'))
Пример #49
0
 def ipaddress_release(self):
     if self.release_form.validate():
         location = self.request.route_path('ipaddresses')
         with boto_error_handler(self.request, location):
             self.log_request(
                 _(u"Releasing ElasticIP {0}").format(self.elastic_ip))
             self.elastic_ip.release()
             msg = _(u'Successfully released {ip} to the cloud')
             notification_msg = msg.format(ip=self.elastic_ip.public_ip)
             self.request.session.flash(notification_msg,
                                        queue=Notification.SUCCESS)
         return HTTPFound(location=location)
     return self.render_dict
Пример #50
0
 def set_volume_choices(self):
     """Populate volume field with volumes available to attach"""
     choices = [('', _(u'select...'))]
     for volume in self.volumes:
         if self.instance and volume.zone == self.instance.placement and volume.attach_data.status is None:
             name_tag = volume.tags.get('Name')
             extra = ' ({name})'.format(name=name_tag) if name_tag else ''
             vol_name = '{id}{extra}'.format(id=volume.id, extra=extra)
             choices.append((volume.id, vol_name))
     if len(choices) == 1:
         choices = [('',
                     _(u'No available volumes in this availability zone'))]
     self.volume_id.choices = choices