Search in sources :

Example 6 with ResourceGroup

use of com.microsoft.azure.management.resources.ResourceGroup in project azure-tools-for-java by Microsoft.

the class CreateArmStorageAccountForm method createStorageAccount.

private boolean createStorageAccount() {
    try {
        boolean isNewResourceGroup = createNewRadioButton.isSelected();
        final String resourceGroupName = isNewResourceGroup ? resourceGrpField.getText() : resourceGrpCombo.getSelectedItem().toString();
        AzureSDKManager.createStorageAccount(((SubscriptionDetail) subscriptionComboBox.getSelectedItem()).getSubscriptionId(), nameTextField.getText(), ((Location) regionComboBox.getSelectedItem()).name(), isNewResourceGroup, resourceGroupName, (Kind) accoountKindCombo.getSelectedItem(), (AccessTier) accessTeirComboBox.getSelectedItem(), (Boolean) encriptonComboBox.getSelectedItem(), replicationComboBox.getSelectedItem().toString());
        // update resource groups cache if new resource group was created when creating storage account
        if (createNewRadioButton.isSelected()) {
            AzureManager azureManager = AuthMethodManager.getInstance().getAzureManager();
            // not signed in; does not matter what we return as storage account already created
            if (azureManager == null) {
                return true;
            }
            SubscriptionDetail subscriptionDetail = (SubscriptionDetail) subscriptionComboBox.getSelectedItem();
            ResourceGroup rg = azureManager.getAzure(subscriptionDetail.getSubscriptionId()).resourceGroups().getByName(resourceGroupName);
            AzureModelController.addNewResourceGroup(subscriptionDetail, rg);
        }
        DefaultLoader.getIdeHelper().invokeLater(new Runnable() {

            @Override
            public void run() {
                if (onCreate != null) {
                    onCreate.run();
                }
            }
        });
        return true;
    } catch (Exception e) {
        String msg = "An error occurred while attempting to create the specified storage account in subscription " + ((SubscriptionDetail) subscriptionComboBox.getSelectedItem()).getSubscriptionId() + ".\n" + String.format(message("webappExpMsg"), e.getMessage());
        DefaultLoader.getIdeHelper().invokeAndWait(() -> DefaultLoader.getUIHelper().showException(msg, e, message("errTtl"), false, true));
        AzurePlugin.log(msg, e);
    }
    return false;
}
Also used : AzureManager(com.microsoft.azuretools.sdkmanage.AzureManager) SubscriptionDetail(com.microsoft.azuretools.authmanage.models.SubscriptionDetail) ResourceGroup(com.microsoft.azure.management.resources.ResourceGroup)

Example 7 with ResourceGroup

use of com.microsoft.azure.management.resources.ResourceGroup in project azure-tools-for-java by Microsoft.

the class SettingsStep method onFinish.

@Override
public boolean onFinish() {
    final boolean isNewResourceGroup = createNewRadioButton.isSelected();
    final String resourceGroupName = isNewResourceGroup ? resourceGrpField.getText() : resourceGrpCombo.getSelectedItem().toString();
    ProgressManager.getInstance().run(new Task.Backgroundable(project, "Creating virtual machine " + model.getName() + "...", false) {

        @Override
        public void run(@NotNull ProgressIndicator progressIndicator) {
            progressIndicator.setIndeterminate(true);
            try {
                String certificate = model.getCertificate();
                byte[] certData = new byte[0];
                if (!certificate.isEmpty()) {
                    File certFile = new File(certificate);
                    if (certFile.exists()) {
                        FileInputStream certStream = null;
                        try {
                            certStream = new FileInputStream(certFile);
                            certData = new byte[(int) certFile.length()];
                            if (certStream.read(certData) != certData.length) {
                                throw new Exception("Unable to process certificate: stream longer than informed size.");
                            }
                        } finally {
                            if (certStream != null) {
                                try {
                                    certStream.close();
                                } catch (IOException ignored) {
                                }
                            }
                        }
                    }
                }
                //                    for (StorageAccount account : AzureManagerImpl.getManager(project).getStorageAccounts(
                //                            model.getSubscription().getId(), true)) {
                //                        if (account.getName().equals(storageAccount.getName())) {
                //                            storageAccount = account;
                //                            break;
                //                        }
                //                    }
                final com.microsoft.azure.management.compute.VirtualMachine vm = AzureSDKManager.createVirtualMachine(model.getSubscription().getSubscriptionId(), model.getName(), resourceGroupName, createNewRadioButton.isSelected(), model.getSize(), model.getRegion().name(), model.getVirtualMachineImage(), model.getKnownMachineImage(), model.isKnownMachineImage(), model.getStorageAccount(), model.getNewStorageAccount(), model.isWithNewStorageAccount(), model.getVirtualNetwork(), model.getNewNetwork(), model.isWithNewNetwork(), model.getSubnet(), model.getPublicIpAddress(), model.isWithNewPip(), model.getAvailabilitySet(), model.isWithNewAvailabilitySet(), model.getUserName(), model.getPassword(), certData.length > 0 ? new String(certData) : null);
                // update resource groups cache if new resource group was created when creating vm
                ResourceGroup rg = null;
                if (createNewRadioButton.isSelected()) {
                    rg = azure.resourceGroups().getByName(resourceGroupName);
                    AzureModelController.addNewResourceGroup(model.getSubscription(), rg);
                }
                if (model.isWithNewStorageAccount() && model.getNewStorageAccount().isNewResourceGroup() && (rg == null || !rg.name().equals(model.getNewStorageAccount().getResourceGroupName()))) {
                    rg = azure.resourceGroups().getByName(model.getNewStorageAccount().getResourceGroupName());
                    AzureModelController.addNewResourceGroup(model.getSubscription(), rg);
                }
                ApplicationManager.getApplication().invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            parent.addChildNode(new com.microsoft.tooling.msservices.serviceexplorer.azure.vmarm.VMNode(parent, model.getSubscription().getSubscriptionId(), vm));
                        } catch (AzureCmdException e) {
                            String msg = "An error occurred while attempting to refresh the list of virtual machines.";
                            DefaultLoader.getUIHelper().showException(msg, e, "Azure Services Explorer - Error Refreshing VM List", false, true);
                            AzurePlugin.log(msg, e);
                        }
                    }
                });
            } catch (Exception e) {
                String msg = "An error occurred while attempting to create the specified virtual machine." + "<br>" + String.format(message("webappExpMsg"), e.getMessage());
                DefaultLoader.getUIHelper().showException(msg, e, message("errTtl"), false, true);
                AzurePlugin.log(msg, e);
            }
        }
    });
    return super.onFinish();
}
Also used : Task(com.intellij.openapi.progress.Task) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException) AzureCmdException(com.microsoft.azuretools.azurecommons.helpers.AzureCmdException) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) AzureCmdException(com.microsoft.azuretools.azurecommons.helpers.AzureCmdException) File(java.io.File) ResourceGroup(com.microsoft.azure.management.resources.ResourceGroup)

Example 8 with ResourceGroup

use of com.microsoft.azure.management.resources.ResourceGroup in project azure-tools-for-java by Microsoft.

the class AzureDockerVMOps method createDockerHostVM.

public static VirtualMachine createDockerHostVM(Azure azureClient, DockerHost newHost) throws AzureDockerException {
    try {
        String resourceGroupName;
        if (newHost.hostVM.resourceGroupName.contains("@")) {
            // Existing resource group
            resourceGroupName = newHost.hostVM.resourceGroupName.split("@")[0];
        } else {
            // Create a new resource group
            resourceGroupName = newHost.hostVM.resourceGroupName;
            ResourceGroup resourceGroup = azureClient.resourceGroups().define(newHost.hostVM.resourceGroupName).withRegion(newHost.hostVM.region).create();
        }
        Network vnet;
        if (newHost.hostVM.vnetName.contains("@")) {
            // reuse existing virtual network
            String vnetName = newHost.hostVM.vnetName.split("@")[0];
            String vnetResourceGroupName = newHost.hostVM.vnetName.split("@")[1];
            vnet = azureClient.networks().getByResourceGroup(vnetResourceGroupName, vnetName);
        } else {
            // create a new virtual network (a subnet will be automatically created as part of this)
            vnet = azureClient.networks().define(newHost.hostVM.vnetName).withRegion(newHost.hostVM.region).withExistingResourceGroup(resourceGroupName).withAddressSpace(newHost.hostVM.vnetAddressSpace).create();
        }
        VirtualMachine.DefinitionStages.WithLinuxRootPasswordOrPublicKeyManagedOrUnmanaged defStage1 = azureClient.virtualMachines().define(newHost.hostVM.name).withRegion(newHost.hostVM.region).withExistingResourceGroup(resourceGroupName).withExistingPrimaryNetwork(vnet).withSubnet(newHost.hostVM.subnetName).withPrimaryPrivateIPAddressDynamic().withNewPrimaryPublicIPAddress(newHost.hostVM.name).withSpecificLinuxImageVersion(newHost.hostVM.osHost.imageReference()).withRootUsername(newHost.certVault.vmUsername);
        VirtualMachine.DefinitionStages.WithLinuxCreateManagedOrUnmanaged defStage2;
        if (newHost.hasPwdLogIn && newHost.hasSSHLogIn) {
            defStage2 = defStage1.withRootPassword(newHost.certVault.vmPwd).withSsh(newHost.certVault.sshPubKey);
        } else {
            defStage2 = (newHost.hasSSHLogIn) ? defStage1.withSsh(newHost.certVault.sshPubKey) : defStage1.withRootPassword(newHost.certVault.vmPwd);
        }
        // todo - temporary not using managed disks as we do not support them yet for docker hosts
        VirtualMachine.DefinitionStages.WithCreate defStage3 = null;
        if (newHost.hostVM.storageAccountName.contains("@")) {
            // Existing storage account
            for (StorageAccount item : azureClient.storageAccounts().list()) {
                String storageAccountName = item.name() + "@";
                if (storageAccountName.equals(newHost.hostVM.storageAccountName)) {
                    defStage3 = defStage2.withUnmanagedDisks().withExistingStorageAccount(item);
                    break;
                }
            }
            if (defStage3 == null)
                throw new AzureDockerException("Can't find storage account " + newHost.hostVM.storageAccountName.split("@")[0]);
        } else {
            defStage3 = defStage2.withUnmanagedDisks().withNewStorageAccount(newHost.hostVM.storageAccountName);
        }
        defStage3 = defStage3.withSize(newHost.hostVM.vmSize);
        defStage3 = defStage3.withTag("dockerhost", newHost.port);
        if (newHost.hasKeyVault) {
            defStage3 = defStage3.withTag("dockervault", newHost.certVault.name);
        }
        return defStage3.create();
    } catch (Exception e) {
        throw new AzureDockerException(e.getMessage(), e);
    }
}
Also used : StorageAccount(com.microsoft.azure.management.storage.StorageAccount) ResourceGroup(com.microsoft.azure.management.resources.ResourceGroup)

Example 9 with ResourceGroup

use of com.microsoft.azure.management.resources.ResourceGroup 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)

Example 10 with ResourceGroup

use of com.microsoft.azure.management.resources.ResourceGroup in project azure-tools-for-java by Microsoft.

the class WebappsModule method fillWebappsNodes.

private void fillWebappsNodes() {
    Map<SubscriptionDetail, List<ResourceGroup>> srgMap = AzureModel.getInstance().getSubscriptionToResourceGroupMap();
    Map<ResourceGroup, List<WebApp>> rgwaMap = AzureModel.getInstance().getResourceGroupToWebAppMap();
    if (srgMap != null) {
        for (SubscriptionDetail sd : srgMap.keySet()) {
            if (!sd.isSelected())
                continue;
            for (ResourceGroup rg : srgMap.get(sd)) {
                for (WebApp webApp : rgwaMap.get(rg)) {
                    addChildNode(new WebappNode(this, webApp, rg, RUN_STATUS.equalsIgnoreCase(webApp.inner().state()) ? WEB_RUN_ICON : WEB_STOP_ICON));
                }
            }
        }
    }
}
Also used : SubscriptionDetail(com.microsoft.azuretools.authmanage.models.SubscriptionDetail) List(java.util.List) ResourceGroup(com.microsoft.azure.management.resources.ResourceGroup) WebApp(com.microsoft.azure.management.appservice.WebApp)

Aggregations

ResourceGroup (com.microsoft.azure.management.resources.ResourceGroup)53 Test (org.junit.Test)22 Region (com.microsoft.azure.management.resources.fluentcore.arm.Region)13 SubscriptionDetail (com.microsoft.azuretools.authmanage.models.SubscriptionDetail)12 ArrayList (java.util.ArrayList)10 Network (com.microsoft.azure.management.network.Network)9 StorageAccount (com.microsoft.azure.management.storage.StorageAccount)9 VirtualMachine (com.microsoft.azure.management.compute.VirtualMachine)8 Creatable (com.microsoft.azure.management.resources.fluentcore.model.Creatable)7 AzureManager (com.microsoft.azuretools.sdkmanage.AzureManager)7 Azure (com.microsoft.azure.management.Azure)6 AppServicePlan (com.microsoft.azure.management.appservice.AppServicePlan)6 WebApp (com.microsoft.azure.management.appservice.WebApp)6 HashMap (java.util.HashMap)5 StopWatch (org.apache.commons.lang3.time.StopWatch)5 PublicIPAddress (com.microsoft.azure.management.network.PublicIPAddress)4 Location (com.microsoft.azure.management.resources.Location)4 CloudException (com.microsoft.azure.CloudException)3 Period (org.joda.time.Period)3 ApplicationGateway (com.microsoft.azure.management.network.ApplicationGateway)2