Exemplo n.º 1
0
def auto_fs_granter(selexp):
    """
    Grants flowspaces for previously conflictive slices at Flowvisor.
    Used in conjunction **and after** the script with the same name
    at expedient.
    
    Flow:
        1. Expedient: manage.py standardize_flowvisor_slices stop
        2. Expedient: manage.py standardize_flowvisor_slices start
        3. Opt-in: manage.py standardize_flowvisor_slices
    """
    from django.conf import settings
    from openflow.optin_manager.xmlrpc_server.models import FVServerProxy
    from openflow.optin_manager.users.models import Priority, UserProfile
    from django.contrib.auth.models import User
    from openflow.optin_manager.opts.helper import opt_fs_into_exp
    from openflow.optin_manager.flowspace.helper import multi_fs_intersect, single_fs_intersect
    from openflow.optin_manager.opts.models import Experiment, ExperimentFLowSpace, UserFlowSpace, AdminFlowSpace, UserOpts

    # If 'slice_ids_to_grant_fs' file exists, do the following.
    # Otherwise warn and skip.
    try:
        user = User.objects.filter(username=settings.ROOT_USERNAME)[0]
        adminFS = AdminFlowSpace.objects.filter(user = user)
        profile = UserProfile.get_or_create_profile(user)
        fv = FVServerProxy.objects.all()[0]
        assigned_priority = profile.max_priority_level - Priority.Strict_Priority_Offset - 1
        all_this_admin_opts = UserOpts.objects.filter(user=user,nice=True)
        for admin_opt in all_this_admin_opts:
            if admin_opt.priority <= assigned_priority:
                assigned_priority = admin_opt.priority - 1
        # Filter by slice "keywords" (name), same as in the previous steps
        flow_space = ExperimentFLowSpace.objects.filter(exp=selexp.id)
        if not flow_space:
            print "No matched flowspaces for slice %s" % selexp.slice_id
            raise Exception('No matched flowspaces for slice %s' % selexp.slice_id)		
        #intersected_flowspace = multi_fs_intersect(flow_space,adminFS,FlowSpace)
        intersected_flowspace = get_used_fs(flow_space)
        fv_args,match_list = opt_fs_into_exp(intersected_flowspace,selexp,user,assigned_priority,True)
        returned_ids = fv.proxy.api.changeFlowSpace(fv_args)
        for i in range(len(match_list)):
            match_list[i].fv_id = returned_ids[i]
            match_list[i].save()
        allopts = UserOpts.objects.filter(user = user).order_by('-priority')
     
        for opt in allopts:
            this_opt_fses = opt.optsflowspace_set.all()
            fs_project = opt.experiment.project_name or ""
            fs_slice = opt.experiment.slice_name or ""
            fs_description = ""
            for fs in this_opt_fses:
                if fs_description != "":
                    fs_description = fs_description + "\n%s" % fs
                else:
                    fs_description = "%s" % fs
        print "Flowspace for slice %s was successfully granted" % selexp.slice_id 
    except Exception as e:
        raise e 
Exemplo n.º 2
0
def opt_in_from_file(request):
    '''
    This is doing the same as add_opt_in function except the input data
    is coming from an uploaded file
    '''

    profile = UserProfile.get_or_create_profile(request.user)

    if (not profile.is_net_admin):
        return HttpResponseRedirect("/dashboard")
    else:
        # find all experiments that the admin can opt into them.
        all_exps = Experiment.objects.all()
        admin_fs = AdminFlowSpace.objects.filter(user=request.user)
        exps = []
        for exp in all_exps:
            exp_fs = ExperimentFLowSpace.objects.filter(exp=exp)
            intersection = multi_fs_intersect(exp_fs, admin_fs, FlowSpace)
            if (len(intersection) > 0):
                exps.append(exp)

        error_msg = []

        if (len(exps) > 0):
            exp_exist = True
            first_exp = exps[0].id
        else:
            exp_exist = False
            first_exp = 0

        if (request.method == "POST"):
            uform = UploadFileForm(request.POST, request.FILES)

            # validate upload file form
            if uform.is_valid():

                # parse the file and find the list of flowspaces to be opted-in
                result = read_fs(request.FILES['file'])

                # check if an error happened while parsing the file,
                if len(result["error"]) == 0:

                    # find the priority for first opt-in
                    assigned_priority = profile.max_priority_level - Priority.Strict_Priority_Offset - 1
                    all_this_admin_opts = UserOpts.objects.filter(
                        user=request.user, nice=True)
                    for admin_opt in all_this_admin_opts:
                        if admin_opt.priority <= assigned_priority:
                            assigned_priority = admin_opt.priority - 1

                    fv_args = []
                    match_list = []
                    opt_expression = ""
                    for i in range(len(result['flowspace'])):

                        # check if slice_id is specified
                        if result['slice_id'][i] == None:
                            error_msg.append(
                                "No opt-in slice specified for flowspace %s" %
                                result['flowspace'])
                            transaction.rollback()
                            break

                        #check if slice_id is valid
                        exp = Experiment.objects.filter(
                            slice_id=result['slice_id'][i])
                        if exp.count() == 0:
                            error_msg.append("No slice exist with id %s" %
                                             result['slice_id'][i])
                            transaction.rollback()
                            break
                        elif exp.count() > 1:
                            raise Exception(
                                "Found more than one slice with the same id: %s. This is unexpected!"
                                % result['slice_id'][i])
                        else:
                            exp = exp[0]

                        if assigned_priority <= 0:
                            error_msg.append("Too many opt-ins")
                            transaction.rollback()
                            break

                        # find the intersection of requested opt-in flowspace, admin's flowspace
                        # and the experiemnt's flowspace:
                        adminFS = AdminFlowSpace.objects.filter(
                            user=request.user)
                        intersected_flowspace = multi_fs_intersect(
                            [result['flowspace'][i]], adminFS, FlowSpace)

                        if len(intersected_flowspace) == 0:
                            error_msg.append("Selected flowspace doesn't have any intersection with admin FS. Admin FS: %s, Selected FS: %s"%\
                                         (adminFS,result['flowspace'][i]))
                            transaction.rollback()
                            break

                        # get the fv args for this opt-in
                        [new_fv_args, new_match_list
                         ] = opt_fs_into_exp(intersected_flowspace, exp,
                                             request.user, assigned_priority,
                                             True)

                        fv_args = fv_args + new_fv_args
                        match_list = match_list + new_match_list

                        opt_expression = opt_expression + exp.project_name + ":" + exp.slice_name + ", "

                        # decrease assigned priority for next opt-in
                        assigned_priority = assigned_priority - 1

                    if len(fv_args) == 0:
                        error_msg.append("Nothing to opt-in!")
                        transaction.rollback()

                    # now send FV Args using an XMLRPC call to FV
                    if len(error_msg) == 0:
                        try:
                            fv = FVServerProxy.objects.all()[0]
                            try:
                                returned_ids = fv.proxy.api.changeFlowSpace(
                                    fv_args)
                                for i in range(len(match_list)):
                                    match_list[i].fv_id = returned_ids[i]
                                    match_list[i].save()
                                opt_expression = opt_expression[:-2]
                                return simple.direct_to_template(
                                    request,
                                    template=
                                    "openflow/optin_manager/opts/opt_in_successful_admin.html",
                                    extra_context={
                                        'expname': opt_expression,
                                    },
                                )
                            except Exception, e:
                                import traceback
                                traceback.print_exc()
                                transaction.rollback()
                                error_msg.append(
                                    "Couldn't opt into the requested experiment, Flowvisor error: %s"
                                    % str(e))
                        except Exception, e:
                            import traceback
                            traceback.print_exc()
                            transaction.rollback()
                            error_msg.append("Flowvisor not set: %s" % str(e))

                # if there is an error while parsing the file
                else:
                    error_msg = result["error"]

        form = AdminOptInForm()
        upload_form = UploadFileForm()
        return simple.direct_to_template(
            request,
            template='openflow/optin_manager/opts/admin_opt_in.html',
            extra_context={
                'user': request.user,
                'experiments': exps,
                'error_msg': error_msg,
                'exp_exist': exp_exist,
                'first_exp': first_exp,
                'form': form,
                'upload_form': upload_form,
            },
        )
Exemplo n.º 3
0
def add_opt_in(request):
    '''
`	The view function for opting in a user or admin flowspace into an experiment
    FOR USER OPTIN:
    request.POST should contain:
    key: experiemnt: database id of the experiment to opted in
    FOR ADMIN OPTIN:
    request.POST should contain:
    key: experiemnt: database id of the experiment to opted in
    key: all flowspace fields as specified in AdminOptInForm
    '''
    profile = UserProfile.get_or_create_profile(request.user)

    ############################
    #      Admin Opt-In        #
    ############################
    if (profile.is_net_admin):

        # find all experiments that the admin can opt into them.
        all_exps = Experiment.objects.all()
        admin_fs = AdminFlowSpace.objects.filter(user=request.user)
        exps = []
        for exp in all_exps:
            exp_fs = ExperimentFLowSpace.objects.filter(exp=exp)
            intersection = multi_fs_intersect(exp_fs, admin_fs, FlowSpace)
            if (len(intersection) > 0):
                exps.append(exp)

        assigned_priority = profile.max_priority_level - Priority.Strict_Priority_Offset - 1
        error_msg = []
        if (request.method == "POST"):
            form = AdminOptInForm(request.POST)
            if form.is_valid():
                all_this_admin_opts = UserOpts.objects.filter(
                    user=request.user, nice=True)
                for admin_opt in all_this_admin_opts:
                    if admin_opt.priority <= assigned_priority:
                        assigned_priority = admin_opt.priority - 1

                if assigned_priority <= 0:
                    error_msg.append("Too many opt-ins")

                # check if the selected experiment is valid:
                selected_exp_id = request.POST['experiment']
                try:
                    selexp = Experiment.objects.get(id=selected_exp_id)
                except:
                    error_msg.append("Invalid experiment selected!")
                if len(error_msg) == 0:
                    requested_opt = form.get_flowspace(FlowSpace)
                    adminFS = AdminFlowSpace.objects.filter(user=request.user)

                    intersected_flowspace = multi_fs_intersect([requested_opt],
                                                               adminFS,
                                                               FlowSpace)
                    for fs in intersected_flowspace:
                        print "\n\nFLOWSPACE"
                        print fs.stringify()
                        print fs.__unicode__()
                    if len(intersected_flowspace) == 0:
                        error_msg.append(
                            "Selected flowspace doesn't have any intersection with admin FS"
                        )
                if len(error_msg) == 0:
                    [fv_args,
                     match_list] = opt_fs_into_exp(intersected_flowspace,
                                                   selexp, request.user,
                                                   assigned_priority, True)
                    try:
                        fv = FVServerProxy.objects.all()[0]
                        try:
                            if len(fv_args) > 0:
                                returned_ids = fv.proxy.api.changeFlowSpace(
                                    fv_args)
                                for i in range(len(match_list)):
                                    match_list[i].fv_id = returned_ids[i]
                                    match_list[i].save()
                            try:
                                allopts = UserOpts.objects.filter(
                                    user=request.user).order_by('-priority')
                                for opt in allopts:
                                    this_opt_fses = opt.optsflowspace_set.all()
                                    fs_description = ""
                                    for fs in this_opt_fses:
                                        if fs_description != "":
                                            fs_description = fs_description + " & %s" % fs
                                        else:
                                            fs_description = "%s" % fs
                                send_mail(
                                    settings.EMAIL_SUBJECT_PREFIX +
                                    "Your Flowspace request has been attended",
                                    "Your Flowspace request has been attended, go to your project and slice page at https://%s to check the Flowspace granted\n\nFlowSpace Granted:\n%s"
                                    % (settings.SITE_DOMAIN.split(':')[0],
                                       fs_description),
                                    from_email=settings.DEFAULT_FROM_EMAIL,
                                    recipient_list=[selexp.owner_email],
                                    #recipient_list=[settings.ROOT_EMAIL],
                                )
                            except Exception as e:
                                print "User email notification could no be sent"
                                print e

                            return simple.direct_to_template(
                                request,
                                template=
                                "openflow/optin_manager/opts/opt_in_successful_admin.html",
                                extra_context={
                                    'expname':
                                    "%s:%s" %
                                    (selexp.project_name, selexp.slice_name),
                                },
                            )
                        except Exception, e:
                            import traceback
                            traceback.print_exc()
                            transaction.rollback()
                            error_msg.append(
                                "Couldn't opt into the requested experiment, Flowvisor error: %s"
                                % str(e))
                    except Exception, e:
                        import traceback
                        traceback.print_exc()
                        transaction.rollback()
                        error_msg.append("Flowvisor not set: %s" % str(e))

        else:
            form = AdminOptInForm()

        # if not a post request, we will start from here
        if (len(exps) > 0):
            exp_exist = True
            first_exp = exps[0].id
        else:
            exp_exist = False
            first_exp = 0

        upload_form = UploadFileForm()
        return simple.direct_to_template(
            request,
            template='openflow/optin_manager/opts/admin_opt_in.html',
            extra_context={
                'user': request.user,
                'experiments': exps,
                'error_msg': error_msg,
                'exp_exist': exp_exist,
                'first_exp': first_exp,
                'form': form,
                'upload_form': upload_form,
            },
        )
Exemplo n.º 4
0
                        a_prev_opt_fses = a_prev_opt.optsflowspace_set.all()
                        for a_prev_opt_fs in a_prev_opt_fses:
                            all_prev_opts_fs.append(a_prev_opt_fs)

                    # now opt out the flowpsaces and clear flowspace and match_struct entries
                    # from the database:
                    del_fv_args = opt_fses_outof_exp(all_prev_opts_fs)

                    # delete all the previous opts into this experiemnt from the database
                    prev_opts.delete()
                else:
                    del_fv_args = []

                # Now opt the user into the selected experiemnt
                [add_fv_args,
                 match_list] = opt_fs_into_exp(userFS, selexp, request.user,
                                               assigned_priority, True)

                try:
                    fv = FVServerProxy.objects.all()[0]
                    try:
                        fv_args = add_fv_args + del_fv_args
                        if len(fv_args) > 0:
                            returned_ids = fv.proxy.api.changeFlowSpace(
                                fv_args)
                            for i in range(len(match_list)):
                                match_list[i].fv_id = returned_ids[i]
                                match_list[i].save()
                        return simple.direct_to_template(
                            request,
                            template=
                            "openflow/optin_manager/opts/opt_in_successful_user.html",
 def handle_noargs(self, **options):
     """
     Grants flowspaces for previously conflictive slices at Flowvisor.
     Used in conjunction **and after** the script with the same name
     at expedient.
     
     Flow:
         1. Expedient: manage.py standardize_flowvisor_slices stop
         2. Expedient: manage.py standardize_flowvisor_slices start
         3. Opt-in: manage.py standardize_flowvisor_slices
     """
     # If 'slice_ids_to_grant_fs' file exists, do the following.
     # Otherwise warn and skip.
     try:
         f = open("%s/slice_ids_to_grant_fs" % path,"r")
         ids = pickle.load(f)
         f.close()
         os.remove("%s/slice_ids_to_grant_fs" % path)
         user = User.objects.filter(username=settings.ROOT_USERNAME)[0]
         adminFS = AdminFlowSpace.objects.filter(user = user)
         profile = UserProfile.get_or_create_profile(user)
         fv = FVServerProxy.objects.all()[0]
         for iden in ids:
             assigned_priority = profile.max_priority_level - Priority.Strict_Priority_Offset - 1
             all_this_admin_opts = UserOpts.objects.filter(user=user,nice=True)
             for admin_opt in all_this_admin_opts:
                 if admin_opt.priority <= assigned_priority:
                     assigned_priority = admin_opt.priority - 1
             # Filter by slice "keywords" (name), same as in the previous steps
             selexp = filter_own_experiment(iden)
             flow_space = ExperimentFLowSpace.objects.filter(exp=selexp.id)
             if not flow_space:
                 print "No matched flowspaces for slice %s" % iden['id']
                 continue 
             #intersected_flowspace = multi_fs_intersect(flow_space,adminFS,FlowSpace)
             intersected_flowspace = get_used_fs(flow_space)
             fv_args,match_list = opt_fs_into_exp(intersected_flowspace,selexp,user,assigned_priority,True)
             #for i in range(len(fv_args)):
             #    for j in range(len(fv_args)):
             #        print fv_args[i] == fv_args[j]
             returned_ids = fv.proxy.api.changeFlowSpace(fv_args)
             for i in range(len(match_list)):
                 match_list[i].fv_id = returned_ids[i]
                 match_list[i].save()
             allopts = UserOpts.objects.filter(user = user).order_by('-priority')
      
             for opt in allopts:
                 this_opt_fses = opt.optsflowspace_set.all()
                 fs_project = opt.experiment.project_name or ""
                 fs_slice = opt.experiment.slice_name or ""
                 fs_description = ""
                 for fs in this_opt_fses:
                     if fs_description != "":
                         fs_description = fs_description + "\n%s" % fs
                     else:
                         fs_description = "%s" % fs
             print "Flowspace for slice %s was successfully granted" % iden['id']
             time.sleep(FLOWVISOR_SLEEP_TIME)
         self.stdout.write("\033[92m%s\033[0m\n" % "Successfully granted flowspaces at FlowVisor\n")
     except Exception as e:
         print e
         self.stdout.write("\033[93mCould not access file with slice IDs. Skipping...\033[0m\n")
Exemplo n.º 6
0
def opt_in_from_file(request):
    '''
    This is doing the same as add_opt_in function except the input data
    is coming from an uploaded file
    '''
    
    profile = UserProfile.get_or_create_profile(request.user)
     
    if (not profile.is_net_admin):
        return HttpResponseRedirect("/dashboard")
    else:
        # find all experiments that the admin can opt into them.
        all_exps = Experiment.objects.all()
        admin_fs = AdminFlowSpace.objects.filter(user=request.user)
        exps = []
        for exp in all_exps:
            exp_fs = ExperimentFLowSpace.objects.filter(exp=exp)
            intersection = multi_fs_intersect(exp_fs,admin_fs,FlowSpace)
            if (len(intersection)>0):
                exps.append(exp)

        error_msg = []
        
        if (len(exps)>0):
            exp_exist = True
            first_exp = exps[0].id
        else:
            exp_exist = False
            first_exp = 0
        
        if (request.method == "POST"):
            uform = UploadFileForm(request.POST, request.FILES)
            
            # validate upload file form
            if uform.is_valid():
                
                # parse the file and find the list of flowspaces to be opted-in
                result = read_fs(request.FILES['file'])
                
                # check if an error happened while parsing the file, 
                if len(result["error"])==0:
                    
                    # find the priority for first opt-in
                    assigned_priority = profile.max_priority_level - Priority.Strict_Priority_Offset - 1
                    all_this_admin_opts = UserOpts.objects.filter(user=request.user,nice=True)
                    for admin_opt in all_this_admin_opts:
                            if admin_opt.priority <= assigned_priority:
                                assigned_priority = admin_opt.priority - 1
                    
                    fv_args = []
                    match_list = []
                    opt_expression = ""
                    for i in range(len(result['flowspace'])):
                        
                        # check if slice_id is specified
                        if result['slice_id'][i]==None:
                            error_msg.append("No opt-in slice specified for flowspace %s"%result['flowspace'])
                            transaction.rollback()
                            break
                        
                        #check if slice_id is valid
                        exp = Experiment.objects.filter(slice_id=result['slice_id'][i])
                        if exp.count()==0:
                            error_msg.append("No slice exist with id %s"%result['slice_id'][i])
                            transaction.rollback()
                            break
                        elif exp.count()>1:
                            raise Exception("Found more than one slice with the same id: %s. This is unexpected!"%result['slice_id'][i])
                        else:
                            exp = exp[0]
                            
                        if assigned_priority <= 0:
                            error_msg.append("Too many opt-ins")
                            transaction.rollback()
                            break
                            
                        # find the intersection of requested opt-in flowspace, admin's flowspace
                        # and the experiemnt's flowspace:
                        adminFS = AdminFlowSpace.objects.filter(user = request.user)
                        intersected_flowspace = multi_fs_intersect([result['flowspace'][i]],adminFS,FlowSpace)
                                                
                        if len(intersected_flowspace) == 0:
                            error_msg.append("Selected flowspace doesn't have any intersection with admin FS. Admin FS: %s, Selected FS: %s"%\
                                         (adminFS,result['flowspace'][i]))
                            transaction.rollback()
                            break
                        

                        # get the fv args for this opt-in
                        [new_fv_args,new_match_list] = opt_fs_into_exp(intersected_flowspace,
                                            exp,request.user,assigned_priority,True)
                        
                        fv_args = fv_args + new_fv_args
                        match_list = match_list + new_match_list
                        
                        opt_expression = opt_expression + exp.project_name + ":" + exp.slice_name + ", "
                        
                        # decrease assigned priority for next opt-in
                        assigned_priority = assigned_priority - 1
                        

                    if len(fv_args)==0:
                        error_msg.append("Nothing to opt-in!")
                        transaction.rollback()
                        
                    # now send FV Args using an XMLRPC call to FV
                    if len(error_msg)==0:
                        try:
                            fv = FVServerProxy.objects.all()[0]
                            try:
                                returned_ids = fv.proxy.api.changeFlowSpace(fv_args)
                                for i in range(len(match_list)):
                                    match_list[i].fv_id = returned_ids[i]
                                    match_list[i].save()
                                opt_expression = opt_expression[:-2]
                                return simple.direct_to_template(request, 
                                    template ="openflow/optin_manager/opts/opt_in_successful_admin.html",
                                    extra_context = {
                                    'expname':opt_expression,
                                    },
                                )
                            except Exception,e:
                                import traceback
                                traceback.print_exc()
                                transaction.rollback()
                                error_msg.append("Couldn't opt into the requested experiment, Flowvisor error: %s"%str(e))
                        except Exception,e:
                            import traceback
                            traceback.print_exc()
                            transaction.rollback()
                            error_msg.append("Flowvisor not set: %s"%str(e)) 
                        
                        
                    
                    
                # if there is an error while parsing the file         
                else:
                    error_msg = result["error"]

        
        form = AdminOptInForm()
        upload_form = UploadFileForm()
        return simple.direct_to_template(request, 
            template = 'openflow/optin_manager/opts/admin_opt_in.html', 
            extra_context = {
                'user':request.user,
                'experiments':exps,
                'error_msg':error_msg,
                'exp_exist':exp_exist,
                'first_exp':first_exp,
                'form':form,
                'upload_form':upload_form,
            },
        )
Exemplo n.º 7
0
def add_opt_in(request):
    '''
`	The view function for opting in a user or admin flowspace into an experiment
    FOR USER OPTIN:
    request.POST should contain:
    key: experiment: database id of the experiment to opted in
    FOR ADMIN OPTIN:
    request.POST should contain:
    key: experiment: database id of the experiment to opted in
    key: all flowspace fields as specified in AdminOptInForm
    ''' 
    profile = UserProfile.get_or_create_profile(request.user)
    
    ############################
    #      Admin Opt-In        #
    ############################   
    if (profile.is_net_admin):
        
        # find all experiments that the admin can opt into them.
        all_exps = Experiment.objects.all().order_by('project_name','slice_name')
        admin_fs = AdminFlowSpace.objects.filter(user=request.user)
        exps = []

        for exp in all_exps:
            exp_fs = ExperimentFLowSpace.objects.filter(exp=exp)
            intersection = multi_fs_intersect(exp_fs,admin_fs,FlowSpace)
            if (len(intersection)>0):
                exps.append(exp)

        ######## XXX Experimental: Show allocated VLANs ######
        allocated_vlans = vlanController.get_allocated_vlans()
        requested_vlans = vlanController.get_requested_vlans_by_all_experiments()
        ########################################################################################

        assigned_priority = profile.max_priority_level - Priority.Strict_Priority_Offset - 1
        error_msg = []
        if (request.method == "POST"):
            form = AdminOptInForm(request.POST)
            if form.is_valid():
                all_this_admin_opts = UserOpts.objects.filter(user=request.user,nice=True)
                for admin_opt in all_this_admin_opts:
                    if admin_opt.priority <= assigned_priority:
                        assigned_priority = admin_opt.priority - 1
                        
                if assigned_priority <= 0:
                    error_msg.append("Too many opt-ins")
         
                # check if the selected experiment is valid:
                selected_exp_id = request.POST['experiment']
                try:
                    selexp = Experiment.objects.get(id = selected_exp_id)
                except:
                    error_msg.append("Invalid experiment selected!")
                if len(error_msg)==0:
                    requested_opt = form.get_flowspace(FlowSpace)
                    adminFS = AdminFlowSpace.objects.filter(user = request.user)
                    
                    intersected_flowspace = multi_fs_intersect([requested_opt],adminFS,FlowSpace)
                    #for fs in intersected_flowspace:
                    #    print "\n\nFLOWSPACE"
                    #    print fs.stringify()
                    #    print fs.__unicode__()
                    if len(intersected_flowspace) == 0:
                        error_msg.append("Selected flowspace doesn't have any intersection with admin FS")
                if len(error_msg)==0:
                    try:
                        [fv_args,match_list] = opt_fs_into_exp(intersected_flowspace,
                                selexp,request.user,assigned_priority,True)
                        fv = FVServerProxy.objects.all()[0]
                        try:
                            if len(fv_args) > 0:
                                returned_ids = fv.proxy.api.changeFlowSpace(fv_args)
                                for i in range(len(match_list)):
                                    match_list[i].fv_id = returned_ids[i]
                                    match_list[i].save()
                            try:
                                allopts = UserOpts.objects.filter(user = request.user).order_by('-priority')
                                for opt in allopts:
                                    this_opt_fses = opt.optsflowspace_set.all()
                                    fs_project = opt.experiment.project_name or ""
                                    fs_slice = opt.experiment.slice_name or ""
                                    fs_description = ""
                                    for fs in this_opt_fses:
                                        if fs_description != "":
                                            fs_description = fs_description + "\n%s"%fs
                                        else:
                                            fs_description = "%s"%fs
                                site_domain_url = " You may access your slice page at Expedient's site to check the granted Flowspace."
                                send_mail(
                                         settings.EMAIL_SUBJECT_PREFIX + "Your Flowspace request has been attended",
                                         "Your Flowspace request has been attended.%s\n\nProject: %s\nSlice: %s\nFlowspace granted:\n\n%s" % (site_domain_url, fs_project, fs_slice, fs_description),
                                         from_email=settings.DEFAULT_FROM_EMAIL,
                                         recipient_list= [selexp.owner_email],
                                         #recipient_list=[settings.ROOT_EMAIL],
                                 )
                            except Exception as e:
                                print "User email notification could not be sent. Exception: %s" % str(e)

                            return simple.direct_to_template(request, 
                                template ="openflow/optin_manager/opts/opt_in_successful_admin.html",
                                extra_context = {
                                    'expname':"%s:%s"%(selexp.project_name,selexp.slice_name),
                                },
                            )
                        except Exception,e:
                            import traceback
                            traceback.print_exc()
                            transaction.rollback()
                            error_msg.append("Couldn't opt into the requested experiment, Flowvisor error: %s"%str(e))
                    except Exception,e:
                        import traceback
                        traceback.print_exc()
                        transaction.rollback()
                        error_msg.append("Flowvisor not set: %s"%str(e))
                
        else:
            form = AdminOptInForm()
                        
        # if not a post request, we will start from here            
        if (len(exps)>0):
            exp_exist = True
            first_exp = exps[0].id
        else:
            exp_exist = False
            first_exp = 0
           
        upload_form = UploadFileForm()
        return simple.direct_to_template(request, 
                        template = 'openflow/optin_manager/opts/admin_opt_in.html', 
                        extra_context = {
                                'user':request.user,
                                'experiments':exps,
                                'error_msg':error_msg,
                                'exp_exist':exp_exist,
                                'first_exp':first_exp,
                                'form':form,
                                'upload_form':upload_form,
                                'requested_vlans':requested_vlans,
                                # Carolina: ceil function to take into account 0-indexed range [0,4095]
                                # has 1 more element that would be normally displaced to another column
                                # (not 5 columns anymore). Displace one element per column to fit.
                                'vlan_list_length': math_ceil(len(allocated_vlans)/5.0),
                                'allocated_vlans': allocated_vlans,
                            },
                    )  
Exemplo n.º 8
0
     for a_prev_opt in prev_opts:
         a_prev_opt_fses = a_prev_opt.optsflowspace_set.all()
         for a_prev_opt_fs in a_prev_opt_fses:
             all_prev_opts_fs.append(a_prev_opt_fs)
     
     # now opt out the flowpsaces and clear flowspace and match_struct entries 
     # from the database:
     del_fv_args = opt_fses_outof_exp(all_prev_opts_fs)
     
     # delete all the previous opts into this experiemnt from the database    
     prev_opts.delete()
 else:
     del_fv_args = []
     
 # Now opt the user into the selected experiemnt
 [add_fv_args,match_list] = opt_fs_into_exp(userFS,selexp,request.user,
                         assigned_priority,True)
     
 try:
     fv = FVServerProxy.objects.all()[0]
     try:
         fv_args = add_fv_args + del_fv_args
         if len(fv_args) > 0:
             returned_ids = fv.proxy.api.changeFlowSpace(fv_args)
             for i in range(len(match_list)):
                 match_list[i].fv_id = returned_ids[i]
                 match_list[i].save()
         return simple.direct_to_template(request, 
             template ="openflow/optin_manager/opts/opt_in_successful_user.html",
             extra_context = {
                 'expname':"%s:%s"%(selexp.project_name,selexp.slice_name),
             },
    def handle_noargs(self, **options):
        """
        Grants flowspaces for previously conflictive slices at Flowvisor.
        Used in conjunction **and after** the script with the same name
        at expedient.
        
        Flow:
            1. Expedient: manage.py standardize_flowvisor_slices stop
            2. Expedient: manage.py standardize_flowvisor_slices start
            3. Opt-in: manage.py standardize_flowvisor_slices
        """
        # If 'slice_ids_to_grant_fs' file exists, do the following.
        # Otherwise warn and skip.
        try:
            f = open("%s/slice_ids_to_grant_fs" % path, "r")
            ids = pickle.load(f)
            f.close()
            os.remove("%s/slice_ids_to_grant_fs" % path)
            user = User.objects.filter(username=settings.ROOT_USERNAME)[0]
            adminFS = AdminFlowSpace.objects.filter(user=user)
            profile = UserProfile.get_or_create_profile(user)
            fv = FVServerProxy.objects.all()[0]
            for iden in ids:
                assigned_priority = profile.max_priority_level - Priority.Strict_Priority_Offset - 1
                all_this_admin_opts = UserOpts.objects.filter(user=user,
                                                              nice=True)
                for admin_opt in all_this_admin_opts:
                    if admin_opt.priority <= assigned_priority:
                        assigned_priority = admin_opt.priority - 1
                # Filter by slice "keywords" (name), same as in the previous steps
                selexp = filter_own_experiment(iden)
                flow_space = ExperimentFLowSpace.objects.filter(exp=selexp.id)
                if not flow_space:
                    print "No matched flowspaces for slice %s" % iden['id']
                    continue
                #intersected_flowspace = multi_fs_intersect(flow_space,adminFS,FlowSpace)
                intersected_flowspace = get_used_fs(flow_space)
                fv_args, match_list = opt_fs_into_exp(intersected_flowspace,
                                                      selexp, user,
                                                      assigned_priority, True)
                #for i in range(len(fv_args)):
                #    for j in range(len(fv_args)):
                #        print fv_args[i] == fv_args[j]
                returned_ids = fv.proxy.api.changeFlowSpace(fv_args)
                for i in range(len(match_list)):
                    match_list[i].fv_id = returned_ids[i]
                    match_list[i].save()
                allopts = UserOpts.objects.filter(
                    user=user).order_by('-priority')

                for opt in allopts:
                    this_opt_fses = opt.optsflowspace_set.all()
                    fs_project = opt.experiment.project_name or ""
                    fs_slice = opt.experiment.slice_name or ""
                    fs_description = ""
                    for fs in this_opt_fses:
                        if fs_description != "":
                            fs_description = fs_description + "\n%s" % fs
                        else:
                            fs_description = "%s" % fs
                print "Flowspace for slice %s was successfully granted" % iden[
                    'id']
                time.sleep(FLOWVISOR_SLEEP_TIME)
            self.stdout.write("\033[92m%s\033[0m\n" %
                              "Successfully granted flowspaces at FlowVisor\n")
        except Exception as e:
            print e
            self.stdout.write(
                "\033[93mCould not access file with slice IDs. Skipping...\033[0m\n"
            )