use of com.vmware.photon.controller.model.adapters.vsphere.util.connection.Connection in project photon-model by vmware.
the class TestVSphereDiskService method deleteDiskFromVSphere.
private void deleteDiskFromVSphere(DiskState diskState) throws Throwable {
Connection connection = createConnection();
String diskFullPath = CustomProperties.of(diskState).getString(DISK_FULL_PATH, null);
ManagedObjectReference diskManager = connection.getServiceContent().getVirtualDiskManager();
ManagedObjectReference datacenterMoRef = VimUtils.convertStringToMoRef(diskState.regionId);
ManagedObjectReference deleteTask = connection.getVimPort().deleteVirtualDiskTask(diskManager, diskFullPath, datacenterMoRef);
TaskInfo info = VimUtils.waitTaskEnd(connection, deleteTask);
String dirName = CustomProperties.of(diskState).getString(DISK_PARENT_DIRECTORY, null);
ManagedObjectReference fileManager = connection.getServiceContent().getFileManager();
deleteTask = connection.getVimPort().deleteDatastoreFileTask(fileManager, dirName, datacenterMoRef);
info = VimUtils.waitTaskEnd(connection, deleteTask);
}
use of com.vmware.photon.controller.model.adapters.vsphere.util.connection.Connection in project photon-model by vmware.
the class ClientUtils method attachDiskToVM.
public static String attachDiskToVM(ArrayOfVirtualDevice devices, ManagedObjectReference vm, DiskService.DiskStateExpanded diskState, ManagedObjectReference diskDatastore, Connection connection, VimPortType vimPort) throws Exception {
String diskPath = VimUtils.uriToDatastorePath(diskState.sourceImageReference);
String diskFullPath = CustomProperties.of(diskState).getString(DISK_FULL_PATH, null);
Boolean insertCdRom = CustomProperties.of(diskState).getBoolean(INSERT_CDROM, false);
VirtualDeviceConfigSpec deviceConfigSpec = null;
if (diskState.type == DiskService.DiskType.HDD) {
VirtualSCSIController scsiController = getFirstScsiController(devices);
// Get available free unit numbers for the given scsi controller.
Integer[] scsiUnits = findFreeScsiUnit(scsiController, devices.getVirtualDevice());
List<VirtualMachineDefinedProfileSpec> pbmSpec = getPbmProfileSpec(diskState);
deviceConfigSpec = createHdd(scsiController.getKey(), scsiUnits[0], diskState, diskFullPath, diskDatastore, pbmSpec, false);
} else if (diskState.type == DiskService.DiskType.CDROM) {
if (insertCdRom) {
if (diskPath == null) {
throw new IllegalStateException(String.format("Cannot insert empty iso file into CD-ROM"));
}
// Find first available CD ROM to insert the iso file
VirtualCdrom cdrom = devices.getVirtualDevice().stream().filter(d -> d instanceof VirtualCdrom).map(d -> (VirtualCdrom) d).findFirst().orElse(null);
if (cdrom == null) {
throw new IllegalStateException(String.format("Could not find Virtual CD ROM to insert %s.", diskPath));
}
insertCdrom(cdrom, diskPath);
deviceConfigSpec = new VirtualDeviceConfigSpec();
deviceConfigSpec.setDevice(cdrom);
deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.EDIT);
} else {
VirtualDevice ideController = getFirstIdeController(devices);
int ideUnit = findFreeUnit(ideController, devices.getVirtualDevice());
int availableUnitNumber = nextUnitNumber(ideUnit);
deviceConfigSpec = createCdrom(ideController, availableUnitNumber);
fillInControllerUnitNumber(diskState, availableUnitNumber);
if (diskPath != null) {
// mount iso image
insertCdrom((VirtualCdrom) deviceConfigSpec.getDevice(), diskPath);
}
// Live add of cd-rom is not possible. Hence it needs to be powered off
// Power off is needed to ADD cd-rom
powerOffVm(connection, vimPort, vm);
}
} else if (diskState.type == DiskService.DiskType.FLOPPY) {
VirtualDevice sioController = getFirstSioController(devices);
int sioUnit = findFreeUnit(sioController, devices.getVirtualDevice());
int availableUnitNumber = nextUnitNumber(sioUnit);
deviceConfigSpec = createFloppy(sioController, availableUnitNumber);
fillInControllerUnitNumber(diskState, availableUnitNumber);
if (diskPath != null) {
insertFloppy((VirtualFloppy) deviceConfigSpec.getDevice(), diskPath);
}
// Power off is needed to ADD floppy
powerOffVm(connection, vimPort, vm);
}
VirtualMachineConfigSpec spec = new VirtualMachineConfigSpec();
spec.getDeviceChange().add(deviceConfigSpec);
ManagedObjectReference reconfigureTask = vimPort.reconfigVMTask(vm, spec);
TaskInfo info = VimUtils.waitTaskEnd(connection, reconfigureTask);
if (info.getState() == TaskInfoState.ERROR) {
VimUtils.rethrow(info.getError());
}
if (!insertCdRom && diskState.type != DiskService.DiskType.HDD) {
// This means it is CDROM or Floppy. Hence power on the VM as it is powered off to
// perform the operation
powerOnVM(connection, vimPort, vm);
}
return diskFullPath;
}
use of com.vmware.photon.controller.model.adapters.vsphere.util.connection.Connection in project photon-model by vmware.
the class VSphereAdapterInstanceService method createCheckForIpTask.
private Runnable createCheckForIpTask(VSphereIOThreadPool pool, Operation taskFinisher, ManagedObjectReference vmRef, Connection connection, String computeLink, ProvisionContext ctx) {
return new Runnable() {
int attemptsLeft = IP_CHECK_TOTAL_WAIT_SECONDS / IP_CHECK_INTERVAL_SECONDS - 1;
@Override
public void run() {
String ip;
Map<String, List<String>> ipV4Addresses = null;
try {
GetMoRef get = new GetMoRef(connection);
// fetch enough to make guessPublicIpV4Address() work
Map<String, Object> props = get.entityProps(vmRef, VimPath.vm_guest_net);
VmOverlay vm = new VmOverlay(vmRef, props);
ip = vm.findPublicIpV4Address(ctx.nics);
ipV4Addresses = vm.getMapNic2IpV4Addresses();
} catch (InvalidPropertyFaultMsg | RuntimeFaultFaultMsg e) {
log(Level.WARNING, "Error getting IP of vm %s, %s, aborting ", VimUtils.convertMoRefToString(vmRef), computeLink);
// complete the task, IP could be assigned during next enumeration cycle
taskFinisher.sendWith(VSphereAdapterInstanceService.this);
connection.close();
return;
}
if (ip != null && ipV4Addresses.entrySet().stream().allMatch(entry -> !entry.getValue().isEmpty())) {
connection.close();
List<String> ips = ipV4Addresses.values().stream().flatMap(List::stream).collect(Collectors.toList());
List<Operation> updateIpAddressOperations = createUpdateIPOperationsForComputeAndNics(computeLink, ip, ipV4Addresses, ctx);
OperationJoin.create(updateIpAddressOperations).setCompletion((o, e) -> {
log(Level.INFO, "Update compute IP [%s] and networkInterfaces ip" + " addresses [%s] for computeLink [%s]: ", ip, ips, computeLink);
// finish task
taskFinisher.sendWith(VSphereAdapterInstanceService.this);
}).sendWith(VSphereAdapterInstanceService.this);
} else if (attemptsLeft > 0) {
attemptsLeft--;
log(Level.INFO, "IP of %s not ready, retrying", computeLink);
// reschedule
pool.schedule(this, IP_CHECK_INTERVAL_SECONDS, TimeUnit.SECONDS);
} else {
connection.close();
if (ip == null && ipV4Addresses.entrySet().stream().allMatch(entry -> entry.getValue().isEmpty())) {
log(Level.INFO, "IP of %s are not ready, giving up", computeLink);
taskFinisher.sendWith(VSphereAdapterInstanceService.this);
} else {
// not all ips are ready still update the ones that are ready
List<Operation> updateIpAddressOperations = createUpdateIPOperationsForComputeAndNics(computeLink, ip, ipV4Addresses, ctx);
List<String> ips = ipV4Addresses.values().stream().flatMap(List::stream).collect(Collectors.toList());
OperationJoin.create(updateIpAddressOperations).setCompletion((o, e) -> {
log(Level.INFO, "Not all ips are ready. Update compute IP [%s] and " + "networkInterfaces ip addresses [%s] for " + "computeLink [%s]: ", ip != null ? ip : "", ips, computeLink);
taskFinisher.sendWith(VSphereAdapterInstanceService.this);
}).sendWith(VSphereAdapterInstanceService.this);
}
}
}
};
}
use of com.vmware.photon.controller.model.adapters.vsphere.util.connection.Connection in project photon-model by vmware.
the class VSphereAdapterInstanceService method handleCreateInstance.
private void handleCreateInstance(ProvisionContext ctx) {
ctx.pool.submit(ctx.getAdapterManagementReference(), ctx.vSphereCredentials, (connection, ce) -> {
if (ctx.fail(ce)) {
return;
}
try {
InstanceClient client = new InstanceClient(connection, ctx);
ComputeState state;
if (ctx.templateMoRef != null) {
state = client.createInstanceFromTemplate(ctx.templateMoRef);
} else if (ctx.image != null) {
ManagedObjectReference moRef = CustomProperties.of(ctx.image).getMoRef(CustomProperties.MOREF);
if (moRef != null) {
// the image is backed by a template VM
state = client.createInstanceFromTemplate(moRef);
} else {
// library item
state = client.createInstanceFromLibraryItem(ctx.image);
}
} else if (ctx.snapshotMoRef != null) {
state = client.createInstanceFromSnapshot();
} else {
state = client.createInstance();
}
if (state == null) {
// assume they will patch the task if they have provisioned the vm
return;
}
// populate state, MAC address being very important
VmOverlay vmOverlay = client.enrichStateFromVm(state);
Operation[] finishTask = new Operation[1];
for (NetworkInterfaceStateWithDetails nic : ctx.nics) {
// request guest customization while vm of powered off
SubnetState subnet = nic.subnet;
if (subnet != null && nic.description != null && nic.description.assignment == IpAssignment.STATIC) {
CustomizationClient cc = new CustomizationClient(connection, ctx.child, vmOverlay.getGuestId());
CustomizationSpec template = new CustomizationSpec();
cc.customizeNic(vmOverlay.getPrimaryMac(), ctx.child.hostName, nic.address, subnet, template);
cc.customizeDns(subnet.dnsServerAddresses, subnet.dnsSearchDomains, template);
ManagedObjectReference task = cc.customizeGuest(client.getVm(), template);
TaskInfo taskInfo = VimUtils.waitTaskEnd(connection, task);
if (taskInfo.getState() == TaskInfoState.ERROR) {
VimUtils.rethrow(taskInfo.getError());
}
}
}
// power on machine before enrichment
if (ctx.child.powerState == PowerState.ON) {
new PowerStateClient(connection).changePowerState(client.getVm(), PowerState.ON, null, 0);
state.powerState = PowerState.ON;
Operation op = ctx.mgr.createTaskPatch(TaskStage.FINISHED);
Boolean awaitIp = CustomProperties.of(ctx.child).getBoolean(ComputeProperties.CUSTOM_PROP_COMPUTE_AWAIT_IP, true);
if (awaitIp) {
Runnable runnable = createCheckForIpTask(ctx.pool, op, client.getVm(), connection.createUnmanagedCopy(), ctx.child.documentSelfLink, ctx);
ctx.pool.schedule(runnable, IP_CHECK_INTERVAL_SECONDS, TimeUnit.SECONDS);
} else {
finishTask[0] = op;
}
} else {
// only finish the task without waiting for IP
finishTask[0] = ctx.mgr.createTaskPatch(TaskStage.FINISHED);
}
updateNicsAfterProvisionSuccess(vmOverlay.getNics(), ctx);
updateDiskLinksAfterProvisionSuccess(state, vmOverlay.getDisks(), ctx);
state.lifecycleState = LifecycleState.READY;
// Find the host link where the computed is provisioned and patch the
// compute state.
queryHostDocumentAndUpdateCompute(ctx, vmOverlay.getHost()).thenCompose(computeState -> {
ComputeState hostState = computeState.iterator().next();
CustomProperties.of(state).put(VC_UUID, CustomProperties.of(hostState).getString(VC_UUID)).put(DATACENTER_SELF_LINK, CustomProperties.of(hostState).getString(DATACENTER_SELF_LINK)).put(COMPUTE_HOST_LINK_PROP_NAME, hostState.documentSelfLink);
return createComputeResourcePatch(state, ctx.computeReference);
}).whenComplete((o, e) -> {
if (e != null) {
ctx.fail(e);
return;
}
if (finishTask.length > 0) {
finishTask[0].sendWith(this);
}
});
} catch (Exception e) {
ctx.fail(e);
}
});
}
use of com.vmware.photon.controller.model.adapters.vsphere.util.connection.Connection in project photon-model by vmware.
the class VSphereAdapterSnapshotService method performSnapshotOperation.
private DeferredResult<SnapshotContext> performSnapshotOperation(SnapshotContext context) {
DeferredResult<SnapshotContext> result = new DeferredResult<>();
VSphereIOThreadPool pool = VSphereIOThreadPoolAllocator.getPool(this);
DeferredResult<AuthCredentialsService.AuthCredentialsServiceState> credentials;
if (IAAS_API_ENABLED) {
credentials = SessionUtil.retrieveExternalToken(this, context.operation.getAuthorizationContext());
} else {
URI authUri = createInventoryUri(this.getHost(), context.parentComputeDescription.description.authCredentialsLink);
Operation op = Operation.createGet(authUri);
credentials = this.sendWithDeferredResult(op, AuthCredentialsService.AuthCredentialsServiceState.class);
}
switch(context.requestType) {
case CREATE:
BiConsumer<AuthCredentialsService.AuthCredentialsServiceState, Throwable> create = (authCredentialsServiceState, throwable) -> {
if (throwable != null) {
result.fail(throwable);
return;
}
pool.submit(context.parentComputeDescription.adapterManagementReference, authCredentialsServiceState, (connection, e) -> {
if (e != null) {
result.fail(e);
} else {
createSnapshot(connection, context, result);
}
});
};
credentials.whenComplete(create);
break;
case DELETE:
BiConsumer<AuthCredentialsService.AuthCredentialsServiceState, Throwable> delete = (authCredentialsServiceState, throwable) -> {
if (throwable != null) {
result.fail(throwable);
return;
}
pool.submit(context.parentComputeDescription.adapterManagementReference, authCredentialsServiceState, (connection, e) -> {
if (e != null) {
result.fail(e);
} else {
deleteSnapshot(context, connection, result);
}
});
};
credentials.whenComplete(delete);
break;
case REVERT:
BiConsumer<AuthCredentialsService.AuthCredentialsServiceState, Throwable> revert = (authCredentialsServiceState, throwable) -> {
if (throwable != null) {
result.fail(throwable);
return;
}
pool.submit(context.parentComputeDescription.adapterManagementReference, authCredentialsServiceState, (connection, e) -> {
if (e != null) {
result.fail(e);
} else {
revertSnapshot(context, connection, result);
}
});
};
credentials.whenComplete(revert);
break;
default:
result.fail(new IllegalStateException("Unsupported requestType " + context.requestType));
}
return result;
}
Aggregations