use of com.microsoft.azure.management.network.NetworkInterface in project azure-sdk-for-java by Azure.
the class VirtualMachineOperationsTests method canDeleteRelatedResourcesFromFailedParallelVMCreations.
@Test
@Ignore("Can't be played from recording for some reason...")
public void canDeleteRelatedResourcesFromFailedParallelVMCreations() {
final int desiredVMCount = 40;
final Region region = Region.US_EAST;
final String resourceGroupName = RG_NAME;
// Create one resource group for everything, to ensure no reliance on resource groups
ResourceGroup resourceGroup = resourceManager.resourceGroups().define(resourceGroupName).withRegion(region).create();
// Needed for tracking related resources
final Map<String, Collection<Creatable<? extends Resource>>> vmNonNicResourceDefinitions = new HashMap<>();
// Tracking NICs separately because they have to be deleted first
final Map<String, Creatable<NetworkInterface>> nicDefinitions = new HashMap<>();
final Map<String, Creatable<VirtualMachine>> vmDefinitions = new HashMap<>();
final Map<String, String> createdResourceIds = new HashMap<>();
final List<Throwable> errors = new ArrayList<>();
// Prepare a number of VM definitions along with their related resource definitions
for (int i = 0; i < desiredVMCount; i++) {
Collection<Creatable<? extends Resource>> relatedDefinitions = new ArrayList<>();
// Define a network for each VM
String networkName = SdkContext.randomResourceName("net", 14);
Creatable<Network> networkDefinition = networkManager.networks().define(networkName).withRegion(region).withExistingResourceGroup(resourceGroup).withAddressSpace("10.0." + i + ".0/29");
relatedDefinitions.add(networkDefinition);
// Define a PIP for each VM
String pipName = SdkContext.randomResourceName("pip", 14);
PublicIPAddress.DefinitionStages.WithCreate pipDefinition = this.networkManager.publicIPAddresses().define(pipName).withRegion(region).withExistingResourceGroup(resourceGroup);
relatedDefinitions.add(pipDefinition);
// Define a NIC for each VM
String nicName = SdkContext.randomResourceName("nic", 14);
Creatable<NetworkInterface> nicDefinition = networkManager.networkInterfaces().define(nicName).withRegion(region).withExistingResourceGroup(resourceGroup).withNewPrimaryNetwork(networkDefinition).withPrimaryPrivateIPAddressDynamic().withNewPrimaryPublicIPAddress(pipDefinition);
// Define a storage account for each VM
String storageAccountName = SdkContext.randomResourceName("st", 14);
Creatable<StorageAccount> storageAccountDefinition = storageManager.storageAccounts().define(storageAccountName).withRegion(region).withExistingResourceGroup(resourceGroup);
relatedDefinitions.add(storageAccountDefinition);
// Define an availability set for each VM
String availabilitySetName = SdkContext.randomResourceName("as", 14);
Creatable<AvailabilitySet> availabilitySetDefinition = computeManager.availabilitySets().define(availabilitySetName).withRegion(region).withExistingResourceGroup(resourceGroup);
relatedDefinitions.add(availabilitySetDefinition);
String vmName = SdkContext.randomResourceName("vm", 14);
// Define a VM
String userName;
if (i == desiredVMCount / 2) {
// Intentionally cause a failure in one of the VMs
userName = "";
} else {
userName = "tester";
}
Creatable<VirtualMachine> vmDefinition = computeManager.virtualMachines().define(vmName).withRegion(region).withExistingResourceGroup(resourceGroup).withNewPrimaryNetworkInterface(nicDefinition).withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(userName).withRootPassword("Abcdef.123456!").withNewStorageAccount(storageAccountDefinition).withSize(VirtualMachineSizeTypes.STANDARD_DS1_V2).withNewAvailabilitySet(availabilitySetDefinition);
// Keep track of all the related resource definitions based on the VM definition
vmNonNicResourceDefinitions.put(vmDefinition.key(), relatedDefinitions);
nicDefinitions.put(vmDefinition.key(), nicDefinition);
vmDefinitions.put(vmDefinition.key(), vmDefinition);
}
// Start the parallel creation of everything
computeManager.virtualMachines().createAsync(new ArrayList<>(vmDefinitions.values())).map(new Func1<Indexable, Indexable>() {
@Override
public Indexable call(Indexable createdResource) {
if (createdResource instanceof Resource) {
Resource resource = (Resource) createdResource;
System.out.println("Created: " + resource.id());
if (resource instanceof VirtualMachine) {
VirtualMachine virtualMachine = (VirtualMachine) resource;
// Record that this VM was created successfully
vmDefinitions.remove(virtualMachine.key());
// Remove the associated resources from cleanup list
vmNonNicResourceDefinitions.remove(virtualMachine.key());
// Remove the associated NIC from cleanup list
nicDefinitions.remove(virtualMachine.key());
} else {
// Add this related resource to potential cleanup list
createdResourceIds.put(resource.key(), resource.id());
}
}
return createdResource;
}
}).onErrorReturn(new Func1<Throwable, Indexable>() {
@Override
public Indexable call(Throwable throwable) {
errors.add(throwable);
return null;
}
}).toBlocking().last();
// Delete remaining successfully created NICs of failed VM creations
Collection<String> nicIdsToDelete = new ArrayList<>();
for (Creatable<NetworkInterface> nicDefinition : nicDefinitions.values()) {
String nicId = createdResourceIds.get(nicDefinition.key());
if (nicId != null) {
nicIdsToDelete.add(nicId);
}
}
if (!nicIdsToDelete.isEmpty()) {
networkManager.networkInterfaces().deleteByIds(nicIdsToDelete);
}
// Delete remaining successfully created resources of failed VM creations
Collection<Completable> deleteObservables = new ArrayList<>();
for (Collection<Creatable<? extends Resource>> relatedResources : vmNonNicResourceDefinitions.values()) {
for (Creatable<? extends Resource> resource : relatedResources) {
String createdResourceId = createdResourceIds.get(resource.key());
if (createdResourceId != null) {
deleteObservables.add(resourceManager.genericResources().deleteByIdAsync(createdResourceId));
}
}
}
// Delete as much as possible, postponing the errors till the end
Completable.mergeDelayError(deleteObservables).await();
// Show any errors
for (Throwable error : errors) {
System.out.println("\n### ERROR ###\n");
if (error instanceof CloudException) {
CloudException ce = (CloudException) error;
System.out.println("CLOUD EXCEPTION: " + ce.getMessage());
} else {
error.printStackTrace();
}
}
System.out.println("Number of failed/cleaned up VM creations: " + vmNonNicResourceDefinitions.size());
// Verifications
final int successfulVMCount = desiredVMCount - vmNonNicResourceDefinitions.size();
final int actualVMCount = computeManager.virtualMachines().listByResourceGroup(resourceGroupName).size();
System.out.println("Number of actual successful VMs: " + actualVMCount);
Assert.assertEquals(successfulVMCount, actualVMCount);
final int actualNicCount = networkManager.networkInterfaces().listByResourceGroup(resourceGroupName).size();
Assert.assertEquals(successfulVMCount, actualNicCount);
final int actualNetworkCount = networkManager.networks().listByResourceGroup(resourceGroupName).size();
Assert.assertEquals(successfulVMCount, actualNetworkCount);
final int actualPipCount = networkManager.publicIPAddresses().listByResourceGroup(resourceGroupName).size();
Assert.assertEquals(successfulVMCount, actualPipCount);
final int actualAvailabilitySetCount = computeManager.availabilitySets().listByResourceGroup(resourceGroupName).size();
Assert.assertEquals(successfulVMCount, actualAvailabilitySetCount);
final int actualStorageAccountCount = storageManager.storageAccounts().listByResourceGroup(resourceGroupName).size();
Assert.assertEquals(successfulVMCount, actualStorageAccountCount);
// Verify that at least one VM failed.
// TODO: Ideally only one, but today the internal RX logic terminates eagerly -- need to change that for parallel creation to terminate more "lazily" in the future
Assert.assertTrue(successfulVMCount < desiredVMCount);
}
use of com.microsoft.azure.management.network.NetworkInterface in project azure-sdk-for-java by Azure.
the class LoadBalancerImpl method afterCreating.
@Override
protected void afterCreating() {
List<Exception> nicExceptions = new ArrayList<>();
// Update the NICs to point to the backend pool
for (Entry<String, String> nicInBackend : this.nicsInBackends.entrySet()) {
String nicId = nicInBackend.getKey();
String backendName = nicInBackend.getValue();
try {
NetworkInterface nic = this.manager().networkInterfaces().getById(nicId);
NicIPConfiguration nicIP = nic.primaryIPConfiguration();
nic.update().updateIPConfiguration(nicIP.name()).withExistingLoadBalancerBackend(this, backendName).parent().apply();
} catch (Exception e) {
nicExceptions.add(e);
}
}
if (!nicExceptions.isEmpty()) {
throw new CompositeException(nicExceptions);
}
this.nicsInBackends.clear();
this.refresh();
}
use of com.microsoft.azure.management.network.NetworkInterface in project azure-sdk-for-java by Azure.
the class PublicIPAddressImpl method getAssignedNetworkInterfaceIPConfiguration.
@Override
public NicIPConfiguration getAssignedNetworkInterfaceIPConfiguration() {
if (this.hasAssignedNetworkInterface()) {
final String refId = this.inner().ipConfiguration().id();
final String parentId = ResourceUtils.parentResourceIdFromResourceId(refId);
final NetworkInterface nic = this.myManager.networkInterfaces().getById(parentId);
final String childName = ResourceUtils.nameFromResourceId(refId);
return nic.ipConfigurations().get(childName);
} else {
return null;
}
}
use of com.microsoft.azure.management.network.NetworkInterface in project azure-sdk-for-java by Azure.
the class ManageNetworkInterface 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(Azure azure) {
final Region region = Region.US_NORTH_CENTRAL;
final String vnetName = SdkContext.randomResourceName("vnet", 24);
final String networkInterfaceName1 = SdkContext.randomResourceName("nic1", 24);
final String networkInterfaceName2 = SdkContext.randomResourceName("nic2", 24);
final String networkInterfaceName3 = SdkContext.randomResourceName("nic3", 24);
final String publicIPAddressLeafDNS1 = SdkContext.randomResourceName("pip1", 24);
final String publicIPAddressLeafDNS2 = SdkContext.randomResourceName("pip2", 24);
// TODO adjust the length of vm name from 8 to 24
final String vmName = SdkContext.randomResourceName("vm", 8);
final String rgName = SdkContext.randomResourceName("rgNEMI", 24);
final String userName = "tirekicker";
final String password = "12NewPA$$w0rd!";
try {
//============================================================
// Create a virtual machine with multiple network interfaces
// Define a virtual network for the VMs in this availability set
System.out.println("Creating a virtual network ...");
Network network = azure.networks().define(vnetName).withRegion(region).withNewResourceGroup(rgName).withAddressSpace("172.16.0.0/16").defineSubnet("Front-end").withAddressPrefix("172.16.1.0/24").attach().defineSubnet("Mid-tier").withAddressPrefix("172.16.2.0/24").attach().defineSubnet("Back-end").withAddressPrefix("172.16.3.0/24").attach().create();
System.out.println("Created a virtual network: " + network.id());
Utils.print(network);
System.out.println("Creating multiple network interfaces");
System.out.println("Creating network interface 1");
NetworkInterface networkInterface1 = azure.networkInterfaces().define(networkInterfaceName1).withRegion(region).withExistingResourceGroup(rgName).withExistingPrimaryNetwork(network).withSubnet("Front-end").withPrimaryPrivateIPAddressDynamic().withNewPrimaryPublicIPAddress(publicIPAddressLeafDNS1).withIPForwarding().create();
System.out.println("Created network interface 1");
Utils.print(networkInterface1);
System.out.println("Creating network interface 2");
NetworkInterface networkInterface2 = azure.networkInterfaces().define(networkInterfaceName2).withRegion(region).withExistingResourceGroup(rgName).withExistingPrimaryNetwork(network).withSubnet("Mid-tier").withPrimaryPrivateIPAddressDynamic().create();
System.out.println("Created network interface 2");
Utils.print(networkInterface2);
System.out.println("Creating network interface 3");
NetworkInterface networkInterface3 = azure.networkInterfaces().define(networkInterfaceName3).withRegion(region).withExistingResourceGroup(rgName).withExistingPrimaryNetwork(network).withSubnet("Back-end").withPrimaryPrivateIPAddressDynamic().create();
System.out.println("Created network interface 3");
Utils.print(networkInterface3);
//=============================================================
// Create a virtual machine with multiple network interfaces
System.out.println("Creating a Windows VM");
Date t1 = new Date();
VirtualMachine vm = azure.virtualMachines().define(vmName).withRegion(region).withExistingResourceGroup(rgName).withExistingPrimaryNetworkInterface(networkInterface1).withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER).withAdminUsername(userName).withAdminPassword(password).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).withExistingSecondaryNetworkInterface(networkInterface2).withExistingSecondaryNetworkInterface(networkInterface3).create();
Date t2 = new Date();
System.out.println("Created VM: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + vm.id());
// Print virtual machine details
Utils.print(vm);
// ===========================================================
// Configure a network interface
System.out.println("Updating the first network interface");
networkInterface1.update().withNewPrimaryPublicIPAddress(publicIPAddressLeafDNS2).apply();
System.out.println("Updated the first network interface");
Utils.print(networkInterface1);
System.out.println();
//============================================================
// List network interfaces
System.out.println("Walking through network inter4faces in resource group: " + rgName);
PagedList<NetworkInterface> networkInterfaces = azure.networkInterfaces().listByResourceGroup(rgName);
for (NetworkInterface networkinterface : networkInterfaces) {
Utils.print(networkinterface);
}
//============================================================
// Delete a network interface
System.out.println("Deleting a network interface: " + networkInterface2.id());
System.out.println("First, deleting the vm");
azure.virtualMachines().deleteById(vm.id());
System.out.println("Second, deleting the network interface");
azure.networkInterfaces().deleteById(networkInterface2.id());
System.out.println("Deleted network interface");
System.out.println("============================================================");
System.out.println("Remaining network interfaces are ...");
networkInterfaces = azure.networkInterfaces().listByResourceGroup(rgName);
for (NetworkInterface networkinterface : networkInterfaces) {
Utils.print(networkinterface);
}
return true;
} catch (Exception f) {
System.out.println(f.getMessage());
f.printStackTrace();
} finally {
try {
System.out.println("Deleting Resource Group: " + rgName);
azure.resourceGroups().deleteByName(rgName);
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;
}
use of com.microsoft.azure.management.network.NetworkInterface in project azure-sdk-for-java by Azure.
the class ManageNetworkSecurityGroup 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(Azure azure) {
final Region region = Region.US_NORTH_CENTRAL;
final String frontEndNSGName = SdkContext.randomResourceName("fensg", 24);
final String backEndNSGName = SdkContext.randomResourceName("bensg", 24);
final String rgName = SdkContext.randomResourceName("rgNEMS", 24);
final String vnetName = SdkContext.randomResourceName("vnet", 24);
final String networkInterfaceName1 = SdkContext.randomResourceName("nic1", 24);
final String networkInterfaceName2 = SdkContext.randomResourceName("nic2", 24);
final String publicIPAddressLeafDNS1 = SdkContext.randomResourceName("pip1", 24);
final String frontEndVMName = SdkContext.randomResourceName("fevm", 24);
final String backEndVMName = SdkContext.randomResourceName("bevm", 24);
final String userName = "tirekicker";
final String sshKey = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCfSPC2K7LZcFKEO+/t3dzmQYtrJFZNxOsbVgOVKietqHyvmYGHEC0J2wPdAqQ/63g/hhAEFRoyehM+rbeDri4txB3YFfnOK58jqdkyXzupWqXzOrlKY4Wz9SKjjN765+dqUITjKRIaAip1Ri137szRg71WnrmdP3SphTRlCx1Bk2nXqWPsclbRDCiZeF8QOTi4JqbmJyK5+0UqhqYRduun8ylAwKKQJ1NJt85sYIHn9f1Rfr6Tq2zS0wZ7DHbZL+zB5rSlAr8QyUdg/GQD+cmSs6LvPJKL78d6hMGk84ARtFo4A79ovwX/Fj01znDQkU6nJildfkaolH2rWFG/qttD azjava@javalib.com";
try {
// Define a virtual network for VMs in this availability set
System.out.println("Creating a virtual network ...");
Network network = azure.networks().define(vnetName).withRegion(region).withNewResourceGroup(rgName).withAddressSpace("172.16.0.0/16").defineSubnet("Front-end").withAddressPrefix("172.16.1.0/24").attach().defineSubnet("Back-end").withAddressPrefix("172.16.2.0/24").attach().create();
System.out.println("Created a virtual network: " + network.id());
Utils.print(network);
//============================================================
// Create a network security group for the front end of a subnet
// front end subnet contains two rules
// - ALLOW-SSH - allows SSH traffic into the front end subnet
// - ALLOW-WEB- allows HTTP traffic into the front end subnet
System.out.println("Creating a security group for the front end - allows SSH and HTTP");
NetworkSecurityGroup frontEndNSG = azure.networkSecurityGroups().define(frontEndNSGName).withRegion(region).withNewResourceGroup(rgName).defineRule("ALLOW-SSH").allowInbound().fromAnyAddress().fromAnyPort().toAnyAddress().toPort(22).withProtocol(SecurityRuleProtocol.TCP).withPriority(100).withDescription("Allow SSH").attach().defineRule("ALLOW-HTTP").allowInbound().fromAnyAddress().fromAnyPort().toAnyAddress().toPort(80).withProtocol(SecurityRuleProtocol.TCP).withPriority(101).withDescription("Allow HTTP").attach().create();
System.out.println("Created a security group for the front end: " + frontEndNSG.id());
Utils.print(frontEndNSG);
//============================================================
// Create a network security group for the back end of a subnet
// back end subnet contains two rules
// - ALLOW-SQL - allows SQL traffic only from the front end subnet
// - DENY-WEB - denies all outbound internet traffic from the back end subnet
System.out.println("Creating a security group for the front end - allows SSH and " + "denies all outbound internet traffic ");
NetworkSecurityGroup backEndNSG = azure.networkSecurityGroups().define(backEndNSGName).withRegion(region).withExistingResourceGroup(rgName).defineRule("ALLOW-SQL").allowInbound().fromAddress("172.16.1.0/24").fromAnyPort().toAnyAddress().toPort(1433).withProtocol(SecurityRuleProtocol.TCP).withPriority(100).withDescription("Allow SQL").attach().defineRule("DENY-WEB").denyOutbound().fromAnyAddress().fromAnyPort().toAnyAddress().toAnyPort().withAnyProtocol().withDescription("Deny Web").withPriority(200).attach().create();
System.out.println("Created a security group for the back end: " + backEndNSG.id());
Utils.print(backEndNSG);
System.out.println("Creating multiple network interfaces");
System.out.println("Creating network interface 1");
//========================================================
// Create a network interface and apply the
// front end network security group
System.out.println("Creating a network interface for the front end");
NetworkInterface networkInterface1 = azure.networkInterfaces().define(networkInterfaceName1).withRegion(region).withExistingResourceGroup(rgName).withExistingPrimaryNetwork(network).withSubnet("Front-end").withPrimaryPrivateIPAddressDynamic().withNewPrimaryPublicIPAddress(publicIPAddressLeafDNS1).withIPForwarding().withExistingNetworkSecurityGroup(frontEndNSG).create();
System.out.println("Created network interface for the front end");
Utils.print(networkInterface1);
//========================================================
// Create a network interface and apply the
// back end network security group
System.out.println("Creating a network interface for the back end");
NetworkInterface networkInterface2 = azure.networkInterfaces().define(networkInterfaceName2).withRegion(region).withExistingResourceGroup(rgName).withExistingPrimaryNetwork(network).withSubnet("Back-end").withPrimaryPrivateIPAddressDynamic().withExistingNetworkSecurityGroup(backEndNSG).create();
Utils.print(networkInterface2);
//=============================================================
// Create a virtual machine (for the front end)
// with the network interface that has the network security group for the front end
System.out.println("Creating a Linux virtual machine (for the front end) - " + "with the network interface that has the network security group for the front end");
Date t1 = new Date();
VirtualMachine frontEndVM = azure.virtualMachines().define(frontEndVMName).withRegion(region).withExistingResourceGroup(rgName).withExistingPrimaryNetworkInterface(networkInterface1).withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(userName).withSsh(sshKey).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).create();
Date t2 = new Date();
System.out.println("Created Linux VM: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + frontEndVM.id());
// Print virtual machine details
Utils.print(frontEndVM);
//=============================================================
// Create a virtual machine (for the back end)
// with the network interface that has the network security group for the back end
System.out.println("Creating a Linux virtual machine (for the back end) - " + "with the network interface that has the network security group for the back end");
t1 = new Date();
VirtualMachine backEndVM = azure.virtualMachines().define(backEndVMName).withRegion(region).withExistingResourceGroup(rgName).withExistingPrimaryNetworkInterface(networkInterface2).withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(userName).withSsh(sshKey).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).create();
t2 = new Date();
System.out.println("Created a Linux VM: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + backEndVM.id());
Utils.print(backEndVM);
//========================================================
// List network security groups
System.out.println("Walking through network security groups");
List<NetworkSecurityGroup> networkSecurityGroups = azure.networkSecurityGroups().listByResourceGroup(rgName);
for (NetworkSecurityGroup networkSecurityGroup : networkSecurityGroups) {
Utils.print(networkSecurityGroup);
}
//========================================================
// Update a network security group
System.out.println("Updating the front end network security group to allow FTP");
frontEndNSG.update().defineRule("ALLOW-FTP").allowInbound().fromAnyAddress().fromAnyPort().toAnyAddress().toPortRange(20, 21).withProtocol(SecurityRuleProtocol.TCP).withDescription("Allow FTP").withPriority(200).attach().apply();
System.out.println("Updated the front end network security group");
Utils.print(frontEndNSG);
return true;
} catch (Exception f) {
System.out.println(f.getMessage());
f.printStackTrace();
} finally {
try {
System.out.println("Deleting Resource Group: " + rgName);
azure.resourceGroups().deleteByName(rgName);
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