Search in sources :

Example 21 with Network

use of com.microsoft.azure.management.network.Network 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);
}
Also used : Completable(rx.Completable) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Network(com.microsoft.azure.management.network.Network) Creatable(com.microsoft.azure.management.resources.fluentcore.model.Creatable) Indexable(com.microsoft.azure.management.resources.fluentcore.model.Indexable) Func1(rx.functions.Func1) ResourceGroup(com.microsoft.azure.management.resources.ResourceGroup) Resource(com.microsoft.azure.management.resources.fluentcore.arm.models.Resource) NetworkInterface(com.microsoft.azure.management.network.NetworkInterface) CloudException(com.microsoft.azure.CloudException) StorageAccount(com.microsoft.azure.management.storage.StorageAccount) Region(com.microsoft.azure.management.resources.fluentcore.arm.Region) Collection(java.util.Collection) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 22 with Network

use of com.microsoft.azure.management.network.Network in project azure-sdk-for-java by Azure.

the class CreateVirtualMachinesInParallel 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 String rgName = SdkContext.randomResourceName("rgCOPD", 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";
    Map<Region, Integer> virtualMachinesByLocation = new HashMap<Region, Integer>();
    // debug target
    /**
         virtualMachinesByLocation.put(Region.US_EAST, 5);
         virtualMachinesByLocation.put(Region.US_SOUTH_CENTRAL, 5);
         */
    // final demo target
    virtualMachinesByLocation.put(Region.US_EAST, 12);
    virtualMachinesByLocation.put(Region.US_SOUTH_CENTRAL, 12);
    virtualMachinesByLocation.put(Region.US_WEST, 12);
    virtualMachinesByLocation.put(Region.US_NORTH_CENTRAL, 12);
    try {
        //=============================================================
        // Create a resource group (Where all resources gets created)
        //
        ResourceGroup resourceGroup = azure.resourceGroups().define(rgName).withRegion(Region.US_EAST).create();
        System.out.println("Created a new resource group - " + resourceGroup.id());
        List<String> publicIpCreatableKeys = new ArrayList<>();
        // Prepare a batch of Creatable definitions
        //
        List<Creatable<VirtualMachine>> creatableVirtualMachines = new ArrayList<>();
        for (Map.Entry<Region, Integer> entry : virtualMachinesByLocation.entrySet()) {
            Region region = entry.getKey();
            Integer vmCount = entry.getValue();
            //=============================================================
            // Create 1 network creatable per region
            // Prepare Creatable Network definition (Where all the virtual machines get added to)
            //
            String networkName = SdkContext.randomResourceName("vnetCOPD-", 20);
            Creatable<Network> networkCreatable = azure.networks().define(networkName).withRegion(region).withExistingResourceGroup(resourceGroup).withAddressSpace("172.16.0.0/16");
            //=============================================================
            // Create 1 storage creatable per region (For storing VMs disk)
            //
            String storageAccountName = SdkContext.randomResourceName("stgcopd", 20);
            Creatable<StorageAccount> storageAccountCreatable = azure.storageAccounts().define(storageAccountName).withRegion(region).withExistingResourceGroup(resourceGroup);
            String linuxVMNamePrefix = SdkContext.randomResourceName("vm-", 15);
            for (int i = 1; i <= vmCount; i++) {
                //=============================================================
                // Create 1 public IP address creatable
                //
                Creatable<PublicIPAddress> publicIPAddressCreatable = azure.publicIPAddresses().define(String.format("%s-%d", linuxVMNamePrefix, i)).withRegion(region).withExistingResourceGroup(resourceGroup).withLeafDomainLabel(SdkContext.randomResourceName("pip", 10));
                publicIpCreatableKeys.add(publicIPAddressCreatable.key());
                //=============================================================
                // Create 1 virtual machine creatable
                Creatable<VirtualMachine> virtualMachineCreatable = azure.virtualMachines().define(String.format("%s-%d", linuxVMNamePrefix, i)).withRegion(region).withExistingResourceGroup(resourceGroup).withNewPrimaryNetwork(networkCreatable).withPrimaryPrivateIPAddressDynamic().withNewPrimaryPublicIPAddress(publicIPAddressCreatable).withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(userName).withSsh(sshKey).withSize(VirtualMachineSizeTypes.STANDARD_DS3_V2).withNewStorageAccount(storageAccountCreatable);
                creatableVirtualMachines.add(virtualMachineCreatable);
            }
        }
        //=============================================================
        // Create !!
        StopWatch stopwatch = new StopWatch();
        System.out.println("Creating the virtual machines");
        stopwatch.start();
        CreatedResources<VirtualMachine> virtualMachines = azure.virtualMachines().create(creatableVirtualMachines);
        stopwatch.stop();
        System.out.println("Created virtual machines");
        for (VirtualMachine virtualMachine : virtualMachines.values()) {
            System.out.println(virtualMachine.id());
        }
        System.out.println("Virtual Machines created: (took " + (stopwatch.getTime() / 1000) + " seconds to create) == " + virtualMachines.size() + " == virtual machines");
        List<String> publicIpResourceIds = new ArrayList<>();
        for (String publicIpCreatableKey : publicIpCreatableKeys) {
            PublicIPAddress pip = (PublicIPAddress) virtualMachines.createdRelatedResource(publicIpCreatableKey);
            publicIpResourceIds.add(pip.id());
        }
        //=============================================================
        // Create 1 Traffic Manager Profile
        //
        String trafficManagerName = SdkContext.randomResourceName("tra", 15);
        TrafficManagerProfile.DefinitionStages.WithEndpoint profileWithEndpoint = azure.trafficManagerProfiles().define(trafficManagerName).withExistingResourceGroup(resourceGroup).withLeafDomainLabel(trafficManagerName).withPerformanceBasedRouting();
        int endpointPriority = 1;
        TrafficManagerProfile.DefinitionStages.WithCreate profileWithCreate = null;
        for (String publicIpResourceId : publicIpResourceIds) {
            String endpointName = String.format("azendpoint-%d", endpointPriority);
            if (endpointPriority == 1) {
                profileWithCreate = profileWithEndpoint.defineAzureTargetEndpoint(endpointName).toResourceId(publicIpResourceId).withRoutingPriority(endpointPriority).attach();
            } else {
                profileWithCreate = profileWithCreate.defineAzureTargetEndpoint(endpointName).toResourceId(publicIpResourceId).withRoutingPriority(endpointPriority).attach();
            }
            endpointPriority++;
        }
        System.out.println("Creating a traffic manager profile for the VMs");
        stopwatch.reset();
        stopwatch.start();
        TrafficManagerProfile trafficManagerProfile = profileWithCreate.create();
        stopwatch.stop();
        System.out.println("Created a traffic manager profile (took " + (stopwatch.getTime() / 1000) + " seconds to create): " + trafficManagerProfile.id());
        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;
}
Also used : HashMap(java.util.HashMap) TrafficManagerProfile(com.microsoft.azure.management.trafficmanager.TrafficManagerProfile) ArrayList(java.util.ArrayList) PublicIPAddress(com.microsoft.azure.management.network.PublicIPAddress) Network(com.microsoft.azure.management.network.Network) Creatable(com.microsoft.azure.management.resources.fluentcore.model.Creatable) ResourceGroup(com.microsoft.azure.management.resources.ResourceGroup) StopWatch(org.apache.commons.lang3.time.StopWatch) StorageAccount(com.microsoft.azure.management.storage.StorageAccount) Region(com.microsoft.azure.management.resources.fluentcore.arm.Region) HashMap(java.util.HashMap) Map(java.util.Map) VirtualMachine(com.microsoft.azure.management.compute.VirtualMachine)

Example 23 with Network

use of com.microsoft.azure.management.network.Network in project azure-sdk-for-java by Azure.

the class ManageVirtualMachinesInParallelWithNetwork 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 int frontendVMCount = 10;
    final int backendVMCount = 10;
    final String rgName = SdkContext.randomResourceName("rgNEPP", 24);
    final String frontEndNsgName = SdkContext.randomResourceName("fensg", 24);
    final String backEndNsgName = SdkContext.randomResourceName("bensg", 24);
    final String networkName = SdkContext.randomResourceName("vnetCOMV", 24);
    final String storageAccountName = SdkContext.randomResourceName("stgCOMV", 20);
    final String userName = "tirekicker";
    final String password = "12NewPA$$w0rd!";
    try {
        // Create a resource group [Where all resources gets created]
        ResourceGroup resourceGroup = azure.resourceGroups().define(rgName).withRegion(Region.US_EAST).create();
        //============================================================
        // Define 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
        Creatable<NetworkSecurityGroup> frontEndNSGCreatable = azure.networkSecurityGroups().define(frontEndNsgName).withRegion(Region.US_EAST).withExistingResourceGroup(resourceGroup).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();
        //============================================================
        // Define 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
        Creatable<NetworkSecurityGroup> backEndNSGCreatable = azure.networkSecurityGroups().define(backEndNsgName).withRegion(Region.US_EAST).withExistingResourceGroup(resourceGroup).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();
        System.out.println("Creating security group for the front ends - allows SSH and HTTP");
        System.out.println("Creating security group for the back ends - allows SSH and denies all outbound internet traffic");
        @SuppressWarnings("unchecked") Collection<NetworkSecurityGroup> networkSecurityGroups = azure.networkSecurityGroups().create(frontEndNSGCreatable, backEndNSGCreatable).values();
        NetworkSecurityGroup frontendNSG = null;
        NetworkSecurityGroup backendNSG = null;
        for (NetworkSecurityGroup nsg : networkSecurityGroups) {
            if (nsg.name().equalsIgnoreCase(frontEndNsgName)) {
                frontendNSG = nsg;
            }
            if (nsg.name().equalsIgnoreCase(backEndNsgName)) {
                backendNSG = nsg;
            }
        }
        System.out.println("Created a security group for the front end: " + frontendNSG.id());
        Utils.print(frontendNSG);
        System.out.println("Created a security group for the back end: " + backendNSG.id());
        Utils.print(backendNSG);
        // Create Network [Where all the virtual machines get added to]
        Network network = azure.networks().define(networkName).withRegion(Region.US_EAST).withExistingResourceGroup(resourceGroup).withAddressSpace("172.16.0.0/16").defineSubnet("Front-end").withAddressPrefix("172.16.1.0/24").withExistingNetworkSecurityGroup(frontendNSG).attach().defineSubnet("Back-end").withAddressPrefix("172.16.2.0/24").withExistingNetworkSecurityGroup(backendNSG).attach().create();
        // Prepare Creatable Storage account definition [For storing VMs disk]
        Creatable<StorageAccount> creatableStorageAccount = azure.storageAccounts().define(storageAccountName).withRegion(Region.US_EAST).withExistingResourceGroup(resourceGroup);
        // Prepare a batch of Creatable Virtual Machines definitions
        List<Creatable<VirtualMachine>> frontendCreatableVirtualMachines = new ArrayList<>();
        for (int i = 0; i < frontendVMCount; i++) {
            Creatable<VirtualMachine> creatableVirtualMachine = azure.virtualMachines().define("VM-FE-" + i).withRegion(Region.US_EAST).withExistingResourceGroup(resourceGroup).withExistingPrimaryNetwork(network).withSubnet("Front-end").withPrimaryPrivateIPAddressDynamic().withoutPrimaryPublicIPAddress().withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(userName).withRootPassword(password).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).withNewStorageAccount(creatableStorageAccount);
            frontendCreatableVirtualMachines.add(creatableVirtualMachine);
        }
        List<Creatable<VirtualMachine>> backendCreatableVirtualMachines = new ArrayList<>();
        for (int i = 0; i < backendVMCount; i++) {
            Creatable<VirtualMachine> creatableVirtualMachine = azure.virtualMachines().define("VM-BE-" + i).withRegion(Region.US_EAST).withExistingResourceGroup(resourceGroup).withExistingPrimaryNetwork(network).withSubnet("Back-end").withPrimaryPrivateIPAddressDynamic().withoutPrimaryPublicIPAddress().withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(userName).withRootPassword(password).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).withNewStorageAccount(creatableStorageAccount);
            backendCreatableVirtualMachines.add(creatableVirtualMachine);
        }
        System.out.println("Creating the virtual machines");
        List<Creatable<VirtualMachine>> allCreatableVirtualMachines = new ArrayList<>();
        allCreatableVirtualMachines.addAll(frontendCreatableVirtualMachines);
        allCreatableVirtualMachines.addAll(backendCreatableVirtualMachines);
        StopWatch stopwatch = new StopWatch();
        stopwatch.start();
        Collection<VirtualMachine> virtualMachines = azure.virtualMachines().create(allCreatableVirtualMachines).values();
        stopwatch.stop();
        System.out.println("Created virtual machines");
        for (VirtualMachine virtualMachine : virtualMachines) {
            System.out.println(virtualMachine.id());
        }
        System.out.println("Virtual Machines create: (took " + (stopwatch.getTime() / 1000) + " seconds) ");
        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;
}
Also used : NetworkSecurityGroup(com.microsoft.azure.management.network.NetworkSecurityGroup) ArrayList(java.util.ArrayList) StopWatch(org.apache.commons.lang3.time.StopWatch) StorageAccount(com.microsoft.azure.management.storage.StorageAccount) Network(com.microsoft.azure.management.network.Network) Creatable(com.microsoft.azure.management.resources.fluentcore.model.Creatable) ResourceGroup(com.microsoft.azure.management.resources.ResourceGroup) VirtualMachine(com.microsoft.azure.management.compute.VirtualMachine)

Example 24 with Network

use of com.microsoft.azure.management.network.Network in project azure-sdk-for-java by Azure.

the class ManageVirtualNetwork 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 String vnetName1 = SdkContext.randomResourceName("vnet1", 20);
    final String vnetName2 = SdkContext.randomResourceName("vnet2", 20);
    final String vnet1FrontEndSubnetName = "frontend";
    final String vnet1BackEndSubnetName = "backend";
    final String vnet1FrontEndSubnetNsgName = "frontendnsg";
    final String vnet1BackEndSubnetNsgName = "backendnsg";
    final String frontEndVMName = SdkContext.randomResourceName("fevm", 24);
    final String backEndVMName = SdkContext.randomResourceName("bevm", 24);
    final String publicIPAddressLeafDnsForFrontEndVM = SdkContext.randomResourceName("pip1", 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";
    final String rgName = SdkContext.randomResourceName("rgNEMV", 24);
    try {
        //============================================================
        // Create a virtual network with specific address-space and two subnet
        // Creates a network security group for backend subnet
        System.out.println("Creating a network security group for virtual network backend subnet...");
        NetworkSecurityGroup backEndSubnetNsg = azure.networkSecurityGroups().define(vnet1BackEndSubnetNsgName).withRegion(Region.US_EAST).withNewResourceGroup(rgName).defineRule("DenyInternetInComing").denyInbound().fromAddress("INTERNET").fromAnyPort().toAnyAddress().toAnyPort().withAnyProtocol().attach().defineRule("DenyInternetOutGoing").denyOutbound().fromAnyAddress().fromAnyPort().toAddress("INTERNET").toAnyPort().withAnyProtocol().attach().create();
        System.out.println("Created network security group");
        // Print the network security group
        Utils.print(backEndSubnetNsg);
        // Create the virtual network with frontend and backend subnets, with
        // network security group rule applied to backend subnet]
        System.out.println("Creating virtual network #1...");
        Network virtualNetwork1 = azure.networks().define(vnetName1).withRegion(Region.US_EAST).withExistingResourceGroup(rgName).withAddressSpace("192.168.0.0/16").withSubnet(vnet1FrontEndSubnetName, "192.168.1.0/24").defineSubnet(vnet1BackEndSubnetName).withAddressPrefix("192.168.2.0/24").withExistingNetworkSecurityGroup(backEndSubnetNsg).attach().create();
        System.out.println("Created a virtual network");
        // Print the virtual network details
        Utils.print(virtualNetwork1);
        //============================================================
        // Update a virtual network
        // Creates a network security group for frontend subnet
        System.out.println("Creating a network security group for virtual network backend subnet...");
        NetworkSecurityGroup frontEndSubnetNsg = azure.networkSecurityGroups().define(vnet1FrontEndSubnetNsgName).withRegion(Region.US_EAST).withExistingResourceGroup(rgName).defineRule("AllowHttpInComing").allowInbound().fromAddress("INTERNET").fromAnyPort().toAnyAddress().toPort(80).withProtocol(SecurityRuleProtocol.TCP).attach().defineRule("DenyInternetOutGoing").denyOutbound().fromAnyAddress().fromAnyPort().toAddress("INTERNET").toAnyPort().withAnyProtocol().attach().create();
        System.out.println("Created network security group");
        // Print the network security group
        Utils.print(frontEndSubnetNsg);
        // Update the virtual network frontend subnet by associating it with network security group
        System.out.println("Associating network security group rule to frontend subnet");
        virtualNetwork1.update().updateSubnet(vnet1FrontEndSubnetName).withExistingNetworkSecurityGroup(frontEndSubnetNsg).parent().apply();
        System.out.println("Network security group rule associated with the frontend subnet");
        // Print the virtual network details
        Utils.print(virtualNetwork1);
        //============================================================
        // Create a virtual machine in each subnet
        // Creates the first virtual machine in frontend subnet
        System.out.println("Creating a Linux virtual machine in the frontend subnet");
        Date t1 = new Date();
        VirtualMachine frontEndVM = azure.virtualMachines().define(frontEndVMName).withRegion(Region.US_EAST).withExistingResourceGroup(rgName).withExistingPrimaryNetwork(virtualNetwork1).withSubnet(vnet1FrontEndSubnetName).withPrimaryPrivateIPAddressDynamic().withNewPrimaryPublicIPAddress(publicIPAddressLeafDnsForFrontEndVM).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);
        // Creates the second virtual machine in the backend subnet
        System.out.println("Creating a Linux virtual machine in the backend subnet");
        Date t3 = new Date();
        VirtualMachine backEndVM = azure.virtualMachines().define(backEndVMName).withRegion(Region.US_EAST).withExistingResourceGroup(rgName).withExistingPrimaryNetwork(virtualNetwork1).withSubnet(vnet1BackEndSubnetName).withPrimaryPrivateIPAddressDynamic().withoutPrimaryPublicIPAddress().withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(userName).withSsh(sshKey).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).create();
        Date t4 = new Date();
        System.out.println("Created Linux VM: (took " + ((t4.getTime() - t3.getTime()) / 1000) + " seconds) " + backEndVM.id());
        // Print virtual machine details
        Utils.print(backEndVM);
        //============================================================
        // Create a virtual network with default address-space and one default subnet
        System.out.println("Creating virtual network #2...");
        Network virtualNetwork2 = azure.networks().define(vnetName2).withRegion(Region.US_EAST).withNewResourceGroup(rgName).create();
        System.out.println("Created a virtual network");
        // Print the virtual network details
        Utils.print(virtualNetwork2);
        for (Network virtualNetwork : azure.networks().listByResourceGroup(rgName)) {
            Utils.print(virtualNetwork);
        }
        //============================================================
        // Delete a virtual network
        System.out.println("Deleting the virtual network");
        azure.networks().deleteById(virtualNetwork2.id());
        System.out.println("Deleted the virtual network");
        return true;
    } catch (Exception e) {
        System.err.println(e.getMessage());
    } 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;
}
Also used : NetworkSecurityGroup(com.microsoft.azure.management.network.NetworkSecurityGroup) Network(com.microsoft.azure.management.network.Network) Date(java.util.Date) VirtualMachine(com.microsoft.azure.management.compute.VirtualMachine)

Example 25 with Network

use of com.microsoft.azure.management.network.Network in project azure-sdk-for-java by Azure.

the class ManageVirtualNetworkAsync 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 String vnetName1 = SdkContext.randomResourceName("vnet1", 20);
    final String vnetName2 = SdkContext.randomResourceName("vnet2", 20);
    final String vnet1FrontEndSubnetName = "frontend";
    final String vnet1BackEndSubnetName = "backend";
    final String vnet1FrontEndSubnetNsgName = "frontendnsg";
    final String vnet1BackEndSubnetNsgName = "backendnsg";
    final String frontEndVMName = SdkContext.randomResourceName("fevm", 24);
    final String backEndVMName = SdkContext.randomResourceName("bevm", 24);
    final String publicIPAddressLeafDnsForFrontEndVM = SdkContext.randomResourceName("pip1", 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";
    final String rgName = SdkContext.randomResourceName("rgNEMV", 24);
    try {
        //============================================================
        // Create a virtual network with specific address-space and two subnet
        // Creates a network security group for backend subnet
        System.out.println("Creating a network security group for virtual network backend subnet...");
        // Creates a network security group for frontend subnet
        System.out.println("Creating a network security group for virtual network backend subnet...");
        final Map<String, Indexable> createdResources = new TreeMap<>();
        Observable.merge(azure.networkSecurityGroups().define(vnet1BackEndSubnetNsgName).withRegion(Region.US_EAST).withNewResourceGroup(rgName).defineRule("DenyInternetInComing").denyInbound().fromAddress("INTERNET").fromAnyPort().toAnyAddress().toAnyPort().withAnyProtocol().attach().defineRule("DenyInternetOutGoing").denyOutbound().fromAnyAddress().fromAnyPort().toAddress("INTERNET").toAnyPort().withAnyProtocol().attach().createAsync().flatMap(new Func1<Indexable, Observable<Indexable>>() {

            @Override
            public Observable<Indexable> call(Indexable indexable) {
                if (indexable instanceof NetworkSecurityGroup) {
                    NetworkSecurityGroup backEndNsg = (NetworkSecurityGroup) indexable;
                    System.out.println("Creating virtual network #1...");
                    return Observable.merge(Observable.just(indexable), azure.networks().define(vnetName1).withRegion(Region.US_EAST).withExistingResourceGroup(rgName).withAddressSpace("192.168.0.0/16").withSubnet(vnet1FrontEndSubnetName, "192.168.1.0/24").defineSubnet(vnet1BackEndSubnetName).withAddressPrefix("192.168.2.0/24").withExistingNetworkSecurityGroup(backEndNsg).attach().createAsync());
                }
                return Observable.just(indexable);
            }
        }), azure.networkSecurityGroups().define(vnet1FrontEndSubnetNsgName).withRegion(Region.US_EAST).withExistingResourceGroup(rgName).defineRule("AllowHttpInComing").allowInbound().fromAddress("INTERNET").fromAnyPort().toAnyAddress().toPort(80).withProtocol(SecurityRuleProtocol.TCP).attach().defineRule("DenyInternetOutGoing").denyOutbound().fromAnyAddress().fromAnyPort().toAddress("INTERNET").toAnyPort().withAnyProtocol().attach().createAsync()).map(new Func1<Indexable, Indexable>() {

            @Override
            public Indexable call(Indexable indexable) {
                if (indexable instanceof NetworkSecurityGroup) {
                    NetworkSecurityGroup nsg = (NetworkSecurityGroup) indexable;
                    System.out.println("Created network security group");
                    // Print the network security group
                    Utils.print(nsg);
                    createdResources.put(nsg.name(), nsg);
                } else if (indexable instanceof Network) {
                    Network vn = (Network) indexable;
                    System.out.println("Created a virtual network");
                    // Print the virtual network details
                    Utils.print(vn);
                    createdResources.put(vn.name(), vn);
                }
                return indexable;
            }
        }).toBlocking().subscribe();
        NetworkSecurityGroup frontEndSubnetNsg = (NetworkSecurityGroup) createdResources.get(vnet1FrontEndSubnetNsgName);
        Network virtualNetwork1 = (Network) createdResources.get(vnetName1);
        //============================================================
        // Update a virtual network
        // Update the virtual network frontend subnet by associating it with network security group
        System.out.println("Associating network security group rule to frontend subnet");
        virtualNetwork1.update().updateSubnet(vnet1FrontEndSubnetName).withExistingNetworkSecurityGroup(frontEndSubnetNsg).parent().applyAsync().toCompletable().await();
        System.out.println("Network security group rule associated with the frontend subnet");
        // Print the virtual network details
        Utils.print(virtualNetwork1);
        //============================================================
        // Create a virtual machine in each subnet and another virtual network
        // Creates the first virtual machine in frontend subnet
        System.out.println("Creating a Linux virtual machine in the frontend subnet");
        // Creates the second virtual machine in the backend subnet
        System.out.println("Creating a Linux virtual machine in the backend subnet");
        // Create a virtual network with default address-space and one default subnet
        System.out.println("Creating virtual network #2...");
        final Date t1 = new Date();
        Observable.merge(azure.virtualMachines().define(frontEndVMName).withRegion(Region.US_EAST).withExistingResourceGroup(rgName).withExistingPrimaryNetwork(virtualNetwork1).withSubnet(vnet1FrontEndSubnetName).withPrimaryPrivateIPAddressDynamic().withNewPrimaryPublicIPAddress(publicIPAddressLeafDnsForFrontEndVM).withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(userName).withSsh(sshKey).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).createAsync(), azure.virtualMachines().define(backEndVMName).withRegion(Region.US_EAST).withExistingResourceGroup(rgName).withExistingPrimaryNetwork(virtualNetwork1).withSubnet(vnet1BackEndSubnetName).withPrimaryPrivateIPAddressDynamic().withoutPrimaryPublicIPAddress().withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(userName).withSsh(sshKey).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).createAsync(), azure.networks().define(vnetName2).withRegion(Region.US_EAST).withNewResourceGroup(rgName).createAsync()).map(new Func1<Indexable, Indexable>() {

            @Override
            public Indexable call(Indexable indexable) {
                Date t2 = new Date();
                long duration = ((t2.getTime() - t1.getTime()) / 1000);
                if (indexable instanceof VirtualMachine) {
                    VirtualMachine vm = (VirtualMachine) indexable;
                    System.out.println("Created Linux VM: (took " + duration + " seconds) " + vm.id());
                    // Print virtual machine details
                    Utils.print(vm);
                } else if (indexable instanceof Network) {
                    Network vn = (Network) indexable;
                    System.out.println("Created a virtual network: took " + duration + " seconds) " + vn.id());
                    // Print the virtual network details
                    Utils.print(vn);
                }
                return indexable;
            }
        });
        //============================================================
        // List virtual networks and print details
        azure.networks().listByResourceGroupAsync(rgName).map(new Func1<Network, Network>() {

            @Override
            public Network call(Network network) {
                Utils.print(network);
                return network;
            }
        }).toBlocking().subscribe();
        return true;
    } catch (Exception e) {
        System.err.println(e.getMessage());
    } 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;
}
Also used : NetworkSecurityGroup(com.microsoft.azure.management.network.NetworkSecurityGroup) TreeMap(java.util.TreeMap) Observable(rx.Observable) Date(java.util.Date) Network(com.microsoft.azure.management.network.Network) Indexable(com.microsoft.azure.management.resources.fluentcore.model.Indexable) VirtualMachine(com.microsoft.azure.management.compute.VirtualMachine)

Aggregations

Network (com.microsoft.azure.management.network.Network)37 VirtualMachine (com.microsoft.azure.management.compute.VirtualMachine)17 Region (com.microsoft.azure.management.resources.fluentcore.arm.Region)15 ArrayList (java.util.ArrayList)14 Creatable (com.microsoft.azure.management.resources.fluentcore.model.Creatable)11 PublicIPAddress (com.microsoft.azure.management.network.PublicIPAddress)10 ResourceGroup (com.microsoft.azure.management.resources.ResourceGroup)10 Date (java.util.Date)10 LoadBalancer (com.microsoft.azure.management.network.LoadBalancer)7 NetworkInterface (com.microsoft.azure.management.network.NetworkInterface)7 StopWatch (org.apache.commons.lang3.time.StopWatch)6 NetworkSecurityGroup (com.microsoft.azure.management.network.NetworkSecurityGroup)5 Indexable (com.microsoft.azure.management.resources.fluentcore.model.Indexable)5 StorageAccount (com.microsoft.azure.management.storage.StorageAccount)5 HashMap (java.util.HashMap)5 Test (org.junit.Test)5 AvailabilitySet (com.microsoft.azure.management.compute.AvailabilitySet)4 Subnet (com.microsoft.azure.management.network.Subnet)4 VirtualNetwork (com.microsoft.tooling.msservices.model.vm.VirtualNetwork)4 VirtualMachineScaleSet (com.microsoft.azure.management.compute.VirtualMachineScaleSet)3