Search in sources :

Example 6 with QueryTask

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

the class AWSComputeStateCreationAdapterService method collectEbsDiskLinks.

/**
 * Collect EBS selfLinks by querying for all EBS disk IDs. Map these selfLinks to
 * their respective instances. These will be used for reconciliation with local state while
 * creating/updating compute state's diskLinks.
 */
private void collectEbsDiskLinks(AWSComputeStateCreationContext context, AWSComputeStateCreationStage next) {
    List<String> diskIds = new ArrayList<>();
    Map<String, Instance> instancesByDiskIds = new HashMap<>();
    context.request.instancesToBeCreated.stream().forEach(instance -> {
        instance.getBlockDeviceMappings().stream().forEach(instanceBlockDeviceMapping -> {
            String id = instanceBlockDeviceMapping.getEbs().getVolumeId();
            instancesByDiskIds.put(id, instance);
            diskIds.add(id);
        });
    });
    context.request.instancesToBeUpdated.values().stream().forEach(instance -> {
        instance.getBlockDeviceMappings().stream().forEach(instanceBlockDeviceMapping -> {
            String id = instanceBlockDeviceMapping.getEbs().getVolumeId();
            instancesByDiskIds.put(id, instance);
            diskIds.add(id);
        });
    });
    // No disks found for current page of instances.
    if (diskIds.isEmpty()) {
        context.creationStage = next;
        handleComputeStateCreateOrUpdate(context);
        return;
    }
    Query ebsQuery = Query.Builder.create().addKindFieldClause(DiskState.class).addCollectionItemClause(ResourceState.FIELD_NAME_ENDPOINT_LINKS, context.request.endpointLink).addInClause(DiskState.FIELD_NAME_ID, diskIds).build();
    QueryTask ebsQueryTask = QueryTask.Builder.createDirectTask().setQuery(ebsQuery).addOption(QueryOption.EXPAND_CONTENT).build();
    ebsQueryTask.tenantLinks = context.request.tenantLinks;
    QueryUtils.startInventoryQueryTask(this, ebsQueryTask).whenComplete((qrt, e) -> {
        if (e != null) {
            logWarning("Error querying diskLinks for endpoint %s", context.request.endpointLink);
            context.creationStage = next;
            handleComputeStateCreateOrUpdate(context);
            return;
        }
        if (qrt.results != null && qrt.results.documentCount > 0) {
            qrt.results.documents.entrySet().forEach(entry -> {
                DiskState state = Utils.fromJson(entry.getValue(), DiskState.class);
                Instance instance = instancesByDiskIds.get(state.id);
                if (instance != null) {
                    if (context.diskLinksByInstances.containsKey(instance)) {
                        context.diskLinksByInstances.get(instance).add(entry.getKey());
                    } else {
                        context.diskLinksByInstances.put(instance, new ArrayList<>(Arrays.asList(entry.getKey())));
                    }
                }
            });
        }
        context.creationStage = next;
        handleComputeStateCreateOrUpdate(context);
    });
}
Also used : QueryTask(com.vmware.xenon.services.common.QueryTask) Query(com.vmware.xenon.services.common.QueryTask.Query) AWSEnumerationUtils.getCDsRepresentingVMsInLocalSystemCreatedByEnumerationQuery(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSEnumerationUtils.getCDsRepresentingVMsInLocalSystemCreatedByEnumerationQuery) Instance(com.amazonaws.services.ec2.model.Instance) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) DiskState(com.vmware.photon.controller.model.resources.DiskService.DiskState) ArrayList(java.util.ArrayList)

Example 7 with QueryTask

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

the class AWSEnumerationAndDeletionAdapterService method getLocalResources.

/**
 * Get the list of compute states already known to the local system. Filter them by parent
 * compute link : AWS.
 */
public void getLocalResources(EnumerationDeletionContext context, AWSEnumerationDeletionSubStage next) {
    // query all ComputeState resources known to the local system.
    logFine(() -> "Getting local resources that need to be reconciled with the AWS endpoint.");
    Query.Builder qBuilder = Query.Builder.create().addKindFieldClause(ComputeState.class).addFieldClause(ComputeState.FIELD_NAME_PARENT_LINK, context.request.original.resourceLink()).addInClause(ComputeState.FIELD_NAME_LIFECYCLE_STATE, Arrays.asList(LifecycleState.PROVISIONING.toString(), LifecycleState.RETIRED.toString()), Occurance.MUST_NOT_OCCUR);
    addScopeCriteria(qBuilder, context);
    QueryTask queryTask = QueryTask.Builder.createDirectTask().setQuery(qBuilder.build()).addOption(QueryOption.EXPAND_CONTENT).setResultLimit(getQueryResultLimit()).build();
    queryTask.tenantLinks = context.parentCompute.tenantLinks;
    // create the query to find resources
    QueryUtils.startInventoryQueryTask(this, queryTask).whenComplete((qrt, e) -> {
        if (e != null) {
            logSevere(() -> String.format("Failure retrieving query results: %s", e.toString()));
            signalErrorToEnumerationAdapter(context, e);
            return;
        }
        populateLocalInstanceInformationFromQueryResults(context, qrt);
        logFine(() -> String.format("Got page No. %d of local resources. %d instances" + " found.", context.pageNo, qrt.results.documentCount));
        context.subStage = next;
        deleteResourcesInLocalSystem(context);
    });
}
Also used : QueryTask(com.vmware.xenon.services.common.QueryTask) Query(com.vmware.xenon.services.common.QueryTask.Query)

Example 8 with QueryTask

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

the class TestAWSEnumerationDocumentCountInLongRun method storeDocumentLinksFromNetworkInterfaceStates.

/**
 * Gets and stores network interface ids from network interface links and security group links, subnet
 * links by querying network interface ids.
 */
private void storeDocumentLinksFromNetworkInterfaceStates() {
    // If there are no network interface links, return.
    if (this.networkInterfaceLinks.isEmpty()) {
        return;
    }
    // Get network interface IDs from network interface links.
    for (String s : this.networkInterfaceLinks) {
        Operation op = Operation.createGet(UriUtils.buildUri(this.host.getUri(), s)).setReferer(this.host.getUri());
        Operation response = this.host.waitForResponse(op);
        Assert.assertTrue("Error retrieving network interface IDs", response.getStatusCode() == 200);
        NetworkInterfaceState state = response.getBody(NetworkInterfaceState.class);
        this.networkInterfaceIds.add(state.id);
    }
    // Query all network interface documents associated with list of network interface IDs.
    QueryTask.Query networkInterfaceQuery = QueryTask.Query.Builder.create().addKindFieldClause(NetworkInterfaceState.class).addInClause(NetworkInterfaceState.FIELD_NAME_ID, this.networkInterfaceIds).build();
    QueryTask q = QueryTask.Builder.createDirectTask().setQuery(networkInterfaceQuery).addOption(QueryTask.QuerySpecification.QueryOption.EXPAND_CONTENT).build();
    Operation queryNetworkInterface = QueryUtils.createQueryTaskOperation(this.host, q, ServiceTypeCluster.INVENTORY_SERVICE).setReferer(this.host.getUri());
    Operation queryResponse = this.host.waitForResponse(queryNetworkInterface);
    Assert.assertTrue("Error retrieving network interface states", queryResponse.getStatusCode() == 200);
    QueryTask qt = queryResponse.getBody(QueryTask.class);
    // Store security group links and subnet links.
    for (String documentLink : qt.results.documentLinks) {
        NetworkInterfaceState nis = Utils.fromJson(qt.results.documents.get(documentLink), NetworkInterfaceState.class);
        this.securityGroupLinks.addAll(nis.securityGroupLinks);
        this.subnetLinks.add(nis.subnetLink);
    }
}
Also used : QueryTask(com.vmware.xenon.services.common.QueryTask) NetworkInterfaceState(com.vmware.photon.controller.model.resources.NetworkInterfaceService.NetworkInterfaceState) Operation(com.vmware.xenon.common.Operation)

Example 9 with QueryTask

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

the class TestAWSEnumerationDocumentCountInLongRun method verifyResourceDuplicates.

/**
 * Verify documents for duplicates after multiple enumerations.
 */
private void verifyResourceDuplicates() {
    int total_dup_resource_count = 0;
    for (Class resource : resourcesList) {
        QueryTask.Query.Builder qBuilder = QueryTask.Query.Builder.create().addKindFieldClause(resource).addFieldClause("endpointLinks.item", this.endpointState.documentSelfLink, QueryTask.QueryTerm.MatchType.TERM, QueryTask.Query.Occurance.MUST_OCCUR);
        if (resource.getSimpleName().equals("ComputeState")) {
            qBuilder.addFieldClause("type", "VM_GUEST", QueryTask.QueryTerm.MatchType.TERM, QueryTask.Query.Occurance.MUST_OCCUR);
        }
        QueryTask resourceQt = QueryTask.Builder.createDirectTask().setQuery(qBuilder.build()).addOption(QueryTask.QuerySpecification.QueryOption.EXPAND_CONTENT).addOption(QueryTask.QuerySpecification.QueryOption.TOP_RESULTS).setResultLimit(10000).build();
        Operation queryDocuments = QueryUtils.createQueryTaskOperation(this.host, resourceQt, ServiceTypeCluster.INVENTORY_SERVICE).setReferer(this.host.getUri());
        Operation queryResponse = this.host.waitForResponse(queryDocuments);
        Assert.assertTrue("Error retrieving enumerated documents", queryResponse.getStatusCode() == 200);
        QueryTask qt = queryResponse.getBody(QueryTask.class);
        Set<String> resourceIdSet = new HashSet<>();
        if (qt.results != null && qt.results.documentLinks != null && qt.results.documentLinks.size() > 0) {
            this.host.log("Number of %s docs: %d", resource.getSimpleName(), qt.results.documentLinks.size());
            for (String resourceDocumentLink : qt.results.documentLinks) {
                Object object = qt.results.documents.get(resourceDocumentLink);
                ResourceState resourceState = Utils.fromJson(object, ResourceState.class);
                String resourceId = resourceState.id;
                if (!resourceIdSet.contains(resourceId)) {
                    resourceIdSet.add(resourceId);
                } else {
                    this.host.log("duplicate %s id = %s, with state: ", resource.getSimpleName(), resourceId, Utils.toJsonHtml(resourceState));
                    total_dup_resource_count++;
                }
            }
        }
    }
    assertEquals("Duplicate resources found: ", 0, total_dup_resource_count);
}
Also used : QueryTask(com.vmware.xenon.services.common.QueryTask) ResourceState(com.vmware.photon.controller.model.resources.ResourceState) Operation(com.vmware.xenon.common.Operation) TestAWSSetupUtils.deleteVMsOnThisEndpoint(com.vmware.photon.controller.model.adapters.awsadapter.TestAWSSetupUtils.deleteVMsOnThisEndpoint) HashSet(java.util.HashSet)

Example 10 with QueryTask

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

the class AWSCostStatsService method getMarkerMetricsOp.

private Operation getMarkerMetricsOp(AWSCostStatsCreationContext context, ComputeState accComputeState) {
    QueryTask qTask = getQueryTaskForMetric(accComputeState);
    Operation.CompletionHandler completionHandler = (operation, exception) -> {
        if (exception != null) {
            logWarning(() -> String.format("Failed to get bill processed time for account: %s", accComputeState.documentSelfLink));
            getFailureConsumer(context).accept(exception);
            return;
        }
        QueryTask body = operation.getBody(QueryTask.class);
        String accountId = accComputeState.customProperties.get(AWS_ACCOUNT_ID_KEY);
        if (body.results.documentCount == 0) {
            ResourceMetrics markerMetrics = new ResourceMetrics();
            markerMetrics.timestampMicrosUtc = getCurrentMonthStartTimeMicros();
            markerMetrics.entries = new HashMap<>();
            markerMetrics.entries.put(AWSConstants.AWS_ACCOUNT_BILL_PROCESSED_TIME_MILLIS, 0d);
            markerMetrics.documentSelfLink = StatsUtil.getMetricKey(accComputeState.documentSelfLink, Utils.getNowMicrosUtc());
            context.accountsMarkersMap.put(accountId, markerMetrics);
        } else {
            ResourceMetrics markerMetrics = body.results.documents.values().stream().map(o -> Utils.fromJson(o, ResourceMetrics.class)).collect(Collectors.toList()).get(0);
            context.accountsMarkersMap.putIfAbsent(accountId, markerMetrics);
        }
    };
    return QueryUtils.createQueryTaskOperation(this, qTask, ServiceTypeCluster.METRIC_SERVICE).setExpiration(Utils.fromNowMicrosUtc(TimeUnit.SECONDS.toMicros(INTERNAL_REQUEST_TIMEOUT_SECONDS))).setCompletion(completionHandler);
}
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) ResourceMetrics(com.vmware.photon.controller.model.monitoring.ResourceMetricsService.ResourceMetrics) QueryTask(com.vmware.xenon.services.common.QueryTask) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Operation(com.vmware.xenon.common.Operation)

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