use of com.vmware.xenon.common.DeferredResult 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.xenon.common.DeferredResult in project photon-model by vmware.
the class AzureInstanceService method updateDiskStates.
/**
* Update {@code computeState.diskState[i].id} with Azure Disks' VHD URI.
*/
private DeferredResult<AzureInstanceContext> updateDiskStates(AzureInstanceContext ctx) {
if (ctx.provisionedVm == null) {
// Do nothing.
return DeferredResult.completed(ctx);
}
List<DeferredResult<Operation>> diskStateDRs = new ArrayList<>();
// Update boot DiskState with Azure osDisk VHD URI in case of unmanaged disks and
// disks id in case of managed disks
{
final OSDisk azureOsDisk = ctx.provisionedVm.storageProfile().osDisk();
final DiskState diskStateToUpdate = new DiskState();
diskStateToUpdate.documentSelfLink = ctx.bootDiskState.documentSelfLink;
diskStateToUpdate.persistent = ctx.bootDiskState.persistent;
diskStateToUpdate.regionId = ctx.provisionedVm.location();
diskStateToUpdate.endpointLink = ctx.endpoint.documentSelfLink;
AdapterUtils.addToEndpointLinks(diskStateToUpdate, ctx.endpoint.documentSelfLink);
// The actual value being updated
if (ctx.useManagedDisks()) {
diskStateToUpdate.id = azureOsDisk.managedDisk().id();
} else {
diskStateToUpdate.id = AzureUtils.canonizeId(azureOsDisk.vhd().uri());
}
diskStateToUpdate.status = DiskService.DiskStatus.ATTACHED;
Operation updateDiskState = Operation.createPatch(ctx.service, diskStateToUpdate.documentSelfLink).setBody(diskStateToUpdate);
DeferredResult<Operation> updateDR = ctx.service.sendWithDeferredResult(updateDiskState).whenComplete((op, exc) -> {
if (exc != null) {
logSevere(() -> String.format("Updating boot DiskState [%s] with VHD URI [%s]: FAILED with %s", ctx.bootDiskState.name, diskStateToUpdate.id, Utils.toString(exc)));
} else {
logFine(() -> String.format("Updating boot DiskState [%s] with VHD URI [%s]: SUCCESS", ctx.bootDiskState.name, diskStateToUpdate.id));
}
});
diskStateDRs.add(updateDR);
}
for (DataDisk azureDataDisk : ctx.provisionedVm.storageProfile().dataDisks()) {
// Find corresponding DiskState by name
Optional<DiskState> dataDiskOpt = ctx.dataDiskStates.stream().map(DiskState.class::cast).filter(dS -> azureDataDisk.name().equals(dS.name)).findFirst();
Optional<DiskState> externalDiskOpt = ctx.externalDataDisks.stream().map(DiskState.class::cast).filter(dS -> azureDataDisk.name().equals(dS.name)).findFirst();
// update disk state
if (dataDiskOpt.isPresent()) {
diskStateDRs.add(createDiskToUpdate(ctx, dataDiskOpt, azureDataDisk));
} else if (externalDiskOpt.isPresent()) {
diskStateDRs.add(createDiskToUpdate(ctx, externalDiskOpt, azureDataDisk));
} else {
// additional disks were created by the custom image. Will always be of
// managed disk type. Create new disk state.
DiskState diskStateToCreate = new DiskState();
diskStateToCreate.id = azureDataDisk.managedDisk().id();
diskStateToCreate.name = azureDataDisk.name();
diskStateToCreate.regionId = ctx.provisionedVm.location();
diskStateToCreate.customProperties = new HashMap<>();
diskStateToCreate.customProperties.put(DISK_CONTROLLER_NUMBER, String.valueOf(azureDataDisk.lun()));
if (azureDataDisk.managedDisk().storageAccountType() != null) {
diskStateToCreate.customProperties.put(AZURE_MANAGED_DISK_TYPE, azureDataDisk.managedDisk().storageAccountType().toString());
} else {
// set to Standard_LRS default
diskStateToCreate.customProperties.put(AZURE_MANAGED_DISK_TYPE, StorageAccountTypes.STANDARD_LRS.toString());
}
diskStateToCreate.customProperties.put(AZURE_DATA_DISK_CACHING, azureDataDisk.caching().toString());
if (azureDataDisk.diskSizeGB() != null) {
diskStateToCreate.capacityMBytes = azureDataDisk.diskSizeGB() * 1024;
}
diskStateToCreate.status = DiskService.DiskStatus.ATTACHED;
diskStateToCreate.persistent = ctx.bootDiskState.persistent;
diskStateToCreate.endpointLink = ctx.endpoint.documentSelfLink;
AdapterUtils.addToEndpointLinks(diskStateToCreate, ctx.endpoint.documentSelfLink);
Operation createDiskState = Operation.createPost(ctx.service, DiskService.FACTORY_LINK).setBody(diskStateToCreate);
DeferredResult<Operation> createDR = ctx.service.sendWithDeferredResult(createDiskState).whenComplete((op, exc) -> {
if (exc != null) {
logSevere(() -> String.format("Creating data DiskState [%s] with disk id [%s]: FAILED " + "with %s", azureDataDisk.name(), azureDataDisk.managedDisk().id(), Utils.toString(exc)));
} else {
logFine(() -> String.format("Creating data DiskState [%s] with disk id [%s]: SUCCESS", azureDataDisk.name(), azureDataDisk.managedDisk().id()));
// update compute state with data disks present on custom image
ComputeState cs = new ComputeState();
List<String> disksLinks = new ArrayList<>();
DiskState diskState = op.getBody(DiskState.class);
disksLinks.add(diskState.documentSelfLink);
cs.diskLinks = disksLinks;
Operation.CompletionHandler completionHandler = (ox, ex) -> {
if (ex != null) {
handleError(ctx, ex);
return;
}
};
sendRequest(Operation.createPatch(ctx.computeRequest.resourceReference).setBody(cs).setCompletion(completionHandler));
}
});
diskStateDRs.add(createDR);
}
}
return DeferredResult.allOf(diskStateDRs).thenApply(ignored -> ctx);
}
use of com.vmware.xenon.common.DeferredResult in project photon-model by vmware.
the class AzureInstanceService method createSecurityGroupsIfNotExist.
private void createSecurityGroupsIfNotExist(AzureInstanceContext ctx, AzureInstanceStage nextStage) {
if (ctx.nics.isEmpty()) {
handleAllocation(ctx, nextStage);
return;
}
NetworkSecurityGroupsInner azureClient = getNetworkManagementClientImpl(ctx).networkSecurityGroups();
List<DeferredResult<NetworkSecurityGroupInner>> createSGDR = ctx.nics.stream().filter(nicCtx -> nicCtx.securityGroupState() != null && nicCtx.securityGroup == null).map(nicCtx -> {
SecurityGroupState sgState = nicCtx.securityGroupState();
String rgName = nicCtx.securityGroupRGState != null ? nicCtx.securityGroupRGState.name : ctx.resourceGroup.name();
String msg = "Create Azure Security Group [" + rgName + "/" + sgState.name + "] for [" + nicCtx.nicStateWithDesc.name + "] NIC for [" + ctx.vmName + "] VM";
return AzureSecurityGroupUtils.createSecurityGroup(this, azureClient, sgState, rgName, ctx.resourceGroup.location(), msg).thenCompose(sg -> {
String addMsg = "Add Azure Security Rules to Group [" + rgName + "/" + sgState.name + "] for [" + nicCtx.nicStateWithDesc.name + "] NIC for [" + ctx.vmName + "] VM";
return AzureSecurityGroupUtils.addSecurityRules(this, azureClient, sgState, rgName, sg, addMsg);
}).thenApply(updatedSG -> {
nicCtx.securityGroup = updatedSG;
return updatedSG;
});
}).collect(Collectors.toList());
DeferredResult.allOf(createSGDR).whenComplete((all, exc) -> {
if (exc != null) {
handleError(ctx, exc);
} else {
handleAllocation(ctx, nextStage);
}
});
}
use of com.vmware.xenon.common.DeferredResult in project photon-model by vmware.
the class AzureLoadBalancerService method getNetworkSecurityGroupInners.
/**
* Get security groups from Azure and store in context
* These are updated to add firewall rules to allow traffic to flow through the load balancer
*
* @param context Azure load balancer context
* @return DeferredResult
*/
private DeferredResult<AzureLoadBalancerContext> getNetworkSecurityGroupInners(AzureLoadBalancerContext context) {
if (CollectionUtils.isEmpty(context.securityGroupStates)) {
return DeferredResult.completed(context);
}
NetworkSecurityGroupsInner azureSecurityGroupClient = context.azureSdkClients.getNetworkManagementClientImpl().networkSecurityGroups();
List<DeferredResult<NetworkSecurityGroupInner>> networkSecurityGroupInners = context.securityGroupStates.stream().map(securityGroupState -> {
String securityGroupName = securityGroupState.name;
final String msg = "Getting Azure Security Group [" + securityGroupName + "].";
return AzureSecurityGroupUtils.getSecurityGroup(this, azureSecurityGroupClient, AzureUtils.getResourceGroupName(securityGroupState.id), securityGroupName, msg);
}).collect(Collectors.toList());
return DeferredResult.allOf(networkSecurityGroupInners).thenApply(networkSecurityGroupInnerList -> {
context.securityGroupInners = networkSecurityGroupInnerList;
return context;
});
}
use of com.vmware.xenon.common.DeferredResult in project photon-model by vmware.
the class IPAddressAllocationTaskService method assignExistingIpToResource.
/**
* The context has all the existing IP address documents owned by the subnet.
* We go through each of those IP address docs and check if it's status is available.
* If it is, we allocate it to the passed in, connected resource.
*
* @param context IPAddressAllocationContext
* @param connectedResourceLink The resource that needs an IP address
* @return A DeferredResult of an IPAddressState
*/
private DeferredResult<IPAddressState> assignExistingIpToResource(IPAddressAllocationContext context, String connectedResourceLink) {
List<IPAddressState> existingIpAddressStates = context.ipAddressStates;
DeferredResult<IPAddressState> returnIp = new DeferredResult<>();
for (IPAddressState addressState : existingIpAddressStates) {
Long longIp = IpHelper.ipStringToLong(addressState.ipAddress);
if (addressState.ipAddressStatus == IPAddressState.IPAddressStatus.AVAILABLE && (!context.unavailableIpAddresses.contains(longIp))) {
context.unavailableIpAddresses.add(longIp);
addressState.ipAddressStatus = IPAddressState.IPAddressStatus.ALLOCATED;
addressState.connectedResourceLink = connectedResourceLink;
logInfo("Picking an existing IP %s for resource %s", addressState.ipAddress, connectedResourceLink);
return updateExistingIpAddressResource(addressState, context);
} else {
context.unavailableIpAddresses.add(longIp);
}
}
returnIp.complete(null);
return returnIp;
}
Aggregations