Search in sources :

Example 41 with ResourceGroup

use of com.microsoft.azure.management.resources.ResourceGroup 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 42 with ResourceGroup

use of com.microsoft.azure.management.resources.ResourceGroup in project azure-sdk-for-java by Azure.

the class AzureTests method testApplicationGatewaysInParallel.

@Test
public void testApplicationGatewaysInParallel() throws Exception {
    String rgName = SdkContext.randomResourceName("rg", 13);
    Region region = Region.US_EAST;
    Creatable<ResourceGroup> resourceGroup = azure.resourceGroups().define(rgName).withRegion(region);
    List<Creatable<ApplicationGateway>> agCreatables = new ArrayList<>();
    agCreatables.add(azure.applicationGateways().define(SdkContext.randomResourceName("ag", 13)).withRegion(Region.US_EAST).withNewResourceGroup(resourceGroup).defineRequestRoutingRule("rule1").fromPrivateFrontend().fromFrontendHttpPort(80).toBackendHttpPort(8080).toBackendIPAddress("10.0.0.1").toBackendIPAddress("10.0.0.2").attach());
    agCreatables.add(azure.applicationGateways().define(SdkContext.randomResourceName("ag", 13)).withRegion(Region.US_EAST).withNewResourceGroup(resourceGroup).defineRequestRoutingRule("rule1").fromPrivateFrontend().fromFrontendHttpPort(80).toBackendHttpPort(8080).toBackendIPAddress("10.0.0.3").toBackendIPAddress("10.0.0.4").attach());
    CreatedResources<ApplicationGateway> created = azure.applicationGateways().create(agCreatables);
    List<ApplicationGateway> ags = new ArrayList<>();
    List<String> agIds = new ArrayList<>();
    for (Creatable<ApplicationGateway> creatable : agCreatables) {
        ApplicationGateway ag = created.get(creatable.key());
        Assert.assertNotNull(ag);
        ags.add(ag);
        agIds.add(ag.id());
    }
    azure.applicationGateways().stop(agIds);
    for (ApplicationGateway ag : ags) {
        Assert.assertEquals(ApplicationGatewayOperationalState.STOPPED, ag.refresh().operationalState());
    }
    azure.applicationGateways().start(agIds);
    for (ApplicationGateway ag : ags) {
        Assert.assertEquals(ApplicationGatewayOperationalState.RUNNING, ag.refresh().operationalState());
    }
    azure.applicationGateways().deleteByIds(agIds);
    for (String id : agIds) {
        Assert.assertNull(azure.applicationGateways().getById(id));
    }
    azure.resourceGroups().beginDeleteByName(rgName);
}
Also used : ApplicationGateway(com.microsoft.azure.management.network.ApplicationGateway) ArrayList(java.util.ArrayList) Region(com.microsoft.azure.management.resources.fluentcore.arm.Region) Creatable(com.microsoft.azure.management.resources.fluentcore.model.Creatable) ResourceGroup(com.microsoft.azure.management.resources.ResourceGroup) Test(org.junit.Test)

Example 43 with ResourceGroup

use of com.microsoft.azure.management.resources.ResourceGroup in project azure-tools-for-java by Microsoft.

the class WebAppDeployDialog method doFillTable.

private void doFillTable() {
    Map<SubscriptionDetail, List<ResourceGroup>> srgMap = AzureModel.getInstance().getSubscriptionToResourceGroupMap();
    Map<ResourceGroup, List<WebApp>> rgwaMap = AzureModel.getInstance().getResourceGroupToWebAppMap();
    Map<ResourceGroup, List<AppServicePlan>> rgaspMap = AzureModel.getInstance().getResourceGroupToAppServicePlanMap();
    if (srgMap == null)
        throw new NullPointerException("srgMap is null");
    if (rgwaMap == null)
        throw new NullPointerException("rgwaMap is null");
    if (rgaspMap == null)
        throw new NullPointerException("rgaspMap is null");
    cleanTable();
    DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
    for (SubscriptionDetail sd : srgMap.keySet()) {
        if (!sd.isSelected())
            continue;
        Map<String, WebAppUtils.AspDetails> aspMap = new HashMap<>();
        try {
            for (ResourceGroup rg : srgMap.get(sd)) {
                for (AppServicePlan asp : rgaspMap.get(rg)) {
                    aspMap.put(asp.id(), new WebAppUtils.AspDetails(asp, rg));
                }
            }
        } catch (NullPointerException npe) {
            LOGGER.error("NPE while initializing App Service Plan map", npe);
        }
        for (ResourceGroup rg : srgMap.get(sd)) {
            for (WebApp wa : rgwaMap.get(rg)) {
                if (wa.javaVersion() != JavaVersion.OFF) {
                    tableModel.addRow(new String[] { wa.name(), wa.javaVersion().toString(), wa.javaContainer() + " " + wa.javaContainerVersion(), wa.resourceGroupName() });
                } else {
                    tableModel.addRow(new String[] { wa.name(), "Off", "N/A", wa.resourceGroupName() });
                }
                WebAppDetails webAppDetails = new WebAppDetails();
                webAppDetails.webApp = wa;
                webAppDetails.subscriptionDetail = sd;
                webAppDetails.resourceGroup = rg;
                webAppDetails.appServicePlan = aspMap.get(wa.appServicePlanId()).getAsp();
                webAppDetails.appServicePlanResourceGroup = aspMap.get(wa.appServicePlanId()).getRg();
                webAppWebAppDetailsMap.put(wa.name(), webAppDetails);
            }
        }
    }
    table.setModel(tableModel);
    if (tableModel.getRowCount() > 0)
        tableModel.fireTableDataChanged();
}
Also used : WebAppDetails(com.microsoft.azuretools.utils.WebAppUtils.WebAppDetails) HashMap(java.util.HashMap) DefaultTableModel(javax.swing.table.DefaultTableModel) WebAppUtils(com.microsoft.azuretools.utils.WebAppUtils) AppServicePlan(com.microsoft.azure.management.appservice.AppServicePlan) SubscriptionDetail(com.microsoft.azuretools.authmanage.models.SubscriptionDetail) List(java.util.List) ResourceGroup(com.microsoft.azure.management.resources.ResourceGroup) WebApp(com.microsoft.azure.management.appservice.WebApp)

Example 44 with ResourceGroup

use of com.microsoft.azure.management.resources.ResourceGroup in project azure-tools-for-java by Microsoft.

the class AzureModelController method updateSubscriptionMaps.

public static synchronized void updateSubscriptionMaps(IProgressIndicator progressIndicator) throws IOException, CanceledByUserException, AuthException {
    AzureManager azureManager = AuthMethodManager.getInstance().getAzureManager();
    // not signed in
    if (azureManager == null) {
        return;
    }
    if (progressIndicator != null && progressIndicator.isCanceled()) {
        clearAll();
        throw new CanceledByUserException();
    }
    AzureModel azureModel = AzureModel.getInstance();
    // to get regions we nees subscription objects
    if (progressIndicator != null)
        progressIndicator.setText("Reading subscription list...");
    List<Subscription> sl = azureManager.getSubscriptions();
    // convert to map to easier find by sid
    Map<String, Subscription> sidToSubscriptionMap = azureModel.createSidToSubscriptionMap();
    for (Subscription s : sl) {
        sidToSubscriptionMap.put(s.subscriptionId(), s);
    }
    azureModel.setSidToSubscriptionMap(sidToSubscriptionMap);
    Map<SubscriptionDetail, List<Location>> sdlocMap = azureModel.createSubscriptionToRegionMap();
    Map<SubscriptionDetail, List<ResourceGroup>> sdrgMap = azureModel.createSubscriptionToResourceGroupMap();
    SubscriptionManager subscriptionManager = azureManager.getSubscriptionManager();
    subscriptionManager.addListener(subscriptionSelectionListener);
    List<SubscriptionDetail> sdl = subscriptionManager.getSubscriptionDetails();
    for (SubscriptionDetail sd : sdl) {
        if (!sd.isSelected())
            continue;
        if (progressIndicator != null && progressIndicator.isCanceled()) {
            clearAll();
            throw new CanceledByUserException();
        }
        System.out.println("sn : " + sd.getSubscriptionName());
        if (progressIndicator != null)
            progressIndicator.setText("Reading subscription '" + sd.getSubscriptionName() + "'");
        Azure azure = azureManager.getAzure(sd.getSubscriptionId());
        List<ResourceGroup> rgList = azure.resourceGroups().list();
        sdrgMap.put(sd, rgList);
        List<Location> locl = sidToSubscriptionMap.get(sd.getSubscriptionId()).listLocations();
        Collections.sort(locl, new Comparator<Location>() {

            @Override
            public int compare(Location lhs, Location rhs) {
                return lhs.displayName().compareTo(rhs.displayName());
            }
        });
        sdlocMap.put(sd, locl);
    }
    azureModel.setSubscriptionToResourceGroupMap(sdrgMap);
    azureModel.setSubscriptionToLocationMap(sdlocMap);
}
Also used : Azure(com.microsoft.azure.management.Azure) AzureManager(com.microsoft.azuretools.sdkmanage.AzureManager) SubscriptionManager(com.microsoft.azuretools.authmanage.SubscriptionManager) SubscriptionDetail(com.microsoft.azuretools.authmanage.models.SubscriptionDetail) Subscription(com.microsoft.azure.management.resources.Subscription) ResourceGroup(com.microsoft.azure.management.resources.ResourceGroup) Location(com.microsoft.azure.management.resources.Location)

Example 45 with ResourceGroup

use of com.microsoft.azure.management.resources.ResourceGroup in project azure-tools-for-java by Microsoft.

the class AzureModelController method subscriptionSelectionChanged.

private static synchronized void subscriptionSelectionChanged(IProgressIndicator progressIndicator) throws IOException, AuthException {
    System.out.println("AzureModelController.subscriptionSelectionChanged: starting");
    AzureManager azureManager = AuthMethodManager.getInstance().getAzureManager();
    // not signed in
    if (azureManager == null) {
        System.out.println("AzureModelController.subscriptionSelectionChanged: azureManager == null -> return");
        return;
    }
    SubscriptionManager subscriptionManager = azureManager.getSubscriptionManager();
    AzureModel azureModel = AzureModel.getInstance();
    Map<SubscriptionDetail, List<ResourceGroup>> srgMap = azureModel.getSubscriptionToResourceGroupMap();
    if (srgMap == null) {
        System.out.println("AzureModelController.subscriptionSelectionChanged: srgMap == null -> return");
        return;
    }
    Map<String, Subscription> sidToSubscriptionMap = azureModel.getSidToSubscriptionMap();
    if (sidToSubscriptionMap == null) {
        System.out.println("AzureModelController.subscriptionSelectionChanged: sidToSubscriptionMap == null -> return");
        return;
    }
    Map<ResourceGroup, List<WebApp>> rgwaMap = azureModel.getResourceGroupToWebAppMap();
    Map<ResourceGroup, List<AppServicePlan>> rgspMap = azureModel.getResourceGroupToAppServicePlanMap();
    System.out.println("AzureModelController.subscriptionSelectionChanged: getting subscription details...");
    List<SubscriptionDetail> sdl = subscriptionManager.getSubscriptionDetails();
    if (sdl == null) {
        System.out.println("AzureModelController.subscriptionSelectionChanged: sdl == null -> return");
        return;
    }
    for (SubscriptionDetail sd : sdl) {
        if (!srgMap.containsKey(sd)) {
            if (!sd.isSelected())
                continue;
            if (progressIndicator != null && progressIndicator.isCanceled()) {
                progressIndicator.setText("Cancelling...");
                clearAll();
                return;
            // FIXME: throw exception?
            }
            Azure azure = azureManager.getAzure(sd.getSubscriptionId());
            // subscription locations
            List<Subscription> sl = azureManager.getSubscriptions();
            System.out.println("Updating subscription locations");
            Subscription subscription = sidToSubscriptionMap.get(sd.getSubscriptionId());
            if (progressIndicator != null)
                progressIndicator.setText(String.format("Updating subscription '%s' locations...", subscription.displayName()));
            List<Location> locl = subscription.listLocations();
            Collections.sort(locl, new Comparator<Location>() {

                @Override
                public int compare(Location lhs, Location rhs) {
                    return lhs.displayName().compareTo(rhs.displayName());
                }
            });
            Map<SubscriptionDetail, List<Location>> sdlocMap = azureModel.getSubscriptionToLocationMap();
            sdlocMap.put(sd, locl);
            // resource group maps
            List<ResourceGroup> rgList = azure.resourceGroups().list();
            srgMap.put(sd, rgList);
            updateResGrDependency(azure, rgList, progressIndicator, rgwaMap, rgspMap);
        } else {
            // find and modify the key
            for (SubscriptionDetail sdk : srgMap.keySet()) {
                if (sdk.equals(sd)) {
                    sdk.setSelected(sd.isSelected());
                }
            }
        }
    }
}
Also used : Azure(com.microsoft.azure.management.Azure) AzureManager(com.microsoft.azuretools.sdkmanage.AzureManager) SubscriptionManager(com.microsoft.azuretools.authmanage.SubscriptionManager) SubscriptionDetail(com.microsoft.azuretools.authmanage.models.SubscriptionDetail) Subscription(com.microsoft.azure.management.resources.Subscription) ResourceGroup(com.microsoft.azure.management.resources.ResourceGroup) Location(com.microsoft.azure.management.resources.Location)

Aggregations

ResourceGroup (com.microsoft.azure.management.resources.ResourceGroup)53 Test (org.junit.Test)22 Region (com.microsoft.azure.management.resources.fluentcore.arm.Region)13 SubscriptionDetail (com.microsoft.azuretools.authmanage.models.SubscriptionDetail)12 ArrayList (java.util.ArrayList)10 Network (com.microsoft.azure.management.network.Network)9 StorageAccount (com.microsoft.azure.management.storage.StorageAccount)9 VirtualMachine (com.microsoft.azure.management.compute.VirtualMachine)8 Creatable (com.microsoft.azure.management.resources.fluentcore.model.Creatable)7 AzureManager (com.microsoft.azuretools.sdkmanage.AzureManager)7 Azure (com.microsoft.azure.management.Azure)6 AppServicePlan (com.microsoft.azure.management.appservice.AppServicePlan)6 WebApp (com.microsoft.azure.management.appservice.WebApp)6 HashMap (java.util.HashMap)5 StopWatch (org.apache.commons.lang3.time.StopWatch)5 PublicIPAddress (com.microsoft.azure.management.network.PublicIPAddress)4 Location (com.microsoft.azure.management.resources.Location)4 CloudException (com.microsoft.azure.CloudException)3 Period (org.joda.time.Period)3 ApplicationGateway (com.microsoft.azure.management.network.ApplicationGateway)2