use of com.vmware.photon.controller.model.adapters.azure.instance.AzureInstanceContext.AzureNicContext in project photon-model by vmware.
the class AzureInstanceService method updateNicStates.
/**
* Update {@code computeState.nicState[i].address} with Azure NICs' private IP.
*/
private DeferredResult<AzureInstanceContext> updateNicStates(AzureInstanceContext ctx) {
if (ctx.nics == null || ctx.nics.isEmpty()) {
// Do nothing.
return DeferredResult.completed(ctx);
}
List<DeferredResult<Void>> updateNICsDR = new ArrayList<>(ctx.nics.size());
for (AzureNicContext nicCtx : ctx.nics) {
if (nicCtx.nic == null) {
continue;
}
final NetworkInterfaceState nicStateToUpdate = new NetworkInterfaceState();
nicStateToUpdate.id = nicCtx.nic.id();
nicStateToUpdate.documentSelfLink = nicCtx.nicStateWithDesc.documentSelfLink;
if (nicCtx.nic.ipConfigurations() != null && !nicCtx.nic.ipConfigurations().isEmpty()) {
nicStateToUpdate.address = nicCtx.nic.ipConfigurations().get(0).privateIPAddress();
}
Operation updateNicOp = Operation.createPatch(ctx.service, nicStateToUpdate.documentSelfLink).setBody(nicStateToUpdate);
DeferredResult<Void> updateNicDR = ctx.service.sendWithDeferredResult(updateNicOp).thenAccept(ignored -> logFine(() -> String.format("Updating NIC state [%s] with Private IP [%s]: SUCCESS", nicCtx.nic.name(), nicStateToUpdate.address)));
updateNICsDR.add(updateNicDR);
}
return DeferredResult.allOf(updateNICsDR).thenApply(ignored -> ctx);
}
use of com.vmware.photon.controller.model.adapters.azure.instance.AzureInstanceContext.AzureNicContext in project photon-model by vmware.
the class AzureInstanceService method createNetwork.
private void createNetwork(AzureInstanceContext ctx, AzureInstanceStage nextStage, List<SubnetInner> subnetsToCreate) {
// All NICs MUST be at the same vNet (no cross vNet VMs),
// so we select the Primary vNet.
final AzureNicContext primaryNic = ctx.getPrimaryNic();
final VirtualNetworkInner vNetToCreate = newAzureVirtualNetwork(ctx, primaryNic, subnetsToCreate);
final String vNetName = primaryNic.networkState.name;
final String vNetRGName = primaryNic.networkRGState != null ? primaryNic.networkRGState.name : ctx.resourceGroup.name();
VirtualNetworksInner azureClient = getNetworkManagementClientImpl(ctx).virtualNetworks();
final String subnetNames = vNetToCreate.subnets().stream().map(SubnetInner::name).collect(Collectors.joining(","));
final String msg = "Creating Azure vNet-Subnet [v=" + vNetName + "; s=" + subnetNames + "] for [" + ctx.vmName + "] VM";
AzureProvisioningCallbackWithRetry<VirtualNetworkInner> handler = new AzureProvisioningCallbackWithRetry<VirtualNetworkInner>(this, msg) {
@Override
protected DeferredResult<VirtualNetworkInner> consumeProvisioningSuccess(VirtualNetworkInner vNet) {
// Populate NICs with Azure Subnet
for (AzureNicContext nicCtx : ctx.nics) {
if (nicCtx.subnet == null) {
nicCtx.subnet = vNet.subnets().stream().filter(subnet -> subnet.name().equals(nicCtx.subnetState.name)).findFirst().get();
}
}
return DeferredResult.completed(vNet);
}
@Override
protected String getProvisioningState(VirtualNetworkInner vNet) {
// or PROVISIONING_STATE_SUCCEEDED if all are Succeeded
if (vNet.subnets().size() == 0) {
return PROVISIONING_STATE_FAILED_NO_SUBNET;
}
String subnetPS = vNet.subnets().stream().map(SubnetInner::provisioningState).filter(ps -> !PROVISIONING_STATE_SUCCEEDED.equalsIgnoreCase(ps)).findFirst().orElse(PROVISIONING_STATE_SUCCEEDED);
if (PROVISIONING_STATE_SUCCEEDED.equalsIgnoreCase(vNet.provisioningState()) && PROVISIONING_STATE_SUCCEEDED.equalsIgnoreCase(subnetPS)) {
return PROVISIONING_STATE_SUCCEEDED;
}
return vNet.provisioningState() + ":" + subnetPS;
}
@Override
protected Runnable checkProvisioningStateCall(ServiceCallback<VirtualNetworkInner> checkProvisioningStateCallback) {
return () -> azureClient.getByResourceGroupAsync(vNetRGName, vNetName, null, /* expand */
checkProvisioningStateCallback);
}
@Override
protected Runnable retryServiceCall(ServiceCallback<VirtualNetworkInner> retryCallback) {
return () -> azureClient.createOrUpdateAsync(vNetRGName, vNetName, vNetToCreate, retryCallback);
}
};
azureClient.createOrUpdateAsync(vNetRGName, vNetName, vNetToCreate, handler);
handler.toDeferredResult().thenApply(ignore -> ctx).whenComplete(thenAllocation(ctx, nextStage, NETWORK_NAMESPACE));
}
use of com.vmware.photon.controller.model.adapters.azure.instance.AzureInstanceContext.AzureNicContext in project photon-model by vmware.
the class AzureInstanceService method createNICs.
private void createNICs(AzureInstanceContext ctx, AzureInstanceStage nextStage) {
if (ctx.nics.isEmpty()) {
handleAllocation(ctx, nextStage);
return;
}
// Shared state between multi async calls {{
AzureCallContext callContext = AzureCallContext.newBatchCallContext(ctx.nics.size());
NetworkInterfacesInner azureClient = getNetworkManagementClientImpl(ctx).networkInterfaces();
for (AzureNicContext nicCtx : ctx.nics) {
final String nicName = nicCtx.nicStateWithDesc.name;
final NetworkInterfaceInner nic = newAzureNetworkInterface(ctx, nicCtx);
String msg = "Creating Azure NIC [" + nicName + "] for [" + ctx.vmName + "] VM";
azureClient.createOrUpdateAsync(ctx.resourceGroup.name(), nicName, nic, new TransitionToCallback<NetworkInterfaceInner>(ctx, nextStage, callContext, msg) {
@Override
protected CompletionStage<NetworkInterfaceInner> handleSuccess(NetworkInterfaceInner nic) {
nicCtx.nic = nic;
return CompletableFuture.completedFuture(nic);
}
});
}
}
use of com.vmware.photon.controller.model.adapters.azure.instance.AzureInstanceContext.AzureNicContext in project photon-model by vmware.
the class AzureInstanceService method createPublicIPs.
private void createPublicIPs(AzureInstanceContext ctx, AzureInstanceStage nextStage) {
if (ctx.nics.isEmpty()) {
handleAllocation(ctx, nextStage);
return;
}
AzureNicContext nicCtx = ctx.getPrimaryNic();
// For now if not specified default to TRUE!
if (nicCtx.nicStateWithDesc.description.assignPublicIpAddress == null) {
nicCtx.nicStateWithDesc.description.assignPublicIpAddress = Boolean.TRUE;
}
if (nicCtx.nicStateWithDesc.description.assignPublicIpAddress == Boolean.FALSE) {
// Do nothing in this method -> proceed to next stage.
handleAllocation(ctx, nextStage);
return;
}
PublicIPAddressesInner azureClient = getNetworkManagementClientImpl(ctx).publicIPAddresses();
final PublicIPAddressInner publicIPAddress = newAzurePublicIPAddress(ctx, nicCtx);
final String publicIPName = ctx.vmName + "-pip";
final String publicIPRGName = ctx.resourceGroup.name();
String msg = "Creating Azure Public IP [" + publicIPName + "] for [" + ctx.vmName + "] VM";
AzureProvisioningCallback<PublicIPAddressInner> handler = new AzureProvisioningCallback<PublicIPAddressInner>(this, msg) {
@Override
protected DeferredResult<PublicIPAddressInner> consumeProvisioningSuccess(PublicIPAddressInner publicIP) {
nicCtx.publicIP = publicIP;
return DeferredResult.completed(publicIP);
}
@Override
protected String getProvisioningState(PublicIPAddressInner publicIP) {
return publicIP.provisioningState();
}
@Override
protected Runnable checkProvisioningStateCall(ServiceCallback<PublicIPAddressInner> checkProvisioningStateCallback) {
return () -> azureClient.getByResourceGroupAsync(publicIPRGName, publicIPName, null, /* expand */
checkProvisioningStateCallback);
}
};
azureClient.createOrUpdateAsync(publicIPRGName, publicIPName, publicIPAddress, handler);
handler.toDeferredResult().thenApply(ignore -> ctx).whenComplete(thenAllocation(ctx, nextStage, NETWORK_NAMESPACE));
}
use of com.vmware.photon.controller.model.adapters.azure.instance.AzureInstanceContext.AzureNicContext 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);
}
Aggregations