use of com.microsoft.azure.management.compute.VirtualMachine in project azure-sdk-for-java by Azure.
the class AzureTests method testManagedDiskVMUpdate.
@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!").withNewDataDisk(100).withNewDataDisk(100, 1, CachingTypes.READ_WRITE).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).create();
linuxVM2.deallocate();
linuxVM2.update().withoutDataDisk(2).withNewDataDisk(200).apply();
azure.resourceGroups().beginDeleteByName(rgName);
}
use of com.microsoft.azure.management.compute.VirtualMachine in project azure-tools-for-java by Microsoft.
the class AzureDeploymentProgressNotification method deployToDockerContainer.
public void deployToDockerContainer(AzureDockerImageInstance dockerImageInstance, String url) {
Date startDate = new Date();
Map<String, String> postEventProperties = new HashMap<String, String>();
postEventProperties.put("DockerFileOption", dockerImageInstance.predefinedDockerfile);
String descriptionTask = String.format("Publishing %s into Docker host %s at port(s) %s", new File(dockerImageInstance.artifactPath).getName(), dockerImageInstance.host.name, dockerImageInstance.dockerPortSettings);
try {
String msg = String.format("Publishing %s to Docker host %s ...", new File(dockerImageInstance.artifactPath).getName(), dockerImageInstance.host.name);
notifyProgress(descriptionTask, startDate, null, 5, msg);
AzureManager azureAuthManager = AuthMethodManager.getInstance().getAzureManager();
// not signed in
if (azureAuthManager == null) {
throw new RuntimeException("User not signed in");
}
AzureDockerHostsManager dockerManager = AzureDockerHostsManager.getAzureDockerHostsManagerEmpty(azureAuthManager);
Azure azureClient = dockerManager.getSubscriptionsMap().get(dockerImageInstance.sid).azureClient;
KeyVaultClient keyVaultClient = dockerManager.getSubscriptionsMap().get(dockerImageInstance.sid).keyVaultClient;
if (dockerImageInstance.hasNewDockerHost) {
msg = String.format("Creating new virtual machine %s ...", dockerImageInstance.host.name);
notifyProgress(descriptionTask, startDate, null, 10, msg);
if (AzureDockerUtils.DEBUG)
System.out.println("Creating new virtual machine: " + new Date().toString());
AzureDockerVMOps.createDockerHostVM(azureClient, dockerImageInstance.host);
if (AzureDockerUtils.DEBUG)
System.out.println("Done creating new virtual machine: " + new Date().toString());
msg = String.format("Get new VM details...");
notifyProgress(descriptionTask, startDate, null, 30, msg);
if (AzureDockerUtils.DEBUG)
System.out.println("Getting the new Docker host details: " + new Date().toString());
VirtualMachine vm = azureClient.virtualMachines().getByResourceGroup(dockerImageInstance.host.hostVM.resourceGroupName, dockerImageInstance.host.hostVM.name);
if (vm != null) {
DockerHost updatedHost = AzureDockerVMOps.getDockerHost(vm, dockerManager.getDockerVaultsMap());
if (updatedHost != null) {
dockerImageInstance.host.hostVM = updatedHost.hostVM;
dockerImageInstance.host.apiUrl = updatedHost.apiUrl;
}
}
if (AzureDockerUtils.DEBUG)
System.out.println("Done getting the new Docker host details: " + new Date().toString());
msg = String.format("Waiting for virtual machine to be up %s ...", dockerImageInstance.host.name);
notifyProgress(descriptionTask, startDate, null, 35, msg);
if (AzureDockerUtils.DEBUG)
System.out.println("Waiting for virtual machine to be up: " + new Date().toString());
AzureDockerVMOps.waitForVirtualMachineStartup(azureClient, dockerImageInstance.host);
if (AzureDockerUtils.DEBUG)
System.out.println("Done Waiting for virtual machine to be up: " + new Date().toString());
msg = String.format("Configuring Docker service for %s ...", dockerImageInstance.host.name);
notifyProgress(descriptionTask, startDate, null, 45, msg);
if (AzureDockerUtils.DEBUG)
System.out.println("Configuring Docker host: " + new Date().toString());
AzureDockerVMOps.installDocker(dockerImageInstance.host);
if (AzureDockerUtils.DEBUG)
System.out.println("Done configuring Docker host: " + new Date().toString());
msg = String.format("Updating Docker hosts ...");
notifyProgress(descriptionTask, startDate, null, 50, msg);
if (AzureDockerUtils.DEBUG)
System.out.println("Refreshing docker hosts: " + new Date().toString());
// dockerManager.refreshDockerHostDetails();
vm = azureClient.virtualMachines().getByResourceGroup(dockerImageInstance.host.hostVM.resourceGroupName, dockerImageInstance.host.hostVM.name);
if (vm != null) {
DockerHost updatedHost = AzureDockerVMOps.getDockerHost(vm, dockerManager.getDockerVaultsMap());
if (updatedHost != null) {
updatedHost.sid = dockerImageInstance.host.sid;
updatedHost.hostVM.sid = dockerImageInstance.host.hostVM.sid;
if (updatedHost.certVault == null) {
updatedHost.certVault = dockerImageInstance.host.certVault;
updatedHost.hasPwdLogIn = dockerImageInstance.host.hasPwdLogIn;
updatedHost.hasSSHLogIn = dockerImageInstance.host.hasSSHLogIn;
updatedHost.isTLSSecured = dockerImageInstance.host.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: " + new Date().toString());
if (AzureDockerUtils.DEBUG)
System.out.println("Finished setting up Docker host");
} else {
msg = String.format("Using virtual machine %s ...", dockerImageInstance.host.name);
notifyProgress(descriptionTask, startDate, null, 50, msg);
}
if (dockerImageInstance.host.session == null) {
if (AzureDockerUtils.DEBUG)
System.out.println("Opening a remote connection to the Docker host: " + new Date().toString());
dockerImageInstance.host.session = AzureDockerSSHOps.createLoginInstance(dockerImageInstance.host);
if (AzureDockerUtils.DEBUG)
System.out.println("Done opening a remote connection to the Docker host: " + new Date().toString());
}
if (dockerImageInstance.hasNewDockerHost) {
if (dockerImageInstance.host.certVault != null && dockerImageInstance.host.certVault.hostName != null) {
AzureDockerUIResources.createDockerKeyVault(null, dockerImageInstance.host, dockerManager);
}
}
msg = String.format("Uploading Dockerfile and artifact %s on %s ...", dockerImageInstance.artifactName, dockerImageInstance.host.name);
notifyProgress(descriptionTask, startDate, null, 60, msg);
if (AzureDockerUtils.DEBUG)
System.out.println("Uploading Dockerfile and artifact: " + new Date().toString());
AzureDockerVMOps.uploadDockerfileAndArtifact(dockerImageInstance, dockerImageInstance.host.session);
if (AzureDockerUtils.DEBUG)
System.out.println("Uploading Dockerfile and artifact: " + new Date().toString());
msg = String.format("Creating Docker image %s on %s ...", dockerImageInstance.dockerImageName, dockerImageInstance.host.name);
notifyProgress(descriptionTask, startDate, null, 80, msg);
if (AzureDockerUtils.DEBUG)
System.out.println("Creating a Docker image to the Docker host: " + new Date().toString());
AzureDockerImageOps.create(dockerImageInstance, dockerImageInstance.host.session);
if (AzureDockerUtils.DEBUG)
System.out.println("Done creating a Docker image to the Docker host: " + new Date().toString());
msg = String.format("Creating Docker container %s for image %s on %s ...", dockerImageInstance.dockerContainerName, dockerImageInstance.dockerImageName, dockerImageInstance.host.name);
notifyProgress(descriptionTask, startDate, null, 90, msg);
if (AzureDockerUtils.DEBUG)
System.out.println("Creating a Docker container to the Docker host: " + new Date().toString());
AzureDockerContainerOps.create(dockerImageInstance, dockerImageInstance.host.session);
if (AzureDockerUtils.DEBUG)
System.out.println("Done creating a Docker container to the Docker host: " + new Date().toString());
msg = String.format("Starting Docker container %s for image %s on %s ...", dockerImageInstance.dockerContainerName, dockerImageInstance.dockerImageName, dockerImageInstance.host.name);
notifyProgress(descriptionTask, startDate, null, 95, msg);
if (AzureDockerUtils.DEBUG)
System.out.println("Starting a Docker container to the Docker host: " + new Date().toString());
AzureDockerContainerOps.start(dockerImageInstance, dockerImageInstance.host.session);
if (AzureDockerUtils.DEBUG)
System.out.println("Done starting a Docker container to the Docker host: " + new Date().toString());
notifyProgress(descriptionTask, startDate, url, 100, message("runStatus"), dockerImageInstance.host.name);
} catch (InterruptedException e) {
postEventProperties.put("PublishInterruptedError", e.getMessage());
notifyProgress(descriptionTask, startDate, url, 100, message("runStatus"), dockerImageInstance.host.name);
} catch (Exception ee) {
postEventProperties.put("PublishError", ee.getMessage());
notifyProgress(descriptionTask, startDate, url, 100, "Error: %s", ee.getMessage());
}
AppInsightsClient.createByType(AppInsightsClient.EventType.DockerContainer, null, "Deploy", postEventProperties);
}
use of com.microsoft.azure.management.compute.VirtualMachine in project azure-tools-for-java by Microsoft.
the class AzureSelectDockerWizard method createDockerContainerDeployTask.
public void createDockerContainerDeployTask(IProject project, AzureDockerImageInstance dockerImageInstance, AzureDockerHostsManager dockerManager) {
String url = AzureDockerUtils.getUrl(dockerImageInstance);
String deploymentName = url;
String jobDescription = String.format("Publishing %s as Docker Container", new File(dockerImageInstance.artifactPath).getName());
AzureDeploymentProgressNotification.createAzureDeploymentProgressNotification(deploymentName, jobDescription);
Map<String, String> postEventProperties = new HashMap<String, String>();
postEventProperties.put("DockerFileOption", dockerImageInstance.predefinedDockerfile);
Job createDockerHostJob = new Job(jobDescription) {
@Override
protected IStatus run(IProgressMonitor progressMonitor) {
try {
// Setup Azure Console and Azure Activity Log Window notifications
MessageConsole console = com.microsoft.azuretools.core.Activator.findConsole(com.microsoft.azuretools.core.Activator.CONSOLE_NAME);
console.activate();
final MessageConsoleStream azureConsoleOut = console.newMessageStream();
progressMonitor.beginTask("start task", 100);
// com.microsoft.azuretools.core.Activator.removeUnNecessaryListener();
DeploymentEventListener undeployListnr = new DeploymentEventListener() {
@Override
public void onDeploymentStep(DeploymentEventArgs args) {
progressMonitor.subTask(args.getDeployMessage());
progressMonitor.worked(args.getDeployCompleteness());
azureConsoleOut.println(String.format("%s: %s", deploymentName, args.getDeployMessage()));
}
};
com.microsoft.azuretools.core.Activator.getDefault().addDeploymentEventListener(undeployListnr);
com.microsoft.azuretools.core.Activator.depEveList.add(undeployListnr);
// Start the real job here
String msg = String.format("Publishing %s to Docker host %s ...", new File(dockerImageInstance.artifactPath).getName(), dockerImageInstance.host.name);
AzureDeploymentProgressNotification.notifyProgress(this, deploymentName, url, 0, msg);
msg = "Connecting to Azure...";
AzureDeploymentProgressNotification.notifyProgress(this, deploymentName, url, 5, msg);
AzureManager azureAuthManager = AuthMethodManager.getInstance().getAzureManager();
// not signed in
if (azureAuthManager == null) {
throw new RuntimeException("User not signed in");
}
AzureDockerHostsManager dockerManager = AzureDockerHostsManager.getAzureDockerHostsManagerEmpty(azureAuthManager);
Azure azureClient = dockerManager.getSubscriptionsMap().get(dockerImageInstance.host.sid).azureClient;
if (progressMonitor.isCanceled()) {
displayWarningOnCreateDockerContainerDeployTask(this, progressMonitor, deploymentName);
return Status.CANCEL_STATUS;
}
if (dockerImageInstance.hasNewDockerHost) {
msg = String.format("Creating new virtual machine %s ...", dockerImageInstance.host.name);
AzureDeploymentProgressNotification.notifyProgress(this, deploymentName, url, 20, msg);
AzureDockerUIResources.printDebugMessage(this, "Creating new virtual machine: " + new Date().toString());
AzureDockerVMOps.createDockerHostVM(azureClient, dockerImageInstance.host);
AzureDockerUIResources.printDebugMessage(this, "Done creating new virtual machine: " + new Date().toString());
if (progressMonitor.isCanceled()) {
displayWarningOnCreateDockerContainerDeployTask(this, progressMonitor, deploymentName);
return Status.CANCEL_STATUS;
}
msg = String.format("Updating Docker hosts ...");
AzureDeploymentProgressNotification.notifyProgress(this, deploymentName, url, 5, msg);
AzureDockerUIResources.printDebugMessage(this, "Getting the new docker host details: " + new Date().toString());
// dockerManager.refreshDockerHostDetails();
VirtualMachine vm = azureClient.virtualMachines().getByResourceGroup(dockerImageInstance.host.hostVM.resourceGroupName, dockerImageInstance.host.hostVM.name);
if (vm != null) {
DockerHost updatedHost = AzureDockerVMOps.getDockerHost(vm, dockerManager.getDockerVaultsMap());
if (updatedHost != null) {
dockerImageInstance.host.hostVM = updatedHost.hostVM;
dockerImageInstance.host.apiUrl = updatedHost.apiUrl;
}
}
AzureDockerUIResources.printDebugMessage(this, "Done getting new Docker host details: " + new Date().toString());
msg = String.format("Waiting for virtual machine to be up %s ...", dockerImageInstance.host.name);
AzureDeploymentProgressNotification.notifyProgress(this, deploymentName, url, 10, msg);
AzureDockerUIResources.printDebugMessage(this, "Waiting for virtual machine to be up: " + new Date().toString());
AzureDockerVMOps.waitForVirtualMachineStartup(azureClient, dockerImageInstance.host);
AzureDockerUIResources.printDebugMessage(this, "Done Waiting for virtual machine to be up: " + new Date().toString());
if (progressMonitor.isCanceled()) {
displayWarningOnCreateDockerContainerDeployTask(this, progressMonitor, deploymentName);
return Status.CANCEL_STATUS;
}
msg = String.format("Configuring Docker service for %s ...", dockerImageInstance.host.name);
AzureDeploymentProgressNotification.notifyProgress(this, deploymentName, url, 10, msg);
AzureDockerUIResources.printDebugMessage(this, "Configuring Docker host: " + new Date().toString());
AzureDockerVMOps.installDocker(dockerImageInstance.host);
AzureDockerUIResources.printDebugMessage(this, "Done configuring Docker host: " + new Date().toString());
msg = String.format("Updating Docker hosts ...");
AzureDeploymentProgressNotification.notifyProgress(this, deploymentName, url, 5, msg);
AzureDockerUIResources.printDebugMessage(this, "Refreshing docker hosts: " + new Date().toString());
// dockerManager.refreshDockerHostDetails();
vm = azureClient.virtualMachines().getByResourceGroup(dockerImageInstance.host.hostVM.resourceGroupName, dockerImageInstance.host.hostVM.name);
if (vm != null) {
DockerHost updatedHost = AzureDockerVMOps.getDockerHost(vm, dockerManager.getDockerVaultsMap());
if (updatedHost != null) {
updatedHost.sid = dockerImageInstance.host.sid;
updatedHost.hostVM.sid = dockerImageInstance.host.hostVM.sid;
if (updatedHost.certVault == null) {
updatedHost.certVault = dockerImageInstance.host.certVault;
updatedHost.hasPwdLogIn = dockerImageInstance.host.hasPwdLogIn;
updatedHost.hasSSHLogIn = dockerImageInstance.host.hasSSHLogIn;
updatedHost.isTLSSecured = dockerImageInstance.host.isTLSSecured;
}
dockerManager.addDockerHostDetails(updatedHost);
if (AzureUIRefreshCore.listeners != null) {
AzureUIRefreshCore.execute(new AzureUIRefreshEvent(AzureUIRefreshEvent.EventType.ADD, updatedHost));
}
}
}
AzureDockerUIResources.printDebugMessage(this, "Done refreshing Docker hosts: " + new Date().toString());
AzureDockerUIResources.printDebugMessage(this, "Finished setting up Docker host");
} else {
msg = String.format("Using virtual machine %s ...", dockerImageInstance.host.name);
AzureDeploymentProgressNotification.notifyProgress(this, deploymentName, url, 55, msg);
}
if (progressMonitor.isCanceled()) {
displayWarningOnCreateDockerContainerDeployTask(this, progressMonitor, deploymentName);
return Status.CANCEL_STATUS;
}
if (dockerImageInstance.host.session == null) {
AzureDockerUIResources.printDebugMessage(this, "Opening a remote connection to the Docker host: " + new Date().toString());
dockerImageInstance.host.session = AzureDockerSSHOps.createLoginInstance(dockerImageInstance.host);
AzureDockerUIResources.printDebugMessage(this, "Done opening a remote connection to the Docker host: " + new Date().toString());
}
if (dockerImageInstance.hasNewDockerHost) {
if (dockerImageInstance.host.certVault != null && dockerImageInstance.host.certVault.hostName != null) {
AzureDockerUIResources.createDockerKeyVault(dockerImageInstance.host, dockerManager);
}
}
msg = String.format("Uploading Dockerfile and artifact %s on %s ...", dockerImageInstance.artifactName, dockerImageInstance.host.name);
AzureDeploymentProgressNotification.notifyProgress(this, deploymentName, url, 15, msg);
AzureDockerUIResources.printDebugMessage(this, "Uploading Dockerfile and artifact: " + new Date().toString());
AzureDockerVMOps.uploadDockerfileAndArtifact(dockerImageInstance, dockerImageInstance.host.session);
AzureDockerUIResources.printDebugMessage(this, "Uploading Dockerfile and artifact: " + new Date().toString());
if (progressMonitor.isCanceled()) {
displayWarningOnCreateDockerContainerDeployTask(this, progressMonitor, deploymentName);
return Status.CANCEL_STATUS;
}
msg = String.format("Creating Docker image %s on %s ...", dockerImageInstance.dockerImageName, dockerImageInstance.host.name);
AzureDeploymentProgressNotification.notifyProgress(this, deploymentName, url, 15, msg);
AzureDockerUIResources.printDebugMessage(this, "Creating a Docker image to the Docker host: " + new Date().toString());
AzureDockerImageOps.create(dockerImageInstance, dockerImageInstance.host.session);
AzureDockerUIResources.printDebugMessage(this, "Done creating a Docker image to the Docker host: " + new Date().toString());
if (progressMonitor.isCanceled()) {
displayWarningOnCreateDockerContainerDeployTask(this, progressMonitor, deploymentName);
return Status.CANCEL_STATUS;
}
msg = String.format("Creating Docker container %s for image %s on %s ...", dockerImageInstance.dockerContainerName, dockerImageInstance.dockerImageName, dockerImageInstance.host.name);
AzureDeploymentProgressNotification.notifyProgress(this, deploymentName, url, 5, msg);
AzureDockerUIResources.printDebugMessage(this, "Creating a Docker container to the Docker host: " + new Date().toString());
AzureDockerContainerOps.create(dockerImageInstance, dockerImageInstance.host.session);
AzureDockerUIResources.printDebugMessage(this, "Done creating a Docker container to the Docker host: " + new Date().toString());
if (progressMonitor.isCanceled()) {
displayWarningOnCreateDockerContainerDeployTask(this, progressMonitor, deploymentName);
return Status.CANCEL_STATUS;
}
msg = String.format("Starting Docker container %s for image %s on %s ...", dockerImageInstance.dockerContainerName, dockerImageInstance.dockerImageName, dockerImageInstance.host.name);
AzureDeploymentProgressNotification.notifyProgress(this, deploymentName, url, 5, msg);
AzureDockerUIResources.printDebugMessage(this, "Starting a Docker container to the Docker host: " + new Date().toString());
AzureDockerContainerOps.start(dockerImageInstance, dockerImageInstance.host.session);
AzureDockerUIResources.printDebugMessage(this, "Done starting a Docker container to the Docker host: " + new Date().toString());
if (progressMonitor.isCanceled()) {
displayWarningOnCreateDockerContainerDeployTask(this, progressMonitor, deploymentName);
return Status.CANCEL_STATUS;
}
AzureDeploymentProgressNotification.notifyProgress(this, deploymentName, url, 100, "");
try {
com.microsoft.azuretools.core.Activator.depEveList.remove(undeployListnr);
com.microsoft.azuretools.core.Activator.removeDeploymentEventListener(undeployListnr);
} catch (Exception ignored) {
}
progressMonitor.done();
AppInsightsClient.create("Deploy as DockerContainer", "", postEventProperties);
return Status.OK_STATUS;
} catch (Exception e) {
String msg = "An error occurred while attempting to publish a Docker container!" + "\n" + e.getMessage();
log.log(Level.SEVERE, "createDockerContainerDeployTask: " + msg, e);
e.printStackTrace();
AzureDeploymentProgressNotification.notifyProgress(this, deploymentName, null, -1, "Error: " + e.getMessage());
return Status.CANCEL_STATUS;
}
}
};
createDockerHostJob.schedule();
}
use of com.microsoft.azure.management.compute.VirtualMachine in project azure-sdk-for-java by Azure.
the class ManageManagedDisks method prepareSpecializedManagedVirtualMachine.
private static VirtualMachine prepareSpecializedManagedVirtualMachine(Azure azure, Region region, String rgName) {
final String userName = "tirekicker";
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;
}
use of com.microsoft.azure.management.compute.VirtualMachine in project azure-sdk-for-java by Azure.
the class ManageVirtualMachineAsync method runSample.
/**
* Main function which runs the actual sample.
* @param azure instance of the azure client
* @return true if sample runs successfully
*/
public static boolean runSample(final Azure azure) {
final Region region = Region.US_WEST_CENTRAL;
final String windowsVMName = Utils.createRandomName("wVM");
final String linuxVMName = Utils.createRandomName("lVM");
final String rgName = Utils.createRandomName("rgCOMV");
final String userName = "tirekicker";
final String password = "12NewPA$$w0rd!";
final String windowsVmKey = "WindowsVM";
final String linuxVmKey = "LinuxVM";
try {
//=============================================================
// Create a Windows virtual machine
// Prepare a creatable data disk for VM
//
final Date t1 = new Date();
final Creatable<Disk> dataDiskCreatable = azure.disks().define(Utils.createRandomName("dsk-")).withRegion(region).withExistingResourceGroup(rgName).withData().withSizeInGB(100);
// Create a data disk to attach to VM
//
Observable<Indexable> dataDiskObservable = azure.disks().define(Utils.createRandomName("dsk-")).withRegion(region).withNewResourceGroup(rgName).withData().withSizeInGB(50).createAsync();
final Map<String, VirtualMachine> createdVms = new TreeMap<>();
dataDiskObservable.flatMap(new Func1<Indexable, Observable<Indexable>>() {
@Override
public Observable<Indexable> call(Indexable createdResource) {
if (createdResource instanceof Disk) {
System.out.println("Creating a Windows VM");
return azure.virtualMachines().define(windowsVMName).withRegion(region).withNewResourceGroup(rgName).withNewPrimaryNetwork("10.0.0.0/28").withPrimaryPrivateIPAddressDynamic().withoutPrimaryPublicIPAddress().withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER).withAdminUsername(userName).withAdminPassword(password).withNewDataDisk(10).withNewDataDisk(dataDiskCreatable).withExistingDataDisk((Disk) createdResource).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).createAsync();
}
return Observable.just(createdResource);
}
}).flatMap(new Func1<Indexable, Observable<Indexable>>() {
@Override
public Observable<Indexable> call(Indexable createdResource) {
if (createdResource instanceof Network) {
// Once Network object is created we can start creation of Linux VM in the same network
Network network = (Network) createdResource;
System.out.println("Created Network");
Utils.print(network);
System.out.println("Creating a Linux VM in the same network");
return azure.virtualMachines().define(linuxVMName).withRegion(region).withExistingResourceGroup(rgName).withExistingPrimaryNetwork(network).withSubnet(// Referencing the default subnet name when no name specified at creation
"subnet1").withPrimaryPrivateIPAddressDynamic().withoutPrimaryPublicIPAddress().withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(userName).withRootPassword(password).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).createAsync();
}
return Observable.just(createdResource);
}
}).map(new Func1<Indexable, Indexable>() {
@Override
public Indexable call(Indexable createdResource) {
if (createdResource instanceof VirtualMachine) {
Date t2 = new Date();
VirtualMachine virtualMachine = (VirtualMachine) createdResource;
if (isWindowsVM(virtualMachine)) {
createdVms.put(windowsVmKey, virtualMachine);
System.out.println("Created Windows VM: " + virtualMachine.id());
} else {
createdVms.put(linuxVmKey, virtualMachine);
System.out.println("Created a Linux VM (in the same virtual network): " + virtualMachine.id());
}
System.out.println("Virtual machine creation took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds");
// Print virtual machine details
Utils.print(virtualMachine);
}
return createdResource;
}
}).toBlocking().subscribe();
final VirtualMachine windowsVM = createdVms.get(windowsVmKey);
final VirtualMachine linuxVM = createdVms.get(linuxVmKey);
//=============================================================
// Update virtual machines
// - Tag the virtual machine on Linux VM
Observable<VirtualMachine> updateLinuxVMChain = linuxVM.update().withTag("who-rocks-on-linux", "java").withTag("where", "on azure").applyAsync().map(new Func1<VirtualMachine, VirtualMachine>() {
@Override
public VirtualMachine call(VirtualMachine virtualMachine) {
System.out.println("Tagged Linux VM: " + virtualMachine.id());
return virtualMachine;
}
});
// - Add a data disk on Windows VM.
Observable<VirtualMachine> updateWindowsVMChain = windowsVM.update().withNewDataDisk(200).applyAsync();
Observable.merge(updateLinuxVMChain, updateWindowsVMChain).toBlocking().subscribe();
//=============================================================
// List virtual machines and print details
azure.virtualMachines().listByResourceGroupAsync(rgName).map(new Func1<VirtualMachine, VirtualMachine>() {
@Override
public VirtualMachine call(VirtualMachine virtualMachine) {
System.out.println("Retrieved details for VM: " + virtualMachine.id());
Utils.print(virtualMachine);
return virtualMachine;
}
}).toBlocking().subscribe();
//=============================================================
// Delete the virtual machines in parallel
Observable.merge(azure.virtualMachines().deleteByIdAsync(windowsVM.id()).toObservable(), azure.virtualMachines().deleteByIdAsync(linuxVM.id()).toObservable()).toBlocking().subscribe();
return true;
} catch (Exception f) {
System.out.println(f.getMessage());
f.printStackTrace();
} finally {
try {
System.out.println("Deleting Resource Group: " + rgName);
azure.resourceGroups().deleteByNameAsync(rgName).await();
System.out.println("Deleted Resource Group: " + rgName);
} catch (NullPointerException npe) {
System.out.println("Did not create any resources in Azure. No clean up is necessary");
} catch (Exception g) {
g.printStackTrace();
}
}
return false;
}
Aggregations