def give_test_permissions(test):
    
    create_test_users(test)
    
    # give permissions
    give_permission_to("can_add_aggregate", Aggregate, test.u1)
    give_permission_to("can_create_project", Project, test.u2)
Esempio n. 2
0
def give_test_permissions(test):

    create_test_users(test)

    # give permissions
    give_permission_to("can_add_aggregate", Aggregate, test.u1)
    give_permission_to("can_create_project", Project, test.u2)
def create_test_aggregates(test):

    from expedient.clearinghouse.aggregate.tests.models import DummyAggregate
    
    give_test_permissions(test)
    
    test.client.login(username=test.u1.username, password="******")
    threadlocals.push_frame(user=test.u1)
    
    test.agg1 = DummyAggregate.objects.create(
        name="Agg1",
    )
    test.agg1.create_resources()
    
    test.agg2 = DummyAggregate.objects.create(
        name="Agg2",
    )
    test.agg2.create_resources()
    
    # give permissions to use aggregates
    give_permission_to("can_use_aggregate", test.agg1, test.u2)
    give_permission_to("can_use_aggregate", test.agg2, test.u2)
    
    test.client.logout()
    threadlocals.pop_frame()
Esempio n. 4
0
 def test_get_aggregates(self):
     proj = self.test_allowed_create()
     
     self.assertEqual(proj.aggregates.count(), 0)
     
     give_permission_to("can_use_aggregate", self.agg1, proj)
     self.assertTrue(has_permission(proj, self.agg1, "can_use_aggregate"))
     self.assertEqual(proj.aggregates.count(), 1)
     self.assertTrue(self.agg1.aggregate_ptr in proj.aggregates)
Esempio n. 5
0
 def post_save(instance, created):
     instance.update_resources()
     give_permission_to("can_use_aggregate",
                        instance,
                        request.user,
                        can_delegate=True)
     give_permission_to("can_edit_aggregate",
                        instance,
                        request.user,
                        can_delegate=True)
 def setUp(self):
     """
     Create some permissions and users.
     """
     self.u1 = User.objects.create_user("user1", "*****@*****.**", "password")
     self.u2 = User.objects.create_user("user2", "*****@*****.**", "password")
     
     create_permission("permission1", description="Permission 1 description.")
     give_permission_to("permission1", self.u1, self.u1, can_delegate=True)
     give_permission_to("permission1", self.u2, self.u1, can_delegate=True)
Esempio n. 7
0
def handle_add_to_slice(request, aggregate, slice):
    """Perform that actual add_to_slice request."""
    
    must_have_permission(request.user, aggregate, "can_use_aggregate")
    must_have_permission(slice.project, aggregate, "can_use_aggregate")
    
    next = request.GET.get("next", None)
    
    give_permission_to("can_use_aggregate", aggregate, slice)

    #success_msg=lambda instance: "Successfully added OpenFlow aggregate %s to slice %s" % (aggregate.name, slice.name)    
    return HttpResponseRedirect(next if next else reverse("slice_detail", args=[slice.id])) 
Esempio n. 8
0
 def add_to_user(self, user, next):
     """
     Works exactly the same as L{add_to_project} but for a user.
     """
     prefix = self.__class__.get_url_name_prefix()
     try:
         return reverse("%s_aggregate_user_add" % prefix,
                        kwargs={'agg_id': self.id,
                                'user_id': user.id})+"?next=%s" % next
     except NoReverseMatch:
         give_permission_to("can_use_aggregate", self.as_leaf_class(), user)
         return next
Esempio n. 9
0
def other_perms_view(request, permission, user, target, redirect_to=None):
    if request.method == "POST":
        give_permission_to(permission, target, user)
        redirect_to = redirect_to or reverse("test_view_crud")
        return HttpResponseRedirect(redirect_to)
    else:
        return HttpResponse("""
Do you want to get %s permission for obj %s?
<form action="" method="POST">
<input type="submit" value="Yes" />
<input type="button" value="No" onclick="document.location='%s'" />
</form>
""" % (permission.name, target, reverse("test_view_crud")))
Esempio n. 10
0
    def setUp(self):
        """
        Create some permissions and users.
        """
        self.u1 = User.objects.create_user("user1", "*****@*****.**",
                                           "password")
        self.u2 = User.objects.create_user("user2", "*****@*****.**",
                                           "password")

        create_permission("permission1",
                          description="Permission 1 description.")
        give_permission_to("permission1", self.u1, self.u1, can_delegate=True)
        give_permission_to("permission1", self.u2, self.u1, can_delegate=True)
Esempio n. 11
0
def handle_add_to_slice(request, aggregate, slice):
    """Perform that actual add_to_slice request."""

    must_have_permission(request.user, aggregate, "can_use_aggregate")
    must_have_permission(slice.project, aggregate, "can_use_aggregate")

    next = request.GET.get("next", None)

    give_permission_to("can_use_aggregate", aggregate, slice)

    #success_msg=lambda instance: "Successfully added OpenFlow aggregate %s to slice %s" % (aggregate.name, slice.name)
    return HttpResponseRedirect(
        next if next else reverse("slice_detail", args=[slice.id]))
Esempio n. 12
0
 def post_save(instance, created):
     give_permission_to("can_use_aggregate", aggregate, slice)
     # Leo added this. Probably due to issue #121 (allow updating
     # (the slice controller without having to start/update it)
     if not created:
         try:
             #aggregate.change_slice_controller(slice)
             for agg in Aggregate.objects.all():
                 agg = agg.as_leaf_class()
                 if agg.leaf_name == "OpenFlowAggregate":
                     agg.change_slice_controller(slice)
         except Exception, e:
             error_msg = str(e)
             print e
Esempio n. 13
0
def other_perms_view(request, permission, user, target, redirect_to=None):
    if request.method == "POST":
        give_permission_to(permission, target, user)
        redirect_to = redirect_to or reverse("test_view_crud")
        return HttpResponseRedirect(redirect_to)
    else:
        return HttpResponse(
"""
Do you want to get %s permission for obj %s?
<form action="" method="POST">
<input type="submit" value="Yes" />
<input type="button" value="No" onclick="document.location='%s'" />
</form>
""" % (permission.name, target, reverse("test_view_crud")))
Esempio n. 14
0
 def post_save(instance, created):
     give_permission_to("can_use_aggregate", aggregate, slice)
     # Leo added this. Probably due to issue #121 (allow updating
     # (the slice controller without having to start/update it)
     if not created:
         try:
             #aggregate.change_slice_controller(slice)
             for agg in Aggregate.objects.all():
                 agg = agg.as_leaf_class()
                 if agg.leaf_name == "OpenFlowAggregate":
                     agg.change_slice_controller(slice)
         except Exception,e:
             error_msg = str(e)
             print e
Esempio n. 15
0
 def post_save(instance, created):
     instance.update_resources()
     give_permission_to(
         "can_use_aggregate",
         instance,
         request.user,
         can_delegate=True
     )
     give_permission_to(
         "can_edit_aggregate",
         instance,
         request.user,
         can_delegate=True
     )
Esempio n. 16
0
def add_aggregate(request, proj_id):
    '''Add/remove aggregates to/from a project'''

    project = get_object_or_404(Project, id=proj_id)
    aggregate_list = Aggregate.objects.exclude(
        id__in=project.aggregates.all().values_list("id", flat=True))

    if request.method == "GET":
        return simple.direct_to_template(
            request,
            template=TEMPLATE_PATH + "/add_aggregates.html",
            extra_context={
                "aggregate_list":
                aggregate_list,
                "project":
                project,
                "breadcrumbs": (
                    ("Home", reverse("home")),
                    ("Project %s" % project.name,
                     reverse("project_detail", args=[project.id])),
                    ("Add Project Aggregates", request.path),
                ),
            })

    elif request.method == "POST":
        # check which submit button was pressed
        try:
            agg_id = int(request.POST.get("id", 0))
        except ValueError:
            raise Http404

        if agg_id not in aggregate_list.values_list("id", flat=True):
            raise Http404

        aggregate = get_object_or_404(Aggregate, id=agg_id).as_leaf_class()

        #Look for the users in the project and give them permission to use the new AM.
        for member in project.members.exclude(is_superuser=True):
            #if not has_permission(member, project, "can_delete_slices"):
            give_permission_to("can_use_aggregate",
                               aggregate,
                               member,
                               giver=None,
                               can_delegate=False)

        return HttpResponseRedirect(
            aggregate.add_to_project(
                project, reverse("project_add_agg", args=[proj_id])))
    else:
        return HttpResponseNotAllowed("GET", "POST")
Esempio n. 17
0
def activate(request, activation_key):
    template_name = 'registration/activate.html'
    activation_key = activation_key.lower() # Normalize before trying anything with it.
    account = RegistrationProfile.objects.activate_user(activation_key)
    if account:
        give_permission_to(
            "can_edit_user", account, account, can_delegate=True)
    return simple.direct_to_template(
        request,
        template=template_name,
        extra_context={
            'account': account,
            'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
        },
    )
Esempio n. 18
0
 def test_allowed_create(self):
     """
     Test that we can create an aggregate.
     """
     give_permission_to("can_add_aggregate", Aggregate, self.u)
     response = self.client.post(reverse("tests_aggregate_create"),
                                 data=dict(
                                     name="dummy agg",
                                     description="aggregate description",
                                     location="Stanford, CA",
                                 ))
     self.assertRedirects(response,
                          "/",
                          msg_prefix="response was %s" % response)
     self.assertEqual(DummyAggregate.objects.all().count(), 1)
Esempio n. 19
0
    def add_controller_to_slice(self, slice, next):
        """
        Works exactly the same as L{add_to_project} but for a slice.
        """
        must_have_permission("user", self.as_leaf_class(), "can_use_aggregate")
        must_have_permission("project", self.as_leaf_class(), "can_use_aggregate")

        prefix = self.__class__.get_url_name_prefix()
        try:
            return reverse("%s_aggregate_slice_controller_add" % prefix,
                           kwargs={'agg_id': self.id,
                                   'slice_id': slice.id})+"?next=%s" % next
        except NoReverseMatch:
            give_permission_to("can_use_aggregate", self.as_leaf_class(), slice)
            return next
Esempio n. 20
0
 def test_allowed_create(self):
     """
     Test that we can create an aggregate.
     """
     give_permission_to("can_add_aggregate", Aggregate, self.u)
     response = self.client.post(
         reverse("tests_aggregate_create"),
         data=dict(
             name="dummy agg",
             description="aggregate description",
             location="Stanford, CA",
         )
     )
     self.assertRedirects(response, "/",
                          msg_prefix="response was %s" % response)
     self.assertEqual(DummyAggregate.objects.all().count(), 1)
Esempio n. 21
0
 def test_allowed_delete(self):
     """
     Tests that delete works when given permission.
     """
     give_permission_to("can_add_aggregate", Aggregate, self.u)
     agg = DummyAggregate.objects.create(
         name="dummy agg",
         description="aggregate description",
         location="Stanford, CA",
     )
     response = test_get_and_post_form(
         client=self.client,
         url=agg.get_delete_url(next="/"),
         params={},
     )
     self.assertRedirects(response, "/")
Esempio n. 22
0
 def test_allowed_delete(self):
     """
     Tests that delete works when given permission.
     """
     give_permission_to("can_add_aggregate", Aggregate, self.u)
     agg = DummyAggregate.objects.create(
         name="dummy agg",
         description="aggregate description",
         location="Stanford, CA",
     )
     response = test_get_and_post_form(
         client=self.client,
         url=agg.get_delete_url(next="/"),
         params={},
     )
     self.assertRedirects(response, "/")
Esempio n. 23
0
def activate(request, activation_key):
    template_name = 'registration/activate.html'
    activation_key = activation_key.lower() # Normalize before trying anything with it.
    # Import only here to avoid every time warning 'DeprecationWarning:
    # the sha module is deprecated; use the hashlib module instead'
    from registration.models import RegistrationProfile
    account = RegistrationProfile.objects.activate_user(activation_key)
    if account:
        give_permission_to(
            "can_edit_user", account, account, can_delegate=True)
    return simple.direct_to_template(
        request,
        template=template_name,
        extra_context={
            'account': account,
            'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
        },
    )
Esempio n. 24
0
    def add_to_project(self, project, next):
        """
        Gives the aggregate a chance to request additional information for a
        project. This method should return a URL to redirect to where the
        user can create or update the additional information the aggregate
        needs. When done, the view at that URL should use the
        C{give_permission} function to give the project
        the "can_use_aggregate" permission::
            
            from expedient.common.permissions.shortcuts import \
                give_permission_to
            
            give_permission_to("can_use_aggregate", self.as_leaf_class(), project)
        
        and then it should redirect to C{next}.
        
        If no extra information is needed, this function can return C{next},
        instead of a custom URL, but it still needs to give the project the
        "can_use_aggregate" permission.
        
        Unless overridden in a subclass, this function will look for a url
        with name <app_name>_aggregate_project_add by reversing the name with
        it parameters 'agg_id' and 'proj_id'. It will append '?next=<next>' to
        the URL if found. Otherwise, it simply gives the permission to the
        project and returns C{next}.
        """

        logger.debug("adding aggregate to project")

        must_have_permission("user", self.as_leaf_class(), "can_use_aggregate")

        prefix = self.__class__.get_url_name_prefix()
        try:
            return reverse("%s_aggregate_project_add" % prefix,
                           kwargs={
                               'agg_id': self.id,
                               'proj_id': project.id
                           }) + "?next=%s" % next
        except NoReverseMatch:
            logger.debug("Giving permission to use aggregate to %s" % project)
            give_permission_to("can_use_aggregate", self.as_leaf_class(),
                               project)
            return next
Esempio n. 25
0
def add_aggregate(request, proj_id):
    '''Add/remove aggregates to/from a project'''
    
    project = get_object_or_404(Project, id=proj_id)
    aggregate_list = Aggregate.objects.exclude(
        id__in=project.aggregates.all().values_list("id", flat=True))
    
    if request.method == "GET":
        return simple.direct_to_template(
            request, template=TEMPLATE_PATH+"/add_aggregates.html",
            extra_context={
                "aggregate_list": aggregate_list,
                "project": project,
                "breadcrumbs": (
                    ("Home", reverse("home")),
                    ("Project %s" % project.name, reverse("project_detail", args=[project.id])),
                    ("Add Project Aggregates", request.path),
                ),
            }
        )
    
    elif request.method == "POST":
        # check which submit button was pressed
        try:
            agg_id = int(request.POST.get("id", 0))
        except ValueError:
            raise Http404

        if agg_id not in aggregate_list.values_list("id", flat=True):
            raise Http404

        aggregate = get_object_or_404(Aggregate, id=agg_id).as_leaf_class()

        #Look for the users in the project and give them permission to use the new AM.
        for member in project.members.exclude(is_superuser=True):
            #if not has_permission(member, project, "can_delete_slices"):
            give_permission_to("can_use_aggregate", aggregate, member, giver=None, can_delegate=False)

        return HttpResponseRedirect(aggregate.add_to_project(
            project, reverse("project_add_agg", args=[proj_id])))
    else:
        return HttpResponseNotAllowed("GET", "POST")
Esempio n. 26
0
 def test_allowed_edit(self):
     """
     Tests that we can edit an existing aggregate.
     """
     give_permission_to("can_add_aggregate", Aggregate, self.u)
     agg = DummyAggregate.objects.create(
         name="dummy agg",
         description="aggregate description",
         location="Stanford, CA",
     )
     response = self.client.post(
         reverse("tests_aggregate_edit", kwargs={"agg_id": 1}),
         data=dict(
             name="Edited dummy agg",
             description="Edited aggregate description",
             location="Stanford, CA",
         ))
     self.assertRedirects(response,
                          "/",
                          msg_prefix="response was %s" % response)
Esempio n. 27
0
 def save(self, *args, **kwargs):
     """
     Override the default save method to enforce permissions.
     """
     pk = getattr(self, "pk", None)
     if not pk:
         # it's a new instance being created
         must_have_permission(permittee_kw, model_func(), create_perm)
     else:
         must_have_permission(permittee_kw, self, edit_perm)
         
     super(model_func(), self).save(*args, **kwargs)
     
     if not pk:
         # it was just created so give creator edit permissions
         d = threadlocals.get_thread_locals()
         give_permission_to(
             edit_perm, self, d[permittee_kw], can_delegate=True)
         give_permission_to(
             delete_perm, self, d[permittee_kw], can_delegate=True)
Esempio n. 28
0
def activate(request, activation_key):
    template_name = 'registration/activate.html'
    activation_key = activation_key.lower(
    )  # Normalize before trying anything with it.
    # Import only here to avoid every time warning 'DeprecationWarning:
    # the sha module is deprecated; use the hashlib module instead'
    from registration.models import RegistrationProfile
    account = RegistrationProfile.objects.activate_user(activation_key)
    if account:
        give_permission_to("can_edit_user",
                           account,
                           account,
                           can_delegate=True)
    return simple.direct_to_template(
        request,
        template=template_name,
        extra_context={
            'account': account,
            'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
        },
    )
Esempio n. 29
0
def create_test_aggregates(test):

    from expedient.clearinghouse.aggregate.tests.models import DummyAggregate

    give_test_permissions(test)

    test.client.login(username=test.u1.username, password="******")
    threadlocals.push_frame(user=test.u1)

    test.agg1 = DummyAggregate.objects.create(name="Agg1", )
    test.agg1.create_resources()

    test.agg2 = DummyAggregate.objects.create(name="Agg2", )
    test.agg2.create_resources()

    # give permissions to use aggregates
    give_permission_to("can_use_aggregate", test.agg1, test.u2)
    give_permission_to("can_use_aggregate", test.agg2, test.u2)

    test.client.logout()
    threadlocals.pop_frame()
Esempio n. 30
0
 def test_allowed_edit(self):
     """
     Tests that we can edit an existing aggregate.
     """
     give_permission_to("can_add_aggregate", Aggregate, self.u)
     agg = DummyAggregate.objects.create(
         name="dummy agg",
         description="aggregate description",
         location="Stanford, CA",
     )
     response = self.client.post(
         reverse("tests_aggregate_edit", kwargs={"agg_id": 1}),
         data=dict(
             name="Edited dummy agg",
             description="Edited aggregate description",
             location="Stanford, CA",
         )
     )
     self.assertRedirects(response, "/",
                          msg_prefix="response was %s" % response)
     
Esempio n. 31
0
 def add_to_project(self, project, next):
     """
     Gives the aggregate a chance to request additional information for a
     project. This method should return a URL to redirect to where the
     user can create or update the additional information the aggregate
     needs. When done, the view at that URL should use the
     C{give_permission} function to give the project
     the "can_use_aggregate" permission::
         
         from expedient.common.permissions.shortcuts import \
             give_permission_to
         
         give_permission_to("can_use_aggregate", self.as_leaf_class(), project)
     
     and then it should redirect to C{next}.
     
     If no extra information is needed, this function can return C{next},
     instead of a custom URL, but it still needs to give the project the
     "can_use_aggregate" permission.
     
     Unless overridden in a subclass, this function will look for a url
     with name <app_name>_aggregate_project_add by reversing the name with
     it parameters 'agg_id' and 'proj_id'. It will append '?next=<next>' to
     the URL if found. Otherwise, it simply gives the permission to the
     project and returns C{next}.
     """
     
     logger.debug("adding aggregate to project")
     
     must_have_permission("user", self.as_leaf_class(), "can_use_aggregate")
     
     prefix = self.__class__.get_url_name_prefix()
     try:
         return reverse("%s_aggregate_project_add" % prefix,
                        kwargs={'agg_id': self.id,
                                'proj_id': project.id})+"?next=%s" % next
     except NoReverseMatch:
         logger.debug("Giving permission to use aggregate to %s" % project)
         give_permission_to("can_use_aggregate", self.as_leaf_class(), project)
         return next
Esempio n. 32
0
def aggregate_crud(request, agg_id=None):
    '''
    Create/update a AlienResource Aggregate.
    '''

    if agg_id != None:
        aggregate = get_object_or_404(AlienResourceAggregateModel, pk=agg_id)
        client = aggregate.client
    else:
        aggregate = None
        client = None

    extra_context_dict = {}
    errors = ""

    if request.method == "GET":
        agg_form = AlienResourceAggregateForm(instance=aggregate)
        client_form = xmlrpcServerProxyForm(instance=client)
        #client_form = PasswordXMLRPCServerProxyForm(instance=client)
        
    elif request.method == "POST":
        agg_form = AlienResourceAggregateForm(
            data=request.POST, instance=aggregate)
        client_form = xmlrpcServerProxyForm(
            data=request.POST, instance=client)
        '''
        client_form = PasswordXMLRPCServerProxyForm(
            data=request.POST, instance=client)
        '''

        if client_form.is_valid() and agg_form.is_valid():
            # Ping is tried after every field check
            client = client_form.save(commit=False)
            aggregate = agg_form.save(commit=False)
            aggregate.client = client
            #s = xmlrpclib.Server('https://'+client.username+':'+client.password+'@'+client.url[8:])

            local_path = os.path.normpath(os.path.join(os.path.dirname(__file__), '..', 'certs'))

            key_path = os.path.join(local_path, "alice-key.pem") # make sure the CA of the AM is the same which issued this certificate (e.g. copy certificates from omni)
            cert_path = os.path.join(local_path, "alice-cert.pem")
            # instanciate the client

            #client2 = GENI3Client('192.168.61.164', 8001, key_path, cert_path)
            # load test credential (look into the `test/creds/TODO.md` to generate these certs)

            with open(os.path.join(local_path, "alice-cred.xml"), 'r') as f:
                TEST_CREDENTIAL = {'geni_value': f.read(), 'geni_version': '3', 'geni_type': 'geni_sfa'}
            with open(os.path.join(local_path, "pizzaslice_cred.xml"), 'r') as f:
                TEST_SLICE_CREDENTIAL = {'geni_value': f.read(), 'geni_version': '3', 'geni_type': 'geni_sfa'}


            #res=client2.listResources([TEST_CREDENTIAL], True, False)

            #s = xmlrpclib.Server('https://'+client.url[8:])

            try:
                #s.ping('ping')
                client2 = GENI3Client(aggregate.get_client_IP(), aggregate.get_client_port(), key_path, cert_path)
            except Exception as e:
                errors = "Could not connect to server: username, password or url are not correct"
                DatedMessage.objects.post_message_to_user(
                    errors, user=request.user, msg_type=DatedMessage.TYPE_ERROR,
                )
                extra_context_dict['errors'] = errors
                writeToLog("Exception: %s" %str(e))

            if not errors:
                client = client_form.save()
                aggregate = agg_form.save(commit=False)
                aggregate.client = client
                aggregate.save()
                agg_form.save_m2m()
                aggregate.save()
                # Update agg_id to sync its resources
                agg_id = aggregate.pk
                # Get resources from AlienResource AM's xmlrpc server every time the AM is updated

                try:
                    do_sync = True
                    '''
                    if agg_form.is_bound:
                        do_sync = agg_form.data.get("sync_resources")
                    else:
                        do_sync = agg_form.initial.get("sync_resources")
                    '''

                    if do_sync:

                        failed_resources = sync_am_resources(agg_id, client2)

                        if failed_resources:
                            DatedMessage.objects.post_message_to_user(
                                "Could not synchronize resources %s within Expedient" % str(failed_resources),
                                user=request.user, msg_type=DatedMessage.TYPE_WARNING,
                            )
                except:
                    warning = "Could not synchronize AM resources within Expedient"
                    DatedMessage.objects.post_message_to_user(
                        errors, user=request.user, msg_type=DatedMessage.TYPE_WARNING,
                    )
                    extra_context_dict['errors'] = warning

                give_permission_to(
                   "can_use_aggregate",
                   aggregate,
                   request.user,
                   can_delegate=True
                )
                give_permission_to(
                    "can_edit_aggregate",
                    aggregate,
                    request.user,
                    can_delegate=True
                )
                DatedMessage.objects.post_message_to_user(
                    "Successfully created/updated aggregate %s" % aggregate.name,
                    user=request.user, msg_type=DatedMessage.TYPE_SUCCESS,
                )
                return HttpResponseRedirect("/")
    else:
        return HttpResponseNotAllowed("GET", "POST")


    if not errors:
        extra_context_dict['available'] = aggregate.check_status() if agg_id else False

    # Updates the dictionary with the common fields
    extra_context_dict.update({
            "agg_form": agg_form,
            "client_form": client_form,
            "create": not agg_id,
            "aggregate": aggregate,
            "breadcrumbs": (
                ('Home', reverse("home")),
                ("%s AlienResource Aggregate" % ("Update" if agg_id else "Create"),
                 request.path),
            )
        })

    return simple.direct_to_template(
        request,
        template="alien_plugin_aggregate_crud.html",
        extra_context=extra_context_dict
    )
Esempio n. 33
0
def aggregate_crud(request, agg_id=None):
    '''
    Create/update a SampleResource Aggregate.
    '''
    if agg_id != None:
        aggregate = get_object_or_404(SampleResourceAggregateModel, pk=agg_id)
        client = aggregate.client
    else:
        aggregate = None
        client = None

    extra_context_dict = {}
    errors = ""

    if request.method == "GET":
        agg_form = SampleResourceAggregateForm(instance=aggregate)
        client_form = xmlrpcServerProxyForm(instance=client)

    elif request.method == "POST":
        agg_form = SampleResourceAggregateForm(data=request.POST,
                                               instance=aggregate)
        client_form = xmlrpcServerProxyForm(data=request.POST, instance=client)

        if client_form.is_valid() and agg_form.is_valid():
            # Ping is tried after every field check
            client = client_form.save(commit=False)
            s = xmlrpclib.Server('https://' + client.username + ':' +
                                 client.password + '@' + client.url[8:])
            try:
                s.ping('ping')
            except:
                errors = "Could not connect to server: username, password or url are not correct"
                DatedMessage.objects.post_message_to_user(
                    errors,
                    user=request.user,
                    msg_type=DatedMessage.TYPE_ERROR,
                )
                extra_context_dict['errors'] = errors

            if not errors:
                client = client_form.save()
                aggregate = agg_form.save(commit=False)
                aggregate.client = client
                aggregate.save()
                agg_form.save_m2m()
                aggregate.save()
                # Update agg_id to sync its resources
                agg_id = aggregate.pk
                # Get resources from SampleResource AM's xmlrpc server every time the AM is updated
                try:
                    do_sync = True
                    if agg_form.is_bound:
                        do_sync = agg_form.data.get("sync_resources")
                    else:
                        do_sync = agg_form.initial.get("sync_resources")

                    if do_sync:
                        failed_resources = sync_am_resources(agg_id, s)

                        if failed_resources:
                            DatedMessage.objects.post_message_to_user(
                                "Could not synchronize resources %s within Expedient"
                                % str(failed_resources),
                                user=request.user,
                                msg_type=DatedMessage.TYPE_WARNING,
                            )
                except:
                    warning = "Could not synchronize AM resources within Expedient"
                    DatedMessage.objects.post_message_to_user(
                        errors,
                        user=request.user,
                        msg_type=DatedMessage.TYPE_WARNING,
                    )
                    extra_context_dict['errors'] = warning

                give_permission_to("can_use_aggregate",
                                   aggregate,
                                   request.user,
                                   can_delegate=True)
                give_permission_to("can_edit_aggregate",
                                   aggregate,
                                   request.user,
                                   can_delegate=True)
                DatedMessage.objects.post_message_to_user(
                    "Successfully created/updated aggregate %s" %
                    aggregate.name,
                    user=request.user,
                    msg_type=DatedMessage.TYPE_SUCCESS,
                )
                return HttpResponseRedirect("/")
    else:
        return HttpResponseNotAllowed("GET", "POST")

    if not errors:
        extra_context_dict['available'] = aggregate.check_status(
        ) if agg_id else False

    # Updates the dictionary with the common fields
    extra_context_dict.update({
        "agg_form":
        agg_form,
        "client_form":
        client_form,
        "create":
        not agg_id,
        "aggregate":
        aggregate,
        "breadcrumbs": (
            ('Home', reverse("home")),
            ("%s SampleResource Aggregate" %
             ("Update" if agg_id else "Create"), request.path),
        )
    })

    return simple.direct_to_template(
        request,
        template="sample_resource_aggregate_crud.html",
        extra_context=extra_context_dict)
Esempio n. 34
0
 def post_save(instance, created):
     give_permission_to("can_delete_slices",
                        instance,
                        instance.owner,
                        giver=None,
                        can_delegate=False)
Esempio n. 35
0
 def post_save(instance, created):
     give_permission_to("can_use_aggregate", aggregate, slice)
Esempio n. 36
0
def aggregate_crud(request, agg_id=None):
    '''
    Create/update an OpenFlow Aggregate.
    '''
    if agg_id != None:
        aggregate = get_object_or_404(OpenFlowAggregate, pk=agg_id)
        client = aggregate.client
    else:
        aggregate = None
        client = None
        
    if request.method == "GET":
        agg_form = OpenFlowAggregateForm(instance=aggregate)
        client_form = PasswordXMLRPCServerProxyForm(instance=client)
        
    elif request.method == "POST":
        logger.debug("aggregate_crud got post")
        agg_form = OpenFlowAggregateForm(
            data=request.POST, instance=aggregate)
        client_form = PasswordXMLRPCServerProxyForm(
            data=request.POST, instance=client)
        logger.debug("Validating")
        if client_form.is_valid() and agg_form.is_valid():
            logger.debug("Forms are valid")
            logger.debug("Got logo %s" % request.POST.get("logo", ""))
            # Save the client first
            client = client_form.save()
            # Then save the aggregate and add the client
            aggregate = agg_form.save(commit=False)
            aggregate.client = client
            aggregate.save()
            agg_form.save_m2m()
            try:
                info = aggregate.client.proxy.get_am_info()
                aggregate.vlan_auto_assignment = info["vlan_auto_assignment"]
                aggregate.flowspace_auto_approval = info["flowspace_auto_approval"]
            except Exception as e:
#                logger.debug("Aggregate %s: could not check automatic resource assignment" % str(aggregate.name))
                pass
            
            try:
                err = ' '
                aggregate.client.proxy.checkFlowVisor() 
                aggregate.setup_new_aggregate(request.build_absolute_uri("/"))
            except Exception as e:
                 err = str(e)
            if err is not ' ':
                #transaction.rollback()
                if "check_fv_set" in err:
                    msg_type = DatedMessage.TYPE_WARNING
                    if agg_id:
                        flowvisor_msg = "Topology could not be updated because could not connect to FlowVisor."
                    else:
                        flowvisor_msg = "New Aggregate set, but there is no FlowVisor connected to it."
                else:
                    flowvisor_msg = err
                    msg_type = DatedMessage.TYPE_ERROR
                DatedMessage.objects.post_message_to_user(
                    flowvisor_msg, user=request.user, msg_type=msg_type,
                )
                return HttpResponseRedirect("/")
            aggregate.save()
            give_permission_to(
                "can_use_aggregate",
                aggregate,
                request.user,
                can_delegate=True
            )
            give_permission_to(
                "can_edit_aggregate",
                aggregate,
                request.user,
                can_delegate=True
            )
            DatedMessage.objects.post_message_to_user(
                "Successfully created/updated aggregate %s. %s" % (aggregate.name,err),
                user=request.user, msg_type=DatedMessage.TYPE_SUCCESS,
            )
            return HttpResponseRedirect(reverse("openflow_aggregate_add_links", args=[aggregate.id]))
        logger.debug("Validation failed")
    else:
        return HttpResponseNotAllowed("GET", "POST")
    
    available = aggregate.check_status() if agg_id else False
    return simple.direct_to_template(
        request,
        template="openflow_aggregate_crud.html",
        extra_context={
            "agg_form": agg_form,
            "client_form": client_form,
            "create": not agg_id,
            "aggregate": aggregate,
            "available": available,
            "breadcrumbs": (
                ('Home', reverse("home")),
                ("%s OpenFlow Aggregate" % ("Update" if agg_id else "Add"),
                 request.path),
            )
        },
    )
Esempio n. 37
0
    def handle_noargs(self, **options):

        username = options.get("username")
        password = options.get("password")

        filename = options.get("filename")
        do_aggs = options.get("load_aggs")
        do_slices = options.get("load_slices")
        start_slices = options.get("start_slices")
        append = options.get("append")

        f = open(filename)
        data = load(f)
        f.close()

        client = Client()
        client.login(username=username, password=password)

        user = User.objects.get(username=username)
        threadlocals.get_thread_locals()["user"] = user

        if do_aggs:
            for agg_dict in data["aggregates"]:
                resp = test_get_and_post_form(
                    client,
                    reverse("openflow_aggregate_create"),
                    agg_dict,
                )

                assert (resp.status_code == 302)
                assert (re.search(r"/openflow/aggregate/\d+/links/$",
                                  resp["Location"]))
        if do_slices:
            for project_dict in data["projects"]:
                project, _ = Project.objects.get_or_create(
                    name=project_dict["name"],
                    description=project_dict["description"],
                )
                create_project_roles(project, user)
                threadlocals.get_thread_locals()["project"] = project

                # add aggregates to project
                for aggregate in OpenFlowAggregate.objects.all():
                    give_permission_to("can_use_aggregate", aggregate, user)
                    give_permission_to("can_use_aggregate", aggregate, project)

                for aggregate in GCFOpenFlowAggregate.objects.all():
                    give_permission_to("can_use_aggregate", aggregate, user)
                    give_permission_to("can_use_aggregate", aggregate, project)

                # add slices to project
                for slice_dict in project_dict["slices"]:
                    slice = Slice.objects.create(
                        name=slice_dict["name"],
                        description=slice_dict["description"],
                        project=project,
                        owner=user,
                    )

                    OpenFlowSliceInfo.objects.create(
                        slice=slice,
                        controller_url=slice_dict["controller_url"],
                        password=slice_dict["password"],
                    )

                    info, _ = GENISliceInfo.objects.get_or_create(
                        slice=slice, )

                    if not info.ssh_private_key or not info.ssh_public_key:
                        info.generate_ssh_keys()
                        info.save()

                    # add aggregates to slices
                    for aggregate in OpenFlowAggregate.objects.all():
                        give_permission_to("can_use_aggregate", aggregate,
                                           slice)

                    for aggregate in GCFOpenFlowAggregate.objects.all():
                        give_permission_to("can_use_aggregate", aggregate,
                                           slice)

                    # add slivers
                    slivers = []
                    for dpid, port in slice_dict["ifaces"]:
                        try:
                            sliver, _ = OpenFlowInterfaceSliver.objects.get_or_create(
                                slice=slice,
                                resource=OpenFlowInterface.objects.get(
                                    port_num=port, switch__datapath_id=dpid),
                            )
                            slivers.append(sliver)
                        except OpenFlowInterface.DoesNotExist:
                            continue

                    # add flowspace
                    for sfs_dict in slice_dict["sfs"]:
                        fs_dict = {}
                        for attr in "dl_src", "dl_dst", "dl_type", "vlan_id", \
                        "nw_src", "nw_dst", "nw_proto", "tp_dst", "tp_src":
                            fs_dict[attr + "_start"] = sfs_dict[attr]
                            fs_dict[attr + "_end"] = sfs_dict[attr]

                        fs = FlowSpaceRule.objects.create(**fs_dict)

                        for sliver in slivers:
                            fs.slivers.add(sliver)

                    if start_slices:
                        tl = threadlocals.get_thread_locals()
                        tl["project"] = project
                        tl["slice"] = slice
                        slice.start(user)
def aggregate_crud(request, agg_id=None):
    '''
    Create/update a ResourceOrchestrator Aggregate.
    '''
    if agg_id != None:
        aggregate = get_object_or_404(ResourceOrchestratorAggregateModel, pk=agg_id)
        client = aggregate.client
    else:
        aggregate = None
        client = None

    extra_context_dict = {}
    errors = ""

    if request.method == "GET":
        agg_form = ResourceOrchestratorAggregateForm(instance=aggregate)
        client_form = xmlrpcServerProxyForm(instance=client)
        
    elif request.method == "POST":
        agg_form = ResourceOrchestratorAggregateForm(
            data=request.POST, instance=aggregate)
        client_form = xmlrpcServerProxyForm(
            data=request.POST, instance=client)

        if client_form.is_valid() and agg_form.is_valid():
            # Ping is tried after every field check
            client = client_form.save(commit=False)
            print "client.certificate.name: ",  client.certificate.name
            print "client.certificate dir>> ",  client.certificate.__dict__
            print "client.certificate.instance dir>> ",  client.certificate.instance.__dict__
            print "client.key.name: ",  client.key.name
            print "client.key.name dir>> ",  client.key.__dict__
            print "client.key.instance.name dir>> ",  client.key.instance.__dict__

            # Retrieve contents of client.key and client.cert, not the whole object
            s = xmlrpc_secure.make_client(client.url, client.key.name, client.certificate.name)
            try:
                # s.GetVersion()
                sync_ro_resources(s)

            # TODO Check what happens when certificates are incorrect! (untrusted)
            # TODO Check what hapens when certificates are not signed by CH!
            except Exception as e:
                print "----------------- Expedient ---> RO connection FAILED! Details: ", e
                if isinstance(e, socket.error):
                    errors = "Could not connect to server: URL is not correct or remote RO is down"
                else:
                    errors = "Could not connect to server: either certificate or URL is not correct"

                DatedMessage.objects.post_message_to_user(
                    errors, user=request.user, msg_type=DatedMessage.TYPE_ERROR,
                )
                extra_context_dict['errors'] = errors

            if not errors:
                client = client_form.save()
                print "\n\n\n\n\nrequest FILES!!!!!!!!!!!! dict ", request.FILES.__dict__
                print "\n\n\n\n\nrequest POST!!!!!!!!!!!! dict ", request.POST.__dict__
                print "\n\n\n\n\nclient 1!!!!!!!!!!!! ", client.__dict__
                print "\n\n\n\n\nclient 1 cert!!!!!!!!!!!! ", dir(client.certificate.storage)
                print "\n\n\n\n\nclient 1 cert location!!!!!!!!!!!! ", client.certificate.storage.base_location, client.certificate.storage.path, client.certificate.storage.base_url, dir(client.certificate.storage.url), client.certificate.storage.listdir
                print "\n\n\n\n\nclient 1 key!!!!!!!!!!!! ", dir(client.key.storage)
                client_xmplrc_secure = xmlrpcServerProxyModel(request.POST, request.FILES)
                print "\n\n\n\n\nclient 2!!!!!!!!!!!! ", dir(client_xmplrc_secure)
                print "\n\n\n\n\nclient 2 certificate!!!!!!!!!!!! ", client_xmplrc_secure.__dict__["certificate"]
                print "\n\n\n\n\nclient 2 certificate!!!!!!!!!!!! 1", dir(client_xmplrc_secure.__dict__["certificate"])

                print "\n\n\n\n\nclient 2 certificate!!!!!!!!!!!! 2", client_xmplrc_secure.__dict__["certificate"].keys()

                for v in client_xmplrc_secure.__dict__["certificate"].values():
                    print "\n\n\n\n\nclient 2 certificate!!!!!!!!!!!! 3", v

                aggregate = agg_form.save(commit=False)

                #if "certificate" in request.FILES:
                #    certificate_contents = request.FILES["certificate"]
                try:
                    certificate_contents = client_xmplrc_secure.__dict__["certificate"].values()[0]
                    certificate_default_storage = client.certificate.storage
                    # from django.core.files.storage import default_storage
                    certificate_name = get_file_name(aggregate)
                    print "certificate_name: ", certificate_name
                    # "certificate_default_storage.location" not good
                    path = certificate_default_storage.save( \
                                os.path.join(DEFAULT_UPLOAD_PATH, "%s.crt" % certificate_name), \
                                ContentFile(certificate_contents.read()))
                    print "path...............", path
                    print "dir(certificate_default_storage): ", dir(certificate_default_storage)
                    print "location(certificate_default_storage): ", certificate_default_storage.location
                    certificate_file = open(path,"wb")
                    for line in certificate_contents.readlines():
                        certificate_file.write(line)
                    certificate_file.close()
                    # Update path of certificate
                    certificate.key.name = path
                    certificate.save()
                except Exception as e:
                    print "certificate.e: ", e

                try:
                    #if "key" in request.FILES:
                    #    key_contents = request.FILES["key"]
                    key_contents = client_xmplrc_secure.__dict__["key"].values()[0]
                    print "key_contents: ", key_contents
                    key_default_storage = client.key.storage
                    key_name = get_file_name(aggregate)
                    print "key_name: ", key_name
                    path = certificate_default_storage.save( \
                                os.path.join(DEFAULT_UPLOAD_PATH, "%s.key" % certificate_name), \
                                ContentFile(certificate_contents.read()))
                    print "path...............", path
                    print "dir(key_default_storage): ", key_default_storage["path"]
                    key_file = open("/opt/felix/%s" % key_name,"wb")
                    for line in key_contents.readlines():
                        key_file.write(line)
                    key_file.close()
                    # Update path of key
                    client.key.name = path
                    client.save()
                except Exception as e:
                    print "key.e: ", e

                aggregate.client = client
                # Set to available
                #aggregate.available = True
                aggregate.save()
                agg_form.save_m2m()
                aggregate.save()
                # Update agg_id to sync its resources
#                agg_id = aggregate.pk
#                # Get resources from ResourceOrchestrator AM's xmlrpc server every time the AM is updated
#                try:
#                    # TODO Process output of GetVersion for more info on associated RMs?
#                    do_sync = True
#                    if agg_form.is_bound:
#                        do_sync = agg_form.data.get("sync_resources")
#                    else:
#                        do_sync = agg_form.initial.get("sync_resources")
#
#                    if do_sync:
#                        failed_resources = sync_ro_resources(agg_id, s)
#
#                        if failed_resources:
#                            DatedMessage.objects.post_message_to_user(
#                                "Could not synchronize resources %s within Expedient" % str(failed_resources),
#                                user=request.user, msg_type=DatedMessage.TYPE_WARNING,
#                            )
#                except:
#                    warning = "Could not synchronize RO resources within Expedient"
#                    DatedMessage.objects.post_message_to_user(
#                        errors, user=request.user, msg_type=DatedMessage.TYPE_WARNING,
#                    )
#                    extra_context_dict['errors'] = warning

                give_permission_to(
                   "can_use_aggregate",
                   aggregate,
                   request.user,
                   can_delegate=True
                )
                give_permission_to(
                    "can_edit_aggregate",
                    aggregate,
                    request.user,
                    can_delegate=True
                )
                DatedMessage.objects.post_message_to_user(
                    "Successfully created/updated aggregate %s" % aggregate.name,
                    user=request.user, msg_type=DatedMessage.TYPE_SUCCESS,
                )
                return HttpResponseRedirect("/")
    else:
        return HttpResponseNotAllowed("GET", "POST")


    if not errors:
        extra_context_dict['available'] = aggregate.check_status() if agg_id else False

    # Updates the dictionary with the common fields
    extra_context_dict.update({
            "agg_form": agg_form,
            "client_form": client_form,
            "create": not agg_id,
            "aggregate": aggregate,
            "breadcrumbs": (
                ('Home', reverse("home")),
                ("%s ResourceOrchestrator Aggregate" % ("Update" if agg_id else "Create"),
                 request.path),
            )
        })

    return simple.direct_to_template(
        request,
        template="resource_orchestrator_aggregate_crud.html",
        extra_context=extra_context_dict
    )
    def handle_noargs(self, **options):
        
        username = options.get("username")
        password = options.get("password")
        
        filename = options.get("filename")
        do_aggs = options.get("load_aggs")
        do_slices = options.get("load_slices")
        start_slices = options.get("start_slices")
        append = options.get("append")
        
        f = open(filename)
        data = load(f)
        f.close()
        
        client = Client()
        client.login(username=username, password=password)

        user = User.objects.get(username=username)
        threadlocals.get_thread_locals()["user"] = user

        if do_aggs:
            for agg_dict in data["aggregates"]:
                resp = test_get_and_post_form(
                    client, reverse("openflow_aggregate_create"),
                    agg_dict,
                )
                
                assert(resp.status_code == 302)
                assert(
                    re.search(
                        r"/openflow/aggregate/\d+/links/$",
                        resp["Location"]))
        if do_slices:
            for project_dict in data["projects"]:
                project, _ = Project.objects.get_or_create(
                    name=project_dict["name"],
                    description=project_dict["description"],
                )
                create_project_roles(project, user)
                threadlocals.get_thread_locals()["project"] = project
                
                # add aggregates to project
                for aggregate in OpenFlowAggregate.objects.all():
                    give_permission_to("can_use_aggregate", aggregate, user)
                    give_permission_to("can_use_aggregate", aggregate, project)

                for aggregate in GCFOpenFlowAggregate.objects.all():
                    give_permission_to("can_use_aggregate", aggregate, user)
                    give_permission_to("can_use_aggregate", aggregate, project)
                
                # add slices to project
                for slice_dict in project_dict["slices"]:
                    slice = Slice.objects.create(
                        name=slice_dict["name"],
                        description=slice_dict["description"],
                        project=project,
                        owner=user,
                    )
                
                    OpenFlowSliceInfo.objects.create(
                        slice=slice,
                        controller_url=slice_dict["controller_url"],
                        password=slice_dict["password"],
                    )

                    info, _ = GENISliceInfo.objects.get_or_create(
                        slice=slice,
                    )
                    
                    if not info.ssh_private_key or not info.ssh_public_key:
                        info.generate_ssh_keys()
                        info.save()
                    
                    # add aggregates to slices
                    for aggregate in OpenFlowAggregate.objects.all():
                        give_permission_to("can_use_aggregate", aggregate, slice)

                    for aggregate in GCFOpenFlowAggregate.objects.all():
                        give_permission_to("can_use_aggregate", aggregate, slice)
                    
                    # add slivers
                    slivers = []
                    for dpid, port in slice_dict["ifaces"]:
                        try:
                            sliver, _ = OpenFlowInterfaceSliver.objects.get_or_create(
                                slice=slice,
                                resource=OpenFlowInterface.objects.get(
                                    port_num=port, switch__datapath_id=dpid),
                            )
                            slivers.append(sliver)
                        except OpenFlowInterface.DoesNotExist:
                            continue
                        
                    # add flowspace
                    for sfs_dict in slice_dict["sfs"]:
                        fs_dict = {}
                        for attr in "dl_src", "dl_dst", "dl_type", "vlan_id", \
                        "nw_src", "nw_dst", "nw_proto", "tp_dst", "tp_src":
                            fs_dict[attr+"_start"] = sfs_dict[attr]
                            fs_dict[attr+"_end"] = sfs_dict[attr]
                        
                        fs = FlowSpaceRule.objects.create(**fs_dict)
                        
                        for sliver in slivers:
                            fs.slivers.add(sliver)
                            
                    if start_slices:
                        tl = threadlocals.get_thread_locals()
                        tl["project"] = project
                        tl["slice"] = slice
                        slice.start(user)
def aggregate_crud(request, agg_id=None):
    '''
    Create/update an Virtualization Aggregate.
    '''
    if agg_id != None:
        aggregate = get_object_or_404(VtPlugin, pk=agg_id)
        client = aggregate.client
    else:
        aggregate = None
        client = None

    extra_context_dict = {}
    errors = ""

    if request.method == "GET":
        agg_form = VTAggregateForm(instance=aggregate)
        client_form = xmlrpcServerProxyForm(instance=client)
        
    elif request.method == "POST":
        agg_form = VTAggregateForm(
            data=request.POST, instance=aggregate)
        client_form = xmlrpcServerProxyForm(
            data=request.POST, instance=client)

        if client_form.is_valid() and agg_form.is_valid():
            # Ping is tried after every field check
            client = client_form.save(commit=False)
            s = xmlrpclib.Server('https://'+client.username+':'+client.password+'@'+client.url[8:])
            try:
                s.ping('ping')
            except:
                errors = "Could not connect to server: username, password or url are not correct"
                DatedMessage.objects.post_message_to_user(
                    errors, user=request.user, msg_type=DatedMessage.TYPE_ERROR,
                )
                extra_context_dict['errors'] = errors
#                return HttpResponseRedirect(request.path) 

            if not errors:
                client = client_form.save()
                aggregate = agg_form.save(commit=False)
                aggregate.client = client
                aggregate.save()
                agg_form.save_m2m()
                aggregate.save()
                give_permission_to(
                   "can_use_aggregate",
                   aggregate,
                   request.user,
                   can_delegate=True
                )
                give_permission_to(
                    "can_edit_aggregate",
                    aggregate,
                    request.user,
                    can_delegate=True
                )
                DatedMessage.objects.post_message_to_user(
                    "Successfully created/updated aggregate %s" % aggregate.name,
                    user=request.user, msg_type=DatedMessage.TYPE_SUCCESS,
                )
                return HttpResponseRedirect("/")
    else:
        return HttpResponseNotAllowed("GET", "POST")

    if not errors:
        extra_context_dict['available'] = aggregate.check_status() if agg_id else False

    # Updates the dictionary with the common fields
    extra_context_dict.update({
            "agg_form": agg_form,
            "client_form": client_form,
            "create": not agg_id,
            "aggregate": aggregate,
            # Previously commented
            # "available": available,
            "breadcrumbs": (
                ('Home', reverse("home")),
                ("%s Virtualization Aggregate" % ("Update" if agg_id else "Add"),
                 request.path),
            )
        })

    return simple.direct_to_template(
        request,
        template="vt_plugin_aggregate_crud.html",
        extra_context=extra_context_dict
    )
Esempio n. 41
0
def aggregate_crud(request, agg_id=None):
    '''
    Create/update a SampleResource Aggregate.
    '''
    if agg_id != None:
        aggregate = get_object_or_404(SampleResourceAggregateModel, pk=agg_id)
        client = aggregate.client
    else:
        aggregate = None
        client = None

    extra_context_dict = {}
    errors = ""

    if request.method == "GET":
        agg_form = SampleResourceAggregateForm(instance=aggregate)
        client_form = xmlrpcServerProxyForm(instance=client)
        
    elif request.method == "POST":
        agg_form = SampleResourceAggregateForm(
            data=request.POST, instance=aggregate)
        client_form = xmlrpcServerProxyForm(
            data=request.POST, instance=client)

        if client_form.is_valid() and agg_form.is_valid():
            # Ping is tried after every field check
            client = client_form.save(commit=False)
            s = xmlrpclib.Server('https://'+client.username+':'+client.password+'@'+client.url[8:])
            try:
                s.ping('ping')
            except:
                errors = "Could not connect to server: username, password or url are not correct"
                DatedMessage.objects.post_message_to_user(
                    errors, user=request.user, msg_type=DatedMessage.TYPE_ERROR,
                )
                extra_context_dict['errors'] = errors

            if not errors:
                client = client_form.save()
                aggregate = agg_form.save(commit=False)
                aggregate.client = client
                aggregate.save()
                agg_form.save_m2m()
                aggregate.save()
                # Update agg_id to sync its resources
                agg_id = aggregate.pk
                # Get resources from SampleResource AM's xmlrpc server every time the AM is updated
                try:
                    do_sync = True
                    if agg_form.is_bound:
                        do_sync = agg_form.data.get("sync_resources")
                    else:
                        do_sync = agg_form.initial.get("sync_resources")

                    if do_sync:
                        failed_resources = sync_am_resources(agg_id, s)

                        if failed_resources:
                            DatedMessage.objects.post_message_to_user(
                                "Could not synchronize resources %s within Expedient" % str(failed_resources),
                                user=request.user, msg_type=DatedMessage.TYPE_WARNING,
                            )
                except:
                    warning = "Could not synchronize AM resources within Expedient"
                    DatedMessage.objects.post_message_to_user(
                        errors, user=request.user, msg_type=DatedMessage.TYPE_WARNING,
                    )
                    extra_context_dict['errors'] = warning

                give_permission_to(
                   "can_use_aggregate",
                   aggregate,
                   request.user,
                   can_delegate=True
                )
                give_permission_to(
                    "can_edit_aggregate",
                    aggregate,
                    request.user,
                    can_delegate=True
                )
                DatedMessage.objects.post_message_to_user(
                    "Successfully created/updated aggregate %s" % aggregate.name,
                    user=request.user, msg_type=DatedMessage.TYPE_SUCCESS,
                )
                return HttpResponseRedirect("/")
    else:
        return HttpResponseNotAllowed("GET", "POST")


    if not errors:
        extra_context_dict['available'] = aggregate.check_status() if agg_id else False

    # Updates the dictionary with the common fields
    extra_context_dict.update({
            "agg_form": agg_form,
            "client_form": client_form,
            "create": not agg_id,
            "aggregate": aggregate,
            "breadcrumbs": (
                ('Home', reverse("home")),
                ("%s SampleResource Aggregate" % ("Update" if agg_id else "Create"),
                 request.path),
            )
        })

    return simple.direct_to_template(
        request,
        template="sample_resource_aggregate_crud.html",
        extra_context=extra_context_dict
    )
Esempio n. 42
0
File: gapi.py Progetto: cargious/ocf
def CreateSliver(slice_urn, rspec, user):
    (project_name, project_desc, slice_name, slice_desc, slice_expiry,
     controller_url, firstname, lastname, affiliation, email, password,
     slivers) = rspec_mod.parse_slice(rspec)

    logger.debug("Parsed Rspec")

    slice_expiry = datetime.fromtimestamp(slice_expiry)

    give_permission_to("can_create_project", Project, user)

    user.first_name = firstname
    user.last_name = lastname
    user.email = email
    profile = UserProfile.get_or_create_profile(user)
    profile.affiliation = affiliation
    user.save()
    profile.save()

    # Check if the slice exists
    try:
        slice = get_slice(slice_urn)
        # update the slice info
        slice.description = slice_desc
        slice.name = slice_name
        slice.expiration_date = slice_expiry
        slice.save()
        # update the project info
        slice.project.name = project_name
        slice.project.description = project_desc
        slice.project.save()
        project = slice.project
    except Slice.DoesNotExist:
        # Check if the project exists
        try:
            project = Project.objects.get(name=project_name)
            # update the project info
            logger.debug("Updating project")
            project.description = project_desc
            project.save()
        except Project.DoesNotExist:
            # create the project
            logger.debug("Creating project")
            project = Project.objects.create(
                name=project_name,
                description=project_desc,
            )
            create_project_roles(project, user)

        # create the slice
        logger.debug("Creating slice")

        try:
            slice = Slice.objects.create(
                name=slice_name,
                description=slice_desc,
                project=project,
                owner=user,
                expiration_date=slice_expiry,
            )
        except IntegrityError:
            raise DuplicateSliceNameException(slice_name)

    logger.debug("Creating/updating slice info")

    # create openflow slice info for the slice
    create_or_update(
        OpenFlowSliceInfo,
        filter_attrs={"slice": slice},
        new_attrs={
            "controller_url": controller_url,
            "password": password,
        },
    )

    logger.debug("creating gapislice")

    # store a pointer to this slice using the slice_urn
    create_or_update(
        GENISliceInfo,
        filter_attrs={
            "slice": slice,
        },
        new_attrs={
            "slice_urn": slice_urn,
        },
    )

    logger.debug("adding resources")

    sliver_ids = []

    # delete all flowspace in the slice
    FlowSpaceRule.objects.filter(slivers__slice=slice).delete()

    # add the new flowspace
    for fs_dict, iface_qs in slivers:
        # give the user, project, slice permission to use the aggregate
        aggregate_ids = list(iface_qs.values_list("aggregate", flat=True))
        for agg_id in aggregate_ids:
            aggregate = Aggregate.objects.get(id=agg_id).as_leaf_class()
            give_permission_to("can_use_aggregate", aggregate, user)
            give_permission_to("can_use_aggregate", aggregate, project)
            give_permission_to("can_use_aggregate", aggregate, slice)

        # Create flowspace
        logger.debug("Creating flowspace %s" % fs_dict)
        fs = FlowSpaceRule.objects.create(**fs_dict)

        # make sure all the selected interfaces are added
        for iface in iface_qs:
            sliver, _ = OpenFlowInterfaceSliver.objects.get_or_create(
                slice=slice, resource=iface)
            sliver_ids.append(sliver.id)
            fs.slivers.add(sliver)

    logger.debug("Deleting old resources")

    # Delete all removed interfaces
    OpenFlowInterfaceSliver.objects.exclude(id__in=sliver_ids).delete()

    logger.debug("Starting the slice %s %s" % (slice, slice.name))

    # make the reservation
    tl = threadlocals.get_thread_locals()
    tl["project"] = project
    tl["slice"] = slice
    slice.start(user)
    logger.debug("Done creating sliver")

    return rspec_mod.create_resv_rspec(user, slice)
Esempio n. 43
0
def CreateSliver(slice_urn, rspec, user):
    (project_name, project_desc, slice_name, slice_desc, slice_expiry,
    controller_url, firstname, lastname, affiliation,
    email, password, slivers) = rspec_mod.parse_slice(rspec)

    logger.debug("Parsed Rspec")
    
    slice_expiry = datetime.fromtimestamp(slice_expiry)

    give_permission_to("can_create_project", Project, user)

    user.first_name = firstname
    user.last_name = lastname
    user.email = email
    profile = UserProfile.get_or_create_profile(user)
    profile.affiliation = affiliation
    user.save()
    profile.save()
    
    # Check if the slice exists
    try:
        slice = get_slice(slice_urn)
        # update the slice info
        slice.description = slice_desc
        slice.name = slice_name
        slice.expiration_date = slice_expiry
        slice.save()
        # update the project info
        slice.project.name = project_name
        slice.project.description = project_desc
        slice.project.save()
        project = slice.project
    except Slice.DoesNotExist:
        # Check if the project exists
        try:
            project = Project.objects.get(name=project_name)
            # update the project info
            logger.debug("Updating project")
            project.description = project_desc
            project.save()
        except Project.DoesNotExist:
            # create the project
            logger.debug("Creating project")
            project = Project.objects.create(
                name=project_name,
                description=project_desc,
            )
            create_project_roles(project, user)
        
        # create the slice
        logger.debug("Creating slice")
        
        try:
            slice = Slice.objects.create(
                name=slice_name,
                description=slice_desc,
                project=project,
                owner=user,
                expiration_date = slice_expiry,
            )
        except IntegrityError:
            raise DuplicateSliceNameException(slice_name)

    logger.debug("Creating/updating slice info")
    
    # create openflow slice info for the slice
    create_or_update(
        OpenFlowSliceInfo,
        filter_attrs={"slice": slice},
        new_attrs={
            "controller_url": controller_url,
            "password": password,
        },
    )
    
    logger.debug("creating gapislice")

    # store a pointer to this slice using the slice_urn
    create_or_update(
        GENISliceInfo,
        filter_attrs={
            "slice": slice,
        },
        new_attrs={
            "slice_urn": slice_urn,
        },
    )
    
    logger.debug("adding resources")

    sliver_ids = []
    
    # delete all flowspace in the slice
    FlowSpaceRule.objects.filter(slivers__slice=slice).delete()
    
    # add the new flowspace
    for fs_dict, iface_qs in slivers:
        # give the user, project, slice permission to use the aggregate
        aggregate_ids = list(iface_qs.values_list("aggregate", flat=True))
        for agg_id in aggregate_ids:
            aggregate = Aggregate.objects.get(id=agg_id).as_leaf_class()
            give_permission_to("can_use_aggregate", aggregate, user)
            give_permission_to("can_use_aggregate", aggregate, project)
            give_permission_to("can_use_aggregate", aggregate, slice)

        # Create flowspace
        logger.debug("Creating flowspace %s" % fs_dict)
        fs = FlowSpaceRule.objects.create(**fs_dict)

        # make sure all the selected interfaces are added
        for iface in iface_qs:
            sliver, _ = OpenFlowInterfaceSliver.objects.get_or_create(
                slice=slice, resource=iface)
            sliver_ids.append(sliver.id)
            fs.slivers.add(sliver)
        
    logger.debug("Deleting old resources")

    # Delete all removed interfaces
    OpenFlowInterfaceSliver.objects.exclude(id__in=sliver_ids).delete()
        
    logger.debug("Starting the slice %s %s" % (slice, slice.name))
    
    # make the reservation
    tl = threadlocals.get_thread_locals()
    tl["project"] = project
    tl["slice"] = slice
    slice.start(user)
    logger.debug("Done creating sliver")

    return rspec_mod.create_resv_rspec(user, slice)
Esempio n. 44
0
    def post_save(instance, created):
	give_permission_to("can_delete_slices", instance, instance.owner, giver=None, can_delegate=False)
Esempio n. 45
0
def aggregate_crud(request, agg_id=None):
    '''
    Create/update an OpenFlow Aggregate.
    '''
    if agg_id != None:
        aggregate = get_object_or_404(OpenFlowAggregate, pk=agg_id)
        client = aggregate.client
    else:
        aggregate = None
        client = None

    if request.method == "GET":
        agg_form = OpenFlowAggregateForm(instance=aggregate)
        client_form = PasswordXMLRPCServerProxyForm(instance=client)

    elif request.method == "POST":
        logger.debug("aggregate_crud got post")
        agg_form = OpenFlowAggregateForm(data=request.POST, instance=aggregate)
        client_form = PasswordXMLRPCServerProxyForm(data=request.POST,
                                                    instance=client)
        logger.debug("Validating")
        if client_form.is_valid() and agg_form.is_valid():
            logger.debug("Forms are valid")
            logger.debug("Got logo %s" % request.POST.get("logo", ""))
            # Save the client first
            client = client_form.save()
            # Then save the aggregate and add the client
            aggregate = agg_form.save(commit=False)
            aggregate.client = client
            aggregate.save()
            agg_form.save_m2m()
            try:
                info = aggregate.client.proxy.get_am_info()
                aggregate.vlan_auto_assignment = info["vlan_auto_assignment"]
                aggregate.flowspace_auto_approval = info[
                    "flowspace_auto_approval"]
            except:
                #                logger.debug("Aggregate %s: could not check automatic resource assignment" % str(aggregate.name))
                pass

            try:
                err = ' '
                aggregate.client.proxy.checkFlowVisor()
                aggregate.setup_new_aggregate(request.build_absolute_uri("/"))
            except Exception as e:
                err = str(e)
            if err is not ' ':
                #transaction.rollback()
                if "check_fv_set" in err:
                    msg_type = DatedMessage.TYPE_WARNING
                    if agg_id:
                        flowvisor_msg = "Topology could not be updated because could not connect to FlowVisor."
                    else:
                        flowvisor_msg = "New Aggregate set, but there is no FlowVisor connected to it."
                else:
                    flowvisor_msg = err
                    msg_type = DatedMessage.TYPE_ERROR
                DatedMessage.objects.post_message_to_user(
                    flowvisor_msg,
                    user=request.user,
                    msg_type=msg_type,
                )
                return HttpResponseRedirect("/")
            aggregate.save()
            give_permission_to("can_use_aggregate",
                               aggregate,
                               request.user,
                               can_delegate=True)
            give_permission_to("can_edit_aggregate",
                               aggregate,
                               request.user,
                               can_delegate=True)
            DatedMessage.objects.post_message_to_user(
                "Successfully created/updated aggregate %s. %s" %
                (aggregate.name, err),
                user=request.user,
                msg_type=DatedMessage.TYPE_SUCCESS,
            )
            return HttpResponseRedirect(
                reverse("openflow_aggregate_add_links", args=[aggregate.id]))
        logger.debug("Validation failed")
    else:
        return HttpResponseNotAllowed("GET", "POST")

    available = aggregate.check_status() if agg_id else False
    return simple.direct_to_template(
        request,
        template="openflow_aggregate_crud.html",
        extra_context={
            "agg_form":
            agg_form,
            "client_form":
            client_form,
            "create":
            not agg_id,
            "aggregate":
            aggregate,
            "available":
            available,
            "breadcrumbs": (
                ('Home', reverse("home")),
                ("%s OpenFlow Aggregate" % ("Update" if agg_id else "Add"),
                 request.path),
            )
        },
    )
Esempio n. 46
0
    def setUp(self):
        """
        Update settings, create DummyOMs and test models and login.
        """
        # add the test application
        self.settings_manager.set(
            OPENFLOW_OTHER_RESOURCES=(
                ("expedient.clearinghouse.resources", "Resource"),
            ),
            DEBUG_PROPAGATE_EXCEPTIONS=True,
        )
        self.su = User.objects.create_superuser(
            "superuser", "*****@*****.**", "password")
        self.test_user_password = "******"
        self.test_user = User.objects.create_user(
            "test_user", "*****@*****.**", self.test_user_password)
        give_permission_to("can_add_aggregate", Aggregate, self.test_user)
        give_permission_to("can_create_project", Project, self.test_user)
        
        for i in range(NUM_DUMMY_OMS):
            om = DummyOM.objects.create()
            om.populate_links(NUM_SWITCHES_PER_AGG, 
                              NUM_LINKS_PER_AGG/2)
            username = "******" % i
            password = "******"
            u = User.objects.create_user(username, "*****@*****.**", password)
    
            # Add the aggregate to the CH
            url = SCHEME + "://%s/dummyom/%s/xmlrpc/" % (HOST, om.id)
            
            proxy = PasswordXMLRPCServerProxy.objects.create(
                username=username, password=password,
                url=url, verify_certs=False,
            )
    
            # test availability
            if not proxy.is_available():
                raise Exception("Problem: Proxy not available")

            proxy.delete()
            
        # create user cert/keys
        self.user_urn = get_user_urn(self.test_user.username)
        self.user_cert, self.user_key = create_x509_cert(self.user_urn)
        
        # get slice creds
        self.slice_cred = geni_clearinghouse.CreateSlice(
            self.user_cert.save_to_string())
        self.slice_gid = credential.Credential(
            string=self.slice_cred).get_gid_object()
        
        # xmlrpc client
        self.rpc = xmlrpclib.ServerProxy(
            "http://testserver" + reverse("openflow_gapi"),
            transport=TestClientTransport(
                defaults={
                    "REMOTE_USER": self.user_cert.save_to_string(),
                    "SSL_CLIENT_CERT": self.user_cert.save_to_string(),
                },
            ),
        )
Esempio n. 47
0
def aggregate_crud(request, agg_id=None):
    '''
    Create/update an Virtualization Aggregate.
    '''
    if agg_id != None:
        aggregate = get_object_or_404(VtPlugin, pk=agg_id)
        client = aggregate.client
    else:
        aggregate = None
        client = None

    if request.method == "GET":
        agg_form = VTAggregateForm(instance=aggregate)
        client_form = xmlrpcServerProxyForm(instance=client)

    elif request.method == "POST":
        agg_form = VTAggregateForm(data=request.POST, instance=aggregate)
        client_form = xmlrpcServerProxyForm(data=request.POST, instance=client)
        if client_form.is_valid() and agg_form.is_valid():
            client = client_form.save(commit=False)
            s = xmlrpclib.Server('https://' + client.username + ':' +
                                 client.password + '@' + client.url[8:])
            try:
                s.ping('ping')
            except:
                DatedMessage.objects.post_message_to_user(
                    'Could not connect to server: username, password or url are not correct',
                    user=request.user,
                    msg_type=DatedMessage.TYPE_ERROR,
                )
                return HttpResponseRedirect(request.path)
            client = client_form.save()
            aggregate = agg_form.save(commit=False)
            aggregate.client = client
            aggregate.save()
            agg_form.save_m2m()
            aggregate.save()
            give_permission_to("can_use_aggregate",
                               aggregate,
                               request.user,
                               can_delegate=True)
            give_permission_to("can_edit_aggregate",
                               aggregate,
                               request.user,
                               can_delegate=True)
            DatedMessage.objects.post_message_to_user(
                "Successfully created/updated aggregate %s" % aggregate.name,
                user=request.user,
                msg_type=DatedMessage.TYPE_SUCCESS,
            )
            return HttpResponseRedirect("/")
    else:
        return HttpResponseNotAllowed("GET", "POST")

    available = aggregate.check_status() if agg_id else False
    return simple.direct_to_template(
        request,
        template="openflow/plugin/aggregate_crud.html",
        extra_context={
            "agg_form":
            agg_form,
            "client_form":
            client_form,
            "create":
            not agg_id,
            "aggregate":
            aggregate,
            #"available": available,
            "breadcrumbs": (
                ('Home', reverse("home")),
                ("%s Virtualization Aggregate" %
                 ("Update" if agg_id else "Add"), request.path),
            )
        },
    )
Esempio n. 48
0
    def setUp(self):
        """
        Update settings, create DummyOMs and test models and login.
        """
        # add the test application
        self.settings_manager.set(
            OPENFLOW_OTHER_RESOURCES=(("expedient.clearinghouse.resources",
                                       "Resource"), ),
            DEBUG_PROPAGATE_EXCEPTIONS=True,
        )
        self.su = User.objects.create_superuser("superuser", "*****@*****.**",
                                                "password")
        self.test_user_password = "******"
        self.test_user = User.objects.create_user("test_user", "*****@*****.**",
                                                  self.test_user_password)
        give_permission_to("can_add_aggregate", Aggregate, self.test_user)
        give_permission_to("can_create_project", Project, self.test_user)

        for i in range(NUM_DUMMY_OMS):
            om = DummyOM.objects.create()
            om.populate_links(NUM_SWITCHES_PER_AGG, NUM_LINKS_PER_AGG / 2)
            username = "******" % i
            password = "******"
            u = User.objects.create_user(username, "*****@*****.**", password)

            # Add the aggregate to the CH
            url = SCHEME + "://%s/dummyom/%s/xmlrpc/" % (HOST, om.id)

            proxy = PasswordXMLRPCServerProxy.objects.create(
                username=username,
                password=password,
                url=url,
                verify_certs=False,
            )

            # test availability
            if not proxy.is_available():
                raise Exception("Problem: Proxy not available")

            proxy.delete()

        # create user cert/keys
        self.user_urn = get_user_urn(self.test_user.username)
        self.user_cert, self.user_key = create_x509_cert(self.user_urn)

        # get slice creds
        self.slice_cred = clearinghouse.CreateSlice(
            self.user_cert.save_to_string())
        self.slice_gid = credential.Credential(
            string=self.slice_cred).get_gid_object()

        # xmlrpc client
        self.rpc = xmlrpclib.ServerProxy(
            "http://testserver" + reverse("openflow_gapi"),
            transport=TestClientTransport(defaults={
                "REMOTE_USER":
                self.user_cert.save_to_string(),
                "SSL_CLIENT_CERT":
                self.user_cert.save_to_string(),
            }, ),
        )