Search in sources :

Example 66 with VirtualMachine

use of com.microsoft.azure.management.compute.VirtualMachine in project photon-model by vmware.

the class AzureDiskEnumerationServiceTest method testVMAndDiskEnumeration.

@Test
public void testVMAndDiskEnumeration() throws Throwable {
    // Exit if it is mock
    if (this.isMock) {
        return;
    }
    this.resourceGroup = SdkContext.randomResourceName(RESOURCE_GROUP_NAME, RESOURCE_GROUP_NAME.length() + 5);
    // Create a vm with one additional disk
    VirtualMachine vm = getAzureSdkClients().getComputeManager().virtualMachines().define("TestVM").withRegion(Region.US_WEST).withNewResourceGroup(this.resourceGroup).withNewPrimaryNetwork("10.0.0.0/28").withPrimaryPrivateIPAddressDynamic().withoutPrimaryPublicIPAddress().withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(AzureTestUtil.AZURE_ADMIN_USERNAME).withRootPassword(AzureTestUtil.AZURE_ADMIN_PASSWORD).withNewDataDisk(5).create();
    assertNotNull(vm);
    DataDisk dataDisk = vm.storageProfile().dataDisks().get(0);
    assertNotNull(dataDisk);
    ComputeEnumerateResourceRequest resourceRequest = kickOffEnumeration();
    ComputeEnumerateAdapterRequest request = new ComputeEnumerateAdapterRequest(resourceRequest, this.authState, this.computeHost);
    // Run VM enumeration
    patchServiceSynchronously(AzureComputeEnumerationAdapterService.SELF_LINK, request);
    // Run disk enumeration
    patchServiceSynchronously(AzureDiskEnumerationAdapterService.SELF_LINK, request);
    // Verify disk state is created in local store
    Map<String, DiskState> diskStateMap = ProvisioningUtils.getResourceStates(getHost(), DiskService.FACTORY_LINK, DiskState.class);
    assertTrue(diskStateMap.keySet().stream().anyMatch(s -> s.equalsIgnoreCase(dataDisk.managedDisk().id())));
    // Detach disk
    vm.update().withoutDataDisk(dataDisk.lun()).apply();
    // Run Disk enumeration
    patchServiceSynchronously(AzureDiskEnumerationAdapterService.SELF_LINK, request);
    // Verify if the status of disk state is updated to Available state or not
    diskStateMap = ProvisioningUtils.getResourceStates(getHost(), DiskService.FACTORY_LINK, DiskState.class);
    diskStateMap.values().forEach(diskState -> {
        if (diskState.name.equalsIgnoreCase(dataDisk.name())) {
            assertTrue("Status of disk state should be Available", diskState.status.equals(DiskService.DiskStatus.AVAILABLE));
        }
    });
}
Also used : VirtualMachine(com.microsoft.azure.management.compute.VirtualMachine) ComputeEnumerateResourceRequest(com.vmware.photon.controller.model.adapterapi.ComputeEnumerateResourceRequest) Region(com.microsoft.azure.management.resources.fluentcore.arm.Region) AzureBaseTest(com.vmware.photon.controller.model.adapters.azure.base.AzureBaseTest) TagsUtil(com.vmware.photon.controller.model.adapters.util.TagsUtil) Level(java.util.logging.Level) TagState(com.vmware.photon.controller.model.resources.TagService.TagState) Map(java.util.Map) After(org.junit.After) EnumerationAction(com.vmware.photon.controller.model.adapterapi.EnumerationAction) ProvisioningUtils(com.vmware.photon.controller.model.tasks.ProvisioningUtils) AzureTestUtil(com.vmware.photon.controller.model.adapters.azure.instance.AzureTestUtil) AzureConstants(com.vmware.photon.controller.model.adapters.azure.constants.AzureConstants) DataDisk(com.microsoft.azure.management.compute.DataDisk) Assert.assertNotNull(org.junit.Assert.assertNotNull) Assert.assertTrue(org.junit.Assert.assertTrue) DiskState(com.vmware.photon.controller.model.resources.DiskService.DiskState) Test(org.junit.Test) TimeUnit(java.util.concurrent.TimeUnit) Disk(com.microsoft.azure.management.compute.Disk) UriUtils(com.vmware.xenon.common.UriUtils) PhotonModelConstants(com.vmware.photon.controller.model.constants.PhotonModelConstants) ComputeEnumerateAdapterRequest(com.vmware.photon.controller.model.adapters.util.ComputeEnumerateAdapterRequest) KnownLinuxVirtualMachineImage(com.microsoft.azure.management.compute.KnownLinuxVirtualMachineImage) DiskService(com.vmware.photon.controller.model.resources.DiskService) SdkContext(com.microsoft.azure.management.resources.fluentcore.utils.SdkContext) DataDisk(com.microsoft.azure.management.compute.DataDisk) ComputeEnumerateResourceRequest(com.vmware.photon.controller.model.adapterapi.ComputeEnumerateResourceRequest) ComputeEnumerateAdapterRequest(com.vmware.photon.controller.model.adapters.util.ComputeEnumerateAdapterRequest) DiskState(com.vmware.photon.controller.model.resources.DiskService.DiskState) VirtualMachine(com.microsoft.azure.management.compute.VirtualMachine) AzureBaseTest(com.vmware.photon.controller.model.adapters.azure.base.AzureBaseTest) Test(org.junit.Test)

Example 67 with VirtualMachine

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

the class VMArmModule 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.getSelectedSubscriptionDetails().stream().filter(subscriptionDetail -> Objects.nonNull(subscriptionDetail) && subscriptionDetail.isSelected()).map(subscriptionDetail -> subscriptionDetail.getSubscriptionId()).collect(Collectors.toSet());
        for (String sid : sidList) {
            try {
                Azure azure = azureManager.getAzure(sid);
                List<VirtualMachine> virtualMachines = azure.virtualMachines().list();
                for (VirtualMachine vm : virtualMachines) {
                    addChildNode(new VMNode(this, sid, vm));
                }
            } catch (Exception ex) {
                failedSubscriptions.add(new ImmutablePair<>(sid, ex.getMessage()));
                continue;
            }
        }
    } catch (Exception ex) {
        DefaultLoader.getUIHelper().logError("An error occurred when trying to load Virtual Machines\n\n" + ex.getMessage(), ex);
    }
    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 : AuthMethodManager(com.microsoft.azuretools.authmanage.AuthMethodManager) VirtualMachine(com.microsoft.azure.management.compute.VirtualMachine) SubscriptionManager(com.microsoft.azuretools.authmanage.SubscriptionManager) Nullable(com.microsoft.azuretools.azurecommons.helpers.Nullable) Node(com.microsoft.tooling.msservices.serviceexplorer.Node) Set(java.util.Set) AzureManager(com.microsoft.azuretools.sdkmanage.AzureManager) Collectors(java.util.stream.Collectors) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) ArrayList(java.util.ArrayList) Objects(java.util.Objects) Azure(com.microsoft.azure.management.Azure) AzureIconSymbol(com.microsoft.tooling.msservices.serviceexplorer.AzureIconSymbol) List(java.util.List) Pair(org.apache.commons.lang3.tuple.Pair) AzureCmdException(com.microsoft.azuretools.azurecommons.helpers.AzureCmdException) DefaultLoader(com.microsoft.tooling.msservices.components.DefaultLoader) AzureRefreshableNode(com.microsoft.tooling.msservices.serviceexplorer.AzureRefreshableNode) Azure(com.microsoft.azure.management.Azure) 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) VirtualMachine(com.microsoft.azure.management.compute.VirtualMachine)

Example 68 with VirtualMachine

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

the class CreateVMWizard method performFinish.

@Override
public boolean performFinish() {
    Operation operation = TelemetryManager.createOperation(VM, CREATE_VM);
    AzureTaskManager.getInstance().runInBackground("Creating virtual machine " + name + "...", new Runnable() {

        @Override
        public void run() {
            try {
                operation.start();
                byte[] certData = new byte[0];
                if (!certificate.isEmpty()) {
                    File certFile = new File(certificate);
                    if (certFile.exists()) {
                        try (FileInputStream 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 {
                        }
                    }
                }
                // create storage account when use choose to create new one
                if (Objects.nonNull(newStorageAccount)) {
                    storageAccount = new CreateStorageAccountTask(newStorageAccount).execute();
                }
                VirtualMachine vm = AzureSDKManager.createVirtualMachine(subscription.getId(), name, resourceGroupName, isNewResourceGroup, size.name(), region.getName(), virtualMachineImage, knownMachineImage, isKnownMachineImage, storageAccount, virtualNetwork, newNetwork, isNewNetwork, subnet, publicIpAddress, withNewPip, availabilitySet, withNewAvailabilitySet, userName, password, certData.length > 0 ? new String(certData) : null);
                // update resource groups cache if new resource group was created when creating storage account
                DefaultLoader.getIdeHelper().invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            node.addChildNode(new VMNode(node, subscription.getId(), vm));
                        } catch (AzureCmdException e) {
                            PluginUtil.displayErrorDialogWithAzureMsg(PluginUtil.getParentShell(), Messages.err, "An error occurred while refreshing the list of virtual machines.", e);
                        }
                    }
                });
            } catch (Exception e) {
                EventUtil.logError(operation, ErrorType.userError, e, null, null);
                DefaultLoader.getIdeHelper().invokeLater(new Runnable() {

                    public void run() {
                        PluginUtil.displayErrorDialogWithAzureMsg(PluginUtil.getParentShell(), "Error Creating Virtual Machine", "An error occurred while trying to create the specified virtual machine", e);
                    }
                });
            } finally {
                operation.complete();
            }
        }
    });
    return true;
}
Also used : AzureCmdException(com.microsoft.azuretools.azurecommons.helpers.AzureCmdException) Operation(com.microsoft.azuretools.telemetrywrapper.Operation) VMNode(com.microsoft.tooling.msservices.serviceexplorer.azure.vmarm.VMNode) File(java.io.File) CreateStorageAccountTask(com.microsoft.azuretools.azureexplorer.helpers.CreateStorageAccountTask) FileInputStream(java.io.FileInputStream) AzureCmdException(com.microsoft.azuretools.azurecommons.helpers.AzureCmdException) VirtualMachine(com.microsoft.azure.management.compute.VirtualMachine)

Aggregations

VirtualMachine (com.microsoft.azure.management.compute.VirtualMachine)68 ArrayList (java.util.ArrayList)21 Region (com.microsoft.azure.management.resources.fluentcore.arm.Region)20 Network (com.microsoft.azure.management.network.Network)17 Date (java.util.Date)12 Disk (com.microsoft.azure.management.compute.Disk)10 PublicIPAddress (com.microsoft.azure.management.network.PublicIPAddress)10 ResourceGroup (com.microsoft.azure.management.resources.ResourceGroup)9 Creatable (com.microsoft.azure.management.resources.fluentcore.model.Creatable)9 Azure (com.microsoft.azure.management.Azure)8 NetworkInterface (com.microsoft.azure.management.network.NetworkInterface)8 IOException (java.io.IOException)8 StopWatch (org.apache.commons.lang3.time.StopWatch)7 VirtualMachineDataDisk (com.microsoft.azure.management.compute.VirtualMachineDataDisk)6 HashMap (java.util.HashMap)6 StorageAccount (com.microsoft.azure.management.storage.StorageAccount)5 JSchException (com.jcraft.jsch.JSchException)4 CloudException (com.microsoft.azure.CloudException)4 DockerHost (com.microsoft.azure.docker.model.DockerHost)4 NetworkSecurityGroup (com.microsoft.azure.management.network.NetworkSecurityGroup)4