Search in sources :

Example 76 with AuthCredentialsServiceState

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

the class TestAzureLongRunningEnumeration method setUp.

@Override
@Before
public void setUp() throws Exception {
    for (int i = 0; i < numOfVMsToTest; i++) {
        String azureName = generateName(azureVMNamePrefix);
        azureVMNames.add(azureName);
        nicSpecs.add(initializeNicSpecs(azureName, false, true, false));
    }
    try {
        /*
             * Init Class-specific (shared between test runs) vars.
             *
             * NOTE: Ultimately this should go to @BeforeClass, BUT BasicReusableHostTestCase.HOST
             * is not accessible.
             */
        if (computeHost == null) {
            PhotonModelServices.startServices(this.host);
            PhotonModelTaskServices.startServices(this.host);
            PhotonModelAdaptersRegistryAdapters.startServices(this.host);
            AzureAdaptersTestUtils.startServicesSynchronouslyAzure(this.host);
            this.host.waitForServiceAvailable(PhotonModelServices.LINKS);
            this.host.waitForServiceAvailable(PhotonModelTaskServices.LINKS);
            // TODO: VSYM-992 - improve test/fix arbitrary timeout
            this.host.setTimeoutSeconds(this.timeoutSeconds);
            // Create a resource pool where the VMs will be housed
            ResourcePoolState resourcePool = createDefaultResourcePool(this.host);
            AuthCredentialsServiceState authCredentials = createDefaultAuthCredentials(this.host, this.clientID, this.clientKey, this.subscriptionId, this.tenantId);
            endpointState = createDefaultEndpointState(this.host, authCredentials.documentSelfLink);
            // create a compute host for the Azure
            computeHost = createDefaultComputeHost(this.host, resourcePool.documentSelfLink, endpointState);
            endpointState.computeHostLink = computeHost.documentSelfLink;
        }
        this.host.waitForServiceAvailable(PhotonModelServices.LINKS);
        this.host.waitForServiceAvailable(PhotonModelTaskServices.LINKS);
        this.nodeStatsUri = UriUtils.buildUri(this.host.getUri(), ServiceUriPaths.CORE_MANAGEMENT);
        this.maxMemoryInMb = this.host.getState().systemInfo.maxMemoryByteCount / BYTES_TO_MB;
        internalTagResourcesMap.put(NetworkState.class, NETWORK_TAG_TYPE_VALUE);
        internalTagResourcesMap.put(SubnetState.class, SUBNET_TAG_TYPE_VALUE);
        internalTagResourcesMap.put(NetworkInterfaceState.class, NETWORK_INTERFACE_TAG_TYPE_VALUE);
        if (!this.isMock) {
            ApplicationTokenCredentials credentials = new ApplicationTokenCredentials(this.clientID, this.tenantId, this.clientKey, AzureEnvironment.AZURE);
            this.computeManagementClient = new ComputeManagementClientImpl(credentials).withSubscriptionId(this.subscriptionId);
            this.resourceManagementClient = new ResourceManagementClientImpl(credentials).withSubscriptionId(this.subscriptionId);
            this.storageManagementClient = new StorageManagementClientImpl(credentials).withSubscriptionId(this.subscriptionId);
            this.networkManagementClient = new NetworkManagementClientImpl(credentials).withSubscriptionId(this.subscriptionId);
        }
    } catch (Throwable e) {
        throw new Exception(e);
    }
}
Also used : NetworkManagementClientImpl(com.microsoft.azure.management.network.implementation.NetworkManagementClientImpl) ResourcePoolState(com.vmware.photon.controller.model.resources.ResourcePoolService.ResourcePoolState) AuthCredentialsServiceState(com.vmware.xenon.services.common.AuthCredentialsService.AuthCredentialsServiceState) StorageManagementClientImpl(com.microsoft.azure.management.storage.implementation.StorageManagementClientImpl) ComputeManagementClientImpl(com.microsoft.azure.management.compute.implementation.ComputeManagementClientImpl) ApplicationTokenCredentials(com.microsoft.azure.credentials.ApplicationTokenCredentials) AzureTestUtil.randomString(com.vmware.photon.controller.model.adapters.azure.instance.AzureTestUtil.randomString) ResourceManagementClientImpl(com.microsoft.azure.management.resources.implementation.ResourceManagementClientImpl) Before(org.junit.Before)

Example 77 with AuthCredentialsServiceState

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

the class AzureUtils method constructStorageDescription.

private static StorageDescription constructStorageDescription(StorageAccountInner sa, ServiceHost host, String serviceSelfLink, ComputeStateWithDescription parent, StorageAccountInner contextStorage, StorageAccountListKeysResultInner keys) {
    AuthCredentialsServiceState storageAuth = new AuthCredentialsServiceState();
    storageAuth.documentSelfLink = UUID.randomUUID().toString();
    storageAuth.customProperties = new HashMap<>();
    for (StorageAccountKey key : keys.keys()) {
        storageAuth.customProperties.put(getStorageAccountKeyName(storageAuth.customProperties), key.value());
    }
    storageAuth.tenantLinks = parent.tenantLinks;
    if (parent.endpointLink != null) {
        storageAuth.customProperties.put(CUSTOM_PROP_ENDPOINT_LINK, parent.endpointLink);
    }
    Operation storageAuthOp = Operation.createPost(createInventoryUri(host, AuthCredentialsService.FACTORY_LINK)).setBody(storageAuth);
    storageAuthOp.setReferer(UriUtils.buildUri(host.getPublicUri(), serviceSelfLink));
    host.sendRequest(storageAuthOp);
    String storageAuthLink = UriUtils.buildUriPath(AuthCredentialsService.FACTORY_LINK, storageAuth.documentSelfLink);
    StorageDescription storageDescription = new StorageDescription();
    storageDescription.id = contextStorage.id();
    storageDescription.regionId = contextStorage.location();
    storageDescription.name = contextStorage.name();
    storageDescription.authCredentialsLink = storageAuthLink;
    storageDescription.resourcePoolLink = parent.resourcePoolLink;
    storageDescription.documentSelfLink = UUID.randomUUID().toString();
    storageDescription.endpointLink = parent.endpointLink;
    AdapterUtils.addToEndpointLinks(storageDescription, parent.endpointLink);
    storageDescription.computeHostLink = parent.documentSelfLink;
    storageDescription.customProperties = new HashMap<>();
    storageDescription.customProperties.put(AZURE_STORAGE_TYPE, AZURE_STORAGE_ACCOUNTS);
    storageDescription.customProperties.put(AZURE_STORAGE_ACCOUNT_URI, null);
    storageDescription.tenantLinks = parent.tenantLinks;
    storageDescription.type = contextStorage.sku().name().toString();
    if (sa != null && sa.creationTime() != null) {
        storageDescription.creationTimeMicros = TimeUnit.MILLISECONDS.toMicros(sa.creationTime().getMillis());
    }
    return storageDescription;
}
Also used : AuthCredentialsServiceState(com.vmware.xenon.services.common.AuthCredentialsService.AuthCredentialsServiceState) StorageAccountKey(com.microsoft.azure.management.storage.StorageAccountKey) Operation(com.vmware.xenon.common.Operation) StorageDescription(com.vmware.photon.controller.model.resources.StorageDescriptionService.StorageDescription)

Example 78 with AuthCredentialsServiceState

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

the class AzureSubscriptionEndpointsEnumerationServiceTest method testAddFirstAzureSubscription.

private void testAddFirstAzureSubscription() throws Throwable {
    // Request for creating computes for 1 Azure Subscriptions
    AzureSubscription subscription = getAzureSubscription(SUBSCRIPTION_ID_1, ACCOUNT_ID_1);
    createAzureEndpointsForSubscriptions(Collections.singletonList(subscription));
    // Query the Endpoints to assert
    ServiceDocumentQueryResult result = this.host.getExpandedFactoryState(UriUtils.buildUri(this.host, EndpointService.FACTORY_LINK));
    Assert.assertEquals(2, result.documents.size());
    // Assert the created Endpoint and other resources
    result.documents.remove(this.endpointLink);
    EndpointState endpointStateCreated = Utils.fromJson(result.documents.values().iterator().next(), EndpointState.class);
    assertCreatedEndpoint(endpointStateCreated, SUBSCRIPTION_ID_1);
    this.createdEndpointLinks.add(endpointStateCreated.documentSelfLink);
    // Assert the root compute under the endpoint
    ComputeState computeStateCreated = getServiceSynchronously(endpointStateCreated.computeLink, ComputeState.class);
    assertCreatedComputeState(computeStateCreated, SUBSCRIPTION_ID_1, ACCOUNT_ID_1);
    // Assert the partial AuthCredentialsState
    AuthCredentialsServiceState authCreated = getServiceSynchronously(endpointStateCreated.authCredentialsLink, AuthCredentialsServiceState.class);
    assertAuthCredentialState(authCreated, SUBSCRIPTION_ID_1);
}
Also used : EndpointState(com.vmware.photon.controller.model.resources.EndpointService.EndpointState) ComputeState(com.vmware.photon.controller.model.resources.ComputeService.ComputeState) AuthCredentialsServiceState(com.vmware.xenon.services.common.AuthCredentialsService.AuthCredentialsServiceState) ServiceDocumentQueryResult(com.vmware.xenon.common.ServiceDocumentQueryResult) AzureSubscription(com.vmware.photon.controller.model.adapters.azure.model.cost.AzureSubscription)

Example 79 with AuthCredentialsServiceState

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

the class BaseAdapterContext method getParentAuth.

/**
 * Populate context with endpoint {@code AuthCredentialsServiceState}.
 *
 * @see #getParentAuthRef(BaseAdapterContext) for any customization.
 */
protected DeferredResult<T> getParentAuth(T context) {
    URI parentAuthRef = getParentAuthRef(context);
    Operation op = Operation.createGet(parentAuthRef);
    return context.service.sendWithDeferredResult(op, AuthCredentialsServiceState.class).thenApply(state -> {
        context.parentAuth = state;
        context.endpointAuth = state;
        return context;
    });
}
Also used : AuthCredentialsServiceState(com.vmware.xenon.services.common.AuthCredentialsService.AuthCredentialsServiceState) Operation(com.vmware.xenon.common.Operation) URI(java.net.URI)

Example 80 with AuthCredentialsServiceState

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

the class DiskContext method populateContextThen.

/**
 * Populates the given initial context and invoke the onSuccess handler when built. At every
 * step, if failure occurs the DiskContext's errorHandler is invoked to cleanup.
 */
public static void populateContextThen(Service service, DiskContext ctx, Consumer<DiskContext> onSuccess) {
    // Step 1: Get disk details
    if (ctx.diskState == null) {
        URI diskUri = createInventoryUri(service.getHost(), DiskService.DiskStateExpanded.buildUri(ctx.diskReference));
        AdapterUtils.getServiceState(service, diskUri, op -> {
            ctx.diskState = op.getBody(DiskService.DiskStateExpanded.class);
            EnumSet<DiskService.DiskType> notSupportedTypes = EnumSet.of(DiskService.DiskType.SSD, DiskService.DiskType.NETWORK);
            if (notSupportedTypes.contains(ctx.diskState.type)) {
                ctx.fail(new IllegalStateException(String.format("Not supported disk type %s.", ctx.diskState.type)));
                return;
            }
            populateContextThen(service, ctx, onSuccess);
        }, ctx.errorHandler);
        return;
    }
    // the disk.
    if (ctx.datastoreName == null && ctx.diskInstanceRequest.requestType == DiskInstanceRequest.DiskRequestType.CREATE) {
        if (ctx.diskState.storageDescription != null) {
            ctx.datastoreName = ctx.diskState.storageDescription.id;
            populateContextThen(service, ctx, onSuccess);
        } else if (ctx.diskState.resourceGroupStates != null && !ctx.diskState.resourceGroupStates.isEmpty()) {
            // There will always be only one resource group state existing for a disk
            ResourceGroupState resource = ctx.diskState.resourceGroupStates.iterator().next();
            ClientUtils.getDatastoresForProfile(service, resource.documentSelfLink, ctx.diskState.endpointLink, ctx.diskState.tenantLinks, ctx.errorHandler, (result) -> {
                if (result.documents != null && result.documents.size() > 0) {
                    // pick the first datastore and proceed.
                    StorageDescription dsStorageDesc = Utils.fromJson(result.documents.values().iterator().next(), StorageDescription.class);
                    ctx.datastoreName = dsStorageDesc.id;
                    ctx.diskState.storageDescriptionLink = dsStorageDesc.documentSelfLink;
                } else {
                    // Since no result found default to the available datastore.
                    ctx.datastoreName = "";
                }
                populateContextThen(service, ctx, onSuccess);
            });
        } else if (CustomProperties.of(ctx.diskState).getString(CustomProperties.DISK_DATASTORE_NAME) != null) {
            ctx.datastoreName = CustomProperties.of(ctx.diskState).getString(CustomProperties.DISK_DATASTORE_NAME);
            populateContextThen(service, ctx, onSuccess);
        } else {
            // Mark empty so that it can fall back to any available datastore from the system.
            ctx.datastoreName = "";
            populateContextThen(service, ctx, onSuccess);
        }
        return;
    }
    // Step 3: Get Credentials
    if (ctx.vSphereCredentials == null) {
        if (IAAS_API_ENABLED) {
            if (ctx.operation == null) {
                ctx.fail(new IllegalArgumentException("Caller operation cannot be empty"));
                return;
            }
            SessionUtil.retrieveExternalToken(service, ctx.operation.getAuthorizationContext()).whenComplete((authCredentialsServiceState, throwable) -> {
                if (throwable != null) {
                    ctx.errorHandler.accept(throwable);
                    return;
                }
                ctx.vSphereCredentials = authCredentialsServiceState;
                populateContextThen(service, ctx, onSuccess);
            });
        } else {
            if (ctx.diskState.authCredentialsLink == null || ctx.diskState.authCredentialsLink.isEmpty()) {
                ctx.fail(new IllegalArgumentException("Auth credentials cannot be empty"));
                return;
            }
            URI credUri = createInventoryUri(service.getHost(), ctx.diskState.authCredentialsLink);
            AdapterUtils.getServiceState(service, credUri, op -> {
                ctx.vSphereCredentials = op.getBody(AuthCredentialsServiceState.class);
                populateContextThen(service, ctx, onSuccess);
            }, ctx.errorHandler);
        }
        return;
    }
    // Step 4: Get the endpoint compute link
    if (ctx.endpointComputeLink == null) {
        URI endpointUri = createInventoryUri(service.getHost(), UriUtils.buildUri(service.getHost(), ctx.diskState.endpointLink));
        AdapterUtils.getServiceState(service, endpointUri, op -> {
            EndpointService.EndpointState endpointState = op.getBody(EndpointService.EndpointState.class);
            ctx.endpointComputeLink = endpointState.computeLink;
            populateContextThen(service, ctx, onSuccess);
        }, ctx.errorHandler);
        return;
    }
    // Step 5: Get the adapter reference to from the endpoint compute link
    if (ctx.adapterManagementReference == null) {
        URI computeUri = createInventoryUri(service.getHost(), UriUtils.buildUri(service.getHost(), ctx.endpointComputeLink));
        AdapterUtils.getServiceState(service, computeUri, op -> {
            ComputeService.ComputeState computeState = op.getBody(ComputeService.ComputeState.class);
            ctx.adapterManagementReference = computeState.adapterManagementReference;
            populateContextThen(service, ctx, onSuccess);
        }, ctx.errorHandler);
        return;
    }
    // Step 6: Obtain reference to the datacenter moref.
    if (ctx.datacenterMoRef == null) {
        try {
            ctx.datacenterMoRef = VimUtils.convertStringToMoRef(ctx.diskState.regionId);
        } catch (IllegalArgumentException ex) {
            ctx.fail(ex);
            return;
        }
    }
    onSuccess.accept(ctx);
}
Also used : AdapterUtils(com.vmware.photon.controller.model.adapters.util.AdapterUtils) Service(com.vmware.xenon.common.Service) AuthCredentialsServiceState(com.vmware.xenon.services.common.AuthCredentialsService.AuthCredentialsServiceState) SessionUtil(com.vmware.photon.controller.model.resources.SessionUtil) Operation(com.vmware.xenon.common.Operation) TaskManager(com.vmware.photon.controller.model.adapters.util.TaskManager) DiskInstanceRequest(com.vmware.photon.controller.model.adapterapi.DiskInstanceRequest) ResourceGroupState(com.vmware.photon.controller.model.resources.ResourceGroupService.ResourceGroupState) ManagedObjectReference(com.vmware.vim25.ManagedObjectReference) Consumer(java.util.function.Consumer) Utils(com.vmware.xenon.common.Utils) EndpointService(com.vmware.photon.controller.model.resources.EndpointService) StorageDescription(com.vmware.photon.controller.model.resources.StorageDescriptionService.StorageDescription) UriUtils(com.vmware.xenon.common.UriUtils) ComputeService(com.vmware.photon.controller.model.resources.ComputeService) IAAS_API_ENABLED(com.vmware.photon.controller.model.UriPaths.IAAS_API_ENABLED) URI(java.net.URI) DiskService(com.vmware.photon.controller.model.resources.DiskService) OperationJoin(com.vmware.xenon.common.OperationJoin) PhotonModelUriUtils.createInventoryUri(com.vmware.photon.controller.model.util.PhotonModelUriUtils.createInventoryUri) EnumSet(java.util.EnumSet) ResourceGroupState(com.vmware.photon.controller.model.resources.ResourceGroupService.ResourceGroupState) EndpointService(com.vmware.photon.controller.model.resources.EndpointService) URI(java.net.URI) ComputeService(com.vmware.photon.controller.model.resources.ComputeService) StorageDescription(com.vmware.photon.controller.model.resources.StorageDescriptionService.StorageDescription) AuthCredentialsServiceState(com.vmware.xenon.services.common.AuthCredentialsService.AuthCredentialsServiceState)

Aggregations

AuthCredentialsServiceState (com.vmware.xenon.services.common.AuthCredentialsService.AuthCredentialsServiceState)98 Operation (com.vmware.xenon.common.Operation)33 Before (org.junit.Before)28 ResourcePoolState (com.vmware.photon.controller.model.resources.ResourcePoolService.ResourcePoolState)25 Test (org.junit.Test)22 ArrayList (java.util.ArrayList)19 UriUtils (com.vmware.xenon.common.UriUtils)18 URI (java.net.URI)18 List (java.util.List)18 HashMap (java.util.HashMap)17 CompletionException (java.util.concurrent.CompletionException)16 ComputeState (com.vmware.photon.controller.model.resources.ComputeService.ComputeState)15 Utils (com.vmware.xenon.common.Utils)15 ComputeDescription (com.vmware.photon.controller.model.resources.ComputeDescriptionService.ComputeDescription)14 StatelessService (com.vmware.xenon.common.StatelessService)13 TimeUnit (java.util.concurrent.TimeUnit)13 Collections (java.util.Collections)12 AmazonEC2AsyncClient (com.amazonaws.services.ec2.AmazonEC2AsyncClient)11 SecurityGroupState (com.vmware.photon.controller.model.resources.SecurityGroupService.SecurityGroupState)11 EndpointState (com.vmware.photon.controller.model.resources.EndpointService.EndpointState)10