Example #1
0
        def rg_wrapper(request, g_id):

            if not request.POST:
                return redirect('django_rg.views.viewgateway', g_id=g_id)

            session = request.session
            username = session['login_email']
            try:
                g = db.read_replica_gateway(g_id)
                if not g:
                    raise Exception("No gateway exists.")
            except Exception as e:
                logging.error("Error reading gateway %s : Exception: %s" %
                              (g_id, e))
                message = "No replica gateway by the name of %s exists." % g_id
                t = loader.get_template(
                    "gateway_templates/viewgateway_failure.html")
                c = Context({'message': message, 'username': username})
                return HttpResponse(t.render(c))

            form = libforms.Password(request.POST)
            if not form.is_valid():
                session['message'] = "Password required."
                return redirect(redirect_view, g_id)
            # Check password hash
            if not RG.authenticate(g, form.cleaned_data['password']):
                session['message'] = "Incorrect password."
                return redirect(redirect_view, g_id)

            return f(request, g_id)
Example #2
0
        def rg_wrapper(request, g_id):
            
            if not request.POST:
                return redirect('django_rg.views.viewgateway', g_id=g_id)

            session = request.session
            username = session['login_email']
            try:
                g = db.read_replica_gateway(g_id)
                if not g:
                    raise Exception("No gateway exists.")
            except Exception as e:
                logging.error("Error reading gateway %s : Exception: %s" % (g_id, e))
                message = "No replica gateway by the name of %s exists." % g_id
                t = loader.get_template("gateway_templates/viewgateway_failure.html")
                c = Context({'message':message, 'username':username})
                return HttpResponse(t.render(c))

            form = libforms.Password(request.POST)
            if not form.is_valid():
                session['message'] = "Password required."
                return redirect(redirect_view, g_id)
            # Check password hash
            if not RG.authenticate(g, form.cleaned_data['password']):
                session['message'] = "Incorrect password."
                return redirect(redirect_view, g_id)

            return f(request, g_id)
Example #3
0
def changeprivacy(request, g_id):
    '''
    Handler for changing privacy settings.
    '''
    session = request.session
    username = session['login_email']
    g_id = int(g_id)

    g = db.read_replica_gateway(g_id)
    if g.private:
        fields = {'private': False}
    else:
        fields = {'private': True}
    try:
        db.update_replica_gateway(g_id, **fields)
        session[
            'new_change'] = "We've changed your gateways's privacy setting."
        session['next_url'] = '/syn/RG/viewgateway/' + str(g_id)
        session['next_message'] = "Click here to go back to your gateway."
        return redirect('/syn/thanks')
    except Exception as e:
        session['message'] = "Unable to update gateway."
        logging.info(message)
        logging.info(e)
        return redirect('django_rg.views.viewgateway', g_id)
Example #4
0
def changepassword(request, g_id):
    '''
    Handler for changing gateway password. Since it can't use precheck because of password reasons,
    must verify POST-ness itself.
    '''
    session = request.session
    username = session['login_email']
    g_id = int(g_id)

    # Precheck
    if request.method != "POST":
        return redirect('/syn/RG/viewgateway/' + str(g_id))

    try:
        g = db.read_replica_gateway(g_id)
        if not g:
            raise Exception("No gateway exists.")
    except Exception as e:
        logging.error("Error reading gateway %d : Exception: %s" % (g_id, e))
        message = "No replica gateway with the ID %d exists." % g_id
        t = loader.get_template("gateway_templates/viewgateway_failure.html")
        c = Context({'message': message, 'username': username})
        return HttpResponse(t.render(c))

    form = libforms.ChangePassword(request.POST)
    if not form.is_valid():
        session['message'] = "You must fill out all password fields."
        return redirect('django_rg.views.viewgateway', g_id)
    else:
        # Check password hash
        if not RG.authenticate(g, form.cleaned_data['oldpassword']):
            session['message'] = "Incorrect password."
            return redirect('django_rg.views.viewgateway', g_id)
        elif form.cleaned_data['newpassword_1'] != form.cleaned_data[
                'newpassword_2']:
            session['message'] = "Your new passwords did not match each other."
            return redirect('django_rg.views.viewgateway', g_id)
        # Ok to change password
        else:
            new_hash = RG.generate_password_hash(
                form.cleaned_data['newpassword_1'])
            fields = {'ms_password_hash': new_hash}
            try:
                db.update_replica_gateway(g_id, **fields)
            except Exception as e:
                logging.error(
                    "Unable to update replica gateway %d. Exception %s" %
                    (g_id, e))
                session['message'] = "Unable to update gateway."
                return redirect('django_rg.views.viewgateway', g_id)

            session['new_change'] = "We've changed your gateways's password."
            session['next_url'] = '/syn/RG/viewgateway/' + str(g_id)
            session['next_message'] = "Click here to go back to your volume."
            return redirect('/syn/thanks')
Example #5
0
def changepassword(request, g_id):
    '''
    Handler for changing gateway password. Since it can't use precheck because of password reasons,
    must verify POST-ness itself.
    '''
    session = request.session
    username = session['login_email']
    g_id = int(g_id)

    # Precheck
    if request.method != "POST":
        return redirect('/syn/RG/viewgateway/' + str(g_id))

    try:
        g = db.read_replica_gateway(g_id)
        if not g:
            raise Exception("No gateway exists.")
    except Exception as e:
        logging.error("Error reading gateway %d : Exception: %s" % (g_id, e))
        message = "No replica gateway with the ID %d exists." % g_id
        t = loader.get_template("gateway_templates/viewgateway_failure.html")
        c = Context({'message':message, 'username':username})
        return HttpResponse(t.render(c))



    form = libforms.ChangePassword(request.POST)
    if not form.is_valid():
        session['message'] = "You must fill out all password fields."
        return redirect('django_rg.views.viewgateway', g_id)
    else:
        # Check password hash
        if not RG.authenticate(g, form.cleaned_data['oldpassword']):
            session['message'] = "Incorrect password."
            return redirect('django_rg.views.viewgateway', g_id)
        elif form.cleaned_data['newpassword_1'] != form.cleaned_data['newpassword_2']:
            session['message'] = "Your new passwords did not match each other."
            return redirect('django_rg.views.viewgateway', g_id)
        # Ok to change password
        else:
            new_hash = RG.generate_password_hash(form.cleaned_data['newpassword_1'])
            fields = {'ms_password_hash':new_hash}
            try:
                db.update_replica_gateway(g_id, **fields)
            except Exception as e:
                logging.error("Unable to update replica gateway %d. Exception %s" % (g_id, e))
                session['message'] = "Unable to update gateway."
                return redirect('django_rg.views.viewgateway', g_id)

            session['new_change'] = "We've changed your gateways's password."
            session['next_url'] = '/syn/RG/viewgateway/' + str(g_id)
            session['next_message'] = "Click here to go back to your volume."
            return redirect('/syn/thanks')
Example #6
0
def changeprivacy(request, g_id):
    '''
    Handler for changing privacy settings.
    '''
    session = request.session
    username = session['login_email']
    g_id = int(g_id)

    g = db.read_replica_gateway(g_id)
    if g.private:
        fields = {'private':False}
    else:
        fields = {'private':True}
    try:
        db.update_replica_gateway(g_id, **fields)
        session['new_change'] = "We've changed your gateways's privacy setting."
        session['next_url'] = '/syn/RG/viewgateway/' + str(g_id)
        session['next_message'] = "Click here to go back to your gateway."
        return redirect('/syn/thanks')
    except Exception as e:
        session['message'] = "Unable to update gateway."
        logging.info(message)
        logging.info(e)
        return redirect('django_rg.views.viewgateway', g_id)
Example #7
0
def delete(request, g_id):
    '''
    View for deleting AG.
    '''

    # Helper method used to simplify error-handling. When fields are entered incorrectly,
    # a session message is set and this method is called.
    def give_delete_form(username, g, session):
        form = gatewayforms.DeleteGateway()
        t = loader.get_template(
            'gateway_templates/delete_replica_gateway.html')
        c = RequestContext(
            request, {
                'username': username,
                'g': g,
                'form': form,
                'message': session.pop('message', "")
            })
        return HttpResponse(t.render(c))

    # Once again isolating transactional for views that update multiple entities
    @transactional(xg=True)
    def delete_and_update(rg_id, attached_volume_ids):
        db.delete_replica_gateway(rg_id)
        for v in attached_volume_ids:
            vol = db.read_volume(v)
            if not vol:
                continue
            new_rg_ids = vol.rg_ids
            new_rg_ids.remove(rg_id)
            attrs = {"rg_ids": new_rg_ids}
            db.update_volume(v, **attrs)
        session.pop("rg_initial_data" + str(g_id), None)

    session = request.session
    username = session['login_email']
    g_id = int(g_id)

    rg = db.read_replica_gateway(g_id)
    if not rg:
        t = loader.get_template(
            'gateway_templates/delete_replica_gateway_failure.html')
        c = RequestContext(request, {'username': username, 'g_name': g_name})
        return HttpResponse(t.render(c))

    if request.POST:
        # Validate input forms
        form = gatewayforms.DeleteGateway(request.POST)
        if form.is_valid():
            if not RG.authenticate(rg, form.cleaned_data['g_password']):
                session['message'] = "Incorrect Replica Gateway password"
                return give_delete_form(username, rg, session)
            if not form.cleaned_data['confirm_delete']:
                session[
                    'message'] = "You must tick the delete confirmation box."
                return give_delete_form(username, rg, session)

            delete_and_update(g_id, rg.volume_ids)
            session['new_change'] = "Your gateway has been deleted."
            session['next_url'] = '/syn/RG/allgateways'
            session['next_message'] = "Click here to see all replica gateways."
            return redirect('/syn/thanks/')

        # invalid forms
        else:
            # Prep error message
            session['message'] = "Invalid form entry: "

            for k, v in form.errors.items():
                session[
                    'message'] = session['message'] + "\"" + k + "\"" + " -> "
                for m in v:
                    session['message'] = session['message'] + m + " "

            return give_delete_form(username, rg, session)
    else:
        # Not a POST, give them blank form
        return give_delete_form(username, rg, session)
Example #8
0
def viewgateway(request, g_id=0):
    '''
    The view for viewing and changing any of the main settings on any RG. Passes
    forms for changing different settings, and the volumes attached to the gateway.
    '''
    session = request.session
    username = session['login_email']
    g_id = int(g_id)

    # Check for any passed error messages and initial_data from state to save db calls.
    message = session.pop('message', "")
    rg_initial_data = session.get('rg_initial_data' + str(g_id), [])

    # Make sure gateway exists.
    g = db.read_replica_gateway(g_id)
    if not g:
        logging.error("Error reading gateway %d : Exception: %s" % (g_id, e))
        message = "No replica gateway with the ID %d exists." % g_id
        t = loader.get_template("gateway_templates/viewgateway_failure.html")
        c = Context({'message': message, 'username': username})
        return HttpResponse(t.render(c))

    # Create forms for changing location, adding volumes,
    # changing password, getting password, and changing config
    location_form = gatewayforms.ModifyGatewayLocation(initial={
        'host': g.host,
        'port': g.port
    })
    add_form = gatewayforms.GatewayAddVolume()
    json_form = gatewayforms.ModifyGatewayConfig()
    password_form = libforms.Password()
    change_password_form = libforms.ChangePassword()

    # Get all attached volumes and their respective owners
    owners = []
    vols = []
    for v_id in g.volume_ids:
        vol = db.read_volume(v_id)
        if not vol:
            logging.error(
                "Volume ID in gateways volume_ids does not map to volume. Gateway: %s"
                % g_name)
        else:
            vols.append(vol)
            attrs = {"SyndicateUser.owner_id ==": vol.owner_id}
            owners.append(db.get_user(attrs))
    vol_owners = zip(vols, owners)

    # Create formatted data based on vols for the formset, if not passed in state.
    if not rg_initial_data:
        for v in vols:
            rg_initial_data.append({'volume_name': v.name, 'remove': False})
        session['rg_initial_data' + str(g_id)] = rg_initial_data

    VolumeFormSet = formset_factory(gatewayforms.GatewayRemoveVolume, extra=0)
    if rg_initial_data:
        formset = VolumeFormSet(initial=rg_initial_data)
    else:
        formset = []

    t = loader.get_template("gateway_templates/viewreplicagateway.html")
    c = RequestContext(
        request, {
            'username': username,
            'gateway': g,
            'message': message,
            'vol_owners': vol_owners,
            'location_form': location_form,
            'add_form': add_form,
            'json_form': json_form,
            'remove_forms': formset,
            'password_form': password_form,
            'change_password_form': change_password_form
        })
    return HttpResponse(t.render(c))
Example #9
0
def removevolumes(request, g_id):
    '''
    This handler allows removal of one or many volumes from an Aqcquisition
    Gateway. It calls multi_update() as a helper method to allow transactional
    updates to the database.
    '''
    # This is a helper method that isolates the @transactional decorator, speeding
    # up the code when it doesn't reach update() in this view and allowing for
    # errors that would break in GAE if the decorator was applied to the entire view.
    # It updates multiple volumes at once
    @transactional(xg=True)
    def multi_update(v_ids, g_id, vfields, gfields):

        for v_id, vfield in zip(v_ids, vfields):
            db.update_volume(v_id, **vfield)
        db.update_replica_gateway(g_id, **gfields)
        session.pop('rg_initial_data' + str(g_id))

    session = request.session
    username = session['login_email']
    g_id = int(g_id)

    VolumeFormSet = formset_factory(gatewayforms.GatewayRemoveVolume, extra=0)
    formset = VolumeFormSet(request.POST)

    # This call is not checked because the formset will always be valid (readonly widgets)
    formset.is_valid()

    volume_ids_to_be_removed = []
    new_rgs_set = []

    initial_and_forms = zip(session.get('rg_initial_data' + str(g_id), []),
                            formset.forms)
    for i, f in initial_and_forms:

        if f.cleaned_data['remove']:
            attrs = {"Volume.name ==": i['volume_name']}
            vols = db.list_volumes(attrs, limit=1)
            vol = vols[0]

            # update each volumes new RG list
            new_rgs = vol.rg_ids
            new_rgs.remove(g_id)
            new_rgs_set.append({'rg_ids': new_rgs})

            # update info for AG update
            volume_ids_to_be_removed.append(vol.volume_id)

    if not volume_ids_to_be_removed:
        session['message'] = "You must select at least one volume to remove."
        return redirect('django_rg.views.viewgateway', g_id)

    old_vids = set(db.read_replica_gateway(g_id).volume_ids)
    new_vids = list(old_vids - set(volume_ids_to_be_removed))
    gfields = {'volume_ids': new_vids}
    try:
        multi_update(volume_ids_to_be_removed, g_id, new_rgs_set, gfields)
    except Exception as e:
        logging.error("Unable to update replica gateway %d. Exception %s" %
                      (g_id, e))
        session['message'] = "Unable to update gateway."
        return redirect('django_rg.views.viewgateway', g_id)
    session['new_change'] = "We've updated your RG's volumes."
    session['next_url'] = '/syn/RG/viewgateway/' + str(g_id)
    session['next_message'] = "Click here to go back to your gateway."
    return redirect('/syn/thanks')
Example #10
0
def addvolume(request, g_id):
    '''
    Handler for adding a volume to the gateay.
    '''

    # This is a helper method that isolates the @transactional decorator, speeding
    # up the code when it doesn't reach update() in this view and allowing for
    # errors that would break in GAE if the decorator was applied to the entire view.
    @transactional(xg=True)
    def update(v_id, g_id, vfields, gfields):
        db.update_volume(v_id, **vfields)
        db.update_replica_gateway(g_id, **gfields)
        session.pop('rg_initial_data' + str(g_id))

    session = request.session
    username = session['login_email']
    g_id = int(g_id)

    form = gatewayforms.GatewayAddVolume(request.POST)
    if form.is_valid():
        attrs = {
            "Volume.name ==":
            form.cleaned_data['volume_name'].strip().replace(" ", "_")
        }
        vols = db.list_volumes(attrs, limit=1)
        if vols:
            volume = vols[0]
            logging.info(volume)
        else:
            session[
                'message'] = "The volume %s doesn't exist." % form.cleaned_data[
                    'volume_name']
            return redirect('django_ag.views.viewgateway', g_id)

        gateway = db.read_replica_gateway(g_id)

        # prepare volume state
        if volume.rg_ids:
            new_rgs = volume.rg_ids
            new_rgs.append(gateway.g_id)
        else:
            new_rgs = [gateway.g_id]
        vfields = {'rg_ids': new_rgs}

        # prepate RG state
        old_vids = gateway.volume_ids
        new_vid = volume.volume_id
        if new_vid in old_vids:
            session[
                'message'] = "That volume is already attached to this gateway!"
            return redirect('django_rg.views.viewgateway', g_id)
        if old_vids:
            old_vids.append(new_vid)
            new_vids = old_vids
        else:
            new_vids = [new_vid]

        # Update and redirect
        try:
            gfields = {'volume_ids': new_vids}
            update(volume.volume_id, g_id, vfields, gfields)
        except Exception as e:
            logging.error(
                "Unable to update replica gateway %s or volume %s. Exception %s"
                % (rg.ms_username, volume.name, e))
            session['message'] = "Unable to update."
            return redirect('django_rg.views.viewgateway', g_id)
        session['new_change'] = "We've updated your RG's volumes."
        session['next_url'] = '/syn/RG/viewgateway/' + str(g_id)
        session['next_message'] = "Click here to go back to your gateway."
        return redirect('/syn/thanks')
    else:
        session['message'] = "Invalid entries for adding volumes."
        return redirect('django_rg.views.viewgateway', g_id)
Example #11
0
def delete(request, g_id):
    '''
    View for deleting AG.
    '''

    # Helper method used to simplify error-handling. When fields are entered incorrectly,
    # a session message is set and this method is called.
    def give_delete_form(username, g, session):
        form = gatewayforms.DeleteGateway()
        t = loader.get_template('gateway_templates/delete_replica_gateway.html')
        c = RequestContext(request, {'username':username, 'g':g, 'form':form, 'message':session.pop('message', "")})
        return HttpResponse(t.render(c))

    # Once again isolating transactional for views that update multiple entities
    @transactional(xg=True)
    def delete_and_update(rg_id, attached_volume_ids):
        db.delete_replica_gateway(rg_id)
        for v in attached_volume_ids:
            vol = db.read_volume(v)
            if not vol:
                continue
            new_rg_ids = vol.rg_ids
            new_rg_ids.remove(rg_id)
            attrs = {"rg_ids":new_rg_ids}
            db.update_volume(v, **attrs)
        session.pop("rg_initial_data" + str(g_id), None)

    session = request.session
    username = session['login_email']
    g_id = int(g_id)

    rg = db.read_replica_gateway(g_id)
    if not rg:
        t = loader.get_template('gateway_templates/delete_replica_gateway_failure.html')
        c = RequestContext(request, {'username':username, 'g_name':g_name})
        return HttpResponse(t.render(c))

    if request.POST:
        # Validate input forms
        form = gatewayforms.DeleteGateway(request.POST)
        if form.is_valid():
            if not RG.authenticate(rg, form.cleaned_data['g_password']):
                session['message'] = "Incorrect Replica Gateway password"
                return give_delete_form(username, rg, session)
            if not form.cleaned_data['confirm_delete']:
                session['message'] = "You must tick the delete confirmation box."
                return give_delete_form(username, rg, session)
            
            delete_and_update(g_id, rg.volume_ids)
            session['new_change'] = "Your gateway has been deleted."
            session['next_url'] = '/syn/RG/allgateways'
            session['next_message'] = "Click here to see all replica gateways."
            return redirect('/syn/thanks/')

        # invalid forms
        else:  
            # Prep error message
            session['message'] = "Invalid form entry: "

            for k, v in form.errors.items():
                session['message'] = session['message'] + "\"" + k + "\"" + " -> " 
                for m in v:
                    session['message'] = session['message'] + m + " "

            return give_delete_form(username, rg, session)
    else:
        # Not a POST, give them blank form
        return give_delete_form(username, rg, session)
Example #12
0
def viewgateway(request, g_id=0):
    '''
    The view for viewing and changing any of the main settings on any RG. Passes
    forms for changing different settings, and the volumes attached to the gateway.
    '''
    session = request.session
    username = session['login_email']
    g_id = int(g_id)

    # Check for any passed error messages and initial_data from state to save db calls.
    message = session.pop('message', "")
    rg_initial_data = session.get('rg_initial_data' + str(g_id), [])

    # Make sure gateway exists.
    g = db.read_replica_gateway(g_id)
    if not g:
        logging.error("Error reading gateway %d : Exception: %s" % (g_id, e))
        message = "No replica gateway with the ID %d exists." % g_id
        t = loader.get_template("gateway_templates/viewgateway_failure.html")
        c = Context({'message':message, 'username':username})
        return HttpResponse(t.render(c))

    # Create forms for changing location, adding volumes,
    # changing password, getting password, and changing config
    location_form = gatewayforms.ModifyGatewayLocation(initial={'host':g.host,
                                                                'port':g.port})
    add_form = gatewayforms.GatewayAddVolume()
    json_form = gatewayforms.ModifyGatewayConfig()
    password_form = libforms.Password()
    change_password_form = libforms.ChangePassword()

    # Get all attached volumes and their respective owners
    owners = []
    vols = []
    for v_id in g.volume_ids:
        vol = db.read_volume(v_id)
        if not vol:
            logging.error("Volume ID in gateways volume_ids does not map to volume. Gateway: %s" % g_name)
        else:
            vols.append(vol)
            attrs = {"SyndicateUser.owner_id ==": vol.owner_id}
            owners.append(db.get_user(attrs))
    vol_owners = zip(vols, owners)

    # Create formatted data based on vols for the formset, if not passed in state.
    if not rg_initial_data:
        for v in vols:
            rg_initial_data.append({'volume_name':v.name,
                                    'remove':False})
        session['rg_initial_data' + str(g_id)] = rg_initial_data

    VolumeFormSet = formset_factory(gatewayforms.GatewayRemoveVolume, extra=0)
    if rg_initial_data:
        formset = VolumeFormSet(initial=rg_initial_data)
    else:
        formset = []

    t = loader.get_template("gateway_templates/viewreplicagateway.html")
    c = RequestContext(request, {'username':username,
                        'gateway':g,
                        'message':message,
                        'vol_owners':vol_owners,
                        'location_form':location_form,
                        'add_form':add_form,
                        'json_form':json_form,
                        'remove_forms':formset,
                        'password_form':password_form,
                        'change_password_form':change_password_form})
    return HttpResponse(t.render(c))
Example #13
0
def removevolumes(request, g_id):
    '''
    This handler allows removal of one or many volumes from an Aqcquisition
    Gateway. It calls multi_update() as a helper method to allow transactional
    updates to the database.
    '''
    # This is a helper method that isolates the @transactional decorator, speeding
    # up the code when it doesn't reach update() in this view and allowing for
    # errors that would break in GAE if the decorator was applied to the entire view.
    # It updates multiple volumes at once
    @transactional(xg=True)
    def multi_update(v_ids, g_id, vfields, gfields):

        for v_id, vfield in zip(v_ids, vfields):
            db.update_volume(v_id, **vfield)
        db.update_replica_gateway(g_id, **gfields)
        session.pop('rg_initial_data' + str(g_id))

    session = request.session
    username = session['login_email']
    g_id = int(g_id)

    VolumeFormSet = formset_factory(gatewayforms.GatewayRemoveVolume, extra=0)
    formset = VolumeFormSet(request.POST)

    # This call is not checked because the formset will always be valid (readonly widgets)
    formset.is_valid()

    volume_ids_to_be_removed = []
    new_rgs_set = []

    initial_and_forms = zip(session.get('rg_initial_data' + str(g_id), []), formset.forms)
    for i, f in initial_and_forms:

        if f.cleaned_data['remove']:
            attrs = {"Volume.name ==":i['volume_name']}
            vols = db.list_volumes(attrs, limit=1)
            vol = vols[0]

            # update each volumes new RG list
            new_rgs = vol.rg_ids
            new_rgs.remove(g_id)
            new_rgs_set.append({'rg_ids':new_rgs})

            # update info for AG update
            volume_ids_to_be_removed.append(vol.volume_id)

    if not volume_ids_to_be_removed:
        session['message'] = "You must select at least one volume to remove."
        return redirect('django_rg.views.viewgateway', g_id)

    old_vids = set(db.read_replica_gateway(g_id).volume_ids)
    new_vids = list(old_vids - set(volume_ids_to_be_removed))
    gfields = {'volume_ids':new_vids}
    try:
        multi_update(volume_ids_to_be_removed, g_id, new_rgs_set, gfields)
    except Exception as e:
         logging.error("Unable to update replica gateway %d. Exception %s" % (g_id, e))
         session['message'] = "Unable to update gateway."
         return redirect('django_rg.views.viewgateway', g_id)
    session['new_change'] = "We've updated your RG's volumes."
    session['next_url'] = '/syn/RG/viewgateway/' + str(g_id)
    session['next_message'] = "Click here to go back to your gateway."
    return redirect('/syn/thanks')
Example #14
0
def addvolume(request, g_id):
    '''
    Handler for adding a volume to the gateay.
    '''

    # This is a helper method that isolates the @transactional decorator, speeding
    # up the code when it doesn't reach update() in this view and allowing for
    # errors that would break in GAE if the decorator was applied to the entire view.
    @transactional(xg=True)
    def update(v_id, g_id, vfields, gfields):
        db.update_volume(v_id, **vfields)
        db.update_replica_gateway(g_id, **gfields)
        session.pop('rg_initial_data' + str(g_id))

    session = request.session
    username = session['login_email']
    g_id = int(g_id)


    form = gatewayforms.GatewayAddVolume(request.POST)
    if form.is_valid():
        attrs = {"Volume.name ==":form.cleaned_data['volume_name'].strip().replace(" ", "_")}
        vols = db.list_volumes(attrs, limit=1)
        if vols:
            volume = vols[0]
            logging.info(volume)
        else:
            session['message'] = "The volume %s doesn't exist." % form.cleaned_data['volume_name']
            return redirect('django_ag.views.viewgateway', g_id)

        gateway = db.read_replica_gateway(g_id)

        # prepare volume state
        if volume.rg_ids:
            new_rgs = volume.rg_ids
            new_rgs.append(gateway.g_id)
        else:
            new_rgs = [gateway.g_id]
        vfields = {'rg_ids':new_rgs}

        # prepate RG state
        old_vids = gateway.volume_ids
        new_vid = volume.volume_id
        if new_vid in old_vids:
            session['message'] = "That volume is already attached to this gateway!"
            return redirect('django_rg.views.viewgateway', g_id)
        if old_vids:
            old_vids.append(new_vid)
            new_vids = old_vids
        else:
            new_vids = [new_vid]

        # Update and redirect
        try:
            gfields={'volume_ids':new_vids}
            update(volume.volume_id, g_id, vfields, gfields)
        except Exception as e:
            logging.error("Unable to update replica gateway %s or volume %s. Exception %s" % (rg.ms_username, volume.name, e))
            session['message'] = "Unable to update."
            return redirect('django_rg.views.viewgateway', g_id)
        session['new_change'] = "We've updated your RG's volumes."
        session['next_url'] = '/syn/RG/viewgateway/' + str(g_id)
        session['next_message'] = "Click here to go back to your gateway."
        return redirect('/syn/thanks')
    else:
        session['message'] = "Invalid entries for adding volumes."
        return redirect('django_rg.views.viewgateway', g_id)
Example #15
0
def changegateways_rg(request, volume_id):
    session = request.session
    username = session['login_email']
    vol = db.read_volume(volume_id)
    if not vol:
        return redirect('django_volume.views.viewvolume', volume_id)

    @transactional(xg=True)
    def update(v_id, gnames, vfields, gfields):
        db.update_volume(v_id, **vfields)
        for g, gfield in zip(gnames, gfields):
            db.update_replica_gateway(g, **gfield)
        session.pop('volume_initial_rgs' + str(volume_id), None)

    # make sure this variable exists, i.e. they came from the settings page.
    if not 'volume_initial_rgs' + str(volume_id) in session:
        return redirect("django_volume.views.volumesettings", volume_id)

    if request.POST:
        passwordform = libforms.Password(request.POST)
        if not passwordform.is_valid():
            session['message'] = "Password required."
            return redirect('django_volume.views.volumesettings', volume_id)
        else:
            hash_check = Volume.generate_password_hash(
                passwordform.cleaned_data['password'], vol.volume_secret_salt)
            if hash_check != vol.volume_secret_salted_hash:
                session['message'] = "Incorrect password."
                return redirect('django_volume.views.volumesettings',
                                volume_id)

        GatewayFormset = formset_factory(forms.Gateway, extra=0)
        formset = GatewayFormset(request.POST)
        formset.is_valid()
        remove_gateways = []
        remove_gateway_names = []
        remove_gateway_ids = []

        for data, form in zip(session['volume_initial_rgs' + str(volume_id)],
                              formset.forms):
            if form.cleaned_data['remove']:
                g = db.read_replica_gateway(data['g_name'])
                remove_gateways.append(g)
                remove_gateway_names.append(data['g_name'])
                remove_gateway_ids.append(g.rg_id)
        if not remove_gateways:
            return redirect('django_volume.views.volumesettings', volume_id)

        new_rgs = list(set(vol.rg_ids) - set(remove_gateway_ids))
        vfields = {'rg_ids': new_rgs}

        gfields = []
        for g in remove_gateways:
            new_vol_ids = g.volume_ids
            new_vol_ids.remove(vol.volume_id)
            gfields.append({"volume_ids": new_vol_ids})
        try:
            update(vol.volume_id, remove_gateway_names, vfields, gfields)
        except Exception as e:
            session['message'] = "Unable to update volume or RG's."
            return redirect('django_volume.views.volumesettings', volume_id)

        session['new_change'] = "We've updated your volume."
        session['next_url'] = '/syn/volume/' + str(vol.volume_id) + '/settings'
        session['next_message'] = "Click here to go back to your volume."
        return redirect('/syn/thanks')

    else:
        return redirect('django_volume.views.volumesettings',
                        volume_id=vol.volume_id)