use of com.vmware.vim25.mo.Datacenter 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.vim25.mo.Datacenter 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);
}
}
use of com.vmware.vim25.mo.Datacenter in project coprhd-controller by CoprHD.
the class HostRescanDeviceController method getRescanAdapter.
private HostRescanAdapter getRescanAdapter(Host host) {
if (HostType.Linux.name().equalsIgnoreCase(host.getType())) {
return new LinuxSystemCLI(host.getHostName(), host.getPortNumber(), host.getUsername(), host.getPassword());
} else if (HostType.AIX.name().equalsIgnoreCase(host.getType())) {
return new AixSystem(host.getHostName(), host.getPortNumber(), host.getUsername(), host.getPassword());
} else if (HostType.HPUX.name().equalsIgnoreCase(host.getType())) {
return new HpuxSystem(host.getHostName(), host.getPortNumber(), host.getUsername(), host.getPassword());
} else if (HostType.Windows.name().equalsIgnoreCase(host.getType())) {
List<AuthnProvider> authProviders = new ArrayList<AuthnProvider>();
for (URI authProviderId : getDbClient().queryByType(AuthnProvider.class, true)) {
AuthnProvider authProvider = getDbClient().queryObject(AuthnProvider.class, authProviderId);
authProviders.add(authProvider);
}
KerberosUtil.initializeKerberos(authProviders);
return WindowsHostDiscoveryAdapter.createWindowsSystem(host);
} else if (HostType.Esx.name().equalsIgnoreCase(host.getType())) {
if (host.getUsername() != null && host.getPassword() != null) {
VCenterAPI vcenterAPI = EsxHostDiscoveryAdapter.createVCenterAPI(host);
List<HostSystem> hostSystems = vcenterAPI.listAllHostSystems();
if (hostSystems != null && !hostSystems.isEmpty()) {
return new HostStorageAPI(hostSystems.get(0));
} else {
return null;
}
} else if (host.getVcenterDataCenter() != null) {
// Lookup the vcenter datacenter and vcenter to retreive the HostSystem
VcenterDataCenter dataCenter = dbClient.queryObject(VcenterDataCenter.class, host.getVcenterDataCenter());
if (dataCenter == null || dataCenter.getInactive()) {
throw DeviceControllerException.exceptions.objectNotFound(host.getVcenterDataCenter());
}
Vcenter vcenter = dbClient.queryObject(Vcenter.class, dataCenter.getVcenter());
if (vcenter == null || vcenter.getInactive()) {
throw DeviceControllerException.exceptions.objectNotFound(dataCenter.getVcenter());
}
VCenterAPI vCenterAPI = VcenterDiscoveryAdapter.createVCenterAPI(vcenter);
String datacenterName = dataCenter.getLabel();
HostSystem hostSystem = vCenterAPI.findHostSystem(datacenterName, host.getHostName());
if (hostSystem != null) {
return new HostStorageAPI(hostSystem);
} else {
return null;
}
}
} else {
// Unanticipated host type
return null;
}
return null;
}
use of com.vmware.vim25.mo.Datacenter in project coprhd-controller by CoprHD.
the class ComputeSystemControllerImpl method unmountAndDetach.
/**
* Unmounts and detaches every datastore and disk associated with the volumes in the export group.
* For each volume in the export group, the backed datastore is unmounted and the associated disk is detached from
* the host.
*
* @param exportGroupId
* export group that contains volumes
* @param hostId
* host to attach and mount to
* @param vcenterId
* vcenter that the host belongs to
* @param vcenterDatacenter
* vcenter datacenter that the host belongs to
* @param stepId
* the id of the workflow step
*/
public void unmountAndDetach(URI exportGroupId, URI hostId, URI vCenterId, URI vcenterDatacenter, String stepId) {
WorkflowStepCompleter.stepExecuting(stepId);
try {
Host esxHost = _dbClient.queryObject(Host.class, hostId);
Vcenter vCenter = _dbClient.queryObject(Vcenter.class, vCenterId);
VcenterDataCenter vCenterDataCenter = _dbClient.queryObject(VcenterDataCenter.class, vcenterDatacenter);
ExportGroup exportGroup = _dbClient.queryObject(ExportGroup.class, exportGroupId);
VCenterAPI api = VcenterDiscoveryAdapter.createVCenterAPI(vCenter);
HostSystem hostSystem = api.findHostSystem(vCenterDataCenter.getLabel(), esxHost.getLabel());
if (hostSystem == null) {
_log.info("Not able to find host " + esxHost.getLabel() + " in vCenter. Unable to validate");
WorkflowStepCompleter.stepSucceded(stepId);
return;
}
HostStorageAPI storageAPI = new HostStorageAPI(hostSystem);
Map<String, Datastore> wwnDatastores = getWwnDatastoreMap(hostSystem);
if (exportGroup != null && exportGroup.getVolumes() != null) {
for (String volume : exportGroup.getVolumes().keySet()) {
BlockObject blockObject = BlockObject.fetch(_dbClient, URI.create(volume));
if (blockObject != null) {
Datastore datastore = getDatastoreByWwn(wwnDatastores, blockObject.getWWN());
if (datastore != null) {
if (VMwareUtils.isDatastoreMountedOnHost(datastore, hostSystem)) {
boolean storageIOControlEnabled = datastore.getIormConfiguration().isEnabled();
if (storageIOControlEnabled) {
setStorageIOControl(api, datastore, false);
}
_log.info("Unmount datastore " + datastore.getName() + " from host " + esxHost.getLabel());
storageAPI.unmountVmfsDatastore(datastore);
if (storageIOControlEnabled) {
setStorageIOControl(api, datastore, true);
}
} else {
_log.info("Datastore " + datastore.getName() + " is not mounted on host " + esxHost.getLabel() + ". Skipping unmounting of datastore.");
}
}
}
// VBDU TODO: COP-28459, If datastore doesn't match, why do we need to run DetachSCSILun() ?
// Test mechanism to invoke a failure. No-op on production systems.
InvokeTestFailure.internalOnlyInvokeTestFailure(InvokeTestFailure.ARTIFICIAL_FAILURE_030);
for (HostScsiDisk entry : storageAPI.listScsiDisks()) {
if (VolumeWWNUtils.wwnMatches(VMwareUtils.getDiskWwn(entry), blockObject.getWWN())) {
if (!VMwareUtils.isDiskOff(entry)) {
_log.info("Detach SCSI Lun " + entry.getCanonicalName() + " from host " + esxHost.getLabel());
storageAPI.detachScsiLun(entry);
} else {
_log.info("SCSI Lun " + entry.getCanonicalName() + " is not in a valid state to detach");
}
}
}
storageAPI.refreshStorage();
// Test mechanism to invoke a failure. No-op on production systems.
InvokeTestFailure.internalOnlyInvokeTestFailure(InvokeTestFailure.ARTIFICIAL_FAILURE_031);
}
}
WorkflowStepCompleter.stepSucceded(stepId);
} catch (Exception ex) {
_log.error(ex.getMessage(), ex);
WorkflowStepCompleter.stepFailed(stepId, DeviceControllerException.errors.jobFailed(ex));
}
}
use of com.vmware.vim25.mo.Datacenter in project coprhd-controller by CoprHD.
the class ComputeUtils method verifyHostInVcenterCluster.
/**
* Validate that the hosts are in their respective cluster. Typically used before
* performing destructive operations, such as decommissioning a host or cluster.
*
* @param hostIds host IDs
* @return false if any host still exists in the vCenter, but is NOT in the cluster assigned to the host in our DB.
*/
public static boolean verifyHostInVcenterCluster(Cluster cluster, List<URI> hostIds) {
// If the cluster isn't returned properly, then something went wrong. We must fail validation.
if (cluster == null || cluster.getInactive()) {
ExecutionUtils.currentContext().logError("The cluster is not active in ViPR DB, therefore we can not proceed with validation.");
return false;
}
// So log it and return.
if (NullColumnValueGetter.isNullURI(cluster.getVcenterDataCenter())) {
ExecutionUtils.currentContext().logInfo("computeutils.decommission.validation.skipped.noVcenterDataCenter", cluster.forDisplay());
return true;
}
VcenterDataCenter dataCenter = execute(new GetVcenterDataCenter(cluster.getVcenterDataCenter()));
// until that's fixed.
if (dataCenter == null || dataCenter.getInactive() || NullColumnValueGetter.isNullURI(dataCenter.getVcenter())) {
ExecutionUtils.currentContext().logError("computeutils.decommission.failure.datacenter", cluster.forDisplay());
return false;
}
Vcenter vcenter = execute(new GetVcenter(dataCenter.getVcenter()));
// until that's fixed.
if (vcenter == null || vcenter.getInactive()) {
ExecutionUtils.currentContext().logError("computeutils.decommission.failure.vcenter", cluster.forDisplay());
return false;
}
VMwareSupport vmware = null;
try {
vmware = new VMwareSupport();
vmware.connect(vcenter.getId());
for (URI hostId : hostIds) {
Host host = BlockStorageUtils.getHost(hostId);
// Do not validate a host no longer in our database
if (host == null || host.getInactive()) {
ExecutionUtils.currentContext().logError("computeutils.decommission.failure.host", "N/A", "host not found or inactive");
return false;
}
// in the vCenter cluster, and therefore we can not perform a deep validation.
if (NullColumnValueGetter.isNullURI(host.getVcenterDataCenter())) {
ExecutionUtils.currentContext().logInfo("computeutils.decommission.validation.skipped.vcenternotinhost", host.getHostName());
continue;
}
// any update to the host using the hostService automatically adds this association.
if (!NullColumnValueGetter.isNullURI(host.getVcenterDataCenter()) && host.getType() != null && host.getType().equalsIgnoreCase((Host.HostType.No_OS).name())) {
ExecutionUtils.currentContext().logInfo("computeutils.decommission.validation.skipped.noOShost", host.getHostName());
continue;
}
HostSystem hostSystem = null;
VCenterAPI api = null;
try {
hostSystem = vmware.getHostSystem(dataCenter.getLabel(), host.getHostName(), false);
// we'll need to hunt it down elsewhere.
if (hostSystem == null) {
// Now look for the host system in other datacenters and clusters. If you find it, return false.
// If you do not find it, return true because it couldn't be found.
api = VcenterDiscoveryAdapter.createVCenterAPI(vcenter);
List<HostSystem> hostSystems = api.listAllHostSystems();
if (hostSystems == null || hostSystems.isEmpty()) {
// No host systems were found. We'll assume this is a lie and report a validation failure.
// But the error can be clear that we can not decommission if we're getting empty responses
// from the vSphere API.
ExecutionUtils.currentContext().logError("computeutils.decommission.failure.host.nohostsatall", host.getHostName());
return false;
}
for (HostSystem foundHostSystem : hostSystems) {
if (foundHostSystem != null && (foundHostSystem.getName().equalsIgnoreCase(host.getLabel()) || (foundHostSystem.getHardware() != null && foundHostSystem.getHardware().systemInfo != null && foundHostSystem.getHardware().systemInfo.uuid != null && foundHostSystem.getHardware().systemInfo.uuid.equalsIgnoreCase(host.getUuid())))) {
// We found a match someplace else in the vcenter. Post an error and return false.
ExecutionUtils.currentContext().logError("computeutils.decommission.failure.host.moved", host.getHostName());
return false;
}
}
// If we get to here, we can't find the host in this vCenter at all and we are going to fail. We don't want to
// delete this host from a vCenter outside of our control.
ExecutionUtils.currentContext().logInfo("computeutils.decommission.failure.host.notinvcenter", host.getHostName());
return false;
} else {
// Make sure the UUID of the host matches what we have in our database.
if (hostSystem.getHardware() != null && hostSystem.getHardware().systemInfo != null && hostSystem.getHardware().systemInfo.uuid != null && !hostSystem.getHardware().systemInfo.uuid.equalsIgnoreCase(host.getUuid())) {
// The host UUID doesn't match what we have in our database. The host may have been renamed.
ExecutionUtils.currentContext().logError("computeutils.decommission.failure.host.uuidmismatch", host.getHostName());
return false;
}
// We found the host, so now we check that the host belongs to the correct cluster
if (hostSystem.getParent() != null && hostSystem.getParent() instanceof ClusterComputeResource) {
ClusterComputeResource clusterResource = (ClusterComputeResource) hostSystem.getParent();
if (clusterResource != null && clusterResource.getMOR() != null && clusterResource.getMOR().getVal() != null && !clusterResource.getMOR().getVal().equalsIgnoreCase(cluster.getExternalId())) {
// Host is in a different cluster, fail the validation
ExecutionUtils.currentContext().logError("computeutils.decommission.failure.host.moved", host.getHostName());
return false;
}
} else {
// We found the host but it doesn't belong to a cluster, fail the validation
ExecutionUtils.currentContext().logError("computeutils.decommission.failure.host.notincluster", host.getHostName());
return false;
}
}
} finally {
if (api != null) {
api.logout();
}
}
}
} finally {
if (vmware != null) {
vmware.disconnect();
}
}
return true;
}
Aggregations