use of com.vmware.photon.controller.model.adapters.vsphere.util.finders.Element in project photon-model by vmware.
the class VSphereAdapterImageEnumerationService method refreshResourcesOnce.
private void refreshResourcesOnce(Set<String> oldImages, ImageEnumerateRequest request, ComputeStateWithDescription parent, Connection connection, TaskManager mgr) {
DatacenterLister lister = new DatacenterLister(connection);
try {
for (Element element : lister.listAllDatacenters()) {
ManagedObjectReference datacenter = element.object;
try {
EnumerationClient client = new EnumerationClient(connection, parent, datacenter);
processAllTemplates(oldImages, request.resourceLink(), request.taskLink(), client, parent.tenantLinks);
} catch (Throwable e) {
mgr.patchTaskToFailure("Error processing vm templates in " + element.path, e);
return;
}
}
} catch (InvalidPropertyFaultMsg | RuntimeFaultFaultMsg e) {
mgr.patchTaskToFailure("Error getting datacenters", e);
return;
}
VapiConnection vapi = VapiConnection.createFromVimConnection(connection);
try {
vapi.login();
LibraryClient libraryClient = vapi.newLibraryClient();
processAllLibraries(oldImages, request.resourceLink(), request.taskLink(), libraryClient, parent.tenantLinks);
mgr.patchTask(TaskStage.FINISHED);
} catch (Throwable t) {
mgr.patchTaskToFailure("Error processing library items", t);
return;
} finally {
vapi.close();
}
// garbage collection runs async
garbageCollectUntouchedImages(oldImages);
}
use of com.vmware.photon.controller.model.adapters.vsphere.util.finders.Element in project photon-model by vmware.
the class InstanceClient method awaitVM.
private ManagedObjectReference awaitVM(String replicatedName, ManagedObjectReference vmFolder, GetMoRef get) throws RuntimeFaultFaultMsg, InvalidPropertyFaultMsg, FinderException {
Element element = this.finder.fullPath(vmFolder);
String path = element.path;
if (path.endsWith("/")) {
path = path + replicatedName;
} else {
path = path + "/" + replicatedName;
}
// paths
if (path.startsWith("/Datacenters")) {
path = path.substring("/Datacenters".length());
}
logger.info("Searching for vm using InventoryPath {}", path);
ManagedObjectReference reference = getVimPort().findByInventoryPath(getServiceContent().getSearchIndex(), path);
Object snapshot = get.entityProp(reference, VimPath.vm_snapshot);
if (snapshot == null) {
int retryCount = 30;
while (retryCount > 0) {
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
return null;
}
snapshot = get.entityProp(reference, VimPath.vm_snapshot);
if (snapshot != null) {
return reference;
}
}
}
return reference;
}
use of com.vmware.photon.controller.model.adapters.vsphere.util.finders.Element in project photon-model by vmware.
the class InstanceClient method getVmFolder.
/**
* Decides in which folder to put the newly created vm.
*
* @return
* @throws InvalidPropertyFaultMsg
* @throws RuntimeFaultFaultMsg
* @throws FinderException
*/
private ManagedObjectReference getVmFolder() throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, FinderException {
// look for a configured folder in compute state
String folderPath = CustomProperties.of(this.ctx.child).getString(RESOURCE_GROUP_NAME);
if (folderPath == null) {
// look for a configured folder in parent
folderPath = CustomProperties.of(this.ctx.parent).getString(RESOURCE_GROUP_NAME);
}
Element vmFolderElement = this.finder.vmFolder();
if (folderPath == null) {
return vmFolderElement.object;
} else {
return getExistingOrCreateNewFolder(vmFolderElement, folderPath);
}
}
use of com.vmware.photon.controller.model.adapters.vsphere.util.finders.Element in project photon-model by vmware.
the class VSphereIncrementalEnumerationService method refreshResourcesOnce.
/**
* This method executes in a thread managed by {@link VSphereIOThreadPoolAllocator}
*/
private void refreshResourcesOnce(Set<String> resourceLinks, ComputeEnumerateResourceRequest request, Connection connection, ComputeService.ComputeStateWithDescription parent, TaskManager mgr) {
VapiConnection vapiConnection = VapiConnection.createFromVimConnection(connection);
try {
vapiConnection.login();
} catch (IOException | RpcException e) {
logWarning(() -> String.format("Cannot login into vAPI endpoint: %s", Utils.toString(e)));
mgr.patchTaskToFailure(e);
return;
}
DatacenterLister lister = new DatacenterLister(connection);
try {
// Get instanceUuid of the vCenter
AboutInfo vCenter = this.connection.getServiceContent().getAbout();
for (Element element : lister.listAllDatacenters()) {
ManagedObjectReference datacenter = element.object;
log(Level.INFO, "Processing datacenter %s (%s)", element.path, VimUtils.convertMoRefToString(element.object));
EnumerationClient client = new EnumerationClient(connection, parent, datacenter);
EnumerationProgress enumerationProgress = new EnumerationProgress(resourceLinks, request, parent, vapiConnection, VimUtils.convertMoRefToString(datacenter), vCenter.getInstanceUuid());
// since we are processing DC sequentially one at a time
enumerationProgress.expectDatacenterCount(1);
VsphereDatacenterEnumerationHelper.processDatacenterInfo(this, element, enumerationProgress);
enumerationProgress.getDcTracker().await();
logInfo("Proceeding to refresh resources on datacenter: %s", enumerationProgress.getDcLink());
refreshResourcesOnDatacenter(client, enumerationProgress, mgr);
}
} catch (Exception e) {
logWarning(String.format("Error during enumeration: %s", Utils.toString(e)));
mgr.patchTaskToFailure(e);
}
try {
vapiConnection.close();
} catch (Exception e) {
logWarning(() -> String.format("Error occurred when closing vAPI connection: %s", Utils.toString(e)));
}
// after all dc's are enumerated untouched resource links are the only ones left
// in resourceLinks
garbageCollectUntouchedComputeResources(request, resourceLinks, mgr);
// cleanup the connection if the enumeration action is REFRESH.
if (EnumerationAction.REFRESH.equals(request.enumerationAction)) {
cleanupConnection();
}
}
use of com.vmware.photon.controller.model.adapters.vsphere.util.finders.Element in project photon-model by vmware.
the class InstanceDiskClient method uploadISOContents.
/**
* Uploads ISO content into the chosen datastore
*/
public DeferredResult<DiskService.DiskStateExpanded> uploadISOContents(byte[] contentToUpload) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, InvalidDatastoreFaultMsg, FileFaultFaultMsg, FinderException {
try {
// 1) fetch data store for the disk
String dsName = this.context.datastoreName;
if (dsName == null || dsName.isEmpty()) {
dsName = ClientUtils.getDefaultDatastore(this.finder);
}
String dataStoreName = dsName;
List<Element> datastoreList = this.finder.datastoreList(dataStoreName);
ManagedObjectReference dsFromSp;
Optional<Element> datastoreOpt = datastoreList.stream().findFirst();
if (datastoreOpt.isPresent()) {
dsFromSp = datastoreOpt.get().object;
} else {
throw new IllegalArgumentException(String.format("No Datastore [%s] present on datacenter", dataStoreName));
}
// 2) Get available hosts for direct upload
String hostName = null;
ArrayOfDatastoreHostMount dsHosts = this.get.entityProp(dsFromSp, VimPath.res_host);
if (dsHosts != null && dsHosts.getDatastoreHostMount() != null) {
DatastoreHostMount dsHost = dsHosts.getDatastoreHostMount().stream().filter(hostMount -> hostMount.getMountInfo() != null && hostMount.getMountInfo().isAccessible() && hostMount.getMountInfo().isMounted()).findFirst().orElse(null);
if (dsHost != null) {
hostName = this.get.entityProp(dsHost.getKey(), VimPath.host_summary_config_name);
}
}
if (hostName == null) {
throw new IllegalStateException(String.format("No host found to upload ISO content " + "for Data Store Disk %s", dataStoreName));
}
// 3) Choose some unique filename
String filename = ClientUtils.getUniqueName(ISO_FILE) + ISO_EXTENSION;
// 4 ) Choose some unique folder name and create it.
String folderName = ClientUtils.getUniqueName(ISO_FOLDER);
ClientUtils.createFolder(this.connection, this.context.datacenterMoRef, String.format(VM_PATH_FORMAT, dataStoreName, folderName));
// 5) form the upload url and acquire generic service ticket for it
String isoUrl = String.format(ISO_UPLOAD_URL, hostName, VimUtils.encode(folderName), VimUtils.encode(filename), VimUtils.encode(dataStoreName));
String ticket = this.connection.getGenericServiceTicket(isoUrl);
// 6) create external client that accepts all certificates
TrustManager[] trustManagers = new TrustManager[] { ClientUtils.getDefaultTrustManager() };
ServiceClient serviceClient = ClientUtils.getCustomServiceClient(trustManagers, this.host, URI.create(isoUrl), this.getClass().getSimpleName());
// 7) PUT operation for the iso content
Operation putISO = Operation.createPut(URI.create(isoUrl));
putISO.setContentType(MEDIA_TYPE_APPLICATION_OCTET_STREAM).setContentLength(contentToUpload.length).addRequestHeader("Cookie", "vmware_cgi_ticket=" + ticket).setBody(contentToUpload).setReferer(this.host.getUri());
return serviceClient.sendWithDeferredResult(putISO).thenApply(op -> {
String diskFullPath = String.format(FULL_PATH, dataStoreName, folderName, filename);
// Update the details of the disk
CustomProperties.of(this.diskState).put(DISK_FULL_PATH, diskFullPath).put(DISK_PARENT_DIRECTORY, String.format(PARENT_DIR, dataStoreName, folderName)).put(DISK_DATASTORE_NAME, dataStoreName);
this.diskState.sourceImageReference = VimUtils.datastorePathToUri(diskFullPath);
return this.diskState;
});
} catch (Exception e) {
return DeferredResult.failed(e);
}
}
Aggregations