Пример #1
0
def create_basic_filter(
        resource_types: Union[List[str], str, None] = None,
        resource_ids: Union[List[str], str, None] = None,
        charge_type: ChargeType = ChargeType.usage) -> QueryFilter:
    if isinstance(resource_types, str):
        resource_types = [resource_types]

    if isinstance(resource_ids, str):
        resource_ids = [resource_ids]

    filters = [
        QueryFilter(dimension=QueryComparisonExpression(
            name="ChargeType",
            operator="In",
            values=[charge_type.value],
        ))
    ]

    if resource_types:
        filters.append(
            QueryFilter(dimension=QueryComparisonExpression(
                name="ResourceType",
                operator="In",
                values=resource_types,
            )))
    if resource_ids:
        filters.append(
            QueryFilter(dimension=QueryComparisonExpression(
                name="ResourceId",
                operator="In",
                values=resource_ids,
            )))

    return QueryFilter(and_property=filters)
Пример #2
0
    def _query_costs(self):
        manager = self.manager
        is_resource_group = manager.type == 'resourcegroup'

        client = manager.get_client('azure.mgmt.costmanagement.CostManagementClient')

        aggregation = {'totalCost': QueryAggregation(name='PreTaxCost', function='Sum')}

        grouping = [QueryGrouping(type='Dimension',
                                  name='ResourceGroupName' if is_resource_group else 'ResourceId')]

        query_filter = None
        if not is_resource_group:
            query_filter = QueryFilter(
                dimension=QueryComparisonExpression(name='ResourceType',
                                                    operator='In',
                                                    values=[manager.resource_type.resource_type]))
            if 'dimension' in query_filter._attribute_map:
                query_filter._attribute_map['dimension']['key'] = 'dimensions'

        dataset = QueryDataset(grouping=grouping, aggregation=aggregation, filter=query_filter)

        timeframe = self.data['timeframe']
        time_period = None

        if timeframe not in CostFilter.preset_timeframes:
            end_time = utcnow().replace(hour=0, minute=0, second=0, microsecond=0)
            start_time = end_time - timedelta(days=timeframe)
            timeframe = 'Custom'
            time_period = QueryTimePeriod(from_property=start_time, to=end_time)

        definition = QueryDefinition(type='ActualCost',
                                     timeframe=timeframe,
                                     time_period=time_period,
                                     dataset=dataset)

        subscription_id = manager.get_session().get_subscription_id()

        scope = '/subscriptions/' + subscription_id

        query = client.query.usage(scope, definition)

        if hasattr(query, '_derserializer'):
            original = query._derserializer._deserialize
            query._derserializer._deserialize = lambda target, data: \
                original(target, self.fix_wrap_rest_response(data))

        result_list = [{query.columns[i].name: v for i, v in enumerate(row)}
                       for row in query.rows]

        for r in result_list:
            if 'ResourceGroupName' in r:
                r['ResourceId'] = scope + '/resourcegroups/' + r.pop('ResourceGroupName')
            r['ResourceId'] = r['ResourceId'].lower()

        return result_list