Revision 3cbd5e47 snf-astakos-app/astakos/im/views.py

b/snf-astakos-app/astakos/im/views.py
87 87
                                  SendNotificationError)
88 88
from astakos.im.endpoints.qh import timeline_charge
89 89
from astakos.im.settings import (COOKIE_NAME, COOKIE_DOMAIN, LOGOUT_NEXT,
90
                                 LOGGING_LEVEL, PAGINATE_BY)
90
                                 LOGGING_LEVEL, PAGINATE_BY, RESOURCES_PRESENTATION_DATA)
91 91
from astakos.im.tasks import request_billing
92 92
from astakos.im.api.callpoint import AstakosCallpoint
93 93

  
......
667 667
                           context_instance=get_context(request,
668 668
                                                        extra_context))
669 669

  
670

  
671

  
672
resource_presentation = {
673
       'compute': {
674
            'help_text':'group compute help text',
675
            'is_abbreviation':False,
676
            'report_desc':''
677
        },
678
        'storage': {
679
            'help_text':'group storage help text',
680
            'is_abbreviation':False,
681
            'report_desc':''
682
        },
683
        'pithos+.diskspace': {
684
            'help_text':'resource pithos+.diskspace help text',
685
            'is_abbreviation':False,
686
            'report_desc':'Pithos+ Diskspace',
687
            'placeholder':'eg. 10GB'
688
        },
689
        'cyclades.vm': {
690
            'help_text':'resource cyclades.vm help text resource cyclades.vm help text resource cyclades.vm help text resource cyclades.vm help text',
691
            'is_abbreviation':True,
692
            'report_desc':'Virtual Machines',
693
            'placeholder':'eg. 2'
694
        },
695
        'cyclades.disksize': {
696
            'help_text':'resource cyclades.disksize help text',
697
            'is_abbreviation':False,
698
            'report_desc':'Disksize',
699
            'placeholder':'eg. 5GB, 2GB etc'
700
        },
701
        'cyclades.disk': {
702
            'help_text':'resource cyclades.disk help text',
703
            'is_abbreviation':False,
704
            'report_desc':'Disk',
705
            'placeholder':'eg. 5GB, 2GB etc'
706
        },
707
        'cyclades.ram': {
708
            'help_text':'resource cyclades.ram help text',
709
            'is_abbreviation':True,
710
            'report_desc':'RAM',
711
            'placeholder':'eg. 4GB'
712
        },
713
        'cyclades.cpu': {
714
            'help_text':'resource cyclades.cpu help text',
715
            'is_abbreviation':True,
716
            'report_desc':'CPUs',
717
            'placeholder':'eg. 1'
718
        },
719
        'cyclades.network.private': {
720
            'help_text':'resource cyclades.network.private help text',
721
            'is_abbreviation':False,
722
            'report_desc':'Network',
723
            'placeholder':'eg. 1'
724
        }
725
    }
670
class ResourcePresentation():
671
    
672
    def __init__(self, data):
673
        self.data = data
674
        
675
    def update_from_result(self, result):
676
        if result.is_success:
677
            for r in result.data:
678
                rname = '%s%s%s' % (r.get('service'), RESOURCE_SEPARATOR, r.get('name'))
679
                if not rname in self.data['resources']:
680
                    self.data['resources'][rname] = {}
681
                    
682
                self.data['resources'][rname].update(r)
683
                self.data['resources'][rname]['id'] = rname
684
                group = r.get('group')
685
                if not group in self.data['groups']:
686
                    self.data['groups'][group] = {}
687
                    
688
                self.data['groups'][r.get('group')].update({'name': r.get('group')})
689
    
690
    def test(self, quota_dict):
691
        for k, v in quota_dict.iteritems():
692
            rname = k
693
            value = v
694
            if not rname in self.data['resources']:
695
                    self.data['resources'][rname] = {}
696
                    
697
 
698
            self.data['resources'][rname]['value'] = value
699
            
700
    
701
    def update_from_result_report(self, result):
702
        if result.is_success:
703
            for r in result.data:
704
                rname = r.get('name')
705
                if not rname in self.data['resources']:
706
                    self.data['resources'][rname] = {}
707
                    
708
                self.data['resources'][rname].update(r)
709
                self.data['resources'][rname]['id'] = rname
710
                group = r.get('group')
711
                if not group in self.data['groups']:
712
                    self.data['groups'][group] = {}
713
                    
714
                self.data['groups'][r.get('group')].update({'name': r.get('group')})
715
                
716
    def get_group_resources(self, group):
717
        return dict(filter(lambda t: t[1].get('group') == group, self.data['resources'].iteritems()))
718
    
719
    def get_groups_resources(self):
720
        for g in self.data['groups']:
721
            yield g, self.get_group_resources(g)
722
    
723
    def get_quota(self, group_quotas):
724
        print '!!!!!', group_quotas
725
        for r, v in group_quotas.iteritems():
726
            rname = str(r)
727
            quota = self.data['resources'].get(rname)
728
            quota['value'] = v
729
            yield quota
730
    
731
    
732
    def get_policies(self, policies_data):
733
        for policy in policies_data:
734
            rname = '%s%s%s' % (policy.get('service'), RESOURCE_SEPARATOR, policy.get('resource'))
735
            policy.update(self.data['resources'].get(rname))
736
            yield policy
737
        
738
    def __repr__(self):
739
        return self.data.__repr__()
740
                
741
    def __iter__(self, *args, **kwargs):
742
        return self.data.__iter__(*args, **kwargs)
743
    
744
    def __getitem__(self, *args, **kwargs):
745
        return self.data.__getitem__(*args, **kwargs)
746
    
747
    def get(self, *args, **kwargs):
748
        return self.data.get(*args, **kwargs)
749
        
750
        
726 751

  
727 752
@require_http_methods(["GET", "POST"])
728 753
@signed_terms_required
729 754
@login_required
730 755
def group_add(request, kind_name='default'):
756
    
731 757
    result = callpoint.list_resources()
732
    print '###', result
733
    resource_catalog = {'resources':defaultdict(defaultdict),
734
                        'groups':defaultdict(list)}
735
    if result.is_success:
736
        for r in result.data:
737
            service = r.get('service', '')
738
            name = r.get('name', '')
739
            group = r.get('group', '')
740
            unit = r.get('unit', '')
741
            fullname = '%s%s%s' % (service, RESOURCE_SEPARATOR, name)
742
            resource_catalog['resources'][fullname] = dict(unit=unit)
743
            resource_catalog['groups'][group].append(fullname)
744
        
745
        resource_catalog = dict(resource_catalog)
746
        for k, v in resource_catalog.iteritems():
747
            resource_catalog[k] = dict(v)
748
    else:
758
    resource_catalog = ResourcePresentation(RESOURCES_PRESENTATION_DATA)
759
    resource_catalog.update_from_result(result)
760
    
761
    if not result.is_success:
749 762
        messages.error(
750 763
            request,
751 764
            'Unable to retrieve system resources: %s' % result.reason
......
765 778
        form_class=AstakosGroupCreationForm
766 779
    )
767 780
    
768
    resources = resource_catalog['resources']
769
    
770
 
771 781
    if request.method == 'POST':
772 782
        form = form_class(request.POST, request.FILES)
773 783
        if form.is_valid():
784
            print '!!!!!!!!!! CLEANED DATA', form.cleaned_data
774 785
            return render_response(
775 786
                template='im/astakosgroup_form_summary.html',
776 787
                context_instance=get_context(request),
777 788
                form = AstakosGroupCreationSummaryForm(form.cleaned_data),
778
                policies = form.policies(),
779
                resource_presentation=resource_presentation,
789
                policies = resource_catalog.get_policies(form.policies()),
780 790
                resource_catalog= resource_catalog,
781
                resources = resources,
782
            
783 791
            )
792
         
784 793
    else:
785 794
        now = datetime.now()
786 795
        data = {
787 796
            'kind': kind,
788 797
        }
789
        for group, resources in resource_catalog['groups'].iteritems():
798
        for group, resources in resource_catalog.get_groups_resources():
790 799
            data['is_selected_%s' % group] = False
791 800
            for resource in resources:
792 801
                data['%s_uplimit' % resource] = ''
......
803 812
        'form': form,
804 813
        'kind': kind,
805 814
        'resource_catalog':resource_catalog,
806
        'resource_presentation':resource_presentation,
807 815
    }, context_processors)
808 816
    return HttpResponse(t.render(c))
809 817

  
......
840 848
            post_save_redirect = '/im/group/%(id)s/'
841 849
            return HttpResponseRedirect(post_save_redirect % new_object)
842 850
        else:
843
            msg = _(astakos_messages.OBJECT_CREATED_FAILED) %\
844
                {"verbose_name": model._meta.verbose_name,
851
            d = {"verbose_name": model._meta.verbose_name,
845 852
                 "reason":result.reason}
853
            msg = _(astakos_messages.OBJECT_CREATED_FAILED) % d 
846 854
            messages.error(request, msg, fail_silently=True)
847 855
    return render_response(
848 856
        template='im/astakosgroup_form_summary.html',
......
857 865
def group_list(request):
858 866
    none = request.user.astakos_groups.none()
859 867
    sorting = request.GET.get('sorting')
860
    q = AstakosGroup.objects.raw("""
868
    query = """
861 869
        SELECT auth_group.id,
862 870
        %s AS groupname,
863 871
        im_groupkind.name AS kindname,
......
880 888
            im_astakosuser_owner.astakosgroup_id = im_astakosgroup.group_ptr_id)
881 889
        LEFT JOIN auth_user as owner ON (
882 890
            im_astakosuser_owner.astakosuser_id = owner.id)
883
        WHERE im_membership.person_id = %s
884
        """ % (DB_REPLACE_GROUP_SCHEME, request.user.id, request.user.id))
891
        WHERE im_membership.person_id = %s 
892
        """ % (DB_REPLACE_GROUP_SCHEME, request.user.id, request.user.id)
893
       
894
    if sorting:
895
        query = query+" ORDER BY %s ASC" %sorting    
896
    else:
897
        query = query+" ORDER BY creation_date DESC"     
898
    q = AstakosGroup.objects.raw(query)
885 899

  
886
            
900
       
901
       
887 902
    # Create the template, context, response
888 903
    template_name = "%s/%s_list.html" % (
889 904
        q.model._meta.app_label,
......
965 980
        form = MembersSortForm({'sort_by': sorting})
966 981
        if form.is_valid():
967 982
            sorting = form.cleaned_data.get('sort_by')
968

  
983
    
984
 
985
    
969 986
    result = callpoint.list_resources()
970
    resource_catalog = {'resources':defaultdict(defaultdict),
971
                        'groups':defaultdict(list)}
972
    if result.is_success:
973
        for r in result.data:
974
            service = r.get('service', '')
975
            name = r.get('name', '')
976
            group = r.get('group', '')
977
            unit = r.get('unit', '')
978
            fullname = '%s%s%s' % (service, RESOURCE_SEPARATOR, name)
979
            resource_catalog['resources'][fullname] = dict(unit=unit, name=name)
980
            resource_catalog['groups'][group].append(fullname)
981
        
982
        resource_catalog = dict(resource_catalog)
983
        for k, v in resource_catalog.iteritems():
984
            resource_catalog[k] = dict(v)
987
    resource_catalog = ResourcePresentation(RESOURCES_PRESENTATION_DATA)
988
    resource_catalog.update_from_result(result)
989

  
990
    
991
    if not result.is_success:
992
        messages.error(
993
            request,
994
            'Unable to retrieve system resources: %s' % result.reason
995
    )
985 996
    
986
    print '####', resource_catalog, obj.quota
997
    print '######', obj.quota
998
   
987 999
    extra_context = {'update_form': update_form,
988 1000
                     'addmembers_form': addmembers_form,
989 1001
                     'page': request.GET.get('page', 1),
990 1002
                     'sorting': sorting,
991 1003
                     'resource_catalog':resource_catalog,
992
                     'resource_presentation':resource_presentation,}
1004
                     'quota':resource_catalog.get_quota(obj.quota)}
993 1005
    for key, value in extra_context.items():
994 1006
        if callable(value):
995 1007
            c[key] = value()
......
1005 1017
@signed_terms_required
1006 1018
@login_required
1007 1019
def group_search(request, extra_context=None, **kwargs):
1008
    print '###', request
1009 1020
    q = request.GET.get('q')
1010 1021
    sorting = request.GET.get('sorting')
1011 1022
    if request.method == 'GET':
......
1050 1061
        if sorting:
1051 1062
            # TODO check sorting value
1052 1063
            queryset = queryset.order_by(sorting)
1064

  
1053 1065
    else:
1054 1066
        queryset = AstakosGroup.objects.none()
1055 1067
    return object_list(
......
1251 1263
    else:
1252 1264
        data = None
1253 1265
        messages.error(request, result.reason)
1266
    resource_catalog = ResourcePresentation(RESOURCES_PRESENTATION_DATA)
1267
    resource_catalog.update_from_result_report(result)
1268
    
1269

  
1270
    
1254 1271
    return render_response('im/resource_list.html',
1255 1272
                           data=data,
1256
                           resource_presentation=resource_presentation,
1257
                           context_instance=get_context(request))
1273
                           context_instance=get_context(request),
1274
			               resource_catalog=resource_catalog,
1275
                           result=result)
1258 1276

  
1259 1277

  
1260 1278
def group_create_list(request):

Also available in: Unified diff