use of com.vmware.photon.controller.model.adapters.vsphere.util.connection.GetMoRef in project photon-model by vmware.
the class Finder method loadFolders.
/**
* Lazily load the datacenter folders
* @throws InvalidPropertyFaultMsg
* @throws RuntimeFaultFaultMsg
* @throws FinderException
*/
private void loadFolders() throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, FinderException {
GetMoRef get = new GetMoRef(this.connection);
Map<String, Object> folders = get.entityProps(this.datacenter, new String[] { "vmFolder", "hostFolder", "datastoreFolder", "networkFolder" });
this.vmFolder = fullPath((ManagedObjectReference) folders.get("vmFolder"));
this.hostFolder = fullPath((ManagedObjectReference) folders.get("hostFolder"));
this.datastoreFolder = fullPath((ManagedObjectReference) folders.get("datastoreFolder"));
this.networkFolder = fullPath((ManagedObjectReference) folders.get("networkFolder"));
}
use of com.vmware.photon.controller.model.adapters.vsphere.util.connection.GetMoRef in project photon-model by vmware.
the class SanityCheckTest method example.
@Test
public void example() throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
BasicConnection conn = new BasicConnection();
String url = System.getProperty("vsphere.url");
String username = System.getProperty("vsphere.username");
String password = System.getProperty("vsphere.password");
conn.setURI(URI.create(url));
conn.setUsername(username);
conn.setPassword(password);
conn.setIgnoreSslErrors(true);
conn.setRequestTimeout(30, TimeUnit.SECONDS);
conn.connect();
AboutInfo about = conn.getServiceContent().getAbout();
System.out.println(Utils.toJsonHtml(about));
ManagedObjectReference rootFolder = conn.getServiceContent().getRootFolder();
GetMoRef getMoRef = new GetMoRef(conn);
String name = getMoRef.entityProp(rootFolder, "name");
System.out.println("Root folder is called \'" + name + "\'");
}
use of com.vmware.photon.controller.model.adapters.vsphere.util.connection.GetMoRef 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.GetMoRef 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.GetMoRef in project photon-model by vmware.
the class VSphereEndpointAdapterService method doValidate.
private void doValidate(AuthCredentialsServiceState credentials, BiConsumer<ServiceErrorResponse, Throwable> callback, URI adapterManagementUri, String id) {
BasicConnection connection = createConnection(adapterManagementUri, credentials);
try {
// login and session creation
connection.connect();
if (id != null && !id.isEmpty()) {
// if a datacenter is configured also validate moref is OK
new GetMoRef(connection).entityProp(VimUtils.convertStringToMoRef(id), VimNames.PROPERTY_NAME);
}
callback.accept(null, null);
} catch (RuntimeFaultFaultMsg | InvalidPropertyFaultMsg | IllegalArgumentException e) {
ServiceErrorResponse r = Utils.toServiceErrorResponse(e);
r.statusCode = STATUS_CODE_BAD_REQUEST;
r.message = String.format("Error looking for datacenter for id '%s'", id);
callback.accept(r, e);
} catch (ConnectionException e) {
String msg = String.format("Cannot establish connection to %s", adapterManagementUri);
logWarning(msg);
callback.accept(null, e);
} finally {
closeQuietly(connection);
}
}
Aggregations