Search in sources :

Example 21 with ServiceDocumentQueryResult

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

the class GCPEnumerationAdapterService method deleteHelper.

/**
 * This helper function deletes all compute states in one deletion page
 * every iteration. For each compute state, its associated disks will
 * also be deleted. After deletion, it will check if there is a next
 * deletion page. If there is, it will delete that page recursively.
 * If there are nothing to delete, it will jump to the finished stage
 * of the whole enumeration.
 * @param ctx The enumeration context.
 * @param results The results of deletion query.
 */
private void deleteHelper(EnumerationContext ctx, ServiceDocumentQueryResult results) {
    if (results.documentCount == 0) {
        checkLinkAndFinishDeleting(ctx, results.nextPageLink);
        return;
    }
    List<Operation> operations = new ArrayList<>();
    results.documents.values().forEach(json -> {
        ComputeState computeState = Utils.fromJson(json, ComputeState.class);
        Long vmId = Long.parseLong(computeState.id);
        if (!ctx.vmIds.contains(vmId)) {
            operations.add(Operation.createDelete(this, computeState.documentSelfLink));
            logFine(() -> String.format("Deleting compute state %s", computeState.documentSelfLink));
            if (computeState.diskLinks != null && !computeState.diskLinks.isEmpty()) {
                computeState.diskLinks.forEach(diskLink -> {
                    operations.add(Operation.createDelete(this, diskLink));
                    logFine(() -> String.format("Deleting disk state %s", diskLink));
                });
            }
        }
    });
    if (operations.isEmpty()) {
        checkLinkAndFinishDeleting(ctx, results.nextPageLink);
        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())));
        }
        checkLinkAndFinishDeleting(ctx, results.nextPageLink);
    }).sendWith(this);
}
Also used : GCPUriPaths(com.vmware.photon.controller.model.adapters.gcp.GCPUriPaths) AuthCredentialsServiceState(com.vmware.xenon.services.common.AuthCredentialsService.AuthCredentialsServiceState) ComputeEnumerateResourceRequest(com.vmware.photon.controller.model.adapterapi.ComputeEnumerateResourceRequest) GCPUtils.privateKeyFromPkcs8(com.vmware.photon.controller.model.adapters.gcp.utils.GCPUtils.privateKeyFromPkcs8) QueryTask(com.vmware.xenon.services.common.QueryTask) OSType(com.vmware.photon.controller.model.ComputeProperties.OSType) GCPInstance(com.vmware.photon.controller.model.adapters.gcp.podo.vm.GCPInstance) ResourceGroupState(com.vmware.photon.controller.model.resources.ResourceGroupService.ResourceGroupState) DiskType(com.vmware.photon.controller.model.resources.DiskService.DiskType) ComputeType(com.vmware.photon.controller.model.resources.ComputeDescriptionService.ComputeDescription.ComputeType) ENVIRONMENT_NAME_GCP(com.vmware.photon.controller.model.resources.ComputeDescriptionService.ComputeDescription.ENVIRONMENT_NAME_GCP) Utils(com.vmware.xenon.common.Utils) GeneralSecurityException(java.security.GeneralSecurityException) GCPInstancesList(com.vmware.photon.controller.model.adapters.gcp.podo.vm.GCPInstancesList) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) ServiceDocumentQueryResult(com.vmware.xenon.common.ServiceDocumentQueryResult) URI(java.net.URI) DEFAULT_DISK_SOURCE_IMAGE(com.vmware.photon.controller.model.adapters.gcp.constants.GCPConstants.DEFAULT_DISK_SOURCE_IMAGE) GCPUtils.assignPowerState(com.vmware.photon.controller.model.adapters.gcp.utils.GCPUtils.assignPowerState) GCPUtils.extractActualInstanceType(com.vmware.photon.controller.model.adapters.gcp.utils.GCPUtils.extractActualInstanceType) ComputeDescription(com.vmware.photon.controller.model.resources.ComputeDescriptionService.ComputeDescription) DISK_AUTO_DELETE(com.vmware.photon.controller.model.adapters.gcp.constants.GCPConstants.DISK_AUTO_DELETE) StatelessService(com.vmware.xenon.common.StatelessService) DEFAULT_DISK_SERVICE_REFERENCE(com.vmware.photon.controller.model.adapters.gcp.constants.GCPConstants.DEFAULT_DISK_SERVICE_REFERENCE) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) GCPDisk(com.vmware.photon.controller.model.adapters.gcp.podo.vm.GCPDisk) TaskManager(com.vmware.photon.controller.model.adapters.util.TaskManager) Set(java.util.Set) DiskState(com.vmware.photon.controller.model.resources.DiskService.DiskState) LIST_VM_TEMPLATE_URI(com.vmware.photon.controller.model.adapters.gcp.constants.GCPConstants.LIST_VM_TEMPLATE_URI) UUID(java.util.UUID) ServiceHost(com.vmware.xenon.common.ServiceHost) List(java.util.List) AUTH_HEADER_BEARER_PREFIX(com.vmware.photon.controller.model.adapters.gcp.constants.GCPConstants.AUTH_HEADER_BEARER_PREFIX) PrivateKey(java.security.PrivateKey) UriUtils(com.vmware.xenon.common.UriUtils) ComputeService(com.vmware.photon.controller.model.resources.ComputeService) QueryOption(com.vmware.xenon.services.common.QueryTask.QuerySpecification.QueryOption) NumericRange(com.vmware.xenon.services.common.QueryTask.NumericRange) DiskService(com.vmware.photon.controller.model.resources.DiskService) PhotonModelUriUtils(com.vmware.photon.controller.model.util.PhotonModelUriUtils) HashMap(java.util.HashMap) ComputeDescriptionService(com.vmware.photon.controller.model.resources.ComputeDescriptionService) GCPUtils(com.vmware.photon.controller.model.adapters.gcp.utils.GCPUtils) MAX_RESULTS(com.vmware.photon.controller.model.adapters.gcp.constants.GCPConstants.MAX_RESULTS) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) PAGE_TOKEN(com.vmware.photon.controller.model.adapters.gcp.constants.GCPConstants.PAGE_TOKEN) UriPaths(com.vmware.photon.controller.model.UriPaths) EnumerationStages(com.vmware.photon.controller.model.adapters.util.enums.EnumerationStages) ComputeState(com.vmware.photon.controller.model.resources.ComputeService.ComputeState) EnumerationAction(com.vmware.photon.controller.model.adapterapi.EnumerationAction) LinkedList(java.util.LinkedList) GCPAccessTokenResponse(com.vmware.photon.controller.model.adapters.gcp.podo.authorization.GCPAccessTokenResponse) AdapterUtils(com.vmware.photon.controller.model.adapters.util.AdapterUtils) GCPUtils.extractRegionFromZone(com.vmware.photon.controller.model.adapters.gcp.utils.GCPUtils.extractRegionFromZone) EncryptionUtils(com.vmware.photon.controller.model.security.util.EncryptionUtils) Operation(com.vmware.xenon.common.Operation) QueryUtils(com.vmware.photon.controller.model.query.QueryUtils) IOException(java.io.IOException) ComputeScopes(com.google.api.services.compute.ComputeScopes) Consumer(java.util.function.Consumer) CUSTOM_OS_TYPE(com.vmware.photon.controller.model.ComputeProperties.CUSTOM_OS_TYPE) DEFAULT_DISK_CAPACITY(com.vmware.photon.controller.model.adapters.gcp.constants.GCPConstants.DEFAULT_DISK_CAPACITY) ComputeStateWithDescription(com.vmware.photon.controller.model.resources.ComputeService.ComputeStateWithDescription) GCPUtils.assignIPAddress(com.vmware.photon.controller.model.adapters.gcp.utils.GCPUtils.assignIPAddress) Collections(java.util.Collections) OperationJoin(com.vmware.xenon.common.OperationJoin) PhotonModelUriUtils.createInventoryUri(com.vmware.photon.controller.model.util.PhotonModelUriUtils.createInventoryUri) JSONWebToken(com.vmware.photon.controller.model.adapters.gcp.utils.JSONWebToken) ComputeState(com.vmware.photon.controller.model.resources.ComputeService.ComputeState) ArrayList(java.util.ArrayList) Operation(com.vmware.xenon.common.Operation)

Example 22 with ServiceDocumentQueryResult

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

the class TestAWSEnumerationTask method testEnumeration.

// Runs the enumeration task on the AWS endpoint to list all the instances on the endpoint.
@Test
public void testEnumeration() throws Throwable {
    this.host.log("Running test: " + this.currentTestName.getMethodName());
    ComputeState vmState = createAWSVMResource(this.host, this.computeHost, this.endpointState, TestAWSSetupUtils.class, zoneId, regionId, null, this.singleNicSpec, this.awsTestContext);
    if (this.isMock) {
        // Just make a call to the enumeration service and make sure that the adapter patches
        // the parent with completion.
        enumerateResources(this.host, this.computeHost, this.endpointState, this.isMock, TEST_CASE_MOCK_MODE);
        return;
    }
    // Overriding the page size to test the pagination logic with limited instances on AWS.
    // This is a functional test
    // so the latency numbers maybe higher from this test due to low page size.
    setQueryPageSize(DEFAULT_TEST_PAGE_SIZE);
    setQueryResultLimit(DEFAULT_TEST_PAGE_SIZE);
    // Provision a single VM . Check initial state.
    vmState = provisionMachine(this.host, vmState, this.isMock, this.instancesToCleanUp);
    queryComputeInstances(this.host, count2);
    queryDocumentsAndAssertExpectedCount(this.host, count2, ComputeDescriptionService.FACTORY_LINK, false);
    if (ENABLE_LOAD_BALANCER_ENUMERATION) {
        this.lbToCleanUp = provisionAWSLoadBalancerWithEC2Client(this.host, this.lbClient, null, this.subnetId, this.securityGroupId, Collections.singletonList(vmState.id));
    }
    // CREATION directly on AWS
    List<String> instanceIdsToDeleteFirstTime = provisionAWSVMWithEC2Client(this.client, this.host, count4, T2_MICRO_INSTANCE_TYPE, this.subnetId, this.securityGroupId);
    List<String> instanceIds = provisionAWSVMWithEC2Client(this.client, this.host, count1, instanceType, this.subnetId, this.securityGroupId);
    instanceIdsToDeleteFirstTime.addAll(instanceIds);
    this.instancesToCleanUp.addAll(instanceIdsToDeleteFirstTime);
    waitForProvisioningToComplete(instanceIdsToDeleteFirstTime, this.host, this.client, ZERO);
    // Xenon does not know about the new instances.
    ProvisioningUtils.queryComputeInstances(this.host, count2);
    // Create S3 bucket on amazon
    Map<String, String> tags = new HashMap<>();
    tags.put(S3_TAG_KEY_1, S3_TAG_VALUE_1);
    tags.put(S3_TAG_KEY_2, S3_TAG_VALUE_2);
    createS3BucketAndTags(tags);
    this.bucketToBeDeleted = TEST_BUCKET_NAME;
    enumerateResources(this.host, this.computeHost, this.endpointState, this.isMock, TEST_CASE_INITIAL);
    // Get a count of how many EBS disks are attached to a VM initially.
    ComputeState csForDiskLinkValidation = getComputeStateFromId(this.instancesToCleanUp.get(0));
    this.initialEbsDiskLinkCount = csForDiskLinkValidation.diskLinks.size();
    // Create a volume to be attached to the VM later.
    CreateVolumeRequest createVolumeRequest = new CreateVolumeRequest().withAvailabilityZone(csForDiskLinkValidation.zoneId).withVolumeType(VolumeType.Gp2).withSize(10);
    CreateVolumeResult createVolumeResult = this.client.createVolume(createVolumeRequest);
    this.testEbsId = createVolumeResult.getVolume().getVolumeId();
    // Validate if the S3 bucket is enumerated.
    validateS3Enumeration(count1, count3);
    // Validate S3 tag state count.
    validateS3TagStatesCreated();
    if (ENABLE_LOAD_BALANCER_ENUMERATION) {
        // Validate Load Balancer State
        validateLoadBalancerState(this.lbToCleanUp, vmState.documentSelfLink);
    }
    // Remove a tag from test S3 bucket.
    tags.clear();
    tags.put(S3_TAG_KEY_1, S3_TAG_VALUE_1);
    createS3BucketAndTags(tags);
    // 5 new resources should be discovered. Mapping to 2 new compute description and 5 new
    // compute states.
    // Even though the "t2.micro" is common to the VM provisioned from Xenon
    // service and the one directly provisioned on EC2, there is no Compute description
    // linking of discovered resources to user defined compute descriptions. So a new system
    // generated compute description will be created for "t2.micro"
    queryDocumentsAndAssertExpectedCount(this.host, count4, ComputeDescriptionService.FACTORY_LINK, false);
    queryDocumentsAndAssertExpectedCount(this.host, count7, ComputeService.FACTORY_LINK, false);
    queryDocumentsAndAssertExpectedCount(this.host, count7, DiskService.FACTORY_LINK, false);
    // Validate at least 4 availability zones were enumerated
    ProvisioningUtils.queryComputeInstancesByType(this.host, count4, ComputeType.ZONE.toString(), false);
    // Update Scenario : Check that the tag information is present for the VM tagged above.
    String vpCId = validateTagAndNetworkAndComputeDescriptionInformation(vmState);
    validateVPCInformation(vpCId);
    // Count should be 1 NICs per discovered VM.
    int totalNetworkInterfaceStateCount = count6 * this.singleNicSpec.numberOfNics();
    validateNetworkInterfaceCount(totalNetworkInterfaceStateCount);
    // One VPC should be discovered in the test.
    queryDocumentsAndAssertExpectedCount(this.host, count1, NetworkService.FACTORY_LINK, false);
    // Verify that the SecurityGroups of the newly created VM has been enumerated and exists
    // locally
    validateSecurityGroupsInformation(vmState.groupLinks);
    // Verify stop flow
    // The first instance of instanceIdsToDeleteFirstTime will be stopped.
    String instanceIdsToStop = instanceIdsToDeleteFirstTime.get(0);
    tagResourcesWithName(this.client, VM_STOPPED_NAME, instanceIdsToStop);
    // Stop one instance
    stopVMsUsingEC2Client(this.client, this.host, new ArrayList<>(Arrays.asList(instanceIdsToStop)));
    // Create stale resources, that later should be deleted by the enumeration
    String staleSubnetDocumentSelfLink = markFirstResourceStateAsStale(host, SubnetState.class, SubnetService.FACTORY_LINK);
    String staleNetworkDocumentSelfLink = markFirstResourceStateAsStale(host, NetworkState.class, NetworkService.FACTORY_LINK);
    // During the enumeration, if one instance is stopped, its public ip address
    // will disappear, then the corresponding link of local ComputeState's public
    // network interface and its document will be removed.
    enumerateResources(this.host, this.computeHost, this.endpointState, this.isMock, TEST_CASE_STOP_VM);
    // Validate that test VM still has same number of diskLinks.
    csForDiskLinkValidation = getComputeStateFromId(this.instancesToCleanUp.get(0));
    assertEquals(csForDiskLinkValidation.diskLinks.size(), this.initialEbsDiskLinkCount);
    // Attach volume to test VM.
    AttachVolumeRequest attachVolumeRequest = new AttachVolumeRequest().withVolumeId(createVolumeResult.getVolume().getVolumeId()).withInstanceId(csForDiskLinkValidation.id).withDevice("/dev/sdh");
    this.client.attachVolume(attachVolumeRequest);
    // Validate stale resources have been deleted
    validateStaleResourceStateDeletion(staleSubnetDocumentSelfLink, staleNetworkDocumentSelfLink);
    // After two enumeration cycles, validate that we did not create duplicate documents for existing
    // S3 bucket and validate that we did not add duplicate tagLink in diskState and removed the tagLink
    // for tag deleted from AWS.
    validateS3Enumeration(count1, count2);
    // Remove region from S3 bucket DiskState.
    removeS3BucketRegionFromDiskState();
    // Validate that deleted S3 tag's local state is deleted.
    validateS3TagStatesCreated();
    enumerateResources(this.host, this.computeHost, this.endpointState, this.isMock, TEST_CASE_ADDITIONAL_VM);
    // Check that newly attached volume got enumerated and the instance now has 1 more diskLink than before.
    csForDiskLinkValidation = getComputeStateFromId(this.instancesToCleanUp.get(0));
    assertEquals(csForDiskLinkValidation.diskLinks.size(), this.initialEbsDiskLinkCount + 1);
    // Validate that diskState of S3 bucket with null region got deleted
    validateBucketStateDeletionForNullRegion();
    // Delete the S3 bucket created in the test
    this.s3Client.deleteBucket(TEST_BUCKET_NAME);
    this.bucketToBeDeleted = null;
    // Because one public NIC and its document are removed,
    // the totalNetworkInterfaceStateCount should go down by 1
    validateRemovalOfPublicNetworkInterface(instanceIdsToStop, totalNetworkInterfaceStateCount - 1);
    // Provision an additional VM with a different instance type. It should re-use the
    // existing compute description created by the enumeration task above.
    List<String> instanceIdsToDeleteSecondTime = provisionAWSVMWithEC2Client(this.client, this.host, count1, TestAWSSetupUtils.instanceType, this.subnetId, this.securityGroupId);
    this.instancesToCleanUp.addAll(instanceIdsToDeleteSecondTime);
    waitForProvisioningToComplete(instanceIdsToDeleteSecondTime, this.host, this.client, ZERO);
    enumerateResources(this.host, this.computeHost, this.endpointState, this.isMock, TEST_CASE_ADDITIONAL_VM);
    // Validate that we do not add duplicate diskLinks after multiple enumerations.
    csForDiskLinkValidation = getComputeStateFromId(this.instancesToCleanUp.get(0));
    assertEquals(csForDiskLinkValidation.diskLinks.size(), this.initialEbsDiskLinkCount + 1);
    // Detach and delete test EBS volume.
    DetachVolumeRequest detachVolumeRequest = new DetachVolumeRequest().withVolumeId(this.testEbsId);
    this.client.detachVolume(detachVolumeRequest);
    // One additional compute state and no additional compute description should be
    // created. 1) compute host CD 2) t2.nano-system generated 3) t2.micro-system generated
    // 4) t2.micro-created from test code.
    queryDocumentsAndAssertExpectedCount(this.host, count4, ComputeDescriptionService.FACTORY_LINK, false);
    ServiceDocumentQueryResult computesResult1 = queryDocumentsAndAssertExpectedCount(this.host, count8, ComputeService.FACTORY_LINK, false);
    // validate the internal tag tor type=ec2_instance is set
    // query for the existing internal tag state for type=ec2_instance.
    // There should be only one internal tag.
    validateTagInEntity(computesResult1, ComputeState.class, ec2_instance.toString());
    ServiceDocumentQueryResult networkInterfaceResult = queryDocumentsAndAssertExpectedCount(this.host, totalNetworkInterfaceStateCount - 1, NetworkInterfaceService.FACTORY_LINK, false);
    validateTagInEntity(networkInterfaceResult, NetworkInterfaceState.class, ec2_net_interface.toString());
    ServiceDocumentQueryResult networkStateResult = queryDocumentsAndAssertExpectedCount(this.host, count1, NetworkService.FACTORY_LINK, false);
    validateTagInEntity(networkStateResult, NetworkState.class, ec2_vpc.toString());
    ServiceDocumentQueryResult subnetStateResult = queryDocumentsAndAssertExpectedCount(this.host, count1, SubnetService.FACTORY_LINK, false);
    // TODO Remove. This is to help debug an intermittent test failure.
    host.log(Level.INFO, "The subnet result state that I am working with is " + Utils.toJsonHtml(subnetStateResult));
    validateTagInEntity(subnetStateResult, SubnetState.class, ec2_subnet.toString());
    queryDocumentsAndAssertExpectedCount(this.host, count8, DiskService.FACTORY_LINK, false);
    // Verify Deletion flow
    // Delete 5 VMs spawned above of type T2_NANO
    deleteVMsUsingEC2Client(this.client, this.host, instanceIdsToDeleteFirstTime);
    enumerateResources(this.host, this.computeHost, this.endpointState, this.isMock, TEST_CASE_DELETE_VMS);
    // Counts should go down. 5 compute states and 5 disk states.
    ServiceDocumentQueryResult computesResult2 = queryDocumentsAndAssertExpectedCount(this.host, count3, ComputeService.FACTORY_LINK, false);
    queryDocumentsAndAssertExpectedCount(this.host, count3, DiskService.FACTORY_LINK, false);
    // Validate that detached test EBS is removed from diskLinks of test instance.
    csForDiskLinkValidation = getComputeStateFromId(this.instancesToCleanUp.get(0));
    assertEquals(csForDiskLinkValidation.diskLinks.size(), this.initialEbsDiskLinkCount);
    // validate the internal tag tor type=ec2_instance is set
    // query for the existing internal tag state for type=ec2_instance.
    // There should be only one internal tag.
    validateTagInEntity(computesResult2, ComputeState.class, ec2_instance.toString());
    // Delete 1 VMs spawned above of type T2_Micro
    deleteVMsUsingEC2Client(this.client, this.host, instanceIdsToDeleteSecondTime);
    enumerateResources(this.host, this.computeHost, this.endpointState, this.isMock, TEST_CASE_DELETE_VM);
    // Compute state and disk state count should go down by 1
    ServiceDocumentQueryResult computesResult3 = queryDocumentsAndAssertExpectedCount(this.host, count2, ComputeService.FACTORY_LINK, false);
    queryDocumentsAndAssertExpectedCount(this.host, count2, DiskService.FACTORY_LINK, false);
    // validate the internal tag tor type=ec2_instance is set
    // query for the existing internal tag state for type=ec2_instance.
    // There should be only one internal tag.
    validateTagInEntity(computesResult3, ComputeState.class, ec2_instance.toString());
    // Validate that the document for the deleted S3 bucket is deleted after enumeration.
    validateS3Enumeration(ZERO, ZERO);
    // Delete test EBS volume.
    DeleteVolumeRequest deleteVolumeRequest = new DeleteVolumeRequest().withVolumeId(this.testEbsId);
    this.client.deleteVolume(deleteVolumeRequest);
    this.testEbsId = null;
}
Also used : ComputeState(com.vmware.photon.controller.model.resources.ComputeService.ComputeState) DeleteVolumeRequest(com.amazonaws.services.ec2.model.DeleteVolumeRequest) CreateVolumeRequest(com.amazonaws.services.ec2.model.CreateVolumeRequest) HashMap(java.util.HashMap) CreateVolumeResult(com.amazonaws.services.ec2.model.CreateVolumeResult) TestAWSSetupUtils.deleteVMsOnThisEndpoint(com.vmware.photon.controller.model.adapters.awsadapter.TestAWSSetupUtils.deleteVMsOnThisEndpoint) ServiceDocumentQueryResult(com.vmware.xenon.common.ServiceDocumentQueryResult) AttachVolumeRequest(com.amazonaws.services.ec2.model.AttachVolumeRequest) DetachVolumeRequest(com.amazonaws.services.ec2.model.DetachVolumeRequest) Test(org.junit.Test)

Example 23 with ServiceDocumentQueryResult

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

the class TestAWSImageEnumerationTask method testPrivateImageEnumeration_single.

/*
     * The image that must be returned:
     *
     * https://console.aws.amazon.com/ec2/v2/home?region=us-east-1#Images:visibility=private-images;
     * imageId=ami-caf25eb0;sort=name
     *
     * under prelude_test @ https://537227425989.signin.aws.amazon.com/console
     */
@Test
@Ignore("https://jira-hzn.eng.vmware.com/browse/VCOM-832")
public void testPrivateImageEnumeration_single() throws Throwable {
    Assume.assumeFalse(this.isMock);
    final EndpointState endpointState = createEndpointState();
    kickOffImageEnumeration(endpointState, PRIVATE, AMAZON_PRIVATE_IMAGE_FILTER);
    // Validate 1 image state is CREATED
    ServiceDocumentQueryResult images = queryDocumentsAndAssertExpectedCount(getHost(), 1, ImageService.FACTORY_LINK, EXACT_COUNT);
    ImageState image = Utils.fromJson(images.documents.values().iterator().next(), ImageState.class);
    // Validate created image is correctly populated
    Assert.assertNull("Private image must NOT have endpointType set.", image.endpointType);
    Assert.assertEquals("Private image must have endpointLink set.", endpointState.documentSelfLink, image.endpointLink);
    Assert.assertEquals("Private image must have tenantLinks set.", endpointState.tenantLinks, image.tenantLinks);
    Assert.assertEquals("Private image id is incorrect.", "ami-caf25eb0", image.id);
    Assert.assertEquals("Private image name is incorrect.", "tapestryPipelineServiceTestService", image.name);
    Assert.assertEquals("Private image 'Name' tag is missing.", 1, image.tagLinks.size());
    TagState nameTag = getServiceSynchronously(image.tagLinks.iterator().next(), TagState.class);
    Assert.assertEquals(image.name, nameTag.value);
}
Also used : EndpointState(com.vmware.photon.controller.model.resources.EndpointService.EndpointState) TagState(com.vmware.photon.controller.model.resources.TagService.TagState) ServiceDocumentQueryResult(com.vmware.xenon.common.ServiceDocumentQueryResult) ImageState(com.vmware.photon.controller.model.resources.ImageService.ImageState) Ignore(org.junit.Ignore) BaseModelTest(com.vmware.photon.controller.model.helpers.BaseModelTest) Test(org.junit.Test)

Example 24 with ServiceDocumentQueryResult

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

the class TestAWSSetupUtils method getNICByAWSId.

/**
 * Lookup a NIC State by aws Id
 */
public static NetworkInterfaceState getNICByAWSId(VerificationHost host, String awsId) throws Throwable {
    URI networkInterfacesURI = UriUtils.buildUri(host, NetworkInterfaceService.FACTORY_LINK);
    networkInterfacesURI = UriUtils.buildExpandLinksQueryUri(networkInterfacesURI);
    networkInterfacesURI = UriUtils.appendQueryParam(networkInterfacesURI, "$filter", String.format("id eq %s", awsId));
    Operation op = host.waitForResponse(Operation.createGet(networkInterfacesURI));
    ServiceDocumentQueryResult result = op.getBody(ServiceDocumentQueryResult.class);
    assertNotNull(result);
    assertNotNull(result.documents);
    if (result.documents.size() == 0) {
        return null;
    }
    return Utils.fromJson(result.documents.values().iterator().next(), NetworkInterfaceState.class);
}
Also used : Operation(com.vmware.xenon.common.Operation) URI(java.net.URI) ProvisioningUtils.createServiceURI(com.vmware.photon.controller.model.tasks.ProvisioningUtils.createServiceURI) ServiceDocumentQueryResult(com.vmware.xenon.common.ServiceDocumentQueryResult)

Example 25 with ServiceDocumentQueryResult

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

the class VsphereDatacenterEnumerationHelper method processDatacenterInfo.

static void processDatacenterInfo(VSphereIncrementalEnumerationService service, Element element, EnumerationProgress ctx) {
    QueryTask task = queryForDatacenter(ctx, element.object.getValue());
    withTaskResults(service, task, (ServiceDocumentQueryResult result) -> {
        if (result.documentLinks.isEmpty()) {
            createDatacenter(service, ctx, element);
        } else {
            ResourceGroupService.ResourceGroupState oldDocument = convertOnlyResultToDocument(result, ResourceGroupService.ResourceGroupState.class);
            updateDatacenter(service, ctx, element, oldDocument);
        }
    });
}
Also used : QueryTask(com.vmware.xenon.services.common.QueryTask) ResourceGroupService(com.vmware.photon.controller.model.resources.ResourceGroupService) ServiceDocumentQueryResult(com.vmware.xenon.common.ServiceDocumentQueryResult)

Aggregations

ServiceDocumentQueryResult (com.vmware.xenon.common.ServiceDocumentQueryResult)64 Test (org.junit.Test)26 ComputeState (com.vmware.photon.controller.model.resources.ComputeService.ComputeState)25 ArrayList (java.util.ArrayList)15 QueryTask (com.vmware.xenon.services.common.QueryTask)14 EndpointState (com.vmware.photon.controller.model.resources.EndpointService.EndpointState)13 Operation (com.vmware.xenon.common.Operation)13 ComputeDescription (com.vmware.photon.controller.model.resources.ComputeDescriptionService.ComputeDescription)12 DiskState (com.vmware.photon.controller.model.resources.DiskService.DiskState)12 HashMap (java.util.HashMap)12 BaseModelTest (com.vmware.photon.controller.model.helpers.BaseModelTest)11 ResourcePoolState (com.vmware.photon.controller.model.resources.ResourcePoolService.ResourcePoolState)11 URI (java.net.URI)11 Map (java.util.Map)11 List (java.util.List)10 StatsCollectionTaskState (com.vmware.photon.controller.model.tasks.monitoring.StatsCollectionTaskService.StatsCollectionTaskState)8 UriUtils (com.vmware.xenon.common.UriUtils)8 Utils (com.vmware.xenon.common.Utils)8 QueryUtils (com.vmware.photon.controller.model.query.QueryUtils)7 ServiceStat (com.vmware.xenon.common.ServiceStats.ServiceStat)7