use of com.vmware.vim25.mo.ClusterComputeResource in project CloudStack-archive by CloudStack-extras.
the class ClusterMO method getHostPropertiesOnCluster.
private ObjectContent[] getHostPropertiesOnCluster(String[] propertyPaths) throws Exception {
if (s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - retrieveProperties() on Host properties. target MOR: " + _mor.get_value() + ", properties: " + new Gson().toJson(propertyPaths));
PropertySpec pSpec = new PropertySpec();
pSpec.setType("HostSystem");
pSpec.setPathSet(propertyPaths);
TraversalSpec cluster2HostTraversal = new TraversalSpec();
cluster2HostTraversal.setType("ClusterComputeResource");
cluster2HostTraversal.setPath("host");
cluster2HostTraversal.setName("cluster2HostTraversal");
ObjectSpec oSpec = new ObjectSpec();
oSpec.setObj(_mor);
oSpec.setSkip(Boolean.TRUE);
oSpec.setSelectSet(new SelectionSpec[] { cluster2HostTraversal });
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
pfSpec.setPropSet(new PropertySpec[] { pSpec });
pfSpec.setObjectSet(new ObjectSpec[] { oSpec });
ObjectContent[] properties = _context.getService().retrieveProperties(_context.getServiceContent().getPropertyCollector(), new PropertyFilterSpec[] { pfSpec });
if (s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - retrieveProperties() done");
return properties;
}
use of com.vmware.vim25.mo.ClusterComputeResource in project cloudstack by apache.
the class HypervisorHostHelper method prepareNetwork.
public static Pair<ManagedObjectReference, String> prepareNetwork(String vSwitchName, String namePrefix, HostMO hostMo, String vlanId, Integer networkRateMbps, Integer networkRateMulticastMbps, long timeOutMs, boolean syncPeerHosts, BroadcastDomainType broadcastDomainType, String nicUuid) throws Exception {
HostVirtualSwitch vSwitch;
if (vSwitchName == null) {
s_logger.info("Detected vswitch name as undefined. Defaulting to vSwitch0");
vSwitchName = "vSwitch0";
}
vSwitch = hostMo.getHostVirtualSwitchByName(vSwitchName);
if (vSwitch == null) {
String msg = "Unable to find vSwitch" + vSwitchName;
s_logger.error(msg);
throw new Exception(msg);
}
boolean createGCTag = false;
String networkName;
Integer vid = null;
/** This is the list of BroadcastDomainTypes we can actually
* prepare networks for in this function.
*/
BroadcastDomainType[] supportedBroadcastTypes = new BroadcastDomainType[] { BroadcastDomainType.Lswitch, BroadcastDomainType.LinkLocal, BroadcastDomainType.Native, BroadcastDomainType.Pvlan, BroadcastDomainType.Storage, BroadcastDomainType.UnDecided, BroadcastDomainType.Vlan, BroadcastDomainType.Vsp };
if (!Arrays.asList(supportedBroadcastTypes).contains(broadcastDomainType)) {
throw new InvalidParameterException("BroadcastDomainType " + broadcastDomainType + " it not supported on a VMWare hypervisor at this time.");
}
if (broadcastDomainType == BroadcastDomainType.Lswitch) {
/**
* Nicira NVP requires each vm to have its own port-group with a dedicated
* vlan. We'll set the name of the pg to the uuid of the nic.
*/
networkName = nicUuid;
// No doubt about this, depending on vid=null to avoid lots of code below
vid = null;
} else {
networkName = composeCloudNetworkName(namePrefix, vlanId, null, networkRateMbps, vSwitchName);
if (vlanId != null && !UNTAGGED_VLAN_NAME.equalsIgnoreCase(vlanId)) {
createGCTag = true;
vid = Integer.parseInt(vlanId);
}
}
HostNetworkSecurityPolicy secPolicy = null;
if (namePrefix.equalsIgnoreCase("cloud.private")) {
secPolicy = new HostNetworkSecurityPolicy();
secPolicy.setAllowPromiscuous(Boolean.TRUE);
secPolicy.setForgedTransmits(Boolean.TRUE);
secPolicy.setMacChanges(Boolean.TRUE);
}
HostNetworkTrafficShapingPolicy shapingPolicy = null;
if (networkRateMbps != null && networkRateMbps.intValue() > 0) {
shapingPolicy = new HostNetworkTrafficShapingPolicy();
shapingPolicy.setEnabled(true);
shapingPolicy.setAverageBandwidth(networkRateMbps.intValue() * 1024L * 1024L);
//
// TODO : people may have different opinion on how to set the following
//
// give 50% premium to peek
shapingPolicy.setPeakBandwidth((long) (shapingPolicy.getAverageBandwidth() * 1.5));
// allow 5 seconds of burst transfer
shapingPolicy.setBurstSize(5 * shapingPolicy.getAverageBandwidth() / 8);
}
boolean bWaitPortGroupReady = false;
if (broadcastDomainType == BroadcastDomainType.Lswitch) {
//if NSX API VERSION >= 4.2, connect to br-int (nsx.network), do not create portgroup else previous behaviour
if (NiciraNvpApiVersion.isApiVersionLowerThan("4.2")) {
//Previous behaviour
if (!hostMo.hasPortGroup(vSwitch, networkName)) {
createNvpPortGroup(hostMo, vSwitch, networkName, shapingPolicy);
bWaitPortGroupReady = true;
} else {
bWaitPortGroupReady = false;
}
}
} else {
if (!hostMo.hasPortGroup(vSwitch, networkName)) {
hostMo.createPortGroup(vSwitch, networkName, vid, secPolicy, shapingPolicy, timeOutMs);
// Setting flag "bWaitPortGroupReady" to false.
// This flag indicates whether we need to wait for portgroup on vCenter.
// Above createPortGroup() method itself ensures creation of portgroup as well as wait for portgroup.
bWaitPortGroupReady = false;
} else {
HostPortGroupSpec spec = hostMo.getPortGroupSpec(networkName);
if (!isSpecMatch(spec, vid, shapingPolicy)) {
hostMo.updatePortGroup(vSwitch, networkName, vid, secPolicy, shapingPolicy);
bWaitPortGroupReady = true;
}
}
}
ManagedObjectReference morNetwork = null;
if (broadcastDomainType != BroadcastDomainType.Lswitch || (broadcastDomainType == BroadcastDomainType.Lswitch && NiciraNvpApiVersion.isApiVersionLowerThan("4.2"))) {
if (bWaitPortGroupReady)
morNetwork = waitForNetworkReady(hostMo, networkName, timeOutMs);
else
morNetwork = hostMo.getNetworkMor(networkName);
if (morNetwork == null) {
String msg = "Failed to create guest network " + networkName;
s_logger.error(msg);
throw new Exception(msg);
}
if (createGCTag) {
NetworkMO networkMo = new NetworkMO(hostMo.getContext(), morNetwork);
networkMo.setCustomFieldValue(CustomFieldConstants.CLOUD_GC, "true");
}
}
if (syncPeerHosts) {
ManagedObjectReference morParent = hostMo.getParentMor();
if (morParent != null && morParent.getType().equals("ClusterComputeResource")) {
// to be conservative, lock cluster
GlobalLock lock = GlobalLock.getInternLock("ClusterLock." + morParent.getValue());
try {
if (lock.lock(DEFAULT_LOCK_TIMEOUT_SECONDS)) {
try {
List<ManagedObjectReference> hosts = hostMo.getContext().getVimClient().getDynamicProperty(morParent, "host");
if (hosts != null) {
for (ManagedObjectReference otherHost : hosts) {
if (!otherHost.getValue().equals(hostMo.getMor().getValue())) {
HostMO otherHostMo = new HostMO(hostMo.getContext(), otherHost);
try {
if (s_logger.isDebugEnabled())
s_logger.debug("Prepare network on other host, vlan: " + vlanId + ", host: " + otherHostMo.getHostName());
prepareNetwork(vSwitchName, namePrefix, otherHostMo, vlanId, networkRateMbps, networkRateMulticastMbps, timeOutMs, false, broadcastDomainType, nicUuid);
} catch (Exception e) {
s_logger.warn("Unable to prepare network on other host, vlan: " + vlanId + ", host: " + otherHostMo.getHostName());
}
}
}
}
} finally {
lock.unlock();
}
} else {
s_logger.warn("Unable to lock cluster to prepare guest network, vlan: " + vlanId);
}
} finally {
lock.releaseRef();
}
}
}
s_logger.info("Network " + networkName + " is ready on vSwitch " + vSwitchName);
return new Pair<ManagedObjectReference, String>(morNetwork, networkName);
}
use of com.vmware.vim25.mo.ClusterComputeResource in project coprhd-controller by CoprHD.
the class VcenterApiClient method removeHost.
public void removeHost(String datacenterName, String clusterNameOrMoRef, String hostname) throws VcenterSystemException, VcenterObjectNotFoundException, VcenterObjectConnectionException {
try {
_log.info("Request to remove host " + hostname + " to datacenter " + datacenterName + " cluster " + clusterNameOrMoRef);
ClusterComputeResource clusterComputeResource = (ClusterComputeResource) createManagedEntityMap(datacenterName, clusterNameOrMoRef, null, false).get("ClusterComputeResource");
HostSystem hostSystem = findByHostname(clusterComputeResource, hostname);
if (hostSystem == null) {
_log.info("Host not found thus no delete necessary");
} else {
// Check that host can be removed (either in maintenance mode or in a !poweredOn or !connected state
try {
checkHostConnectedPoweredOn(hostSystem);
_log.info("Host " + hostname + " connected and powered on so now check maintenance mode");
if (!hostSystem.getRuntime().isInMaintenanceMode()) {
_log.error("Host " + hostname + " must be in maintenance mode before deletion");
throw new VcenterSystemException("Host " + hostname + " must be in maintenance mode before deletion");
}
} catch (VcenterObjectConnectionException e) {
_log.info("Host is not connected and/or powered on so go ahead and remove without maintenance mode check");
}
// Remove
Integer hostOperationTimeout = Integer.parseInt(propertyInfo.getProperty("vcenter_host_operation_timeout"));
VcenterTaskMonitor taskMonitor = new VcenterTaskMonitor(hostOperationTimeout);
Task deleteHostTask = hostSystem.destroy_Task();
// call blocks
VcenterTaskMonitor.TaskStatus taskStatus = taskMonitor.monitor(deleteHostTask);
if (taskStatus == VcenterTaskMonitor.TaskStatus.SUCCESS) {
_log.info("Delete host " + hostname + " task succeeded");
} else if (taskStatus == VcenterTaskMonitor.TaskStatus.ERROR) {
String errorMessage = "Delete host " + hostname + " task failed - " + taskMonitor.errorDescription;
_log.error(errorMessage);
throw new VcenterSystemException(errorMessage);
} else if (taskStatus == VcenterTaskMonitor.TaskStatus.TIMED_OUT) {
_log.error("Delete host " + hostname + " task timed out at " + taskMonitor.progressPercent);
throw new VcenterSystemException("Delete host " + hostname + " task timed out at " + taskMonitor.progressPercent);
} else {
// Should not execute - Just here in case someone ever added a new state so we catch it
_log.error("Unknown task status encountered tracking delete host " + taskStatus);
throw new VcenterSystemException("Unknown task status encountered tracking delete host " + taskStatus);
}
}
} catch (VcenterSystemException | VcenterObjectNotFoundException | VcenterObjectConnectionException e) {
throw e;
} catch (Exception e) {
_log.error("Exception removing host: " + e);
throw new VcenterSystemException(e.getLocalizedMessage());
}
}
use of com.vmware.vim25.mo.ClusterComputeResource in project coprhd-controller by CoprHD.
the class VcenterApiClient method addHost.
public String addHost(String datacenterName, String clusterNameOrMoRef, String hostname, String username, String password) throws VcenterSystemException, VcenterObjectNotFoundException, VcenterObjectConnectionException {
try {
_log.info("Request to add host " + hostname + " to datacenter " + datacenterName + " cluster " + clusterNameOrMoRef);
ClusterComputeResource clusterComputeResource = (ClusterComputeResource) createManagedEntityMap(datacenterName, clusterNameOrMoRef, null, false).get("ClusterComputeResource");
HostSystem hostSystem = findByHostname(clusterComputeResource, hostname);
if (hostSystem == null) {
_log.info("Host " + hostname + " does not exist and will be added");
if (username == null || username.trim().equals("") || password == null || password.trim().equals("")) {
_log.error("Username and/or password missing - Both required to add host to cluster");
throw new VcenterSystemException("Username and/or password missing - Both required to add host to cluster");
}
HostConnectSpec hostConnectSpec = new HostConnectSpec();
hostConnectSpec.setHostName(hostname);
hostConnectSpec.setUserName(username);
hostConnectSpec.setPassword(password);
// ie
hostConnectSpec.setSslThumbprint(getHostCertificate(hostname, username, password));
// 1D:0C:63:FC:58:58:1C:66:F0:5B:C4:0B:F3:84:0E:27:E9:59:83:F7
_log.info("Attempt to add host " + hostname + " to " + datacenterName + "/" + clusterComputeResource.getName());
Integer hostOperationTimeout = Integer.parseInt(propertyInfo.getProperty("vcenter_host_operation_timeout"));
Integer hostOperationTimeoutMillis = hostOperationTimeout * 1000;
Integer retryCount = 1;
Long startTimeMillis = System.currentTimeMillis();
Long cutoffTimeMillis = startTimeMillis + hostOperationTimeoutMillis;
VcenterTaskMonitor taskMonitor = new VcenterTaskMonitor(hostOperationTimeout);
Task addHostTask = clusterComputeResource.addHost_Task(hostConnectSpec, true, null, null);
// call blocks
VcenterTaskMonitor.TaskStatus taskStatus = taskMonitor.monitor(addHostTask);
while ((System.currentTimeMillis() < cutoffTimeMillis) && taskStatus == VcenterTaskMonitor.TaskStatus.ERROR) {
_log.info("Add host " + hostname + " retry error " + taskMonitor.errorDescription + " count " + retryCount);
// Retry is time based and if each retry executes very quickly (ie milliseconds) then we should
Thread.sleep(60000);
// throttle and only retry every 60 seconds
addHostTask = clusterComputeResource.addHost_Task(hostConnectSpec, true, null, null);
// call blocks
taskStatus = taskMonitor.monitor(addHostTask);
retryCount++;
}
if (taskStatus == VcenterTaskMonitor.TaskStatus.SUCCESS) {
_log.info("Add host " + hostname + " task succeeded - Attempt to find host in cluster");
hostSystem = findByHostname(clusterComputeResource, hostname);
} else if (taskStatus == VcenterTaskMonitor.TaskStatus.ERROR) {
String errorMessage = "Add host " + hostname + " task failed - " + taskMonitor.errorDescription;
if (taskMonitor.errorDescription.contains("already exists.")) {
errorMessage += " - Ensure adding host to correct cluster or remove host from its existing cluster";
}
_log.error(errorMessage);
throw new VcenterSystemException(errorMessage);
} else if (taskStatus == VcenterTaskMonitor.TaskStatus.TIMED_OUT) {
_log.error("Add host " + hostname + " task timed out at " + taskMonitor.progressPercent);
throw new VcenterSystemException("Add host " + hostname + " task timed out at " + taskMonitor.progressPercent);
} else {
// Should not execute - Just here in case someone ever added a new state so we catch it
_log.error("Unknown task status encountered tracking add host " + taskStatus);
throw new VcenterSystemException("Unknown task status encountered tracking add host " + taskStatus);
}
trackHostTasks(hostSystem, hostOperationTimeout);
// Only take host out of maintenance mode if it's being added. We don't want to exit maintenance mode on other hosts since
// customer may have intentionally put it on that.
exitMaintenanceModeHost(hostSystem);
}
// Some nice conveniences to reconnect and exit maintenance mode to ready the host for action
reconnectHost(hostSystem);
// Collect some details
StringBuffer hostDetails = new StringBuffer();
hostDetails.append("Host ").append(datacenterName).append("/").append(clusterComputeResource.getName()).append("/").append(hostname).append(" ");
String os = hostSystem.getPropertyByPath("config.product.version").toString();
hostDetails.append("OS ").append(os).append(" ");
String key = hostSystem.getMOR().getVal();
hostDetails.append("key ").append(key).append(" ");
String connectionState = hostSystem.getRuntime().getConnectionState().toString();
hostDetails.append("Connection State ").append(connectionState).append(" ");
String powerState = hostSystem.getRuntime().getPowerState().toString();
hostDetails.append("Power State ").append(powerState).append(" ");
boolean maintenanceMode = hostSystem.getRuntime().isInMaintenanceMode();
hostDetails.append("Maintenance Mode ").append(maintenanceMode).append(" ");
_log.info(hostDetails.toString());
return hostSystem.getMOR().getVal();
} catch (VcenterSystemException | VcenterObjectNotFoundException | VcenterObjectConnectionException e) {
throw e;
} catch (Exception e) {
_log.error("Exception adding host: " + e);
throw new VcenterSystemException(e.getLocalizedMessage());
}
}
use of com.vmware.vim25.mo.ClusterComputeResource in project photon-model by vmware.
the class Lister method listFolder.
private List<Element> listFolder() throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, FinderException {
PropertyFilterSpec spec = new PropertyFilterSpec();
ObjectSpec objSpec = new ObjectSpec();
objSpec.setObj(this.start);
TraversalSpec selectionSpec = new TraversalSpec();
selectionSpec.setPath("childEntity");
selectionSpec.setType("Folder");
selectionSpec.setSkip(false);
objSpec.getSelectSet().add(selectionSpec);
spec.getObjectSet().add(objSpec);
// Retrieve all objects that we can deal with
String[] childTypes = { "Folder", "Datacenter", "VirtualMachine", "Network", "ComputeResource", "ClusterComputeResource", "Datastore" };
for (String t : childTypes) {
PropertySpec pspec = new PropertySpec();
pspec.setType(t);
pspec.getPathSet().add("name");
// Additional basic properties.
if (t.equals("ComputeResource") || t.equals("ClusterComputeResource")) {
// The ComputeResource and ClusterComputeResource are dereferenced in
// the ResourcePoolFlag. Make sure they always have their resourcePool
// field populated.
pspec.getPathSet().add("resourcePool");
}
spec.getPropSet().add(pspec);
}
return callPropertyCollectorAndConvert(spec);
}
Aggregations