use of com.microsoft.azure.management.resources.fluentcore.model.Creatable in project azure-sdk-for-java by Azure.
the class ManageSimpleTrafficManager 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";
final int vmCountPerRegion = 2;
Set<Region> regions = new HashSet<>(Arrays.asList(Region.US_EAST, Region.US_WEST));
try {
//=============================================================
// Create a shared resource group for all the resources so they can all be deleted together
//
ResourceGroup resourceGroup = azure.resourceGroups().define(rgName).withRegion(Region.US_EAST).create();
System.out.println("Created a new resource group - " + resourceGroup.id());
// Prepare a batch of creatable VM definitions to put behind the traffic manager
//
List<Creatable<VirtualMachine>> creatableVirtualMachines = new ArrayList<>();
for (Region region : regions) {
String linuxVMNamePrefix = SdkContext.randomResourceName("vm", 15);
for (int i = 0; i < vmCountPerRegion; i++) {
//=============================================================
// Create a virtual machine in its own virtual network
String vmName = String.format("%s-%d", linuxVMNamePrefix, i);
Creatable<VirtualMachine> vmDefinition = azure.virtualMachines().define(vmName).withRegion(region).withExistingResourceGroup(resourceGroup).withNewPrimaryNetwork("10.0.0.0/29").withPrimaryPrivateIPAddressDynamic().withNewPrimaryPublicIPAddress(vmName).withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS).withRootUsername(userName).withSsh(sshKey).withSize(VirtualMachineSizeTypes.STANDARD_A1);
creatableVirtualMachines.add(vmDefinition);
}
}
//=============================================================
// Create the VMs !!
StopWatch stopwatch = new StopWatch();
System.out.println("Creating the virtual machines...");
stopwatch.start();
Collection<VirtualMachine> virtualMachines = azure.virtualMachines().create(creatableVirtualMachines).values();
stopwatch.stop();
System.out.println(String.format("Created virtual machines in %d seconds.", stopwatch.getTime() / 1000));
//=============================================================
// Create 1 traffic manager profile
//
String trafficManagerName = SdkContext.randomResourceName("tra", 15);
TrafficManagerProfile.DefinitionStages.WithEndpoint profileWithEndpoint = azure.trafficManagerProfiles().define(trafficManagerName).withExistingResourceGroup(resourceGroup).withLeafDomainLabel(trafficManagerName).withPerformanceBasedRouting();
TrafficManagerProfile.DefinitionStages.WithCreate profileWithCreate = null;
int routingPriority = 1;
for (VirtualMachine vm : virtualMachines) {
String endpointName = SdkContext.randomResourceName("ep", 15);
profileWithCreate = profileWithEndpoint.defineAzureTargetEndpoint(endpointName).toResourceId(vm.getPrimaryPublicIPAddressId()).withRoutingPriority(routingPriority++).attach();
}
stopwatch.reset();
stopwatch.start();
TrafficManagerProfile trafficManagerProfile = profileWithCreate.create();
stopwatch.stop();
System.out.println(String.format("Created a traffic manager profile %s\n in %d seconds.", trafficManagerProfile.id(), stopwatch.getTime() / 1000));
//=============================================================
// Modify the traffic manager to use priority based routing
//
trafficManagerProfile.update().withPriorityBasedRouting().apply();
System.out.println("Modified the traffic manager to use priority-based routing.");
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.resources.fluentcore.model.Creatable in project azure-sdk-for-java by Azure.
the class TestLoadBalancer method ensureVMs.
// Ensure VMs for the LB
private static VirtualMachine[] ensureVMs(Networks networks, VirtualMachines vms, AvailabilitySets availabilitySets, int count) throws Exception {
// Create a network for the VMs
Network network = networks.define("net" + TEST_ID).withRegion(REGION).withNewResourceGroup(GROUP_NAME).withAddressSpace("10.0.0.0/28").withSubnet("subnet1", "10.0.0.0/29").withSubnet("subnet2", "10.0.0.8/29").create();
Creatable<AvailabilitySet> availabilitySetDefinition = availabilitySets.define("as" + TEST_ID).withRegion(REGION).withExistingResourceGroup(GROUP_NAME).withSku(AvailabilitySetSkuTypes.MANAGED);
// Create the requested number of VM definitions
String userName = "testuser" + TEST_ID;
List<Creatable<VirtualMachine>> vmDefinitions = new ArrayList<>();
for (int i = 0; i < count; i++) {
String vmName = SdkContext.randomResourceName("vm", 15);
Creatable<VirtualMachine> vm = vms.define(vmName).withRegion(REGION).withExistingResourceGroup(GROUP_NAME).withExistingPrimaryNetwork(network).withSubnet(network.subnets().values().iterator().next().name()).withPrimaryPrivateIPAddressDynamic().withoutPrimaryPublicIPAddress().withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_14_04_LTS).withRootUsername(userName).withRootPassword("Abcdef.123456").withNewAvailabilitySet(availabilitySetDefinition).withSize(VirtualMachineSizeTypes.STANDARD_A1);
vmDefinitions.add(vm);
}
CreatedResources<VirtualMachine> createdVMs2 = vms.create(vmDefinitions);
VirtualMachine[] array = new VirtualMachine[createdVMs2.size()];
for (int index = 0; index < createdVMs2.size(); index++) {
array[index] = createdVMs2.get(vmDefinitions.get(index).key());
}
return array;
}
use of com.microsoft.azure.management.resources.fluentcore.model.Creatable in project azure-sdk-for-java by Azure.
the class ManageSqlDatabasesAcrossDifferentDataCenters 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 sqlServerName = Utils.createRandomName("sqlserver");
final String rgName = Utils.createRandomName("rgRSSDRE");
final String administratorLogin = "sqladmin3423";
final String administratorPassword = "myS3cureP@ssword";
final String slaveSqlServer1Name = "slave1sql";
final String slaveSqlServer2Name = "slave2sql";
final String databaseName = "mydatabase";
final String networkNamePrefix = "network";
final String virtualMachineNamePrefix = "samplevm";
try {
// ============================================================
// Create a SQL Server, with 2 firewall rules.
SqlServer masterSqlServer = azure.sqlServers().define(sqlServerName).withRegion(Region.US_EAST).withNewResourceGroup(rgName).withAdministratorLogin(administratorLogin).withAdministratorPassword(administratorPassword).create();
Utils.print(masterSqlServer);
// ============================================================
// Create a Database in master SQL server created above.
System.out.println("Creating a database");
SqlDatabase masterDatabase = masterSqlServer.databases().define(databaseName).withEdition(DatabaseEditions.BASIC).create();
Utils.print(masterDatabase);
// ============================================================
// Create secondary SQLServer/Database for the master database
System.out.println("Creating server in secondary location for master SQL Server");
SqlServer sqlServerInSecondaryLocation = azure.sqlServers().define(Utils.createRandomName(slaveSqlServer1Name)).withRegion(masterDatabase.defaultSecondaryLocation()).withExistingResourceGroup(rgName).withAdministratorLogin(administratorLogin).withAdministratorPassword(administratorPassword).create();
Utils.print(sqlServerInSecondaryLocation);
System.out.println("Creating database in slave SQL Server.");
SqlDatabase secondaryDatabase = sqlServerInSecondaryLocation.databases().define(databaseName).withSourceDatabase(masterDatabase).withMode(CreateMode.ONLINE_SECONDARY).create();
Utils.print(secondaryDatabase);
// ============================================================
// Create another slave SQLServer/Database for the master database
System.out.println("Creating server in another location for master SQL Server");
SqlServer sqlServerInEurope = azure.sqlServers().define(Utils.createRandomName(slaveSqlServer2Name)).withRegion(Region.EUROPE_WEST).withExistingResourceGroup(rgName).withAdministratorLogin(administratorLogin).withAdministratorPassword(administratorPassword).create();
Utils.print(sqlServerInEurope);
System.out.println("Creating database in second slave SQL Server.");
SqlDatabase secondaryDatabaseInEurope = sqlServerInEurope.databases().define(databaseName).withSourceDatabase(masterDatabase).withMode(CreateMode.ONLINE_SECONDARY).create();
Utils.print(secondaryDatabaseInEurope);
// ============================================================
// Create Virtual Networks in different regions
List<Region> regions = new ArrayList<>();
regions.add(Region.US_EAST);
regions.add(Region.US_WEST);
regions.add(Region.EUROPE_NORTH);
regions.add(Region.ASIA_SOUTHEAST);
regions.add(Region.JAPAN_EAST);
List<Creatable<Network>> creatableNetworks = new ArrayList<>();
System.out.println("Creating virtual networks in different regions.");
for (Region region : regions) {
creatableNetworks.add(azure.networks().define(Utils.createRandomName(networkNamePrefix)).withRegion(region).withExistingResourceGroup(rgName));
}
Collection<Network> networks = azure.networks().create(creatableNetworks).values();
// ============================================================
// Create virtual machines attached to different virtual networks created above.
List<Creatable<VirtualMachine>> creatableVirtualMachines = new ArrayList<>();
System.out.println("Creating virtual machines in different regions.");
for (Network network : networks) {
String vmName = Utils.createRandomName(virtualMachineNamePrefix);
Creatable<PublicIPAddress> publicIPAddressCreatable = azure.publicIPAddresses().define(vmName).withRegion(network.region()).withExistingResourceGroup(rgName).withLeafDomainLabel(vmName);
creatableVirtualMachines.add(azure.virtualMachines().define(vmName).withRegion(network.region()).withExistingResourceGroup(rgName).withExistingPrimaryNetwork(network).withSubnet(network.subnets().values().iterator().next().name()).withPrimaryPrivateIPAddressDynamic().withNewPrimaryPublicIPAddress(publicIPAddressCreatable).withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER).withAdminUsername(administratorLogin).withAdminPassword(administratorPassword).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2));
}
HashMap<String, String> ipAddresses = new HashMap<>();
for (VirtualMachine virtualMachine : azure.virtualMachines().create(creatableVirtualMachines).values()) {
ipAddresses.put(virtualMachine.name(), virtualMachine.getPrimaryPublicIPAddress().ipAddress());
}
System.out.println("Adding firewall rule for each of virtual network network");
List<SqlServer> sqlServers = new ArrayList<>();
sqlServers.add(sqlServerInSecondaryLocation);
sqlServers.add(sqlServerInEurope);
sqlServers.add(masterSqlServer);
for (SqlServer sqlServer : sqlServers) {
for (Map.Entry<String, String> ipAddress : ipAddresses.entrySet()) {
sqlServer.firewallRules().define(ipAddress.getKey()).withIPAddress(ipAddress.getValue()).create();
}
}
for (SqlServer sqlServer : sqlServers) {
System.out.println("Print firewall rules in Sql Server in " + sqlServer.regionName());
List<SqlFirewallRule> firewallRules = sqlServer.firewallRules().list();
for (SqlFirewallRule firewallRule : firewallRules) {
Utils.print(firewallRule);
}
}
// Delete the SQL Server.
System.out.println("Deleting all Sql Servers");
for (SqlServer sqlServer : sqlServers) {
azure.sqlServers().deleteById(sqlServer.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 (Exception e) {
System.out.println("Did not create any resources in Azure. No clean up is necessary");
}
}
return false;
}
use of com.microsoft.azure.management.resources.fluentcore.model.Creatable 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);
}
use of com.microsoft.azure.management.resources.fluentcore.model.Creatable 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);
}
Aggregations