Search in sources :

Example 1 with CloudException

use of com.microsoft.azure.CloudException in project azure-sdk-for-java by Azure.

the class LoadBalancerBackendImpl method getVirtualMachineIds.

@Override
public Set<String> getVirtualMachineIds() {
    Set<String> vmIds = new HashSet<>();
    Map<String, String> nicConfigs = this.backendNicIPConfigurationNames();
    if (nicConfigs != null) {
        for (String nicId : nicConfigs.keySet()) {
            try {
                NetworkInterface nic = this.parent().manager().networkInterfaces().getById(nicId);
                if (nic == null || nic.virtualMachineId() == null) {
                    continue;
                } else {
                    vmIds.add(nic.virtualMachineId());
                }
            } catch (CloudException | IllegalArgumentException e) {
                continue;
            }
        }
    }
    return vmIds;
}
Also used : NetworkInterface(com.microsoft.azure.management.network.NetworkInterface) CloudException(com.microsoft.azure.CloudException) HashSet(java.util.HashSet)

Example 2 with CloudException

use of com.microsoft.azure.CloudException in project azure-sdk-for-java by Azure.

the class RedisCacheOperationsTests method canCRUDRedisCache.

@Test
public void canCRUDRedisCache() throws Exception {
    // Create
    Creatable<ResourceGroup> resourceGroups = resourceManager.resourceGroups().define(RG_NAME_SECOND).withRegion(Region.US_CENTRAL);
    Creatable<RedisCache> redisCacheDefinition1 = redisManager.redisCaches().define(RR_NAME).withRegion(Region.ASIA_EAST).withNewResourceGroup(RG_NAME).withBasicSku();
    Creatable<RedisCache> redisCacheDefinition2 = redisManager.redisCaches().define(RR_NAME_SECOND).withRegion(Region.US_CENTRAL).withNewResourceGroup(resourceGroups).withPremiumSku().withShardCount(10).withPatchSchedule(DayOfWeek.SUNDAY, 10, Period.minutes(302));
    Creatable<RedisCache> redisCacheDefinition3 = redisManager.redisCaches().define(RR_NAME_THIRD).withRegion(Region.US_CENTRAL).withNewResourceGroup(resourceGroups).withPremiumSku(2).withRedisConfiguration("maxclients", "2").withNonSslPort();
    CreatedResources<RedisCache> batchRedisCaches = redisManager.redisCaches().create(redisCacheDefinition1, redisCacheDefinition2, redisCacheDefinition3);
    StorageAccount storageAccount = storageManager.storageAccounts().define(SA_NAME).withRegion(Region.US_CENTRAL).withExistingResourceGroup(RG_NAME_SECOND).create();
    RedisCache redisCache = batchRedisCaches.get(redisCacheDefinition1.key());
    RedisCache redisCachePremium = batchRedisCaches.get(redisCacheDefinition3.key());
    Assert.assertEquals(RG_NAME, redisCache.resourceGroupName());
    Assert.assertEquals(SkuName.BASIC, redisCache.sku().name());
    // List by Resource Group
    List<RedisCache> redisCaches = redisManager.redisCaches().listByResourceGroup(RG_NAME);
    boolean found = false;
    for (RedisCache existingRedisCache : redisCaches) {
        if (existingRedisCache.name().equals(RR_NAME)) {
            found = true;
        }
    }
    Assert.assertTrue(found);
    Assert.assertEquals(1, redisCaches.size());
    // List all Redis resources
    redisCaches = redisManager.redisCaches().list();
    found = false;
    for (RedisCache existingRedisCache : redisCaches) {
        if (existingRedisCache.name().equals(RR_NAME)) {
            found = true;
        }
    }
    Assert.assertTrue(found);
    Assert.assertTrue(redisCaches.size() >= 3);
    // Get
    RedisCache redisCacheGet = redisManager.redisCaches().getByResourceGroup(RG_NAME, RR_NAME);
    Assert.assertNotNull(redisCacheGet);
    Assert.assertEquals(redisCache.id(), redisCacheGet.id());
    Assert.assertEquals(redisCache.provisioningState(), redisCacheGet.provisioningState());
    // Get Keys
    RedisAccessKeys redisKeys = redisCache.keys();
    Assert.assertNotNull(redisKeys);
    Assert.assertNotNull(redisKeys.primaryKey());
    Assert.assertNotNull(redisKeys.secondaryKey());
    // Regen key
    RedisAccessKeys oldKeys = redisCache.refreshKeys();
    RedisAccessKeys updatedPrimaryKey = redisCache.regenerateKey(RedisKeyType.PRIMARY);
    RedisAccessKeys updatedSecondaryKey = redisCache.regenerateKey(RedisKeyType.SECONDARY);
    Assert.assertNotNull(oldKeys);
    Assert.assertNotNull(updatedPrimaryKey);
    Assert.assertNotNull(updatedSecondaryKey);
    Assert.assertNotEquals(oldKeys.primaryKey(), updatedPrimaryKey.primaryKey());
    Assert.assertEquals(oldKeys.secondaryKey(), updatedPrimaryKey.secondaryKey());
    Assert.assertNotEquals(oldKeys.secondaryKey(), updatedSecondaryKey.secondaryKey());
    Assert.assertNotEquals(updatedPrimaryKey.secondaryKey(), updatedSecondaryKey.secondaryKey());
    Assert.assertEquals(updatedPrimaryKey.primaryKey(), updatedSecondaryKey.primaryKey());
    // Update to STANDARD Sku from BASIC SKU
    redisCache = redisCache.update().withStandardSku().apply();
    Assert.assertEquals(SkuName.STANDARD, redisCache.sku().name());
    Assert.assertEquals(SkuFamily.C, redisCache.sku().family());
    try {
        redisCache.update().withBasicSku(1).apply();
        fail();
    } catch (CloudException e) {
    // expected since Sku downgrade is not supported
    }
    // Refresh
    redisCache.refresh();
    // delete
    redisManager.redisCaches().deleteById(redisCache.id());
    // Premium SKU Functionality
    RedisCachePremium premiumCache = redisCachePremium.asPremium();
    Assert.assertEquals(SkuFamily.P, premiumCache.sku().family());
    // Redis configuration update
    premiumCache.update().withRedisConfiguration("maxclients", "3").apply();
    premiumCache.update().withoutRedisConfiguration("maxclients").apply();
    premiumCache.update().withoutRedisConfiguration().apply();
    premiumCache.update().withPatchSchedule(DayOfWeek.MONDAY, 1).withPatchSchedule(DayOfWeek.TUESDAY, 5).apply();
    // Reboot
    premiumCache.forceReboot(RebootType.ALL_NODES);
    // Patch Schedule
    List<ScheduleEntry> patchSchedule = premiumCache.listPatchSchedules();
    Assert.assertEquals(2, patchSchedule.size());
    premiumCache.deletePatchSchedule();
    patchSchedule = redisManager.redisCaches().getById(premiumCache.id()).asPremium().listPatchSchedules();
    Assert.assertNull(patchSchedule);
// currently throws because SAS url of the container should be provided as
// {"error":{
//      "code":"InvalidRequestBody",
//      "message": "One of the SAS URIs provided could not be used for the following reason:
//                  The SAS token is poorly formatted.\r\nRequestID=ed105089-b93b-427e-9cbb-d78ed80d23b0",
//      "target":null}}
// com.microsoft.azure.CloudException: One of the SAS URIs provided could not be used for the following reason: The SAS token is poorly formatted.
/*premiumCache.exportData(storageAccount.name(),"snapshot1");

        premiumCache.importData(Arrays.asList("snapshot1"));*/
}
Also used : CloudException(com.microsoft.azure.CloudException) StorageAccount(com.microsoft.azure.management.storage.StorageAccount) ResourceGroup(com.microsoft.azure.management.resources.ResourceGroup) Test(org.junit.Test)

Example 3 with CloudException

use of com.microsoft.azure.CloudException in project azure-sdk-for-java by Azure.

the class PolicyTests method canCRUDPolicyAssignment.

@Test
@Ignore("Not authorized for scope - 'Microsoft.Authorization/policydefinitions/write'")
public void canCRUDPolicyAssignment() throws Exception {
    // Create definition
    PolicyDefinition definition = resourceManager.policyDefinitions().define("policy1").withPolicyRuleJson(policyRule).withPolicyType(PolicyType.CUSTOM).withDisplayName("My Policy").withDescription("This is my policy").create();
    // Create assignment
    ResourceGroup group = resourceManager.resourceGroups().define("rgassignment115095").withRegion(Region.UK_WEST).create();
    PolicyAssignment assignment = resourceManager.policyAssignments().define("assignment1").forResourceGroup(group).withPolicyDefinition(definition).withDisplayName("My Assignment").create();
    // Verify
    try {
        GenericResource resource = resourceManager.genericResources().define("webassignment115095").withRegion(Region.US_SOUTH_CENTRAL).withExistingResourceGroup(group).withResourceType("sites").withProviderNamespace("Microsoft.Web").withoutPlan().withApiVersion("2015-08-01").withParentResourcePath("").withProperties(new ObjectMapper().readTree("{\"SiteMode\":\"Limited\",\"ComputeMode\":\"Shared\"}")).create();
        fail();
    } catch (CloudException ce) {
        // expected
        Assert.assertTrue(ce.getMessage().contains("disallowed"));
    }
    // Delete
    resourceManager.resourceGroups().define(group.name());
    resourceManager.policyAssignments().deleteById(assignment.id());
    resourceManager.policyDefinitions().deleteById(definition.id());
}
Also used : CloudException(com.microsoft.azure.CloudException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 4 with CloudException

use of com.microsoft.azure.CloudException in project azure-sdk-for-java by Azure.

the class ServicePrincipalImpl method createResourceAsync.

@Override
public Observable<ServicePrincipal> createResourceAsync() {
    ActiveDirectoryApplication application = (ActiveDirectoryApplication) ((Object) super.createdModel(applicationCreatable.key()));
    createParameters.withAppId(application.applicationId());
    Observable<ServicePrincipal> sp = manager.inner().servicePrincipals().createAsync(createParameters).map(innerToFluentMap(this)).flatMap(new Func1<ServicePrincipal, Observable<ServicePrincipal>>() {

        @Override
        public Observable<ServicePrincipal> call(ServicePrincipal servicePrincipal) {
            return refreshCredentialsAsync();
        }
    });
    if (roles == null || roles.isEmpty()) {
        return sp;
    }
    return sp.flatMap(new Func1<ServicePrincipal, Observable<ServicePrincipal>>() {

        @Override
        public Observable<ServicePrincipal> call(final ServicePrincipal servicePrincipal) {
            return Observable.from(roles.entrySet()).flatMap(new Func1<Map.Entry<String, BuiltInRole>, Observable<?>>() {

                @Override
                public Observable<?> call(Map.Entry<String, BuiltInRole> role) {
                    return manager().roleAssignments().define(UUID.randomUUID().toString()).forServicePrincipal(servicePrincipal).withBuiltInRole(role.getValue()).withScope(role.getKey()).createAsync().retryWhen(new Func1<Observable<? extends Throwable>, Observable<?>>() {

                        @Override
                        public Observable<?> call(Observable<? extends Throwable> observable) {
                            return observable.zipWith(Observable.range(1, 30), new Func2<Throwable, Integer, Integer>() {

                                @Override
                                public Integer call(Throwable throwable, Integer integer) {
                                    if (throwable instanceof CloudException && ((CloudException) throwable).body().code().equalsIgnoreCase("PrincipalNotFound")) {
                                        return integer;
                                    } else {
                                        throw Exceptions.propagate(throwable);
                                    }
                                }
                            }).flatMap(new Func1<Integer, Observable<?>>() {

                                @Override
                                public Observable<?> call(Integer i) {
                                    return Observable.timer(i, TimeUnit.SECONDS);
                                }
                            });
                        }
                    });
                }
            }).last().map(new Func1<Object, ServicePrincipal>() {

                @Override
                public ServicePrincipal call(Object o) {
                    return servicePrincipal;
                }
            });
        }
    }).map(new Func1<ServicePrincipal, ServicePrincipal>() {

        @Override
        public ServicePrincipal call(ServicePrincipal servicePrincipal) {
            for (PasswordCredentialImpl<?> passwordCredential : passwordCredentials) {
                passwordCredential.exportAuthFile((ServicePrincipalImpl) servicePrincipal);
            }
            for (CertificateCredentialImpl<?> certificateCredential : certificateCredentials) {
                certificateCredential.exportAuthFile((ServicePrincipalImpl) servicePrincipal);
            }
            return servicePrincipal;
        }
    });
}
Also used : ServicePrincipal(com.microsoft.azure.management.graphrbac.ServicePrincipal) BuiltInRole(com.microsoft.azure.management.graphrbac.BuiltInRole) CloudException(com.microsoft.azure.CloudException) Observable(rx.Observable) ActiveDirectoryApplication(com.microsoft.azure.management.graphrbac.ActiveDirectoryApplication) Func1(rx.functions.Func1) HashMap(java.util.HashMap) Map(java.util.Map) Func2(rx.functions.Func2)

Example 5 with CloudException

use of com.microsoft.azure.CloudException in project azure-tools-for-java by Microsoft.

the class AzureDockerCertVaultOps method createOrUpdateVault.

public static void createOrUpdateVault(Azure azureClient, AzureDockerCertVault certVault, KeyVaultClient keyVaultClient) throws AzureDockerException {
    if (azureClient == null || keyVaultClient == null || certVault == null || certVault.name == null || certVault.hostName == null || certVault.resourceGroupName == null || certVault.region == null || (certVault.servicePrincipalId == null && certVault.userId == null)) {
        throw new AzureDockerException("Unexpected argument values; azureClient, vault name, hostName, resourceGroupName, region and userName/servicePrincipalId cannot be null");
    }
    try {
        Vault vault = null;
        try {
            if (certVault.id != null) {
                vault = azureClient.vaults().getById(certVault.id);
            } else {
                for (ResourceGroup group : azureClient.resourceGroups().list()) {
                    for (Vault vaultItem : azureClient.vaults().listByResourceGroup(group.name())) {
                        if (vaultItem.name().equals(certVault.name)) {
                            vault = vaultItem;
                            break;
                        }
                    }
                    if (vault != null)
                        break;
                }
            }
        } catch (CloudException e) {
            if (e.body().code().equals("ResourceNotFound") || e.body().code().equals("ResourceGroupNotFound")) {
                // Vault does no exist
                vault = null;
            } else {
                throw e;
            }
        }
        if (vault == null) {
            // Vault does not exist so this is the create op
            Vault.DefinitionStages.WithGroup withGroup = azureClient.vaults().define(certVault.name).withRegion(certVault.region);
            Vault.DefinitionStages.WithAccessPolicy withAccessPolicy;
            if (certVault.resourceGroupName.contains("@")) {
                // use existing resource group as selected by the user
                withAccessPolicy = withGroup.withExistingResourceGroup(certVault.resourceGroupName.split("@")[0]);
                certVault.resourceGroupName = certVault.resourceGroupName.split("@")[0];
            } else {
                withAccessPolicy = withGroup.withNewResourceGroup(certVault.resourceGroupName);
            }
            Vault.DefinitionStages.WithCreate withCreate = certVault.servicePrincipalId != null ? withAccessPolicy.defineAccessPolicy().forServicePrincipal(certVault.servicePrincipalId).allowSecretAllPermissions().attach() : withAccessPolicy.defineAccessPolicy().forUser(certVault.userId).allowSecretAllPermissions().attach();
            withCreate.withTag("dockerhost", "true").create();
        } else {
            // If original owner is an AD user, we might fail to set vault permissions
            try {
                setVaultPermissionsAll(azureClient, certVault);
            } catch (Exception e) {
                DefaultLoader.getUIHelper().logError(String.format("WARN: Can't set permissions to %s: %s\n", vault.vaultUri(), e.getMessage()), e);
            }
        }
        vault = azureClient.vaults().getByResourceGroup(certVault.resourceGroupName, certVault.name);
        String vaultUri = vault.vaultUri();
        // add a retry policy to make sure it got created and it is readable
        for (int sleepMs = 5000; sleepMs <= 2000000; sleepMs += 5000) {
            try {
                keyVaultClient.listSecrets(vaultUri);
                break;
            } catch (Exception e) {
                try {
                    if (DEBUG)
                        System.out.format("WARN: can't find %s (sleepMs: %d)\n", vaultUri, sleepMs);
                    if (DEBUG)
                        System.out.println(e.getMessage());
                    //            DefaultLoader.getUIHelper().logError(String.format("WARN: Can't connect to %s: %s (sleepMs: %d)\n", vaultUri, e.getMessage(), sleepMs), e);
                    try {
                        // Windows only - flush local DNS to reflect the new Key Vault URI
                        if (System.getProperty("os.name").toLowerCase().contains("win")) {
                            Process p = Runtime.getRuntime().exec("cmd /c ipconfig /flushdns");
                        }
                    } catch (Exception ignored) {
                    }
                    Thread.sleep(5000);
                } catch (Exception ignored) {
                }
            }
        }
        Map<String, String> secretsMap = getSecretsMap(certVault);
        // TODO: remove this after enabling parallel secrets write from above
        for (Map.Entry<String, String> entry : secretsMap.entrySet()) {
            try {
                if (entry.getValue() != null && !entry.getValue().isEmpty()) {
                    keyVaultClient.setSecret(new SetSecretRequest.Builder(vaultUri, entry.getKey(), entry.getValue()).build());
                }
            } catch (Exception e) {
                DefaultLoader.getUIHelper().logError(String.format("WARN: Unexpected error writing to %s: %s\n", vaultUri, e.getMessage()), e);
                System.out.format("ERROR: can't write %s secret %s: %s\n", vaultUri, entry.getKey(), entry.getValue());
                System.out.println(e.getMessage());
            }
        }
        if (keyVaultClient.listSecrets(vaultUri).size() > 0 && certVault.hostName != null && !certVault.hostName.isEmpty()) {
            keyVaultClient.setSecret(new SetSecretRequest.Builder(vaultUri, SECRETENTRY_DOCKERHOSTNAMES, certVault.hostName).build());
        } else {
            // something unexpected went wrong... delete the vault
            if (DEBUG)
                System.out.println("ERROR: something went wrong");
            throw new RuntimeException("Key vault has no secrets");
        }
    } catch (Exception e) {
        DefaultLoader.getUIHelper().logError(String.format("WARN: Unexpected error creating Azure Key Vault %s - %s\n", certVault.name, e.getMessage()), e);
        throw new AzureDockerException(e.getMessage());
    }
}
Also used : CloudException(com.microsoft.azure.CloudException) AzureDockerException(com.microsoft.azure.docker.model.AzureDockerException) CloudException(com.microsoft.azure.CloudException) AzureDockerException(com.microsoft.azure.docker.model.AzureDockerException) Vault(com.microsoft.azure.management.keyvault.Vault) AzureDockerCertVault(com.microsoft.azure.docker.model.AzureDockerCertVault) HashMap(java.util.HashMap) Map(java.util.Map) ResourceGroup(com.microsoft.azure.management.resources.ResourceGroup)

Aggregations

CloudException (com.microsoft.azure.CloudException)35 Test (org.junit.Test)20 ProductInner (fixtures.lro.implementation.ProductInner)17 SubProductInner (fixtures.lro.implementation.SubProductInner)6 ArrayList (java.util.ArrayList)6 CloudError (com.microsoft.azure.CloudError)5 AzureClient (com.sequenceiq.cloudbreak.cloud.azure.client.AzureClient)5 CloudConnectorException (com.sequenceiq.cloudbreak.cloud.exception.CloudConnectorException)5 HashMap (java.util.HashMap)5 CloudResource (com.sequenceiq.cloudbreak.cloud.model.CloudResource)4 AzureCredentialView (com.sequenceiq.cloudbreak.cloud.azure.view.AzureCredentialView)3 ActionWentFailException (com.sequenceiq.cloudbreak.service.Retry.ActionWentFailException)3 VirtualMachine (com.microsoft.azure.management.compute.VirtualMachine)2 AddressSpace (com.microsoft.azure.management.network.AddressSpace)2 NetworkInterface (com.microsoft.azure.management.network.NetworkInterface)2 SubnetInner (com.microsoft.azure.management.network.implementation.SubnetInner)2 VirtualNetworkInner (com.microsoft.azure.management.network.implementation.VirtualNetworkInner)2 Deployment (com.microsoft.azure.management.resources.Deployment)2 ResourceGroup (com.microsoft.azure.management.resources.ResourceGroup)2 Region (com.microsoft.azure.management.resources.fluentcore.arm.Region)2