Beispiel #1
0
def resource_usage(request):

    resources_meta = presentation.RESOURCES

    current_usage = quotas.get_user_quotas(request.user)
    current_usage = json.dumps(current_usage['system'])
    resource_catalog, resource_groups = _resources_catalog(for_usage=True)
    if resource_catalog is False:
        # on fail resource_groups contains the result object
        result = resource_groups
        messages.error(
            request, 'Unable to retrieve system resources: %s' % result.reason)

    resource_catalog = json.dumps(resource_catalog)
    resource_groups = json.dumps(resource_groups)
    resources_order = json.dumps(resources_meta.get('resources_order'))

    return render_response(
        'im/resource_usage.html',
        context_instance=get_context(request),
        resource_catalog=resource_catalog,
        resource_groups=resource_groups,
        resources_order=resources_order,
        current_usage=current_usage,
        token_cookie_name=settings.COOKIE_NAME,
        usage_update_interval=settings.USAGE_UPDATE_INTERVAL)
Beispiel #2
0
def resource_usage(request):

    resources_meta = presentation.RESOURCES

    current_usage = quotas.get_user_quotas(request.user)
    current_usage = json.dumps(current_usage['system'])
    resource_catalog, resource_groups = _resources_catalog()
    if resource_catalog is False:
        # on fail resource_groups contains the result object
        result = resource_groups
        messages.error(request, 'Unable to retrieve system resources: %s' %
                       result.reason)

    resource_catalog = json.dumps(resource_catalog)
    resource_groups = json.dumps(resource_groups)
    resources_order = json.dumps(resources_meta.get('resources_order'))

    return render_response('im/resource_usage.html',
                           context_instance=get_context(request),
                           resource_catalog=resource_catalog,
                           resource_groups=resource_groups,
                           resources_order=resources_order,
                           current_usage=current_usage,
                           token_cookie_name=settings.COOKIE_NAME,
                           usage_update_interval=
                           settings.USAGE_UPDATE_INTERVAL)
Beispiel #3
0
def quotas(request):
    visible_resources = get_visible_resources()
    resource_names = [r.name for r in visible_resources]
    memberships = request.user.projectmembership_set.actually_accepted()
    sources = [project_ref(m.project.uuid) for m in memberships]
    result = get_user_quotas(request.user, resources=resource_names,
                             sources=sources)
    return json_response(result)
Beispiel #4
0
def get_quotas(user):
    """Transform the resource usage dictionary of a user.

    Return a list of dictionaries that represent the quotas of the user. Each
    dictionary has the following form:

    {
        'project': <Project instance>,
        'resources': [('Resource Name1', <Resource dict>),
                      ('Resource Name2', <Resource dict>),...]
    }

    where 'Resource Name' is the name of the resource and <Resource dict> is
    the dictionary that is returned by list_user_quotas and has the following
    fields:

        pending, project_pending, project_limit, project_usage, usage.

    Note, the get_quota_usage function returns many dicts, but we only keep the
    ones that have limit > 0
    """
    usage = get_user_quotas(user)

    quotas = []
    for project_id, resource_dict in usage.iteritems():
        source = {}
        source['project'] = Project.objects.get(uuid=project_id)
        q_res = source['resources'] = []

        for resource_name, resource in resource_dict.iteritems():
            # Chech if the resource is useful to display
            project_limit = resource['project_limit']
            usage = resource['usage']
            r = get_resource(resource_name)
            if not is_resource_useful(r, project_limit, usage):
                continue

            usage = units.show(usage, r.unit)
            limit = units.show(resource['limit'], r.unit)
            taken_by_others = resource['project_usage'] - resource['usage']
            effective_limit = min(resource['limit'],
                                  project_limit - taken_by_others)
            if effective_limit < 0:
                effective_limit = 0
            effective_limit = units.show(effective_limit, r.unit)

            if limit != effective_limit:
                limit += " (Effective Limit: " + effective_limit + ")"

            q_res.append((
                r.report_desc,
                usage,
                limit,
            ))

        quotas.append(source)

    return quotas
Beispiel #5
0
def resource_usage(request):

    resources_meta = presentation.RESOURCES

    # resolve uuids of projects the user consumes quota from
    user = request.user
    quota_filters = Q(usage_min__gt=0, limit__gt=0)
    quota_uuids = map(
        lambda k: k[1],
        quotas.get_users_quotas_counters([user], flt=quota_filters)[0].keys(),
    )
    # resolve uuids of projects the user is member to
    user_memberships = request.user.projectmembership_set.actually_accepted()
    membership_uuids = [m.project.uuid for m in user_memberships]

    # merge uuids
    uuids = set(quota_uuids + membership_uuids)
    uuid_refs = map(quotas.project_ref, uuids)

    user_quotas = quotas.get_user_quotas(request.user, sources=uuid_refs)
    projects = Project.objects.filter(uuid__in=uuids)
    user_projects = projects_api.get_projects_details(projects)
    resource_catalog, resource_groups = _resources_catalog()

    if resource_catalog is False:
        # on fail resource_groups contains the result object
        result = resource_groups
        messages.error(
            request, 'Unable to retrieve system resources: %s' % result.reason)

    # Exclude projects that are terminated *and* the user has no active
    # resources (usage>0)
    non_terminated_projects = [
        p["id"] for p in user_projects if p["state"] != "terminated"
    ]
    user_quotas = dict([(p_id, p_quotas)
                        for (p_id, p_quotas) in user_quotas.items()
                        if p_id in non_terminated_projects
                        or filter(lambda x: x["usage"] > 0, p_quotas.values())
                        ])

    resource_catalog = json.dumps(resource_catalog)
    resource_groups = json.dumps(resource_groups)
    resources_order = json.dumps(resources_meta.get('resources_order'))
    projects_details = json.dumps(user_projects, default=_dthandler)
    user_quotas = json.dumps(user_quotas)

    interval = settings.USAGE_UPDATE_INTERVAL
    return render_response('im/resource_usage.html',
                           context_instance=get_context(request),
                           resource_catalog=resource_catalog,
                           resource_groups=resource_groups,
                           resources_order=resources_order,
                           projects_details=projects_details,
                           user_quotas=user_quotas,
                           token_cookie_name=settings.COOKIE_NAME,
                           usage_update_interval=interval)
Beispiel #6
0
def quotas(request):
    visible_resources = get_visible_resources()
    resource_names = [r.name for r in visible_resources]
    memberships = request.user.projectmembership_set.actually_accepted()
    memberships = memberships.exclude(project__state__in=Project.HIDDEN_STATES)

    sources = [project_ref(m.project.uuid) for m in memberships]
    result = get_user_quotas(request.user, resources=resource_names,
                             sources=sources)
    return json_response(result)
Beispiel #7
0
def resource_usage(request):

    resources_meta = presentation.RESOURCES

    # resolve uuids of projects the user consumes quota from
    user = request.user
    quota_filters = Q(usage_min__gt=0, limit__gt=0)
    quota_uuids = map(lambda k: k[1],
                      quotas.get_users_quotas_counters([user],
                                                       flt=quota_filters)[0].keys(),)
    # resolve uuids of projects the user is member to
    user_memberships = request.user.projectmembership_set.actually_accepted()
    membership_uuids = [m.project.uuid for m in user_memberships]

    # merge uuids
    uuids = set(quota_uuids + membership_uuids)
    uuid_refs = map(quotas.project_ref, uuids)

    user_quotas = quotas.get_user_quotas(request.user, sources=uuid_refs)
    projects = Project.objects.filter(uuid__in=uuids)
    user_projects = projects_api.get_projects_details(projects)
    resource_catalog, resource_groups = _resources_catalog()

    if resource_catalog is False:
        # on fail resource_groups contains the result object
        result = resource_groups
        messages.error(request, 'Unable to retrieve system resources: %s' %
                       result.reason)

    # Exclude projects that are terminated *and* the user has no active
    # resources (usage>0)
    non_terminated_projects = [p["id"] for p in user_projects
                               if p["state"] != "terminated"]
    user_quotas = dict([(p_id,  p_quotas)
                        for (p_id, p_quotas) in user_quotas.items()
                        if p_id in non_terminated_projects
                        or
                        filter(lambda x: x["usage"] > 0, p_quotas.values())])

    resource_catalog = json.dumps(resource_catalog)
    resource_groups = json.dumps(resource_groups)
    resources_order = json.dumps(resources_meta.get('resources_order'))
    projects_details = json.dumps(user_projects, default=_dthandler)
    user_quotas = json.dumps(user_quotas)

    interval = settings.USAGE_UPDATE_INTERVAL
    return render_response('im/resource_usage.html',
                           context_instance=get_context(request),
                           resource_catalog=resource_catalog,
                           resource_groups=resource_groups,
                           resources_order=resources_order,
                           projects_details=projects_details,
                           user_quotas=user_quotas,
                           token_cookie_name=settings.COOKIE_NAME,
                           usage_update_interval=interval)
Beispiel #8
0
def get_quotas(user):
    """Transform the resource usage dictionary of a user.

    Return a list of dictionaries that represent the quotas of the user. Each
    dictionary has the following form:

    {
        'project': <Project instance>,
        'resources': [('Resource Name1', <Resource dict>),
                      ('Resource Name2', <Resource dict>),...]
    }

    where 'Resource Name' is the name of the resource and <Resource dict> is
    the dictionary that is returned by list_user_quotas and has the following
    fields:

        pending, project_pending, project_limit, project_usage, usage.

    Note, the get_quota_usage function returns many dicts, but we only keep the
    ones that have limit > 0
    """
    usage = get_user_quotas(user)

    quotas = []
    for project_id, resource_dict in usage.iteritems():
        source = {}
        source['project'] = Project.objects.get(uuid=project_id)
        q_res = source['resources'] = []

        for resource_name, resource in resource_dict.iteritems():
            # Chech if the resource is useful to display
            project_limit = resource['project_limit']
            usage = resource['usage']
            r = get_resource(resource_name)
            if not is_resource_useful(r, project_limit, usage):
                continue

            usage = units.show(usage, r.unit)
            limit = units.show(resource['limit'], r.unit)
            taken_by_others = resource['project_usage'] - resource['usage']
            effective_limit = min(resource['limit'], project_limit - taken_by_others)
            if effective_limit < 0:
                effective_limit = 0
            effective_limit = units.show(effective_limit, r.unit)

            if limit != effective_limit:
                limit += " (Effective Limit: " + effective_limit + ")"

            q_res.append((r.report_desc, usage, limit,))

        quotas.append(source)

    return quotas
Beispiel #9
0
    def handle(self, *args, **options):
        if len(args) != 1:
            raise CommandError("Please provide a user ID or email")

        identifier = args[0]
        if identifier.isdigit():
            users = AstakosUser.objects.filter(id=int(identifier))
        else:
            try:
                uuid.UUID(identifier)
            except:
                users = AstakosUser.objects.filter(email__iexact=identifier)
            else:
                users = AstakosUser.objects.filter(uuid=identifier)
        if users.count() == 0:
            field = "id" if identifier.isdigit() else "email"
            msg = "Unknown user with %s '%s'" % (field, identifier)
            raise CommandError(msg)

        for user in users:
            kv = OrderedDict(
                [
                    ("id", user.id),
                    ("uuid", user.uuid),
                    ("status", user.status_display),
                    ("email", user.email),
                    ("first name", user.first_name),
                    ("last name", user.last_name),
                    ("admin", user.is_superuser),
                    ("last login", user.last_login),
                    ("date joined", user.date_joined),
                    ("last update", user.updated),
                    # ('token', user.auth_token),
                    ("token expiration", user.auth_token_expires),
                    ("providers", user.auth_providers_display),
                    ("groups", [elem.name for elem in user.groups.all()]),
                    ("permissions", [elem.codename for elem in user.user_permissions.all()]),
                    ("group permissions", user.get_group_permissions()),
                    ("email_verified", user.email_verified),
                    ("moderated", user.moderated),
                    ("rejected", user.is_rejected),
                    ("active", user.is_active),
                    ("username", user.username),
                    ("activation_sent_date", user.activation_sent),
                    ("last_login_details", user.last_login_info_display),
                ]
            )

            if get_latest_terms():
                has_signed_terms = user.signed_terms
                kv["has_signed_terms"] = has_signed_terms
                if has_signed_terms:
                    kv["date_signed_terms"] = user.date_signed_terms

            utils.pprint_table(self.stdout, [kv.values()], kv.keys(), options["output_format"], vertical=True)

            if options["list_quotas"] and user.is_accepted():
                unit_style = options["unit_style"]
                check_style(unit_style)

                quotas = get_user_quotas(user)
                if quotas:
                    self.stdout.write("\n")
                    print_data, labels = show_user_quotas(quotas, style=unit_style)
                    utils.pprint_table(self.stdout, print_data, labels, options["output_format"], title="User Quota")

            if options["list_projects"]:
                print_data, labels = ownerships(user)
                if print_data:
                    self.stdout.write("\n")
                    utils.pprint_table(
                        self.stdout, print_data, labels, options["output_format"], title="Owned Projects"
                    )

                print_data, labels = memberships(user)
                if print_data:
                    self.stdout.write("\n")
                    utils.pprint_table(
                        self.stdout, print_data, labels, options["output_format"], title="Project Memberships"
                    )
Beispiel #10
0
def quotas(request):
    visible_resources = get_visible_resources()
    resource_names = [r.name for r in visible_resources]
    result = get_user_quotas(request.user, resources=resource_names)
    return json_response(result)
Beispiel #11
0
def quotas(request):
    visible_resources = get_visible_resources()
    resource_names = [r.name for r in visible_resources]
    result = get_user_quotas(request.user, resources=resource_names)
    return json_response(result)
Beispiel #12
0
    def handle(self, *args, **options):
        if len(args) != 1:
            raise CommandError("Please provide a user ID or email")

        identifier = args[0]
        if identifier.isdigit():
            users = AstakosUser.objects.filter(id=int(identifier))
        else:
            try:
                uuid.UUID(identifier)
            except:
                users = AstakosUser.objects.filter(email__iexact=identifier)
            else:
                users = AstakosUser.objects.filter(uuid=identifier)
        if users.count() == 0:
            field = 'id' if identifier.isdigit() else 'email'
            msg = "Unknown user with %s '%s'" % (field, identifier)
            raise CommandError(msg)

        for user in users:
            kv = OrderedDict([
                ('id', user.id),
                ('uuid', user.uuid),
                ('status', user.status_display),
                ('email', user.email),
                ('first name', user.first_name),
                ('last name', user.last_name),
                ('admin', user.is_superuser),
                ('last login', user.last_login),
                ('date joined', user.date_joined),
                ('last update', user.updated),
                #('token', user.auth_token),
                ('token expiration', user.auth_token_expires),
                ('providers', user.auth_providers_display),
                ('groups', [elem.name for elem in user.groups.all()]),
                ('permissions',
                 [elem.codename for elem in user.user_permissions.all()]),
                ('group permissions', user.get_group_permissions()),
                ('email_verified', user.email_verified),
                ('moderated', user.moderated),
                ('rejected', user.is_rejected),
                ('active', user.is_active),
                ('username', user.username),
                ('activation_sent_date', user.activation_sent),
                ('last_login_details', user.last_login_info_display),
            ])

            if get_latest_terms():
                has_signed_terms = user.signed_terms
                kv['has_signed_terms'] = has_signed_terms
                if has_signed_terms:
                    kv['date_signed_terms'] = user.date_signed_terms

            utils.pprint_table(self.stdout, [kv.values()],
                               kv.keys(),
                               options["output_format"],
                               vertical=True)

            if options["list_quotas"] and user.is_accepted():
                unit_style = options["unit_style"]
                check_style(unit_style)

                quotas = get_user_quotas(user)
                if quotas:
                    self.stdout.write("\n")
                    print_data, labels = show_user_quotas(quotas,
                                                          style=unit_style)
                    utils.pprint_table(self.stdout,
                                       print_data,
                                       labels,
                                       options["output_format"],
                                       title="User Quota")

            if options["list_projects"]:
                print_data, labels = ownerships(user)
                if print_data:
                    self.stdout.write("\n")
                    utils.pprint_table(self.stdout,
                                       print_data,
                                       labels,
                                       options["output_format"],
                                       title="Owned Projects")

                print_data, labels = memberships(user)
                if print_data:
                    self.stdout.write("\n")
                    utils.pprint_table(self.stdout,
                                       print_data,
                                       labels,
                                       options["output_format"],
                                       title="Project Memberships")
Beispiel #13
0
def quotas(request):
    result = get_user_quotas(request.user)
    return json_response(result)