use of com.microsoft.azure.SubResource in project photon-model by vmware.
the class AzureInstanceService method createVM.
private void createVM(AzureInstanceContext ctx, AzureInstanceStage nextStage) {
ComputeDescriptionService.ComputeDescription description = ctx.child.description;
Map<String, String> customProperties = description.customProperties;
if (customProperties == null) {
handleError(ctx, new IllegalStateException("Custom properties not specified"));
return;
}
// DiskService.DiskStateExpanded bootDisk = ctx.bootDiskState;
if (ctx.bootDiskState == null) {
handleError(ctx, new IllegalStateException("Azure bootDisk not specified"));
return;
}
String cloudConfig = null;
if (ctx.bootDiskState.bootConfig != null && ctx.bootDiskState.bootConfig.files.length > CLOUD_CONFIG_DEFAULT_FILE_INDEX) {
cloudConfig = ctx.bootDiskState.bootConfig.files[CLOUD_CONFIG_DEFAULT_FILE_INDEX].contents;
}
VirtualMachineInner request = new VirtualMachineInner();
request.withLocation(ctx.resourceGroup.location());
SubResource availabilitySetSubResource = new SubResource().withId(ctx.availabilitySet.id());
request.withAvailabilitySet(availabilitySetSubResource);
// Set OS profile.
OSProfile osProfile = new OSProfile();
osProfile.withComputerName(ctx.vmName);
if (ctx.childAuth != null) {
osProfile.withAdminUsername(ctx.childAuth.userEmail);
osProfile.withAdminPassword(EncryptionUtils.decrypt(ctx.childAuth.privateKey));
}
if (cloudConfig != null) {
try {
osProfile.withCustomData(Base64.getEncoder().encodeToString(cloudConfig.getBytes(Utils.CHARSET)));
} catch (UnsupportedEncodingException e) {
logWarning(() -> "Error encoding user data");
return;
}
}
request.withOsProfile(osProfile);
// Set hardware profile.
HardwareProfile hardwareProfile = new HardwareProfile();
hardwareProfile.withVmSize(description.instanceType != null ? VirtualMachineSizeTypes.fromString(description.instanceType) : VirtualMachineSizeTypes.BASIC_A0);
request.withHardwareProfile(hardwareProfile);
// Set storage profile.
// Create destination OS VHD
final OSDisk osDisk = newAzureOsDisk(ctx);
final StorageProfile storageProfile = new StorageProfile();
storageProfile.withOsDisk(osDisk);
List<DataDisk> dataDisks = new ArrayList<>();
List<Integer> LUNsOnImage = new ArrayList<>();
storageProfile.withImageReference(ctx.imageSource.asImageReferenceInner());
if (ctx.imageSource.type == ImageSource.Type.PRIVATE_IMAGE) {
// set LUNs of data disks present on the custom image.
final ImageState imageState = ctx.imageSource.asImageState();
if (imageState != null && imageState.diskConfigs != null) {
for (DiskConfiguration diskConfig : imageState.diskConfigs) {
if (diskConfig.properties != null && diskConfig.properties.containsKey(AzureConstants.AZURE_DISK_LUN)) {
DataDisk imageDataDisk = new DataDisk();
int lun = Integer.parseInt(diskConfig.properties.get(AzureConstants.AZURE_DISK_LUN));
LUNsOnImage.add(lun);
imageDataDisk.withLun(lun);
imageDataDisk.withCreateOption(DiskCreateOptionTypes.FROM_IMAGE);
dataDisks.add(imageDataDisk);
}
}
}
String dataDiskCaching = ctx.bootDiskState.customProperties.get(AZURE_DATA_DISK_CACHING);
if (dataDiskCaching != null) {
dataDisks.stream().forEach(dataDisk -> dataDisk.withCaching(CachingTypes.fromString(dataDiskCaching)));
}
String diskType = ctx.bootDiskState.customProperties.get(AZURE_MANAGED_DISK_TYPE);
if (diskType != null) {
ManagedDiskParametersInner managedDiskParams = new ManagedDiskParametersInner();
managedDiskParams.withStorageAccountType(StorageAccountTypes.fromString(diskType));
dataDisks.stream().forEach(dataDisk -> dataDisk.withManagedDisk(managedDiskParams));
}
}
// choose LUN greater than the one specified in case of custom image. Else start from zero.
int LUNForAdditionalDisk = LUNsOnImage.size() == 0 ? 0 : Collections.max(LUNsOnImage) + 1;
dataDisks.addAll(newAzureDataDisks(ctx, LUNForAdditionalDisk));
storageProfile.withDataDisks(dataDisks);
request.withStorageProfile(storageProfile);
// Set network profile {{
NetworkProfile networkProfile = new NetworkProfile();
networkProfile.withNetworkInterfaces(new ArrayList<>());
for (AzureNicContext nicCtx : ctx.nics) {
NetworkInterfaceReferenceInner nicRef = new NetworkInterfaceReferenceInner();
nicRef.withId(nicCtx.nic.id());
// NOTE: First NIC is marked as Primary.
nicRef.withPrimary(networkProfile.networkInterfaces().isEmpty());
networkProfile.networkInterfaces().add(nicRef);
}
request.withNetworkProfile(networkProfile);
logFine(() -> String.format("Creating virtual machine with name [%s]", ctx.vmName));
AzureAsyncCallback<VirtualMachineInner> callback = new AzureAsyncCallback<VirtualMachineInner>() {
@Override
public void onError(Throwable e) {
// exception and try again with a shorter name
if (isIncorrectNameLength(e)) {
request.osProfile().withComputerName(generateWindowsComputerName(ctx.vmName));
getComputeManagementClientImpl(ctx).virtualMachines().createOrUpdateAsync(ctx.resourceGroup.name(), ctx.vmName, request, this);
return;
}
handleCloudError(String.format("Provisioning VM %s: FAILED. Details:", ctx.vmName), ctx, COMPUTE_NAMESPACE, e);
}
// Cannot tell for sure, but these checks should be enough
private boolean isIncorrectNameLength(Throwable e) {
if (e instanceof CloudException) {
CloudException ce = (CloudException) e;
CloudError body = ce.body();
if (body != null) {
String code = body.code();
String target = body.target();
return INVALID_PARAMETER.equals(code) && COMPUTER_NAME.equals(target) && request.osProfile().computerName().length() > WINDOWS_COMPUTER_NAME_MAX_LENGTH && body.message().toLowerCase().contains("windows");
}
}
return false;
}
private String generateWindowsComputerName(String vmName) {
String computerName = vmName;
if (vmName.length() > WINDOWS_COMPUTER_NAME_MAX_LENGTH) {
// Take the first 12 and the last 3 chars of the generated VM name
computerName = vmName.substring(0, 12) + vmName.substring(vmName.length() - 3, vmName.length());
}
return computerName;
}
@Override
public void onSuccess(VirtualMachineInner result) {
logFine(() -> String.format("Successfully created vm [%s]", result.name()));
ctx.provisionedVm = result;
ComputeState cs = new ComputeState();
// Azure for some case changes the case of the vm id.
ctx.vmId = result.id().toLowerCase();
cs.id = ctx.vmId;
cs.type = ComputeType.VM_GUEST;
cs.environmentName = ComputeDescription.ENVIRONMENT_NAME_AZURE;
cs.lifecycleState = LifecycleState.READY;
if (ctx.child.customProperties == null) {
cs.customProperties = new HashMap<>();
} else {
cs.customProperties = ctx.child.customProperties;
}
cs.customProperties.put(RESOURCE_GROUP_NAME, ctx.resourceGroup.name());
Operation.CompletionHandler completionHandler = (ox, exc) -> {
if (exc != null) {
handleError(ctx, exc);
return;
}
handleAllocation(ctx, nextStage);
};
sendRequest(Operation.createPatch(ctx.computeRequest.resourceReference).setBody(cs).setCompletion(completionHandler));
}
};
getComputeManagementClientImpl(ctx).virtualMachines().createOrUpdateAsync(ctx.resourceGroup.name(), ctx.vmName, request, callback);
}
use of com.microsoft.azure.SubResource in project photon-model by vmware.
the class AzureLoadBalancerService method buildLoadBalancingRules.
/**
* Build Azure load balancing rule model
*
* @param context Azure load balancer context
* @return List of LoadBalancingRuleInner objects
*/
private List<LoadBalancingRuleInner> buildLoadBalancingRules(AzureLoadBalancerContext context) {
List<LoadBalancingRuleInner> loadBalancingRules = Lists.newArrayList();
int index = 1;
for (RouteConfiguration routes : context.loadBalancerStateExpanded.routes) {
ProbeInner probeInner = findMatchingProbe(context, index);
LoadBalancingRuleInner loadBalancingRule = new LoadBalancingRuleInner();
loadBalancingRule.withName(String.format("%s-lb-rule-%s", context.loadBalancerStateExpanded.name, index++));
loadBalancingRule.withBackendPort(Integer.valueOf(routes.instancePort));
loadBalancingRule.withFrontendPort(Integer.valueOf(routes.port));
loadBalancingRule.withBackendAddressPool(new SubResource().withId(context.loadBalancerAzure.backendAddressPools().get(0).id()));
// Converting HTTP and HTTPS to TCP to send to Azure as Azure only supports TCP or UCP
if (StringUtils.equalsIgnoreCase("HTTP", routes.protocol) || StringUtils.equalsIgnoreCase("HTTPS", routes.protocol)) {
routes.protocol = TransportProtocol.TCP.toString();
}
boolean isTcpProtocol = StringUtils.equalsIgnoreCase(TransportProtocol.TCP.toString(), routes.protocol);
boolean isUdpProtocol = StringUtils.equalsIgnoreCase(TransportProtocol.UDP.toString(), routes.protocol);
AssertUtil.assertTrue(isTcpProtocol || isUdpProtocol, String.format("Unsupported protocol %s. Only UDP and TCP are supported.", routes.protocol));
loadBalancingRule.withProtocol(new TransportProtocol(routes.protocol));
// TODO support more than one frontend case
loadBalancingRule.withFrontendIPConfiguration(new SubResource().withId(context.loadBalancerAzure.frontendIPConfigurations().get(0).id()));
if (probeInner != null) {
loadBalancingRule.withProbe(new SubResource().withId(probeInner.id()));
}
loadBalancingRules.add(loadBalancingRule);
}
return loadBalancingRules;
}
use of com.microsoft.azure.SubResource in project photon-model by vmware.
the class AzureTestUtil method addAzureGatewayToVirtualNetwork.
/**
* Adds Gateway to Virtual Network in Azure
*/
private static void addAzureGatewayToVirtualNetwork(String resourceGroupName, AzureNicSpecs nicSpecs, NetworkManagementClientImpl networkManagementClient) throws CloudException, IOException, InterruptedException {
// create Gateway Subnet
SubnetInner gatewaySubnetParams = new SubnetInner();
gatewaySubnetParams.withName(nicSpecs.gateway.name);
gatewaySubnetParams.withAddressPrefix(nicSpecs.gateway.cidr);
SubnetInner gatewaySubnet = networkManagementClient.subnets().createOrUpdate(resourceGroupName, nicSpecs.network.name, AzureConstants.GATEWAY_SUBNET_NAME, gatewaySubnetParams);
// create Public IP
PublicIPAddressInner publicIPAddressParams = new PublicIPAddressInner();
publicIPAddressParams.withPublicIPAllocationMethod(IPAllocationMethod.DYNAMIC);
publicIPAddressParams.withLocation(nicSpecs.gateway.zoneId);
PublicIPAddressInner publicIPAddress = networkManagementClient.publicIPAddresses().createOrUpdate(resourceGroupName, nicSpecs.gateway.publicIpName, publicIPAddressParams);
SubResource publicIPSubResource = new SubResource();
publicIPSubResource.withId(publicIPAddress.id());
// create IP Configuration
VirtualNetworkGatewayIPConfigurationInner ipConfiguration = new VirtualNetworkGatewayIPConfigurationInner();
ipConfiguration.withName(nicSpecs.gateway.ipConfigurationName);
ipConfiguration.withSubnet(gatewaySubnet);
ipConfiguration.withPrivateIPAllocationMethod(IPAllocationMethod.DYNAMIC);
ipConfiguration.withPublicIPAddress(publicIPSubResource);
// create Virtual Network Gateway
VirtualNetworkGatewayInner virtualNetworkGateway = new VirtualNetworkGatewayInner();
virtualNetworkGateway.withGatewayType(VirtualNetworkGatewayType.VPN);
virtualNetworkGateway.withVpnType(VpnType.ROUTE_BASED);
VirtualNetworkGatewaySku vNetGatewaySku = new VirtualNetworkGatewaySku();
vNetGatewaySku.withName(VirtualNetworkGatewaySkuName.STANDARD);
vNetGatewaySku.withTier(VirtualNetworkGatewaySkuTier.STANDARD);
vNetGatewaySku.withCapacity(2);
virtualNetworkGateway.withSku(vNetGatewaySku);
virtualNetworkGateway.withLocation(AZURE_RESOURCE_GROUP_LOCATION);
List<VirtualNetworkGatewayIPConfigurationInner> ipConfigurations = new ArrayList<>();
ipConfigurations.add(ipConfiguration);
virtualNetworkGateway.withIpConfigurations(ipConfigurations);
// Call the async variant because the virtual network gateway provisioning depends on
// the public IP address assignment which is time-consuming operation
networkManagementClient.virtualNetworkGateways().createOrUpdateAsync(resourceGroupName, nicSpecs.gateway.name, virtualNetworkGateway, new ServiceCallback<VirtualNetworkGatewayInner>() {
@Override
public void failure(Throwable throwable) {
throw new RuntimeException("Error creating Azure Virtual Network Gateway.", throwable);
}
@Override
public void success(VirtualNetworkGatewayInner response) {
}
});
}
Aggregations