Search in sources :

Example 11 with QueryTask

use of com.vmware.xenon.services.common.QueryTask in project photon-model by vmware.

the class AWSEndpointAdapterService method checkIfAccountExistsAndGetExistingDocuments.

private void checkIfAccountExistsAndGetExistingDocuments(EndpointConfigRequest req, Operation op) {
    if (req.isMockRequest) {
        req.accountAlreadyExists = false;
        op.setBody(req);
        op.complete();
        return;
    }
    String accountId = getAccountId(req.endpointProperties.get(ARN_KEY), req.endpointProperties.get(EndpointConfigRequest.PRIVATE_KEYID_KEY), req.endpointProperties.get(EndpointConfigRequest.PRIVATE_KEY_KEY));
    if (accountId != null && !accountId.isEmpty()) {
        QueryTask queryTask = QueryUtils.createAccountQuery(accountId, PhotonModelConstants.EndpointType.aws.name(), req.tenantLinks);
        queryTask.tenantLinks = req.tenantLinks;
        QueryUtils.startInventoryQueryTask(this, queryTask).whenComplete((qrt, e) -> {
            if (e != null) {
                logSevere(() -> String.format("Failure retrieving query results for compute host corresponding to" + "the account ID: %s", e.toString()));
                op.fail(e);
                return;
            }
            if (qrt.results.documentCount > 0) {
                req.accountAlreadyExists = true;
                Object state = qrt.results.documents.values().iterator().next();
                ComputeState computeHost = Utils.fromJson(state, ComputeState.class);
                req.existingComputeState = computeHost;
                getComputeDescription(req, computeHost.descriptionLink, op);
            } else {
                req.accountAlreadyExists = false;
                op.setBody(req);
                op.complete();
                return;
            }
        });
    } else {
        // If the account Id cannot be looked up with the given set of credentials then de duplication is not possible.
        req.accountAlreadyExists = false;
        op.setBody(req);
        op.complete();
    }
}
Also used : ComputeState(com.vmware.photon.controller.model.resources.ComputeService.ComputeState) QueryTask(com.vmware.xenon.services.common.QueryTask)

Example 12 with QueryTask

use of com.vmware.xenon.services.common.QueryTask in project photon-model by vmware.

the class AzureComputeEnumerationAdapterService method disassociateComputeStates.

/**
 * Deletes undiscovered resources.
 * <p>
 * The logic works by recording a timestamp when enumeration starts. This timestamp is used to
 * lookup resources which haven't been touched as part of current enumeration cycle. The other
 * data point this method uses is the virtual machines discovered as part of list vm call.
 * <p>
 * Finally, delete on a resource is invoked only if it meets two criteria: - Timestamp older
 * than current enumeration cycle. - VM not present on Azure.
 * <p>
 * The method paginates through list of resources for deletion.
 */
private void disassociateComputeStates(EnumerationContext ctx, ComputeEnumerationSubStages next) {
    Query.Builder qBuilder = Builder.create().addKindFieldClause(ComputeState.class).addFieldClause(ComputeState.FIELD_NAME_PARENT_LINK, ctx.request.resourceLink()).addRangeClause(ComputeState.FIELD_NAME_UPDATE_TIME_MICROS, NumericRange.createLessThanRange(ctx.enumerationStartTimeInMicros)).addInClause(ComputeState.FIELD_NAME_LIFECYCLE_STATE, Arrays.asList(LifecycleState.PROVISIONING.toString(), LifecycleState.RETIRED.toString()), Occurance.MUST_NOT_OCCUR);
    addScopeCriteria(qBuilder, ComputeState.class, ctx);
    QueryTask q = QueryTask.Builder.createDirectTask().addOption(QueryOption.EXPAND_CONTENT).setQuery(qBuilder.build()).setResultLimit(getQueryResultLimit()).build();
    q.tenantLinks = ctx.parentCompute.tenantLinks;
    logFine(() -> "Querying compute resources for deletion");
    QueryUtils.startInventoryQueryTask(this, q).whenComplete((queryTask, e) -> {
        if (e != null) {
            handleError(ctx, e);
            return;
        }
        if (queryTask.results.nextPageLink == null) {
            logFine(() -> "No compute states match for deletion");
            ctx.subStage = next;
            handleSubStage(ctx);
            return;
        }
        ctx.deletionNextPageLink = queryTask.results.nextPageLink;
        disassociateOrRetireHelper(ctx, next);
    });
}
Also used : ComputeState(com.vmware.photon.controller.model.resources.ComputeService.ComputeState) QueryTask(com.vmware.xenon.services.common.QueryTask) Query(com.vmware.xenon.services.common.QueryTask.Query) Builder(com.vmware.xenon.services.common.QueryTask.Query.Builder)

Example 13 with QueryTask

use of com.vmware.xenon.services.common.QueryTask in project photon-model by vmware.

the class AzureComputeEnumerationAdapterService method disassociateOrRetireHelper.

/**
 * Helper method to paginate through resources to be deleted.
 */
private void disassociateOrRetireHelper(EnumerationContext ctx, ComputeEnumerationSubStages next) {
    if (ctx.deletionNextPageLink == null) {
        logFine(() -> String.format("Finished %s of compute states for Azure", ctx.request.preserveMissing ? "retiring" : "deletion"));
        ctx.subStage = next;
        handleSubStage(ctx);
        return;
    }
    CompletionHandler completionHandler = (o, e) -> {
        if (e != null) {
            handleError(ctx, e);
            return;
        }
        QueryTask queryTask = o.getBody(QueryTask.class);
        ctx.deletionNextPageLink = queryTask.results.nextPageLink;
        List<Operation> operations = new ArrayList<>();
        for (Object s : queryTask.results.documents.values()) {
            ComputeState computeState = Utils.fromJson(s, ComputeState.class);
            String vmId = computeState.id;
            // present in Azure but have older timestamp in local repository.
            if (ctx.vmIds.contains(vmId) || ctx.regionIds.contains(vmId)) {
                continue;
            }
            if (ctx.request.preserveMissing) {
                logFine(() -> String.format("Retiring compute state %s", computeState.documentSelfLink));
                ComputeState cs = new ComputeState();
                cs.powerState = PowerState.OFF;
                cs.lifecycleState = LifecycleState.RETIRED;
                operations.add(Operation.createPatch(this, computeState.documentSelfLink).setBody(cs));
            } else {
                // Deleting the localResourceState is done by disassociating the endpointLink from the
                // localResourceState. If the localResourceState isn't associated with any other
                // endpointLink, we issue a delete then
                Operation dOp = PhotonModelUtils.createRemoveEndpointLinksOperation(this, ctx.request.endpointLink, computeState);
                if (dOp != null) {
                    dOp.sendWith(getHost());
                    logFine(() -> String.format("Deleting compute state %s", computeState.documentSelfLink));
                }
                if (computeState.diskLinks != null && !computeState.diskLinks.isEmpty()) {
                    computeState.diskLinks.forEach(dl -> {
                        sendRequest(Operation.createGet(this, dl).setCompletion((op, ex) -> {
                            if (ex != null) {
                                logWarning(() -> String.format("Error retrieving " + "diskState: %s", ex.getMessage()));
                            } else {
                                DiskState diskState = op.getBody(DiskState.class);
                                Operation diskOp = PhotonModelUtils.createRemoveEndpointLinksOperation(this, ctx.request.endpointLink, diskState);
                                if (diskOp != null) {
                                    diskOp.sendWith(getHost());
                                    logFine(() -> String.format("Deleting disk state %s of machine %s", dl, computeState.documentSelfLink));
                                }
                            }
                        }));
                    });
                }
                if (computeState.networkInterfaceLinks != null && !computeState.networkInterfaceLinks.isEmpty()) {
                    computeState.networkInterfaceLinks.forEach(nil -> {
                        sendRequest(Operation.createGet(this, nil).setCompletion((op, ex) -> {
                            if (ex != null) {
                                logWarning(() -> String.format("Error retrieving NetworkInterface state: %s", ex.getMessage()));
                            } else {
                                NetworkInterfaceState networkInterfaceState = op.getBody(NetworkInterfaceState.class);
                                Operation nicOp = PhotonModelUtils.createRemoveEndpointLinksOperation(this, ctx.request.endpointLink, networkInterfaceState);
                                if (nicOp != null) {
                                    nicOp.sendWith(getHost());
                                    logFine(() -> String.format("Deleting NetworkInterface state %s of machine %s", nil, computeState.documentSelfLink));
                                }
                            }
                        }));
                    });
                }
            }
        }
        if (operations.size() == 0) {
            logFine(() -> String.format("No compute/disk states to %s", ctx.request.preserveMissing ? "retire" : "delete"));
            disassociateOrRetireHelper(ctx, next);
            return;
        }
        OperationJoin.create(operations).setCompletion((ops, exs) -> {
            if (exs != null) {
                // We don't want to fail the whole data collection if some of the
                // operation fails.
                exs.values().forEach(ex -> logWarning(() -> String.format("Error: %s", ex.getMessage())));
            }
            disassociateOrRetireHelper(ctx, next);
        }).sendWith(this);
    };
    logFine(() -> String.format("Querying page [%s] for resources to be %s", ctx.deletionNextPageLink, ctx.request.preserveMissing ? "retire" : "delete"));
    sendRequest(Operation.createGet(createInventoryUri(this.getHost(), ctx.deletionNextPageLink)).setCompletion(completionHandler));
}
Also used : PowerState(com.vmware.photon.controller.model.resources.ComputeService.PowerState) Arrays(java.util.Arrays) ComputeEnumerateResourceRequest(com.vmware.photon.controller.model.adapterapi.ComputeEnumerateResourceRequest) ServiceTypeCluster(com.vmware.photon.controller.model.util.ClusterUtil.ServiceTypeCluster) LifecycleState(com.vmware.photon.controller.model.resources.ComputeService.LifecycleState) DISK_CONTROLLER_NUMBER(com.vmware.photon.controller.model.adapters.azure.constants.AzureConstants.DISK_CONTROLLER_NUMBER) Action1(rx.functions.Action1) StringUtils(org.apache.commons.lang3.StringUtils) Azure(com.microsoft.azure.management.Azure) Utils(com.vmware.xenon.common.Utils) Pair(org.apache.commons.lang3.tuple.Pair) SubnetState(com.vmware.photon.controller.model.resources.SubnetService.SubnetState) Map(java.util.Map) StorageDescription(com.vmware.photon.controller.model.resources.StorageDescriptionService.StorageDescription) OSDisk(com.microsoft.azure.management.compute.OSDisk) ResourceEnumerationTaskService(com.vmware.photon.controller.model.tasks.ResourceEnumerationTaskService) NetworkInterfaceState(com.vmware.photon.controller.model.resources.NetworkInterfaceService.NetworkInterfaceState) StatelessService(com.vmware.xenon.common.StatelessService) Set(java.util.Set) NetworkInterfaceService(com.vmware.photon.controller.model.resources.NetworkInterfaceService) StorageAccountTypes(com.microsoft.azure.management.compute.StorageAccountTypes) TagService(com.vmware.photon.controller.model.resources.TagService) CompletionHandler(com.vmware.xenon.common.Operation.CompletionHandler) SOURCE_TASK_LINK(com.vmware.photon.controller.model.constants.PhotonModelConstants.SOURCE_TASK_LINK) InstanceViewStatus(com.microsoft.azure.management.compute.InstanceViewStatus) DeferredResult(com.vmware.xenon.common.DeferredResult) UriUtils(com.vmware.xenon.common.UriUtils) ComputeService(com.vmware.photon.controller.model.resources.ComputeService) NumericRange(com.vmware.xenon.services.common.QueryTask.NumericRange) AZURE_DATA_DISK_CACHING(com.vmware.photon.controller.model.adapters.azure.constants.AzureConstants.AZURE_DATA_DISK_CACHING) ImageReferenceInner(com.microsoft.azure.management.compute.implementation.ImageReferenceInner) VirtualMachinesInner(com.microsoft.azure.management.compute.implementation.VirtualMachinesInner) ComputeDescriptionService(com.vmware.photon.controller.model.resources.ComputeDescriptionService) PhotonModelUtils(com.vmware.photon.controller.model.resources.util.PhotonModelUtils) RegionInfo(com.vmware.photon.controller.model.adapterapi.RegionEnumerationResponse.RegionInfo) TagsUtil(com.vmware.photon.controller.model.adapters.util.TagsUtil) ArrayList(java.util.ArrayList) TagState(com.vmware.photon.controller.model.resources.TagService.TagState) ServiceStateCollectionUpdateRequest(com.vmware.xenon.common.ServiceStateCollectionUpdateRequest) Query(com.vmware.xenon.services.common.QueryTask.Query) EnumerationStages(com.vmware.photon.controller.model.adapters.util.enums.EnumerationStages) OperatingSystemTypes(com.microsoft.azure.management.compute.OperatingSystemTypes) BiConsumer(java.util.function.BiConsumer) AZURE_DIAGNOSTIC_STORAGE_ACCOUNT_LINK(com.vmware.photon.controller.model.adapters.azure.constants.AzureConstants.AZURE_DIAGNOSTIC_STORAGE_ACCOUNT_LINK) AZURE_STORAGE_ACCOUNT_URI(com.vmware.photon.controller.model.adapters.azure.constants.AzureConstants.AZURE_STORAGE_ACCOUNT_URI) VirtualMachineInner(com.microsoft.azure.management.compute.implementation.VirtualMachineInner) AdapterUtils(com.vmware.photon.controller.model.adapters.util.AdapterUtils) DataDisk(com.microsoft.azure.management.compute.DataDisk) ResourceState(com.vmware.photon.controller.model.resources.ResourceState) QueryUtils(com.vmware.photon.controller.model.query.QueryUtils) ENVIRONMENT_NAME_AZURE(com.vmware.photon.controller.model.resources.ComputeDescriptionService.ComputeDescription.ENVIRONMENT_NAME_AZURE) QueryTop(com.vmware.photon.controller.model.query.QueryUtils.QueryTop) CUSTOM_OS_TYPE(com.vmware.photon.controller.model.ComputeProperties.CUSTOM_OS_TYPE) ComputeStateWithDescription(com.vmware.photon.controller.model.resources.ComputeService.ComputeStateWithDescription) PhotonModelConstants(com.vmware.photon.controller.model.constants.PhotonModelConstants) ComputeEnumerateAdapterRequest(com.vmware.photon.controller.model.adapters.util.ComputeEnumerateAdapterRequest) RegionEnumerationResponse(com.vmware.photon.controller.model.adapterapi.RegionEnumerationResponse) QuerySpecification(com.vmware.xenon.services.common.QueryTask.QuerySpecification) PhotonModelUriUtils.createInventoryUri(com.vmware.photon.controller.model.util.PhotonModelUriUtils.createInventoryUri) AuthCredentialsServiceState(com.vmware.xenon.services.common.AuthCredentialsService.AuthCredentialsServiceState) QueryTask(com.vmware.xenon.services.common.QueryTask) AZURE_RESOURCE_GROUP_NAME(com.vmware.photon.controller.model.adapters.azure.constants.AzureConstants.AZURE_RESOURCE_GROUP_NAME) OSType(com.vmware.photon.controller.model.ComputeProperties.OSType) AzureUriPaths(com.vmware.photon.controller.model.adapters.azure.AzureUriPaths) AZURE_MANAGED_DISK_TYPE(com.vmware.photon.controller.model.adapters.azure.constants.AzureConstants.AZURE_MANAGED_DISK_TYPE) ComputeType(com.vmware.photon.controller.model.resources.ComputeDescriptionService.ComputeDescription.ComputeType) AzureSdkClients(com.vmware.photon.controller.model.adapters.azure.utils.AzureSdkClients) AzureUtils.injectOperationContext(com.vmware.photon.controller.model.adapters.azure.utils.AzureUtils.injectOperationContext) CUSTOM_PROP_ENDPOINT_LINK(com.vmware.photon.controller.model.constants.PhotonModelConstants.CUSTOM_PROP_ENDPOINT_LINK) URI(java.net.URI) TagsUtil.newTagState(com.vmware.photon.controller.model.adapters.util.TagsUtil.newTagState) EndpointState(com.vmware.photon.controller.model.resources.EndpointService.EndpointState) AzureConstants(com.vmware.photon.controller.model.adapters.azure.constants.AzureConstants) AzureConstants.getQueryResultLimit(com.vmware.photon.controller.model.adapters.azure.constants.AzureConstants.getQueryResultLimit) ComputeDescription(com.vmware.photon.controller.model.resources.ComputeDescriptionService.ComputeDescription) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) 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) List(java.util.List) AzureUtils(com.vmware.photon.controller.model.adapters.azure.utils.AzureUtils) AzureUtils.getResourceGroupName(com.vmware.photon.controller.model.adapters.azure.utils.AzureUtils.getResourceGroupName) TAG_KEY_TYPE(com.vmware.photon.controller.model.constants.PhotonModelConstants.TAG_KEY_TYPE) Entry(java.util.Map.Entry) NetworkInterfacesInner(com.microsoft.azure.management.network.implementation.NetworkInterfacesInner) QueryOption(com.vmware.xenon.services.common.QueryTask.QuerySpecification.QueryOption) InstanceViewTypes(com.microsoft.azure.management.compute.InstanceViewTypes) TagsUtil.setTagLinksToResourceState(com.vmware.photon.controller.model.adapters.util.TagsUtil.setTagLinksToResourceState) Builder(com.vmware.xenon.services.common.QueryTask.Query.Builder) DiskService(com.vmware.photon.controller.model.resources.DiskService) AzureUtils.isDiskManaged(com.vmware.photon.controller.model.adapters.azure.utils.AzureUtils.isDiskManaged) Default(com.vmware.photon.controller.model.adapters.azure.utils.AzureDeferredResultServiceCallback.Default) QueryByPages(com.vmware.photon.controller.model.query.QueryUtils.QueryByPages) AZURE_OSDISK_CACHING(com.vmware.photon.controller.model.adapters.azure.constants.AzureConstants.AZURE_OSDISK_CACHING) PublicIPAddress(com.microsoft.azure.management.network.PublicIPAddress) HashMap(java.util.HashMap) HashSet(java.util.HashSet) AuthCredentialsService(com.vmware.xenon.services.common.AuthCredentialsService) TagsUtil.updateLocalTagStates(com.vmware.photon.controller.model.adapters.util.TagsUtil.updateLocalTagStates) ComputeState(com.vmware.photon.controller.model.resources.ComputeService.ComputeState) EnumerationAction(com.vmware.photon.controller.model.adapterapi.EnumerationAction) AzureResourceType(com.vmware.photon.controller.model.adapters.azure.constants.AzureConstants.AzureResourceType) ExecutorService(java.util.concurrent.ExecutorService) Iterator(java.util.Iterator) NetworkInterfaceIPConfigurationInner(com.microsoft.azure.management.network.implementation.NetworkInterfaceIPConfigurationInner) Operation(com.vmware.xenon.common.Operation) Page(com.microsoft.azure.Page) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) NetworkInterfaceReferenceInner(com.microsoft.azure.management.compute.implementation.NetworkInterfaceReferenceInner) AzureDeferredResultServiceCallback(com.vmware.photon.controller.model.adapters.azure.utils.AzureDeferredResultServiceCallback) NetworkInterfaceInner(com.microsoft.azure.management.network.implementation.NetworkInterfaceInner) Collections(java.util.Collections) OperationJoin(com.vmware.xenon.common.OperationJoin) RESOURCE_GROUP_NAME(com.vmware.photon.controller.model.ComputeProperties.RESOURCE_GROUP_NAME) ComputeState(com.vmware.photon.controller.model.resources.ComputeService.ComputeState) QueryTask(com.vmware.xenon.services.common.QueryTask) NetworkInterfaceState(com.vmware.photon.controller.model.resources.NetworkInterfaceService.NetworkInterfaceState) DiskState(com.vmware.photon.controller.model.resources.DiskService.DiskState) CompletionHandler(com.vmware.xenon.common.Operation.CompletionHandler) ArrayList(java.util.ArrayList) List(java.util.List) Operation(com.vmware.xenon.common.Operation)

Example 14 with QueryTask

use of com.vmware.xenon.services.common.QueryTask in project photon-model by vmware.

the class AzureComputeHostStatsGatherer method handleComputeQueryCompletion.

/**
 * Get all the children computes and create a query task for each to query the metrics.
 */
private void handleComputeQueryCompletion(QueryTask queryTask, Throwable failure, AzureStatsDataHolder statsData) {
    if (failure != null) {
        logSevere(failure.getMessage());
        statsData.error = failure;
        statsData.stage = ComputeHostMetricsStages.ERROR;
        handleMetricDiscovery(statsData);
        return;
    }
    if (queryTask == null || queryTask.results == null) {
        sendFailurePatch(statsData, new RuntimeException(String.format("Unexpected query result for '%s'", queryTask.documentSelfLink)));
        return;
    }
    if (queryTask.results.documentLinks != null) {
        statsData.childComputeLinks.addAll(queryTask.results.documentLinks);
    }
    if (queryTask.results.nextPageLink != null) {
        Operation op = Operation.createGet(createInventoryUri(this.getHost(), queryTask.results.nextPageLink));
        sendWithDeferredResult(op).whenComplete((o, e) -> handleComputeQueryCompletion(o.getBody(QueryTask.class), e, statsData));
        return;
    }
    int computeCount = Math.toIntExact(statsData.childComputeLinks.size());
    // No children found, proceed to finish
    if (computeCount <= 0) {
        statsData.stage = ComputeHostMetricsStages.FINISHED;
        handleMetricDiscovery(statsData);
        return;
    }
    // Create multiple operations, one each for a VM compute.
    List<Operation> statOperations = new ArrayList<>(computeCount);
    for (String computeLink : statsData.childComputeLinks) {
        Operation statsOp = getStatsQueryTaskOperation(statsData, computeLink);
        statOperations.add(statsOp);
    }
    OperationJoin.create(statOperations).setCompletion((ops, failures) -> handleQueryTaskResponseAndConsolidateStats(ops, failures, statsData)).sendWith(this, 50);
}
Also used : ServiceTypeCluster(com.vmware.photon.controller.model.util.ClusterUtil.ServiceTypeCluster) QueryTask(com.vmware.xenon.services.common.QueryTask) ServiceDocument(com.vmware.xenon.common.ServiceDocument) HashMap(java.util.HashMap) AzureUriPaths(com.vmware.photon.controller.model.adapters.azure.AzureUriPaths) ResourceMetricsService(com.vmware.photon.controller.model.monitoring.ResourceMetricsService) MatchType(com.vmware.xenon.services.common.QueryTask.QueryTerm.MatchType) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Utils(com.vmware.xenon.common.Utils) Query(com.vmware.xenon.services.common.QueryTask.Query) ComputeState(com.vmware.photon.controller.model.resources.ComputeService.ComputeState) Map(java.util.Map) URI(java.net.URI) ComputeStats(com.vmware.photon.controller.model.adapterapi.ComputeStatsResponse.ComputeStats) ExecutorService(java.util.concurrent.ExecutorService) AdapterUtils(com.vmware.photon.controller.model.adapters.util.AdapterUtils) AzureConstants.getQueryResultLimit(com.vmware.photon.controller.model.adapters.azure.constants.AzureConstants.getQueryResultLimit) ComputeStatsResponse(com.vmware.photon.controller.model.adapterapi.ComputeStatsResponse) ComputeStatsRequest(com.vmware.photon.controller.model.adapterapi.ComputeStatsRequest) StatelessService(com.vmware.xenon.common.StatelessService) Operation(com.vmware.xenon.common.Operation) QueryUtils(com.vmware.photon.controller.model.query.QueryUtils) Set(java.util.Set) ServiceStat(com.vmware.xenon.common.ServiceStats.ServiceStat) Consumer(java.util.function.Consumer) List(java.util.List) ConcurrentSkipListMap(java.util.concurrent.ConcurrentSkipListMap) UriUtils(com.vmware.xenon.common.UriUtils) PhotonModelConstants(com.vmware.photon.controller.model.constants.PhotonModelConstants) ComputeService(com.vmware.photon.controller.model.resources.ComputeService) QueryOption(com.vmware.xenon.services.common.QueryTask.QuerySpecification.QueryOption) Collections(java.util.Collections) OperationJoin(com.vmware.xenon.common.OperationJoin) PhotonModelUriUtils.createInventoryUri(com.vmware.photon.controller.model.util.PhotonModelUriUtils.createInventoryUri) ResourceMetrics(com.vmware.photon.controller.model.monitoring.ResourceMetricsService.ResourceMetrics) ArrayList(java.util.ArrayList) Operation(com.vmware.xenon.common.Operation)

Example 15 with QueryTask

use of com.vmware.xenon.services.common.QueryTask in project photon-model by vmware.

the class AzureComputeHostStatsGatherer method aggregateComputeStatsResponses.

/**
 * Aggregates stats from all the compute VMs to make up compute Host stats.
 */
private ComputeStats aggregateComputeStatsResponses(AzureStatsDataHolder statsData, List<QueryTask> items) {
    int numberOfComputeResponse = items.size();
    ComputeStats computeStats = new ComputeStats();
    computeStats.computeLink = statsData.computeHost.documentSelfLink;
    Map<String, ServiceStat> statMap = new HashMap<>();
    // Gather all the stats in a single response.
    for (QueryTask queryResult : items) {
        if (queryResult.results.documents != null) {
            for (String key : queryResult.results.documents.keySet()) {
                ResourceMetrics metric = Utils.fromJson(queryResult.results.documents.get(key), ResourceMetrics.class);
                for (Map.Entry<String, Double> entry : metric.entries.entrySet()) {
                    String metricName = entry.getKey();
                    if (statMap.containsKey(metricName)) {
                        statMap.get(metricName).latestValue += entry.getValue();
                    } else {
                        ServiceStat stat = new ServiceStat();
                        stat.latestValue = entry.getValue();
                        statMap.put(metricName, stat);
                    }
                }
            }
        }
    }
    computeStats.statValues = new ConcurrentSkipListMap<>();
    // Divide each metric value by the number of computes to get an average value.
    for (String key : statMap.keySet()) {
        ServiceStat serviceStatValue = statMap.get(key);
        serviceStatValue.unit = PhotonModelConstants.getUnitForMetric(key);
        serviceStatValue.sourceTimeMicrosUtc = Utils.getNowMicrosUtc();
        serviceStatValue.latestValue = serviceStatValue.latestValue / numberOfComputeResponse;
        computeStats.statValues.put(key, Collections.singletonList(serviceStatValue));
    }
    return computeStats;
}
Also used : ServiceStat(com.vmware.xenon.common.ServiceStats.ServiceStat) ResourceMetrics(com.vmware.photon.controller.model.monitoring.ResourceMetricsService.ResourceMetrics) QueryTask(com.vmware.xenon.services.common.QueryTask) ComputeStats(com.vmware.photon.controller.model.adapterapi.ComputeStatsResponse.ComputeStats) HashMap(java.util.HashMap) HashMap(java.util.HashMap) Map(java.util.Map) ConcurrentSkipListMap(java.util.concurrent.ConcurrentSkipListMap)

Aggregations

QueryTask (com.vmware.xenon.services.common.QueryTask)147 Query (com.vmware.xenon.services.common.QueryTask.Query)62 Operation (com.vmware.xenon.common.Operation)61 ComputeState (com.vmware.photon.controller.model.resources.ComputeService.ComputeState)39 ArrayList (java.util.ArrayList)26 QueryUtils (com.vmware.photon.controller.model.query.QueryUtils)20 List (java.util.List)20 ResourceMetrics (com.vmware.photon.controller.model.monitoring.ResourceMetricsService.ResourceMetrics)19 UriUtils (com.vmware.xenon.common.UriUtils)18 Utils (com.vmware.xenon.common.Utils)17 HashSet (java.util.HashSet)16 HashMap (java.util.HashMap)14 QueryOption (com.vmware.xenon.services.common.QueryTask.QuerySpecification.QueryOption)12 TimeUnit (java.util.concurrent.TimeUnit)12 ComputeEnumerateResourceRequest (com.vmware.photon.controller.model.adapterapi.ComputeEnumerateResourceRequest)11 AdapterUtils (com.vmware.photon.controller.model.adapters.util.AdapterUtils)11 ComputeDescription (com.vmware.photon.controller.model.resources.ComputeDescriptionService.ComputeDescription)11 ServiceTypeCluster (com.vmware.photon.controller.model.util.ClusterUtil.ServiceTypeCluster)11 URI (java.net.URI)11 Set (java.util.Set)11