Search in sources :

Example 11 with ResourceMetrics

use of com.vmware.photon.controller.model.monitoring.ResourceMetricsService.ResourceMetrics in project photon-model by vmware.

the class SingleResourceStatsAggregationTaskService method setDefaultMetricValue.

/**
 * Sets metric constants related to a resource to '0' value.
 * Metric constants like 'EstimatedCharges', 'Cost', 'CurrentBurnRatePerHour',
 * 'AverageBurnRatePerHour' stored in 'lastRollupTimeForMetric' map attribute will be
 * set to 0 when project is newly created or has all endpoints removed.
 */
private List<Operation> setDefaultMetricValue(SingleResourceStatsAggregationTaskState currentState, List<Operation> operations, Set<String> publishedKeys) {
    Map<String, Long> lastRollTimeMetric = currentState.lastRollupTimeForMetric;
    for (Entry<String, Long> aggregateEntries : lastRollTimeMetric.entrySet()) {
        // value is null when project is newly created and raw metrics are not yet generated.
        // upon stats aggregation value is set to 0. As project resources don't exist,
        // only newly created projects will have aggregate-metrics services generated .
        Long aggregateMetricLastRollUpTime = aggregateEntries.getValue() == null ? 0L : aggregateEntries.getValue();
        ResourceMetrics resourceMetrics = new ResourceMetrics();
        resourceMetrics.entries = new HashMap<>();
        resourceMetrics.entries.put(aggregateEntries.getKey(), 0.0);
        resourceMetrics.timestampMicrosUtc = aggregateMetricLastRollUpTime;
        resourceMetrics.documentSelfLink = StatsUtil.getMetricKey(currentState.resourceLink, Utils.getNowMicrosUtc());
        operations.add(Operation.createPost(UriUtils.buildUri(ClusterUtil.getClusterUri(getHost(), ServiceTypeCluster.METRIC_SERVICE), ResourceMetricsService.FACTORY_LINK)).setBody(resourceMetrics));
        publishedKeys.add(aggregateEntries.getKey());
        ServiceStats.ServiceStat lastUpdateStat = new ServiceStats.ServiceStat();
        lastUpdateStat.name = aggregateEntries.getKey();
        lastUpdateStat.latestValue = aggregateMetricLastRollUpTime;
        URI inMemoryStatsUri = UriUtils.buildStatsUri(UriUtils.extendUri(ClusterUtil.getClusterUri(getHost(), ServiceTypeCluster.INVENTORY_SERVICE), currentState.resourceLink));
        operations.add(Operation.createPost(inMemoryStatsUri).setBody(lastUpdateStat));
    }
    return operations;
}
Also used : ResourceMetrics(com.vmware.photon.controller.model.monitoring.ResourceMetricsService.ResourceMetrics) ServiceStats(com.vmware.xenon.common.ServiceStats) URI(java.net.URI)

Example 12 with ResourceMetrics

use of com.vmware.photon.controller.model.monitoring.ResourceMetricsService.ResourceMetrics in project photon-model by vmware.

the class AWSCostStatsService method createAccountStats.

protected void createAccountStats(AWSCostStatsCreationContext statsData, LocalDate billMonth, AwsAccountDetailDto awsAccountDetailDto) {
    Consumer<ComputeState> accountStatsProcessor = (accountComputeState) -> {
        ComputeStats accountStats = new ComputeStats();
        accountStats.statValues = new ConcurrentHashMap<>();
        accountStats.computeLink = accountComputeState.documentSelfLink;
        if (isBillUpdated(statsData, awsAccountDetailDto)) {
            logWithContext(statsData, Level.INFO, () -> String.format("Persisting cost of Account: %s (%s) for month: %s", awsAccountDetailDto.id, accountComputeState.documentSelfLink, billMonth));
            ServiceStat costStat = createStat(AWSStatsNormalizer.getNormalizedUnitValue(DIMENSION_CURRENCY_VALUE), AWSStatsNormalizer.getNormalizedStatKeyValue(AWSConstants.COST), awsAccountDetailDto.billProcessedTimeMillis, awsAccountDetailDto.cost);
            accountStats.statValues.put(costStat.name, Collections.singletonList(costStat));
            ServiceStat otherCostsStat = createStat(AWSStatsNormalizer.getNormalizedUnitValue(DIMENSION_CURRENCY_VALUE), AWSConstants.OTHER_CHARGES, awsAccountDetailDto.billProcessedTimeMillis, awsAccountDetailDto.otherCharges);
            accountStats.statValues.put(otherCostsStat.name, Collections.singletonList(otherCostsStat));
            ServiceStat oneTimeChargesStat = createStat(AWSStatsNormalizer.getNormalizedUnitValue(DIMENSION_CURRENCY_VALUE), PhotonModelConstants.ACCOUNT_ONE_TIME_CHARGES, awsAccountDetailDto.billProcessedTimeMillis, awsAccountDetailDto.accountOneTimeCharges);
            accountStats.statValues.put(oneTimeChargesStat.name, Collections.singletonList(oneTimeChargesStat));
        }
        if (!accountStats.statValues.isEmpty()) {
            statsData.statsResponse.statsList.add(accountStats);
        }
    };
    processAccountStats(statsData, billMonth, awsAccountDetailDto, accountStatsProcessor);
    ResourceMetrics prevMarkerMetrics = statsData.accountsMarkersMap.get(awsAccountDetailDto.id);
    if (prevMarkerMetrics != null) {
        prevMarkerMetrics.entries.putAll(transformMapDataTypes(awsAccountDetailDto.lineCountPerInterval));
    }
}
Also used : AuthCredentialsServiceState(com.vmware.xenon.services.common.AuthCredentialsService.AuthCredentialsServiceState) Arrays(java.util.Arrays) DateTimeZone(org.joda.time.DateTimeZone) AWS_ACCOUNT_BILL_PROCESSED_TIME_MILLIS(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.AWS_ACCOUNT_BILL_PROCESSED_TIME_MILLIS) AWSCsvBillParser(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSCsvBillParser) ServiceTypeCluster(com.vmware.photon.controller.model.util.ClusterUtil.ServiceTypeCluster) QueryTask(com.vmware.xenon.services.common.QueryTask) ServiceDocument(com.vmware.xenon.common.ServiceDocument) ComputeType(com.vmware.photon.controller.model.resources.ComputeDescriptionService.ComputeDescription.ComputeType) EndpointAllocationTaskService(com.vmware.photon.controller.model.tasks.EndpointAllocationTaskService) SingleResourceStatsCollectionTaskState(com.vmware.photon.controller.model.tasks.monitoring.SingleResourceStatsCollectionTaskService.SingleResourceStatsCollectionTaskState) ProgressListener(com.amazonaws.event.ProgressListener) STORAGE_TYPE_EBS(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.STORAGE_TYPE_EBS) Utils(com.vmware.xenon.common.Utils) STORAGE_TYPE_S3(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.STORAGE_TYPE_S3) ACCOUNT_IS_AUTO_DISCOVERED(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.ACCOUNT_IS_AUTO_DISCOVERED) Map(java.util.Map) URI(java.net.URI) ProgressEventType(com.amazonaws.event.ProgressEventType) AWSMissingResourcesEnumerationService(com.vmware.photon.controller.model.adapters.awsadapter.enumeration.AWSMissingResourcesEnumerationService) Path(java.nio.file.Path) AWSClientManager(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSClientManager) EndpointState(com.vmware.photon.controller.model.resources.EndpointService.EndpointState) PrintWriter(java.io.PrintWriter) ComputeStatsResponse(com.vmware.photon.controller.model.adapterapi.ComputeStatsResponse) ComputeStatsRequest(com.vmware.photon.controller.model.adapterapi.ComputeStatsRequest) StatelessService(com.vmware.xenon.common.StatelessService) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) TaskManager(com.vmware.photon.controller.model.adapters.util.TaskManager) Set(java.util.Set) DiskState(com.vmware.photon.controller.model.resources.DiskService.DiskState) Occurance(com.vmware.xenon.services.common.QueryTask.Query.Occurance) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) AwsServiceDetailDto(com.vmware.photon.controller.model.adapters.aws.dto.AwsServiceDetailDto) Objects(java.util.Objects) List(java.util.List) AWS_LINKED_ACCOUNT_IDS(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.AWS_LINKED_ACCOUNT_IDS) Stream(java.util.stream.Stream) UriUtils(com.vmware.xenon.common.UriUtils) Entry(java.util.Map.Entry) QueryOption(com.vmware.xenon.services.common.QueryTask.QuerySpecification.QueryOption) AwsServices(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSCsvBillParser.AwsServices) ResourceMetrics(com.vmware.photon.controller.model.monitoring.ResourceMetricsService.ResourceMetrics) SingleResourceTaskCollectionStage(com.vmware.photon.controller.model.tasks.monitoring.SingleResourceStatsCollectionTaskService.SingleResourceTaskCollectionStage) AwsAccountDetailDto(com.vmware.photon.controller.model.adapters.aws.dto.AwsAccountDetailDto) TransferManager(com.amazonaws.services.s3.transfer.TransferManager) QueryByPages(com.vmware.photon.controller.model.query.QueryUtils.QueryByPages) OperationContext(com.vmware.xenon.common.OperationContext) AWS_ACCOUNT_ID_KEY(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.AWS_ACCOUNT_ID_KEY) HashMap(java.util.HashMap) ComputeDescriptionService(com.vmware.photon.controller.model.resources.ComputeDescriptionService) GetObjectRequest(com.amazonaws.services.s3.model.GetObjectRequest) ResourceMetricsService(com.vmware.photon.controller.model.monitoring.ResourceMetricsService) Function(java.util.function.Function) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) ProgressEvent(com.amazonaws.event.ProgressEvent) HashSet(java.util.HashSet) AuthCredentialsService(com.vmware.xenon.services.common.AuthCredentialsService) Query(com.vmware.xenon.services.common.QueryTask.Query) UriPaths(com.vmware.photon.controller.model.UriPaths) CollectionUtils(org.apache.commons.collections.CollectionUtils) ComputeState(com.vmware.photon.controller.model.resources.ComputeService.ComputeState) BiConsumer(java.util.function.BiConsumer) ComputeStats(com.vmware.photon.controller.model.adapterapi.ComputeStatsResponse.ComputeStats) AwsClientType(com.vmware.photon.controller.model.adapters.awsadapter.AWSConstants.AwsClientType) StatsUtil(com.vmware.photon.controller.model.tasks.monitoring.StatsUtil) ExecutorService(java.util.concurrent.ExecutorService) AdapterUtils(com.vmware.photon.controller.model.adapters.util.AdapterUtils) AmazonS3Exception(com.amazonaws.services.s3.model.AmazonS3Exception) ResourceState(com.vmware.photon.controller.model.resources.ResourceState) Files(java.nio.file.Files) StringWriter(java.io.StringWriter) Operation(com.vmware.xenon.common.Operation) QueryUtils(com.vmware.photon.controller.model.query.QueryUtils) IOException(java.io.IOException) ServiceStat(com.vmware.xenon.common.ServiceStats.ServiceStat) AwsResourceDetailDto(com.vmware.photon.controller.model.adapters.aws.dto.AwsResourceDetailDto) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) LocalDate(org.joda.time.LocalDate) ConcurrentSkipListMap(java.util.concurrent.ConcurrentSkipListMap) Paths(java.nio.file.Paths) ClusterUtil(com.vmware.photon.controller.model.util.ClusterUtil) AWSStatsNormalizer(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSStatsNormalizer) ComputeStateWithDescription(com.vmware.photon.controller.model.resources.ComputeService.ComputeStateWithDescription) PhotonModelConstants(com.vmware.photon.controller.model.constants.PhotonModelConstants) AWSClientManagerFactory(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSClientManagerFactory) ServiceDocumentDescription(com.vmware.xenon.common.ServiceDocumentDescription) Collections(java.util.Collections) OperationJoin(com.vmware.xenon.common.OperationJoin) PhotonModelUriUtils.createInventoryUri(com.vmware.photon.controller.model.util.PhotonModelUriUtils.createInventoryUri) ComputeState(com.vmware.photon.controller.model.resources.ComputeService.ComputeState) ServiceStat(com.vmware.xenon.common.ServiceStats.ServiceStat) ResourceMetrics(com.vmware.photon.controller.model.monitoring.ResourceMetricsService.ResourceMetrics) ComputeStats(com.vmware.photon.controller.model.adapterapi.ComputeStatsResponse.ComputeStats) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 13 with ResourceMetrics

use of com.vmware.photon.controller.model.monitoring.ResourceMetricsService.ResourceMetrics in project photon-model by vmware.

the class AWSCostStatsService method createMarkerMetrics.

private void createMarkerMetrics(AWSCostStatsCreationContext context, AwsAccountDetailDto accountDto) {
    List<ComputeState> accountComputeStates = context.awsAccountIdToComputeStates.get(accountDto.id);
    if ((accountComputeStates == null) || accountComputeStates.isEmpty()) {
        logFine(() -> "AWS account with ID '%s' is not configured yet. Not creating marker metrics for the same.");
        return;
    }
    // We use root compute state representing this account to save the account level stats
    Map<String, ComputeState> rootComputesByEndpoint = findRootAccountComputeStateByEndpoint(accountComputeStates);
    URI uri = UriUtils.buildUri(ClusterUtil.getClusterUri(getHost(), ServiceTypeCluster.METRIC_SERVICE), ResourceMetricsService.FACTORY_LINK);
    for (ComputeState compute : rootComputesByEndpoint.values()) {
        ResourceMetrics markerMetrics = new ResourceMetrics();
        markerMetrics.documentSelfLink = StatsUtil.getMetricKey(compute.documentSelfLink, Utils.getNowMicrosUtc());
        markerMetrics.entries = new HashMap<>();
        markerMetrics.entries.putAll(transformMapDataTypes(accountDto.lineCountPerInterval));
        markerMetrics.entries.put(AWS_ACCOUNT_BILL_PROCESSED_TIME_MILLIS, accountDto.billProcessedTimeMillis.doubleValue());
        markerMetrics.timestampMicrosUtc = getCurrentMonthStartTimeMicros();
        markerMetrics.customProperties = new HashMap<>();
        markerMetrics.customProperties.put(ResourceMetrics.PROPERTY_RESOURCE_LINK, compute.documentSelfLink);
        markerMetrics.customProperties.put(PhotonModelConstants.CONTAINS_BILL_PROCESSED_TIME_STAT, Boolean.TRUE.toString());
        markerMetrics.documentExpirationTimeMicros = Utils.getNowMicrosUtc() + TimeUnit.DAYS.toMicros(7);
        sendRequest(Operation.createPost(uri).setBodyNoCloning(markerMetrics));
    }
}
Also used : ComputeState(com.vmware.photon.controller.model.resources.ComputeService.ComputeState) ResourceMetrics(com.vmware.photon.controller.model.monitoring.ResourceMetricsService.ResourceMetrics) URI(java.net.URI)

Example 14 with ResourceMetrics

use of com.vmware.photon.controller.model.monitoring.ResourceMetricsService.ResourceMetrics in project photon-model by vmware.

the class LongRunEndToEndAzureStatsAggregation method checkExpirationTime.

/**
 * Performs check to verify that expiration time for aggregate metric documents for every
 * compute resource has been set to be expired after 56 days.
 */
private void checkExpirationTime(ServiceDocumentQueryResult aggrResult) {
    long expectedExpirationTime = Utils.getNowMicrosUtc() + TimeUnit.DAYS.toMicros(DEFAULT_RETENTION_LIMIT_DAYS);
    for (Object aggrDocument : aggrResult.documents.values()) {
        ResourceMetrics aggrMetric = Utils.fromJson(aggrDocument, ResourceMetrics.class);
        // Make sure all the documents have expiration time set.
        assertTrue("Expiration time is not correctly set.", aggrMetric.documentExpirationTimeMicros < expectedExpirationTime);
    }
}
Also used : AzureTestUtil.getResourceMetrics(com.vmware.photon.controller.model.adapters.azure.instance.AzureTestUtil.getResourceMetrics) ResourceMetrics(com.vmware.photon.controller.model.monitoring.ResourceMetricsService.ResourceMetrics)

Example 15 with ResourceMetrics

use of com.vmware.photon.controller.model.monitoring.ResourceMetricsService.ResourceMetrics in project photon-model by vmware.

the class TestAzureStatsCollection method getResourceMetrics.

/**
 * Query to get ResourceMetrics document for a specific resource containing a specific metric.
 * @param resourceLink Link to the resource on which stats are being collected.
 * @param metricKey Metric name.
 * @return ResourceMetrics document.
 */
private ResourceMetrics getResourceMetrics(String resourceLink, String metricKey) {
    QueryTask qt = QueryTask.Builder.createDirectTask().addOption(QueryOption.EXPAND_CONTENT).addOption(QueryOption.SORT).orderDescending(ServiceDocument.FIELD_NAME_SELF_LINK, ServiceDocumentDescription.TypeName.STRING).setQuery(QueryTask.Query.Builder.create().addKindFieldClause(ResourceMetrics.class).addFieldClause(ServiceDocument.FIELD_NAME_SELF_LINK, UriUtils.buildUriPath(ResourceMetricsService.FACTORY_LINK, UriUtils.getLastPathSegment(resourceLink)), QueryTask.QueryTerm.MatchType.PREFIX).addRangeClause(QueryTask.QuerySpecification.buildCompositeFieldName(ResourceMetrics.FIELD_NAME_ENTRIES, metricKey), QueryTask.NumericRange.createDoubleRange(0.0, Double.MAX_VALUE, true, true)).build()).build();
    Operation op = QueryUtils.createQueryTaskOperation(this.host, qt, ServiceTypeCluster.METRIC_SERVICE).setReferer(this.host.getUri()).setBody(qt).setCompletion((o, e) -> {
        if (e != null) {
            this.host.log(Level.WARNING, e.toString());
        }
    });
    Operation result = this.host.waitForResponse(op);
    QueryTask qtResult = result.getBody(QueryTask.class);
    ResourceMetrics resourceMetric = null;
    if (qtResult.results.documentLinks.size() > 0) {
        String documentLink = qtResult.results.documentLinks.get(0);
        resourceMetric = Utils.fromJson(qtResult.results.documents.get(documentLink), ResourceMetrics.class);
    }
    return resourceMetric;
}
Also used : ResourceMetrics(com.vmware.photon.controller.model.monitoring.ResourceMetricsService.ResourceMetrics) QueryTask(com.vmware.xenon.services.common.QueryTask) Operation(com.vmware.xenon.common.Operation)

Aggregations

ResourceMetrics (com.vmware.photon.controller.model.monitoring.ResourceMetricsService.ResourceMetrics)31 QueryTask (com.vmware.xenon.services.common.QueryTask)19 ArrayList (java.util.ArrayList)12 Operation (com.vmware.xenon.common.Operation)10 Query (com.vmware.xenon.services.common.QueryTask.Query)9 HashMap (java.util.HashMap)9 Map (java.util.Map)9 ComputeState (com.vmware.photon.controller.model.resources.ComputeService.ComputeState)7 ServiceStat (com.vmware.xenon.common.ServiceStats.ServiceStat)7 URI (java.net.URI)7 ServiceStats (com.vmware.xenon.common.ServiceStats)6 ResourceMetricsService (com.vmware.photon.controller.model.monitoring.ResourceMetricsService)5 SingleResourceStatsCollectionTaskState (com.vmware.photon.controller.model.tasks.monitoring.SingleResourceStatsCollectionTaskService.SingleResourceStatsCollectionTaskState)5 ServiceDocument (com.vmware.xenon.common.ServiceDocument)5 UriUtils (com.vmware.xenon.common.UriUtils)5 UriPaths (com.vmware.photon.controller.model.UriPaths)4 ComputeStats (com.vmware.photon.controller.model.adapterapi.ComputeStatsResponse.ComputeStats)4 List (java.util.List)4 ComputeStatsRequest (com.vmware.photon.controller.model.adapterapi.ComputeStatsRequest)3 AwsServices (com.vmware.photon.controller.model.adapters.awsadapter.util.AWSCsvBillParser.AwsServices)3