def _query_costs(self): client = self.manager.get_client('azure.mgmt.costmanagement.CostManagementClient') aggregation = {'totalCost': QueryAggregation(name='PreTaxCost')} grouping = [QueryGrouping(type='Dimension', name='ResourceId')] dataset = QueryDataset(grouping=grouping, aggregation=aggregation) 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(timeframe=timeframe, time_period=time_period, dataset=dataset) subscription_id = self.manager.get_session().subscription_id scope = '/subscriptions/' + subscription_id query = client.query.usage_by_scope(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)[0] result = [{result.columns[i].name: v for i, v in enumerate(row)} for row in result.rows] result = {r['ResourceId'].lower(): r for r in result} return result
def _make_expected_call(self, mock, timeframe): grouping = [QueryGrouping(type='Dimension', name='ResourceId')] aggregation = {'totalCost': QueryAggregation(name='PreTaxCost')} dataset = QueryDataset(grouping=grouping, aggregation=aggregation) definition = QueryDefinition(timeframe=timeframe, dataset=dataset) subscription_id = self.session.get_subscription_id() return call('/subscriptions/' + subscription_id, definition)
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
def create_cost_query( timeframe: Union[TimeframeType, Tuple[datetime, Union[datetime, timedelta]]], cost_type: ExportType = ExportType.amortized_cost, granularity: GranularityType = GranularityType.none, grouping: Union[List[GroupByBase], GroupByBase, None] = None, filter: QueryFilter = None, ) -> QueryDefinition: if isinstance(timeframe, TimeframeType): if timeframe == TimeframeType.custom: raise ValueError( "Instead of custom timeframe type, supply a tuple of start end datetime or start datetime and timedelta." ) time_period = None else: from_property, to_property = timeframe timeframe = TimeframeType.custom time_period = QueryTimePeriod( from_property=from_property, to=to_property if isinstance(to_property, datetime) else (from_property + to_property), ) if grouping: if isinstance(grouping, GroupByBase): grouping = [grouping] grouping = [g.clause() for g in grouping] return QueryDefinition( type=cost_type, timeframe=timeframe, time_period=time_period, dataset=QueryDataset( granularity=granularity, aggregation={"totalCost": QueryAggregation(name="Cost")}, grouping=grouping, filter=filter, ), )