Search in sources :

Example 36 with Azure

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

the class AzureSDKManager method createVirtualMachine.

public static VirtualMachine createVirtualMachine(String subscriptionId, @NotNull String name, @NotNull String resourceGroup, boolean withNewResourceGroup, @NotNull String size, @NotNull String region, final VirtualMachineImage vmImage, Object knownImage, boolean isKnownImage, final StorageAccount storageAccount, com.microsoft.tooling.msservices.model.storage.StorageAccount newStorageAccount, boolean withNewStorageAccount, final Network network, VirtualNetwork newNetwork, boolean withNewNetwork, @NotNull String subnet, @Nullable PublicIPAddress pip, boolean withNewPip, @Nullable AvailabilitySet availabilitySet, boolean withNewAvailabilitySet, @NotNull final String username, @Nullable final String password, @Nullable String publicKey) throws Exception {
    AzureManager azureManager = AuthMethodManager.getInstance().getAzureManager();
    Azure azure = azureManager.getAzure(subscriptionId);
    boolean isWindows;
    if (isKnownImage) {
        isWindows = knownImage instanceof KnownWindowsVirtualMachineImage;
    } else {
        isWindows = vmImage.osDiskImage().operatingSystem().equals(OperatingSystemTypes.WINDOWS);
    }
    // ------ Resource Group ------
    VirtualMachine.DefinitionStages.WithGroup withGroup = azure.virtualMachines().define(name).withRegion(region);
    Creatable<ResourceGroup> newResourceGroup = null;
    VirtualMachine.DefinitionStages.WithNetwork withNetwork;
    if (withNewResourceGroup) {
        newResourceGroup = azure.resourceGroups().define(resourceGroup).withRegion(region);
        withNetwork = withGroup.withNewResourceGroup(newResourceGroup);
    } else {
        withNetwork = withGroup.withExistingResourceGroup(resourceGroup);
    }
    // ------ Virtual Network -----
    VirtualMachine.DefinitionStages.WithPublicIPAddress withPublicIpAddress;
    if (withNewNetwork) {
        Network.DefinitionStages.WithGroup networkWithGroup = azure.networks().define(newNetwork.name).withRegion(region);
        Creatable<Network> newVirtualNetwork;
        if (withNewResourceGroup) {
            newVirtualNetwork = networkWithGroup.withNewResourceGroup(newResourceGroup).withAddressSpace(newNetwork.addressSpace).withSubnet(newNetwork.subnet.name, newNetwork.subnet.addressSpace);
        } else {
            newVirtualNetwork = networkWithGroup.withExistingResourceGroup(resourceGroup).withAddressSpace(newNetwork.addressSpace).withSubnet(newNetwork.subnet.name, newNetwork.subnet.addressSpace);
        }
        withPublicIpAddress = withNetwork.withNewPrimaryNetwork(newVirtualNetwork).withPrimaryPrivateIPAddressDynamic();
    //            withPublicIpAddress = withNetwork.withNewPrimaryNetwork("10.0.0.0/28").
    //                    .withPrimaryPrivateIpAddressDynamic();
    } else {
        withPublicIpAddress = withNetwork.withExistingPrimaryNetwork(network).withSubnet(subnet).withPrimaryPrivateIPAddressDynamic();
    }
    // ------ Public IP Address------
    VirtualMachine.DefinitionStages.WithOS withOS;
    if (pip == null) {
        if (withNewPip) {
            withOS = withPublicIpAddress.withNewPrimaryPublicIPAddress(name + "pip");
        } else {
            withOS = withPublicIpAddress.withoutPrimaryPublicIPAddress();
        }
    } else {
        withOS = withPublicIpAddress.withExistingPrimaryPublicIPAddress(pip);
    }
    // ------ OS and credentials -----
    VirtualMachine.DefinitionStages.WithCreate withCreate;
    if (isWindows) {
        VirtualMachine.DefinitionStages.WithWindowsAdminUsernameManagedOrUnmanaged withWindowsAdminUsername;
        if (isKnownImage) {
            withWindowsAdminUsername = withOS.withPopularWindowsImage((KnownWindowsVirtualMachineImage) knownImage);
        } else {
            withWindowsAdminUsername = withOS.withSpecificWindowsImageVersion(vmImage.imageReference());
        }
        withCreate = withWindowsAdminUsername.withAdminUsername(username).withAdminPassword(password).withUnmanagedDisks();
    } else {
        VirtualMachine.DefinitionStages.WithLinuxRootPasswordOrPublicKeyManagedOrUnmanaged withLinuxRootPasswordOrPublicKey;
        if (isKnownImage) {
            withLinuxRootPasswordOrPublicKey = withOS.withPopularLinuxImage((KnownLinuxVirtualMachineImage) knownImage).withRootUsername(username);
        } else {
            withLinuxRootPasswordOrPublicKey = withOS.withSpecificLinuxImageVersion(vmImage.imageReference()).withRootUsername(username);
        }
        VirtualMachine.DefinitionStages.WithLinuxCreateManagedOrUnmanaged withLinuxCreate;
        // we assume either password or public key is not empty
        if (password != null && !password.isEmpty()) {
            withLinuxCreate = withLinuxRootPasswordOrPublicKey.withRootPassword(password);
            if (publicKey != null) {
                withLinuxCreate = withLinuxCreate.withSsh(publicKey);
            }
        } else {
            withLinuxCreate = withLinuxRootPasswordOrPublicKey.withSsh(publicKey);
        }
        withCreate = withLinuxCreate.withUnmanagedDisks();
    }
    withCreate = withCreate.withSize(size);
    // ---- Storage Account --------
    if (withNewStorageAccount) {
        StorageAccount.DefinitionStages.WithCreate newAccount;
        StorageAccount.DefinitionStages.WithGroup withGroupAccount = azure.storageAccounts().define(newStorageAccount.getName()).withRegion(newStorageAccount.getLocation());
        if (newStorageAccount.isNewResourceGroup()) {
            newAccount = withGroupAccount.withNewResourceGroup(newStorageAccount.getResourceGroupName());
        } else {
            newAccount = withGroupAccount.withExistingResourceGroup(newStorageAccount.getResourceGroupName());
        }
        // only general purpose accounts used to create vm
        newAccount.withGeneralPurposeAccountKind().withSku(SkuName.fromString(newStorageAccount.getType()));
        withCreate = withCreate.withNewStorageAccount(newAccount);
    } else {
        withCreate = withCreate.withExistingStorageAccount(storageAccount);
    }
    if (withNewAvailabilitySet) {
        withCreate = withCreate.withNewAvailabilitySet(name + "as");
    } else if (availabilitySet != null) {
        withCreate = withCreate.withExistingAvailabilitySet(availabilitySet);
    }
    return withCreate.create();
}
Also used : Azure(com.microsoft.azure.management.Azure) AzureManager(com.microsoft.azuretools.sdkmanage.AzureManager) KnownWindowsVirtualMachineImage(com.microsoft.azure.management.compute.KnownWindowsVirtualMachineImage) Network(com.microsoft.azure.management.network.Network) VirtualNetwork(com.microsoft.tooling.msservices.model.vm.VirtualNetwork) ResourceGroup(com.microsoft.azure.management.resources.ResourceGroup)

Example 37 with Azure

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

the class AzureSDKManager method createStorageAccount.

public static StorageAccount createStorageAccount(String subscriptionId, String name, String region, boolean newResourceGroup, String resourceGroup, Kind kind, AccessTier accessTier, boolean enableEncription, String skuName) throws Exception {
    AzureManager azureManager = AuthMethodManager.getInstance().getAzureManager();
    Azure azure = azureManager.getAzure(subscriptionId);
    StorageAccount.DefinitionStages.WithGroup newStorageAccountBlank = azure.storageAccounts().define(name).withRegion(region);
    StorageAccount.DefinitionStages.WithCreate newStorageAccountWithGroup;
    if (newResourceGroup) {
        newStorageAccountWithGroup = newStorageAccountBlank.withNewResourceGroup(resourceGroup);
    } else {
        newStorageAccountWithGroup = newStorageAccountBlank.withExistingResourceGroup(resourceGroup);
    }
    if (kind == Kind.BLOB_STORAGE) {
        newStorageAccountWithGroup = newStorageAccountWithGroup.withBlobStorageAccountKind().withAccessTier(accessTier);
    } else {
        newStorageAccountWithGroup = newStorageAccountWithGroup.withGeneralPurposeAccountKind();
    }
    if (enableEncription) {
        newStorageAccountWithGroup = newStorageAccountWithGroup.withEncryption(new Encryption());
    }
    return newStorageAccountWithGroup.withSku(SkuName.fromString(skuName)).create();
}
Also used : Azure(com.microsoft.azure.management.Azure) AzureManager(com.microsoft.azuretools.sdkmanage.AzureManager) Encryption(com.microsoft.azure.management.storage.Encryption)

Example 38 with Azure

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

the class RedisCacheModule method refreshItems.

@Override
protected void refreshItems() throws AzureCmdException {
    List<Pair<String, String>> failedSubscriptions = new ArrayList<>();
    try {
        AzureManager azureManager = AuthMethodManager.getInstance().getAzureManager();
        // not signed in
        if (azureManager == null) {
            return;
        }
        SubscriptionManager subscriptionManager = azureManager.getSubscriptionManager();
        Set<String> sidList = subscriptionManager.getAccountSidList();
        for (String sid : sidList) {
            try {
                Azure azure = azureManager.getAzure(sid);
                for (RedisCache cache : azure.redisCaches().list()) {
                    addChildNode(new RedisCacheNode(this, sid, cache));
                }
            } catch (Exception ex) {
                failedSubscriptions.add(new ImmutablePair<>(sid, ex.getMessage()));
                continue;
            }
        }
    } catch (Exception ex) {
        DefaultLoader.getUIHelper().logError("An error occurred when trying to load Redis Caches\n\n" + ex.getMessage(), ex);
    }
    if (!failedSubscriptions.isEmpty()) {
        StringBuilder errorMessage = new StringBuilder("An error occurred when trying to load Redis Caches for the subscriptions:\n\n");
        for (Pair error : failedSubscriptions) {
            errorMessage.append(error.getKey()).append(": ").append(error.getValue()).append("\n");
        }
        DefaultLoader.getUIHelper().logError("An error occurred when trying to load Redis Caches\n\n" + errorMessage.toString(), null);
    }
}
Also used : Azure(com.microsoft.azure.management.Azure) RedisCache(com.microsoft.azure.management.redis.RedisCache) AzureManager(com.microsoft.azuretools.sdkmanage.AzureManager) ArrayList(java.util.ArrayList) SubscriptionManager(com.microsoft.azuretools.authmanage.SubscriptionManager) AzureCmdException(com.microsoft.azuretools.azurecommons.helpers.AzureCmdException) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) Pair(org.apache.commons.lang3.tuple.Pair)

Example 39 with Azure

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

the class StorageModule method refreshItems.

@Override
protected void refreshItems() throws AzureCmdException {
    List<Pair<String, String>> failedSubscriptions = new ArrayList<>();
    try {
        AzureManager azureManager = AuthMethodManager.getInstance().getAzureManager();
        // not signed in
        if (azureManager == null) {
            return;
        }
        SubscriptionManager subscriptionManager = azureManager.getSubscriptionManager();
        Set<String> sidList = subscriptionManager.getAccountSidList();
        for (String sid : sidList) {
            try {
                Azure azure = azureManager.getAzure(sid);
                List<com.microsoft.azure.management.storage.StorageAccount> storageAccounts = azure.storageAccounts().list();
                for (StorageAccount sm : storageAccounts) {
                    addChildNode(new StorageNode(this, sid, sm));
                }
            } catch (Exception ex) {
                failedSubscriptions.add(new ImmutablePair<>(sid, ex.getMessage()));
                continue;
            }
        }
    } catch (Exception ex) {
        DefaultLoader.getUIHelper().logError("An error occurred when trying to load Storage Accounts\n\n" + ex.getMessage(), ex);
    }
    // load External Accounts
    for (ClientStorageAccount clientStorageAccount : ExternalStorageHelper.getList(getProject())) {
        ClientStorageAccount storageAccount = StorageClientSDKManager.getManager().getStorageAccount(clientStorageAccount.getConnectionString());
    //            addChildNode(new ExternalStorageNode(this, storageAccount));
    }
    if (!failedSubscriptions.isEmpty()) {
        StringBuilder errorMessage = new StringBuilder("An error occurred when trying to load Storage Accounts for the subscriptions:\n\n");
        for (Pair error : failedSubscriptions) {
            errorMessage.append(error.getKey()).append(": ").append(error.getValue()).append("\n");
        }
        DefaultLoader.getUIHelper().logError("An error occurred when trying to load Storage Accounts\n\n" + errorMessage.toString(), null);
    }
}
Also used : Azure(com.microsoft.azure.management.Azure) AzureManager(com.microsoft.azuretools.sdkmanage.AzureManager) ArrayList(java.util.ArrayList) ClientStorageAccount(com.microsoft.tooling.msservices.model.storage.ClientStorageAccount) SubscriptionManager(com.microsoft.azuretools.authmanage.SubscriptionManager) AzureCmdException(com.microsoft.azuretools.azurecommons.helpers.AzureCmdException) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) StorageAccount(com.microsoft.azure.management.storage.StorageAccount) ClientStorageAccount(com.microsoft.tooling.msservices.model.storage.ClientStorageAccount) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) Pair(org.apache.commons.lang3.tuple.Pair)

Example 40 with Azure

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

the class AzureNewDockerWizard method createHost.

public void createHost() {
    AzureDockerPreferredSettings dockerPreferredSettings = dockerManager.getDockerPreferredSettings();
    if (dockerPreferredSettings == null) {
        dockerPreferredSettings = new AzureDockerPreferredSettings();
    }
    dockerPreferredSettings.dockerApiName = newHost.apiUrl;
    dockerPreferredSettings.region = newHost.hostVM.region;
    dockerPreferredSettings.vmSize = newHost.hostVM.vmSize;
    dockerPreferredSettings.vmOS = newHost.hostOSType.name();
    dockerManager.setDockerPreferredSettings(dockerPreferredSettings);
    Job createDockerHostJob = new Job("Creating Docker virtual machine " + newHost.name) {

        @Override
        protected IStatus run(IProgressMonitor progressMonitor) {
            progressMonitor.beginTask("start task", 100);
            try {
                DockerHost dockerHost = newHost;
                progressMonitor.subTask(String.format("Reading subscription details for Docker host %s ...", dockerHost.apiUrl));
                progressMonitor.worked(5);
                Azure azureClient = dockerManager.getSubscriptionsMap().get(dockerHost.sid).azureClient;
                if (progressMonitor.isCanceled()) {
                    if (displayWarningOnCreateHostCancelAction() == 0) {
                        progressMonitor.done();
                        return Status.CANCEL_STATUS;
                    }
                }
                progressMonitor.subTask(String.format("Creating new virtual machine %s ...", dockerHost.name));
                progressMonitor.worked(10);
                if (AzureDockerUtils.DEBUG)
                    System.out.println("Creating new virtual machine: " + new Date().toString());
                AzureDockerVMOps.createDockerHostVM(azureClient, dockerHost);
                if (AzureDockerUtils.DEBUG)
                    System.out.println("Done creating new virtual machine: " + new Date().toString());
                if (progressMonitor.isCanceled()) {
                    if (displayWarningOnCreateHostCancelAction() == 0) {
                        progressMonitor.done();
                        return Status.CANCEL_STATUS;
                    }
                }
                progressMonitor.subTask("Getting the new Docker virtual machines details...");
                progressMonitor.worked(5);
                if (AzureDockerUtils.DEBUG)
                    System.out.println("Getting the new Docker hosts details: " + new Date().toString());
                VirtualMachine vm = azureClient.virtualMachines().getByResourceGroup(dockerHost.hostVM.resourceGroupName, dockerHost.hostVM.name);
                if (vm != null) {
                    DockerHost updatedHost = AzureDockerVMOps.getDockerHost(vm, dockerManager.getDockerVaultsMap());
                    if (updatedHost != null) {
                        dockerHost.hostVM = updatedHost.hostVM;
                        dockerHost.apiUrl = updatedHost.apiUrl;
                    }
                }
                if (AzureDockerUtils.DEBUG)
                    System.out.println("Done getting the new Docker hosts details: " + new Date().toString());
                if (progressMonitor.isCanceled()) {
                    if (displayWarningOnCreateHostCancelAction() == 0) {
                        progressMonitor.done();
                        return Status.CANCEL_STATUS;
                    }
                }
                progressMonitor.subTask(String.format("Waiting for virtual machine %s to be up...", dockerHost.name));
                progressMonitor.worked(55);
                if (AzureDockerUtils.DEBUG)
                    System.out.println("Waiting for virtual machine to be up: " + new Date().toString());
                AzureDockerVMOps.waitForVirtualMachineStartup(azureClient, dockerHost);
                if (AzureDockerUtils.DEBUG)
                    System.out.println("Done Waiting for virtual machine to be up: " + new Date().toString());
                if (progressMonitor.isCanceled()) {
                    if (displayWarningOnCreateHostCancelAction() == 0) {
                        progressMonitor.done();
                        return Status.CANCEL_STATUS;
                    }
                }
                progressMonitor.subTask(String.format("Configuring Docker service for %s ...", dockerHost.apiUrl));
                progressMonitor.worked(15);
                if (AzureDockerUtils.DEBUG)
                    System.out.println("Configuring Docker host: " + new Date().toString());
                AzureDockerVMOps.installDocker(dockerHost);
                if (AzureDockerUtils.DEBUG)
                    System.out.println("Done configuring Docker host: " + new Date().toString());
                if (AzureDockerUtils.DEBUG)
                    System.out.println("Finished setting up Docker host");
                if (progressMonitor.isCanceled()) {
                    if (displayWarningOnCreateHostCancelAction() == 0) {
                        progressMonitor.done();
                        return Status.CANCEL_STATUS;
                    }
                }
                if (dockerHost.certVault != null && dockerHost.certVault.hostName != null) {
                    AzureDockerUIResources.createDockerKeyVault(dockerHost, dockerManager);
                }
                progressMonitor.subTask("Refreshing the Docker virtual machines details...");
                progressMonitor.worked(5);
                if (AzureDockerUtils.DEBUG)
                    System.out.println("Refreshing Docker hosts details: " + new Date().toString());
                vm = azureClient.virtualMachines().getByResourceGroup(dockerHost.hostVM.resourceGroupName, dockerHost.hostVM.name);
                if (vm != null) {
                    DockerHost updatedHost = AzureDockerVMOps.getDockerHost(vm, dockerManager.getDockerVaultsMap());
                    if (updatedHost != null) {
                        updatedHost.sid = dockerHost.sid;
                        updatedHost.hostVM.sid = dockerHost.hostVM.sid;
                        if (updatedHost.certVault == null) {
                            updatedHost.certVault = dockerHost.certVault;
                            updatedHost.hasPwdLogIn = dockerHost.hasPwdLogIn;
                            updatedHost.hasSSHLogIn = dockerHost.hasSSHLogIn;
                            updatedHost.isTLSSecured = dockerHost.isTLSSecured;
                        }
                        dockerManager.addDockerHostDetails(updatedHost);
                        if (AzureUIRefreshCore.listeners != null) {
                            AzureUIRefreshCore.execute(new AzureUIRefreshEvent(AzureUIRefreshEvent.EventType.ADD, updatedHost));
                        }
                    }
                }
                if (AzureDockerUtils.DEBUG)
                    System.out.println("Done refreshing Docker hosts details: " + new Date().toString());
                if (progressMonitor.isCanceled()) {
                    if (displayWarningOnCreateHostCancelAction() == 0) {
                        progressMonitor.done();
                        return Status.CANCEL_STATUS;
                    }
                }
                progressMonitor.done();
                return Status.OK_STATUS;
            } catch (Exception e) {
                String msg = "An error occurred while attempting to create Docker host." + "\n" + e.getMessage();
                log.log(Level.SEVERE, "createHost: " + msg, e);
                e.printStackTrace();
                return Status.CANCEL_STATUS;
            }
        //				progressMonitor.subTask("");
        //				progressMonitor.worked(1);
        //				if (progressMonitor.isCanceled()) {
        //					if (displayWarningOnCreateHostCancelAction() == 0) {
        //						progressMonitor.done();
        //						return Status.CANCEL_STATUS;
        //					}
        //				}
        //
        //				for (int i = 0; i < 10; i++) {
        //					try {
        //						Thread.sleep(3000);
        //						progressMonitor.subTask("doing " + i);
        //						// Report that 10 units are done
        //						progressMonitor.worked(10);
        //					} catch (InterruptedException e1) {
        //						e1.printStackTrace();
        //					}
        //				}
        }
    };
    createDockerHostJob.schedule();
//    	DefaultLoader.getIdeHelper().runInBackground(null, "Creating Docker virtual machine " + newHost.name + "...", false, true, "Creating Docker virtual machine " + newHost.name + "...", new Runnable() {
//            @Override
//            public void run() {
//                DefaultLoader.getIdeHelper().invokeLater(new Runnable() {
//                    @Override
//                    public void run() {
//                    	
//                    }
//                });
//            }
//        });
}
Also used : IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) Azure(com.microsoft.azure.management.Azure) DockerHost(com.microsoft.azure.docker.model.DockerHost) Job(org.eclipse.core.runtime.jobs.Job) AzureUIRefreshEvent(com.microsoft.azuretools.utils.AzureUIRefreshEvent) AzureDockerPreferredSettings(com.microsoft.azure.docker.model.AzureDockerPreferredSettings) Date(java.util.Date) VirtualMachine(com.microsoft.azure.management.compute.VirtualMachine)

Aggregations

Azure (com.microsoft.azure.management.Azure)144 File (java.io.File)75 ArrayList (java.util.ArrayList)20 HashMap (java.util.HashMap)20 ExecutorService (java.util.concurrent.ExecutorService)17 ComputeService (com.vmware.photon.controller.model.resources.ComputeService)16 DiskService (com.vmware.photon.controller.model.resources.DiskService)16 ComputeEnumerateResourceRequest (com.vmware.photon.controller.model.adapterapi.ComputeEnumerateResourceRequest)15 EnumerationAction (com.vmware.photon.controller.model.adapterapi.EnumerationAction)15 AzureUriPaths (com.vmware.photon.controller.model.adapters.azure.AzureUriPaths)15 AzureConstants (com.vmware.photon.controller.model.adapters.azure.constants.AzureConstants)15 AzureResourceType (com.vmware.photon.controller.model.adapters.azure.constants.AzureConstants.AzureResourceType)15 AzureConstants.getQueryResultLimit (com.vmware.photon.controller.model.adapters.azure.constants.AzureConstants.getQueryResultLimit)15 AzureDeferredResultServiceCallback (com.vmware.photon.controller.model.adapters.azure.utils.AzureDeferredResultServiceCallback)15 Default (com.vmware.photon.controller.model.adapters.azure.utils.AzureDeferredResultServiceCallback.Default)15 AzureSdkClients (com.vmware.photon.controller.model.adapters.azure.utils.AzureSdkClients)15 AzureUtils (com.vmware.photon.controller.model.adapters.azure.utils.AzureUtils)15 AzureUtils.getResourceGroupName (com.vmware.photon.controller.model.adapters.azure.utils.AzureUtils.getResourceGroupName)15 AdapterUtils (com.vmware.photon.controller.model.adapters.util.AdapterUtils)15 ComputeEnumerateAdapterRequest (com.vmware.photon.controller.model.adapters.util.ComputeEnumerateAdapterRequest)15