com.microsoft.azure.management.compute.VirtualMachine Java Examples

The following examples show how to use com.microsoft.azure.management.compute.VirtualMachine. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TestVirtualMachineInAvailabilitySet.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
@Override
public VirtualMachine createResource(VirtualMachines virtualMachines) throws Exception {
    final String vmName = "vm" + this.testId;
    final String newRgName = SdkContext.randomResourceName("rgVmInAvail", 10);
    final String newAvailSetName = SdkContext.randomResourceName("avai", 10);

    VirtualMachine vm = virtualMachines.define(vmName)
            .withRegion(Region.US_EAST)
            .withNewResourceGroup(newRgName)
            .withNewPrimaryNetwork("10.0.0.0/28")
            .withPrimaryPrivateIPAddressDynamic()
            .withoutPrimaryPublicIPAddress()
            .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
            .withRootUsername("testuser")
            .withRootPassword("12NewPA$$w0rd!")
            .withComputerName("myvm123")
            .withSize(VirtualMachineSizeTypes.STANDARD_D3_V2)
            .withNewAvailabilitySet(newAvailSetName)
            .create();

    Assert.assertNotNull(vm.availabilitySetId());
    Assert.assertNotNull(vm.computerName());
    Assert.assertTrue(vm.computerName().equalsIgnoreCase("myvm123"));
    return vm;
}
 
Example #2
Source File: VirtualMachineEncryptionHelper.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
/**
 * Perform any post processing after initiating VM encryption through Legacy extension.
 *
 * @param encryptConfig the user provided encryption config
 * @return the encryption progress monitor
 */
private <T extends VirtualMachineEncryptionConfiguration<T>> Observable<DiskVolumeEncryptionMonitor> legacyExtensionEncryptPostProcessingAsync(final EncryptionSettings.Enable<T> encryptConfig) {
    // Retrieve the encryption key URL after extension install or update
    return retrieveEncryptionExtensionStatusStringAsync(ERROR_EXPECTED_KEY_VAULT_URL_NOT_FOUND)
            // Update the VM's OS Disk (in storage profile) with the encryption metadata
            .flatMap(new Func1<String, Observable<VirtualMachine>>() {
                @Override
                public Observable<VirtualMachine> call(String keyVaultSecretUrl) {
                    return updateVMStorageProfileAsync(encryptConfig, keyVaultSecretUrl);
                }
            })
            // Gets the encryption status
            .flatMap(new Func1<VirtualMachine, Observable<DiskVolumeEncryptionMonitor>>() {
                @Override
                public Observable<DiskVolumeEncryptionMonitor> call(VirtualMachine virtualMachine) {
                    return osType == OperatingSystemTypes.LINUX
                            ? new LinuxDiskVolumeLegacyEncryptionMonitorImpl(virtualMachine.id(), virtualMachine.manager()).refreshAsync()
                            : new WindowsVolumeLegacyEncryptionMonitorImpl(virtualMachine.id(), virtualMachine.manager()).refreshAsync();
                }
            });
}
 
Example #3
Source File: VirtualMachineEncryptionHelper.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
/**
 * Perform any post processing after initiating VM encryption through Legacy extension.
 *
 * @param encryptConfig the user provided encryption config
 * @return the encryption progress monitor
 */
private Observable<DiskVolumeEncryptionMonitor> legacyExtensionDecryptPostProcessingAsync(final EncryptionSettings.Disable encryptConfig) {
    return retrieveEncryptionExtensionStatusStringAsync(ERROR_ENCRYPTION_EXTENSION_STATUS_IS_EMPTY)
            // Update the VM's OS profile by marking encryption disabled
            .flatMap(new Func1<String, Observable<VirtualMachine>>() {
                @Override
                public Observable<VirtualMachine> call(String status) {
                    return updateVMStorageProfileAsync(encryptConfig);
                }
            })
            // Gets the encryption status
            .flatMap(new Func1<VirtualMachine, Observable<DiskVolumeEncryptionMonitor>>() {
                @Override
                public Observable<DiskVolumeEncryptionMonitor> call(VirtualMachine virtualMachine) {
                    return osType == OperatingSystemTypes.LINUX
                            ? new LinuxDiskVolumeLegacyEncryptionMonitorImpl(virtualMachine.id(), virtualMachine.manager()).refreshAsync()
                            : new WindowsVolumeLegacyEncryptionMonitorImpl(virtualMachine.id(), virtualMachine.manager()).refreshAsync();
                }
            });
}
 
Example #4
Source File: TestVirtualMachineDataDisk.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
@Override
public VirtualMachine updateResource(VirtualMachine virtualMachine) throws Exception {
    virtualMachine = virtualMachine.update()
            .withoutUnmanagedDataDisk("disk2")
            .defineUnmanagedDataDisk("disk3")
                .withNewVhd(10)
                .withLun(2)
                .attach()
            .apply();
    Assert.assertTrue(virtualMachine.unmanagedDataDisks().size() == 2);
    VirtualMachineUnmanagedDataDisk disk3 = null;
    for (VirtualMachineUnmanagedDataDisk dataDisk : virtualMachine.unmanagedDataDisks().values()) {
        if (dataDisk.name().equalsIgnoreCase("disk3")) {
            disk3 = dataDisk;
            break;
        }
    }
    Assert.assertNotNull(disk3);
    Assert.assertTrue(disk3.cachingType() == CachingTypes.READ_WRITE);
    Assert.assertTrue(disk3.size() == 10);
    return virtualMachine;
}
 
Example #5
Source File: VirtualMachineEncryptionHelper.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
/**
 * Prepare encryption extension using provided configuration and install it in the virtual machine.
 *
 * @param encryptSettings the volume encryption configuration
 * @return an observable that emits updated virtual machine
 */
private <T extends VirtualMachineEncryptionConfiguration<T>> Observable<VirtualMachine> installEncryptionExtensionAsync(final EncryptionSettings.Enable<T> encryptSettings) {
    return Observable.defer(new Func0<Observable<VirtualMachine>>() {
        @Override
        public Observable<VirtualMachine> call() {
            final String typeName = EncryptionExtensionIdentifier.typeName(osType);
            return virtualMachine.update()
                    .defineNewExtension(typeName)
                        .withPublisher(EncryptionExtensionIdentifier.publisherName())
                        .withType(typeName)
                        .withVersion(encryptSettings.encryptionExtensionVersion())
                        .withPublicSettings(encryptSettings.extensionPublicSettings())
                        .withProtectedSettings(encryptSettings.extensionProtectedSettings())
                        .withMinorVersionAutoUpgrade()
                        .attach()
                    .applyAsync();
        }
    });
}
 
Example #6
Source File: AzureVirtualMachineServiceTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private PagedList<VirtualMachine> createPagedListWithOnePage() {
    PagedList<VirtualMachine> pagedList = new PagedList<>() {
        @Override
        public Page<VirtualMachine> nextPage(String nextPageLink) throws RestException {
            return null;
        }

        @Override
        public void loadNextPage() {
        }

        @Override
        public boolean hasNextPage() {
            return false;
        }
    };
    pagedList.add(createVirtualMachine(INSTANCE_1));
    return pagedList;
}
 
Example #7
Source File: TestVirtualMachineSizes.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
@Override
public VirtualMachine createResource(VirtualMachines virtualMachines) throws Exception {
    List<VirtualMachineSize> availableSizes = virtualMachines.sizes().listByRegion(Region.US_EAST);
    Assert.assertTrue(availableSizes.size() > 0);
    System.out.println("VM Sizes: " + availableSizes);
    final String vmName = "vm" + this.testId;
    VirtualMachine vm = virtualMachines.define(vmName)
            .withRegion(Region.US_EAST)
            .withNewResourceGroup()
            .withNewPrimaryNetwork("10.0.0.0/28")
            .withPrimaryPrivateIPAddressDynamic()
            .withoutPrimaryPublicIPAddress()
            .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER)
            .withAdminUsername("testuser")
            .withAdminPassword("12NewPA$$w0rd!")
            .withSize(availableSizes.get(0).name()) // Use the first size
            .create();

    Assert.assertTrue(vm.size().toString().equalsIgnoreCase(availableSizes.get(0).name()));
    return vm;
}
 
Example #8
Source File: AzureCloudResourceService.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
public List<CloudResource> getAttachedOsDiskResources(AuthenticatedContext authenticatedContext, List<CloudResource> instanceList,
        String resourceGroupName) {

    List<CloudResource> osDiskList = new ArrayList<>();
    AzureClient client = authenticatedContext.getParameter(AzureClient.class);
    PagedList<VirtualMachine> virtualMachines = client.getVirtualMachines(resourceGroupName);
    virtualMachines.loadAll();

    instanceList.forEach(vm -> {
        Optional<VirtualMachine> matchingAzureVmOptional = virtualMachines
                .stream()
                .filter(azureVirtualMachine -> vm.getName().equals(azureVirtualMachine.name()))
                .findFirst();
        matchingAzureVmOptional.ifPresentOrElse(
                matchingAzureVm ->
                        osDiskList.add(collectOsDisk(vm.getInstanceId(), matchingAzureVm)),
                () -> LOGGER.warn("No Azure VM metadata found for the VM: " + vm.getInstanceId()));
            }
    );

    return osDiskList;
}
 
Example #9
Source File: AzureVirtualMachineService.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private void fillVmStatuses(List<CloudInstance> cloudInstances, List<CloudVmInstanceStatus> statuses, Map<String, VirtualMachine> virtualMachines) {
    LOGGER.info("Fill vm statuses from returned virtualmachines from azure: {}", virtualMachines.keySet());
    for (CloudInstance cloudInstance : cloudInstances) {
        virtualMachines.values().stream()
                .filter(virtualMachine -> virtualMachine.name().equals(cloudInstance.getInstanceId()))
                .findFirst()
                .ifPresentOrElse(virtualMachine -> {
                    PowerState virtualMachinePowerState = virtualMachine.powerState();
                    String computerName = virtualMachine.computerName();
                    cloudInstance.putParameter(INSTANCE_NAME, computerName);
                    statuses.add(new CloudVmInstanceStatus(cloudInstance, AzureInstanceStatus.get(virtualMachinePowerState)));
                }, () -> statuses.stream()
                        .filter(cvis -> cvis.getCloudInstance().getInstanceId().equals(cloudInstance.getInstanceId()))
                        .findAny()
                        .ifPresentOrElse(cloudInstanceWithStatus -> logTheStatusOfTheCloudInstance(cloudInstanceWithStatus),
                                () -> statuses.add(new CloudVmInstanceStatus(cloudInstance, InstanceStatus.TERMINATED))));
    }
}
 
Example #10
Source File: TestVirtualMachine.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public VirtualMachine updateResource(VirtualMachine resource) throws Exception {
    resource = resource.update()
            .withSize(VirtualMachineSizeTypes.STANDARD_D3_V2)
            .withNewDataDisk(100)
            .apply();
    return resource;
}
 
Example #11
Source File: AzureMetadataCollectorTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private VirtualMachine createVirtualMachine(String name) {
    VirtualMachine virtualMachine = mock(VirtualMachine.class);
    NetworkInterface networkInterface = mock(NetworkInterface.class);
    NicIPConfiguration nicIPConfiguration = mock(NicIPConfiguration.class);
    when(virtualMachine.name()).thenReturn(name);
    when(virtualMachine.getPrimaryNetworkInterface()).thenReturn(networkInterface);
    when(networkInterface.primaryIPConfiguration()).thenReturn(nicIPConfiguration);
    when(networkInterface.primaryPrivateIP()).thenReturn(PRIVATE_IP);
    when(nicIPConfiguration.subnetName()).thenReturn(SUBNET_NAME);
    return virtualMachine;
}
 
Example #12
Source File: VirtualMachineImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Observable<VirtualMachine> createResourceAsync() {
    //
    // -- set creation-time only properties
    setOSDiskDefaults();
    setOSProfileDefaults();
    setHardwareProfileDefaults();
    //
    if (isManagedDiskEnabled()) {
        managedDataDisks.setDataDisksDefaults();
    } else {
        UnmanagedDataDiskImpl.setDataDisksDefaults(this.unmanagedDataDisks, this.vmName);
    }
    this.handleUnManagedOSAndDataDisksStorageSettings();
    this.bootDiagnosticsHandler.handleDiagnosticsSettings();
    this.handleNetworkSettings();
    this.createNewProximityPlacementGroup();
    this.handleAvailabilitySettings();
    this.virtualMachineMsiHandler.processCreatedExternalIdentities();
    this.virtualMachineMsiHandler.handleExternalIdentities();
    final VirtualMachineImpl self = this;
    return this.manager().inner().virtualMachines()
            .createOrUpdateAsync(resourceGroupName(), vmName, inner())
            .map(new Func1<VirtualMachineInner, VirtualMachine>() {
                @Override
                public VirtualMachine call(VirtualMachineInner virtualMachineInner) {
                    reset(virtualMachineInner);
                    return self;
                }

            });
}
 
Example #13
Source File: TestVirtualMachineDataDisk.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public VirtualMachine createResource(VirtualMachines virtualMachines) throws Exception {
    final String vmName = "vm" + this.testId;
    VirtualMachine virtualMachine = virtualMachines.define(vmName)
            .withRegion(Region.US_EAST)
            .withNewResourceGroup()
            .withNewPrimaryNetwork("10.0.0.0/28")
            .withPrimaryPrivateIPAddressDynamic()
            .withoutPrimaryPublicIPAddress()
            .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER)
            .withAdminUsername("testuser")
            .withAdminPassword("12NewPA$$w0rd!")
            .withUnmanagedDisks()
            .withNewUnmanagedDataDisk(30)
            .defineUnmanagedDataDisk("disk2")
                .withNewVhd(20)
                .withCaching(CachingTypes.READ_ONLY)
                .attach()
            .withSize(VirtualMachineSizeTypes.STANDARD_A8)
            .create();

    Assert.assertTrue(virtualMachine.size().equals(VirtualMachineSizeTypes.STANDARD_A8));
    Assert.assertTrue(virtualMachine.unmanagedDataDisks().size() == 2);
    VirtualMachineUnmanagedDataDisk disk2 = null;
    for (VirtualMachineUnmanagedDataDisk dataDisk : virtualMachine.unmanagedDataDisks().values()) {
        if (dataDisk.name().equalsIgnoreCase("disk2")) {
            disk2 = dataDisk;
            break;
        }
    }
    Assert.assertNotNull(disk2);
    Assert.assertTrue(disk2.cachingType() == CachingTypes.READ_ONLY);
    Assert.assertTrue(disk2.size() == 20);
    return virtualMachine;
}
 
Example #14
Source File: VirtualMachineEncryptionHelper.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
/**
 * Updates the virtual machine's OS Disk model with the encryption specific details.
 *
 * @param encryptSettings the configuration specific to disabling the encryption
 * @return an observable that emits updated virtual machine
 */
private Observable<VirtualMachine> updateVMStorageProfileAsync(final EncryptionSettings encryptSettings) {
    DiskEncryptionSettings diskEncryptionSettings = encryptSettings.storageProfileEncryptionSettings();
    return virtualMachine.update()
            .withOSDiskEncryptionSettings(diskEncryptionSettings)
            .applyAsync();
}
 
Example #15
Source File: AzureVirtualMachineServiceTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetVirtualMachinesByIdShouldReturnOneVirtualMachinesWhenOnlyTheFirstPageAvailable() {
    Set<String> privateInstanceIds = createPrivateInstanceIds();
    PagedList<VirtualMachine> virtualMachinesWithOnePage = createPagedListWithOnePage();

    when(azureClient.getVirtualMachines(RESOURCE_GROUP)).thenReturn(virtualMachinesWithOnePage);

    Map<String, VirtualMachine> actual = underTest.getVirtualMachinesByName(azureClient, RESOURCE_GROUP, privateInstanceIds);

    assertEquals(INSTANCE_1, actual.get(INSTANCE_1).name());
    assertEquals(1, actual.size());
}
 
Example #16
Source File: VirtualMachineEncryptionHelper.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
/**
 * Perform any post processing after initiating VM encryption through NoAAD extension.
 *
 * @param virtualMachine the encrypted virtual machine
 * @return the encryption progress monitor
 */
private Observable<DiskVolumeEncryptionMonitor> noAADExtensionEncryptPostProcessingAsync(final VirtualMachine virtualMachine) {
    // Gets the encryption status
    return osType == OperatingSystemTypes.LINUX
            ? new LinuxDiskVolumeNoAADEncryptionMonitorImpl(virtualMachine.id(), virtualMachine.manager()).refreshAsync()
            : new WindowsVolumeNoAADEncryptionMonitorImpl(virtualMachine.id(), virtualMachine.manager()).refreshAsync();
}
 
Example #17
Source File: VirtualMachineEncryptionHelper.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
/**
 * Disables encryption on the given disk volume.
 *
 * @param volumeType the disk volume
 * @return an observable that emits the decryption status
 */
Observable<DiskVolumeEncryptionMonitor> disableEncryptionAsync(final DiskVolumeType volumeType) {
    final EncryptionSettings.Disable encryptSettings = EncryptionSettings.createDisable(volumeType);
    //
    return validateBeforeDecryptAsync(volumeType)
            // Update the encryption extension
            .flatMap(new Func1<VirtualMachineExtension, Observable<VMExtTuple>>() {
                @Override
                public Observable<VMExtTuple> call(final VirtualMachineExtension virtualMachineExtension) {
                    return updateEncryptionExtensionAsync(encryptSettings, virtualMachineExtension)
                            .map(new Func1<VirtualMachine, VMExtTuple>() {
                                @Override
                                public VMExtTuple call(VirtualMachine virtualMachine) {
                                    return new VMExtTuple(virtualMachine, virtualMachineExtension);
                                }
                            });
                }
            })
            .flatMap(new Func1<VMExtTuple, Observable<DiskVolumeEncryptionMonitor>>() {
                @Override
                public Observable<DiskVolumeEncryptionMonitor> call(VMExtTuple vmExt) {
                    if (EncryptionExtensionIdentifier.isNoAADVersion(osType, vmExt.encryptExtension.versionName())) {
                        return noAADExtensionDecryptPostProcessingAsync(vmExt.virtualMachine);
                    } else {
                        return legacyExtensionDecryptPostProcessingAsync(encryptSettings);
                    }
                }
            });
}
 
Example #18
Source File: TestVirtualMachine.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public VirtualMachine createResource(VirtualMachines virtualMachines) throws Exception {
    final String vmName = "vm" + this.testId;
    final VirtualMachine[] vms = new VirtualMachine[1];
    final SettableFuture<VirtualMachine> future = SettableFuture.create();

    Observable<Indexable> resourceStream = virtualMachines.define(vmName)
            .withRegion(Region.US_EAST)
            .withNewResourceGroup()
            .withNewPrimaryNetwork("10.0.0.0/28")
            .withPrimaryPrivateIPAddressDynamic()
            .withoutPrimaryPublicIPAddress()
            .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER)
            .withAdminUsername("testuser")
            .withAdminPassword("12NewPA$$w0rd!")
            .withNewDataDisk(150)
            .withSize(VirtualMachineSizeTypes.STANDARD_D1_V2)
            .createAsync();

    Utils.<VirtualMachine>rootResource(resourceStream)
            .subscribe(new Action1<VirtualMachine>() {
                @Override
                public void call(VirtualMachine virtualMachine) {
                    future.set(virtualMachine);
                }
            });
    vms[0] = future.get();

    Assert.assertEquals(1, vms[0].dataDisks().size());
    VirtualMachineDataDisk dataDisk = vms[0].dataDisks().values().iterator().next();
    Assert.assertEquals(150, dataDisk.size());
    Assert.assertEquals(128, vms[0].osDiskSize());
    Disk osDisk = virtualMachines.manager().disks().getById(vms[0].osDiskId());
    Assert.assertNotNull(osDisk);
    Assert.assertEquals(128, osDisk.sizeInGB());

    return vms[0];
}
 
Example #19
Source File: AzureVirtualMachineServiceTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private PagedList<VirtualMachine> createPagedList() {
    PagedList<VirtualMachine> pagedList = new PagedList<>() {
        @Override
        public Page<VirtualMachine> nextPage(String nextPageLink) throws RestException {
            return null;
        }
    };
    pagedList.add(createVirtualMachine(INSTANCE_1));
    pagedList.add(createVirtualMachine(INSTANCE_2));
    pagedList.add(createVirtualMachine(INSTANCE_3));
    return pagedList;
}
 
Example #20
Source File: AzureTests.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Test
public void testManagedDiskVMUpdate() throws Exception {
    final String rgName = SdkContext.randomResourceName("rg", 13);
    final String linuxVM2Name = SdkContext.randomResourceName("vm" + "-", 10);
    final String linuxVM2Pip = SdkContext.randomResourceName("pip" + "-", 18);
    VirtualMachine linuxVM2 = azure.virtualMachines().define(linuxVM2Name)
            .withRegion(Region.US_EAST)
            .withNewResourceGroup(rgName)
            .withNewPrimaryNetwork("10.0.0.0/28")
            .withPrimaryPrivateIPAddressDynamic()
            .withNewPrimaryPublicIPAddress(linuxVM2Pip)
            .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
            .withRootUsername("tester")
            .withRootPassword("Abcdef.123456!")
            // Begin: Managed data disks
            .withNewDataDisk(100)
            .withNewDataDisk(100, 1, CachingTypes.READ_WRITE)
            // End: Managed data disks
            .withSize(VirtualMachineSizeTypes.STANDARD_D3_V2)
            .create();

    linuxVM2.deallocate();
    linuxVM2.update()
            .withoutDataDisk(2)
            .withNewDataDisk(200)
            .apply();
    azure.resourceGroups().beginDeleteByName(rgName);
}
 
Example #21
Source File: TestVirtualMachineNics.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public VirtualMachine updateResource(VirtualMachine virtualMachine) throws Exception {
    final String secondaryNicName = "nic" + this.testId;
    virtualMachine.powerOff();
    virtualMachine.deallocate();
    virtualMachine = virtualMachine.update()
            .withoutSecondaryNetworkInterface(secondaryNicName)
            .apply();

    Assert.assertTrue(virtualMachine.networkInterfaceIds().size() == 2);
    return virtualMachine;
}
 
Example #22
Source File: ManageManagedDisks.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
private static VirtualMachine prepareSpecializedManagedVirtualMachine(Azure azure, Region region, String rgName) {
    final String userName = "tirekicker";
    // [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Serves as an example, not for deployment. Please change when using this in your code.")]
    final String password = "12NewPA$$w0rd!";
    final String linuxVMName1 = SdkContext.randomResourceName("vm" + "-", 10);
    final String publicIPDnsLabel = SdkContext.randomResourceName("pip" + "-", 20);

    VirtualMachine linuxVM = azure.virtualMachines().define(linuxVMName1)
            .withRegion(region)
            .withNewResourceGroup(rgName)
            .withNewPrimaryNetwork("10.0.0.0/28")
            .withPrimaryPrivateIPAddressDynamic()
            .withNewPrimaryPublicIPAddress(publicIPDnsLabel)
            .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
            .withRootUsername(userName)
            .withRootPassword(password)
            .withNewDataDisk(100)
            .withNewDataDisk(200)
            .withSize(VirtualMachineSizeTypes.STANDARD_D3_V2)
            .create();

    // De-provision the virtual machine
    deprovisionAgentInLinuxVM(linuxVM.getPrimaryPublicIPAddress().fqdn(), 22, userName, password);
    System.out.println("Deallocate VM: " + linuxVM.id());
    linuxVM.deallocate();
    System.out.println("Deallocated VM: " + linuxVM.id() + "; state = " + linuxVM.powerState());
    System.out.println("Generalize VM: " + linuxVM.id());
    linuxVM.generalize();
    System.out.println("Generalized VM: " + linuxVM.id());
    return linuxVM;
}
 
Example #23
Source File: ManageUserAssignedMSIEnabledVirtualMachine.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
private static RunCommandResult runCommandOnVM(Azure azure, VirtualMachine virtualMachine, List<String> commands) {
    RunCommandInput runParams = new RunCommandInput()
            .withCommandId("RunShellScript")
            .withScript(commands);

    return azure.virtualMachines().runCommand(virtualMachine.resourceGroupName(), virtualMachine.name(), runParams);
}
 
Example #24
Source File: ManageServicePrincipal.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
private static void useAuthFile(String authFilePath) throws IOException {
    // use just created auth file to sign in.
    Azure azure = Azure.configure()
            .withLogLevel(LogLevel.BODY)
            .authenticate(new File(authFilePath))
            .withDefaultSubscription();
    // list virtualMachines, if any.
    List<VirtualMachine> resourceGroups = azure.virtualMachines().list();
    for (VirtualMachine vm : resourceGroups) {
        Utils.print(vm);
    }
}
 
Example #25
Source File: AzureCloudResourceService.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private CloudResource collectOsDisk(String instanceId, VirtualMachine virtualMachine) {
    StorageProfile storageProfile = virtualMachine.storageProfile();
    OSDisk osDisk = storageProfile.osDisk();
    LOGGER.debug("OS disk {} found for VM {}", osDisk.name(), virtualMachine.name());
    return CloudResource.builder()
            .name(osDisk.name())
            .instanceId(instanceId)
            .status(CommonStatus.CREATED)
            .persistent(true)
            .reference(osDisk.managedDisk().id())
            .type(ResourceType.AZURE_DISK)
            .build();
}
 
Example #26
Source File: AzureVirtualMachineService.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Retryable(backoff = @Backoff(delay = 1000, multiplier = 2, maxDelay = 10000), maxAttempts = 5)
public Map<String, VirtualMachine> getVirtualMachinesByName(AzureClient azureClient, String resourceGroup, Collection<String> privateInstanceIds) {
    LOGGER.debug("Starting to retrieve vm metadata from Azure for ids: {}", privateInstanceIds);
    PagedList<VirtualMachine> virtualMachines = azureClient.getVirtualMachines(resourceGroup);
    while (hasMissingVm(virtualMachines, privateInstanceIds) && virtualMachines.hasNextPage()) {
        virtualMachines.loadNextPage();
    }
    validateResponse(virtualMachines, privateInstanceIds);
    return collectVirtualMachinesByName(privateInstanceIds, virtualMachines);
}
 
Example #27
Source File: AzureVirtualMachineService.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Retryable(backoff = @Backoff(delay = 1000, multiplier = 2, maxDelay = 10000), maxAttempts = 5)
public Map<String, VirtualMachine> getVmsFromAzureAndFillStatuses(AuthenticatedContext ac, List<CloudInstance> cloudInstances,
        List<CloudVmInstanceStatus> statuses) {
    Map<String, VirtualMachine> virtualMachines = getVmsFromAzureAndFillStatusesIfResourceGroupRemoved(ac, cloudInstances, statuses);
    LOGGER.info("VirtualMachines from Azure: {}", virtualMachines.keySet());
    refreshInstanceViews(virtualMachines);
    fillVmStatuses(cloudInstances, statuses, virtualMachines);
    return virtualMachines;
}
 
Example #28
Source File: AzureVirtualMachineService.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Retryable(backoff = @Backoff(delay = 1000, multiplier = 2, maxDelay = 10000), maxAttempts = 5)
public void refreshInstanceViews(Map<String, VirtualMachine> virtualMachines) {
    LOGGER.info("Parallel instanceviews refresh to download instance view fields from azure, like PowerState of the machines: {}",
            virtualMachines.keySet());
    List<Completable> refreshInstanceViewCompletables = new ArrayList<>();
    for (VirtualMachine virtualMachine : virtualMachines.values()) {
        refreshInstanceViewCompletables.add(Completable.fromObservable(virtualMachine.refreshInstanceViewAsync()).subscribeOn(Schedulers.io()));
    }
    Completable.merge(refreshInstanceViewCompletables).await();
}
 
Example #29
Source File: AzureVirtualMachineService.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private Map<String, VirtualMachine> getVmsFromAzureAndFillStatusesIfResourceGroupRemoved(AuthenticatedContext ac, List<CloudInstance> cloudInstances,
        List<CloudVmInstanceStatus> statuses) {
    LOGGER.info("Get vms from azure: {}", cloudInstances);
    AzureClient azureClient = ac.getParameter(AzureClient.class);
    ArrayListMultimap<String, String> resourceGroupInstanceMultimap = cloudInstances.stream()
            .collect(Multimaps.toMultimap(
                    cloudInstance -> azureResourceGroupMetadataProvider.getResourceGroupName(ac.getCloudContext(), cloudInstance),
                    CloudInstance::getInstanceId,
                    ArrayListMultimap::create));

    Map<String, VirtualMachine> virtualMachines = new HashMap<>();
    for (Map.Entry<String, Collection<String>> resourceGroupInstanceIdsMap : resourceGroupInstanceMultimap.asMap().entrySet()) {
        LOGGER.info("Get vms for resource group and add to all virtualmachines: {}", resourceGroupInstanceIdsMap.getKey());
        try {
            virtualMachines.putAll(getVirtualMachinesByName(azureClient,
                    resourceGroupInstanceIdsMap.getKey(), resourceGroupInstanceIdsMap.getValue()));
        } catch (CloudException e) {
            LOGGER.debug("Exception occurred during the list of Virtual Machines by resource group", e);
            for (String instance : resourceGroupInstanceIdsMap.getValue()) {
                cloudInstances.stream().filter(cloudInstance -> instance.equals(cloudInstance.getInstanceId())).findFirst().ifPresent(cloudInstance -> {
                    if (e.body() != null && "ResourceNotFound".equals(e.body().code())) {
                        statuses.add(new CloudVmInstanceStatus(cloudInstance, InstanceStatus.TERMINATED));
                    } else {
                        String msg = String.format("Failed to get VM's state from Azure: %s", e.toString());
                        statuses.add(new CloudVmInstanceStatus(cloudInstance, InstanceStatus.UNKNOWN, msg));
                    }
                });
            }
        }
    }
    return virtualMachines;
}
 
Example #30
Source File: AzureClient.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
public void detachDiskFromVm(String id, VirtualMachine vm) {
    LOGGER.debug("detach managed disk with id={}", id);
    VirtualMachineDataDisk dataDisk = vm.dataDisks()
            .values()
            .stream()
            .filter(virtualMachineDataDisk -> virtualMachineDataDisk.id().equals(id))
            .findFirst()
            .orElseThrow(() -> new CloudConnectorException(String.format("Virtual machine does not have attached data disk with id %s", id)));
    int lun = dataDisk.lun();
    LOGGER.debug("detaches a managed data disk with LUN {} from the virtual machine {}", lun, vm);
    vm.update().withoutDataDisk(lun).apply();
}