Add the option to filter by host when retrieving of unregistered VMs (#9925)

Co-authored-by: Nicolas Vazquez <nicovazquez90@gmail.com>
This commit is contained in:
dahn 2025-02-10 17:06:39 +01:00 committed by GitHub
parent 4f604c00b6
commit aa6c581e40
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
27 changed files with 921 additions and 819 deletions

View File

@ -46,6 +46,7 @@ public class ApiConstants {
public static final String BACKUP_OFFERING_NAME = "backupofferingname";
public static final String BACKUP_OFFERING_ID = "backupofferingid";
public static final String BASE64_IMAGE = "base64image";
public static final String BATCH_SIZE = "batchsize";
public static final String BITS = "bits";
public static final String BOOTABLE = "bootable";
public static final String BIND_DN = "binddn";
@ -437,11 +438,12 @@ public class ApiConstants {
public static final String STATE = "state";
public static final String STATS = "stats";
public static final String STATUS = "status";
public static final String STORAGE_TYPE = "storagetype";
public static final String STORAGE_POLICY = "storagepolicy";
public static final String STORAGE_MOTION_ENABLED = "storagemotionenabled";
public static final String STORAGE_CAPABILITIES = "storagecapabilities";
public static final String STORAGE_CUSTOM_STATS = "storagecustomstats";
public static final String STORAGE_MOTION_ENABLED = "storagemotionenabled";
public static final String STORAGE_POLICY = "storagepolicy";
public static final String STORAGE_POOL = "storagepool";
public static final String STORAGE_TYPE = "storagetype";
public static final String SUBNET = "subnet";
public static final String OWNER = "owner";
public static final String SWAP_OWNER = "swapowner";
@ -1106,6 +1108,7 @@ public class ApiConstants {
public static final String PARAMETER_DESCRIPTION_IS_TAG_A_RULE = "Whether the informed tag is a JS interpretable rule or not.";
public static final String NFS_MOUNT_OPTIONS = "nfsmountopts";
public static final String VMWARE_DC = "vmwaredc";
/**
* This enum specifies IO Drivers, each option controls specific policies on I/O.

View File

@ -152,7 +152,7 @@ public class HostResponse extends BaseResponseWithAnnotations {
@Deprecated
@SerializedName("memoryallocated")
@Param(description = "the amount of the host's memory currently allocated")
private long memoryAllocated;
private Long memoryAllocated;
@SerializedName("memoryallocatedpercentage")
@Param(description = "the amount of the host's memory currently allocated in percentage")
@ -395,7 +395,7 @@ public class HostResponse extends BaseResponseWithAnnotations {
this.memWithOverprovisioning=memWithOverprovisioning;
}
public void setMemoryAllocated(long memoryAllocated) {
public void setMemoryAllocated(Long memoryAllocated) {
this.memoryAllocated = memoryAllocated;
}
@ -659,8 +659,8 @@ public class HostResponse extends BaseResponseWithAnnotations {
return memoryTotal;
}
public long getMemoryAllocated() {
return memoryAllocated;
public Long getMemoryAllocated() {
return memoryAllocated == null ? 0 : memoryAllocated;
}
public void setMemoryAllocatedPercentage(String memoryAllocatedPercentage) {

View File

@ -47,14 +47,14 @@ public class DynamicRoleBasedAPIAccessChecker extends AdapterBase implements API
private RoleService roleService;
private List<PluggableService> services;
private Map<RoleType, Set<String>> annotationRoleBasedApisMap = new HashMap<RoleType, Set<String>>();
private Map<RoleType, Set<String>> annotationRoleBasedApisMap = new HashMap<>();
private static final Logger LOGGER = Logger.getLogger(DynamicRoleBasedAPIAccessChecker.class.getName());
protected DynamicRoleBasedAPIAccessChecker() {
super();
for (RoleType roleType : RoleType.values()) {
annotationRoleBasedApisMap.put(roleType, new HashSet<String>());
annotationRoleBasedApisMap.put(roleType, new HashSet<>());
}
}

View File

@ -22,12 +22,15 @@ import com.cloud.dc.VmwareDatacenterVO;
import com.cloud.dc.VsphereStoragePolicy;
import com.cloud.exception.DiscoveryException;
import com.cloud.exception.ResourceInUseException;
import com.cloud.hypervisor.vmware.mo.HostMO;
import com.cloud.storage.StoragePool;
import com.cloud.utils.Pair;
import com.cloud.utils.component.PluggableService;
import com.cloud.utils.exception.CloudRuntimeException;
import org.apache.cloudstack.api.command.admin.zone.AddVmwareDcCmd;
import org.apache.cloudstack.api.command.admin.zone.ImportVsphereStoragePoliciesCmd;
import org.apache.cloudstack.api.command.admin.zone.ListVmwareDcVmsCmd;
import org.apache.cloudstack.api.command.admin.zone.ListVmwareDcHostsCmd;
import org.apache.cloudstack.api.command.admin.zone.ListVmwareDcsCmd;
import org.apache.cloudstack.api.command.admin.zone.ListVsphereStoragePoliciesCmd;
import org.apache.cloudstack.api.command.admin.zone.ListVsphereStoragePolicyCompatiblePoolsCmd;
@ -53,5 +56,7 @@ public interface VmwareDatacenterService extends PluggableService {
List<StoragePool> listVsphereStoragePolicyCompatibleStoragePools(ListVsphereStoragePolicyCompatiblePoolsCmd cmd);
List<UnmanagedInstanceTO> listVMsInDatacenter(ListVmwareDcVmsCmd cmd);
List<HostMO> listHostsInDatacenter(ListVmwareDcHostsCmd cmd);
Pair<String, List<UnmanagedInstanceTO>> listVMsInDatacenter(ListVmwareDcVmsCmd cmd);
}

View File

@ -19,10 +19,12 @@ package com.cloud.hypervisor.vmware.manager;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.rmi.RemoteException;
import java.time.Duration;
import java.time.Instant;
@ -43,10 +45,11 @@ import javax.inject.Inject;
import javax.naming.ConfigurationException;
import javax.persistence.EntityExistsException;
import com.cloud.hypervisor.vmware.util.VmwareClient;
import org.apache.cloudstack.api.command.admin.zone.AddVmwareDcCmd;
import org.apache.cloudstack.api.command.admin.zone.ImportVsphereStoragePoliciesCmd;
import org.apache.cloudstack.api.command.admin.zone.ListVmwareDcVmsCmd;
import org.apache.cloudstack.api.command.admin.zone.ListVmwareDcHostsCmd;
import org.apache.cloudstack.api.command.admin.zone.ListVmwareDcItems;
import org.apache.cloudstack.api.command.admin.zone.ListVmwareDcsCmd;
import org.apache.cloudstack.api.command.admin.zone.ListVsphereStoragePoliciesCmd;
import org.apache.cloudstack.api.command.admin.zone.ListVsphereStoragePolicyCompatiblePoolsCmd;
@ -87,6 +90,7 @@ import com.cloud.dc.ClusterDetailsDao;
import com.cloud.dc.ClusterVO;
import com.cloud.dc.ClusterVSMMapVO;
import com.cloud.dc.DataCenterVO;
import com.cloud.dc.VmwareDatacenter;
import com.cloud.dc.VsphereStoragePolicy;
import com.cloud.dc.VsphereStoragePolicyVO;
import com.cloud.dc.dao.ClusterDao;
@ -112,7 +116,8 @@ import com.cloud.hypervisor.HypervisorGuruManager;
import com.cloud.hypervisor.dao.HypervisorCapabilitiesDao;
import com.cloud.hypervisor.vmware.LegacyZoneVO;
import com.cloud.hypervisor.vmware.VmwareCleanupMaid;
import com.cloud.dc.VmwareDatacenter;
import com.cloud.hypervisor.vmware.util.VmwareClient;
import com.cloud.hypervisor.vmware.util.VmwareClientException;
import com.cloud.hypervisor.vmware.VmwareDatacenterService;
import com.cloud.dc.VmwareDatacenterVO;
import com.cloud.hypervisor.vmware.VmwareDatacenterZoneMap;
@ -165,13 +170,18 @@ import com.cloud.utils.db.TransactionCallbackNoReturn;
import com.cloud.utils.db.TransactionStatus;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.script.Script;
import com.cloud.utils.ssh.SshHelper;
import com.cloud.vm.DomainRouterVO;
import com.cloud.vm.dao.UserVmCloneSettingDao;
import com.cloud.vm.dao.VMInstanceDao;
// TODO move these items upstream?
import com.vmware.pbm.PbmProfile;
import com.vmware.vim25.AboutInfo;
import com.vmware.vim25.ManagedObjectReference;
import com.vmware.vim25.InvalidLocaleFaultMsg;
import com.vmware.vim25.InvalidLoginFaultMsg;
import com.vmware.vim25.RuntimeFaultFaultMsg;
import com.vmware.vim25.InvalidPropertyFaultMsg;
import org.jetbrains.annotations.NotNull;
public class VmwareManagerImpl extends ManagerBase implements VmwareManager, VmwareStorageMount, Listener, VmwareDatacenterService, Configurable {
private static final Logger s_logger = Logger.getLogger(VmwareManagerImpl.class);
@ -247,11 +257,11 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
private StorageLayer _storage;
private final String _privateNetworkVSwitchName = "vSwitch0";
private int _portsPerDvPortGroup = DEFAULT_PORTS_PER_DV_PORT_GROUP;
private final int _portsPerDvPortGroup = DEFAULT_PORTS_PER_DV_PORT_GROUP;
private boolean _fullCloneFlag;
private boolean _instanceNameFlag;
private String _serviceConsoleName;
private String _managemetPortGroupName;
private String _managementPortGroupName;
private String _defaultSystemVmNicAdapterType = VirtualEthernetCardType.E1000.toString();
private String _recycleHungWorker = "false";
private int _additionalPortRangeStart;
@ -265,7 +275,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
private final Random _rand = new Random(System.currentTimeMillis());
private static ScheduledExecutorService templateCleanupScheduler = Executors.newScheduledThreadPool(1, new NamedThreadFactory("Vmware-FullyClonedTemplateCheck"));;
private static final ScheduledExecutorService templateCleanupScheduler = Executors.newScheduledThreadPool(1, new NamedThreadFactory("Vmware-FullyClonedTemplateCheck"));
private final VmwareStorageManager _storageMgr;
private final GlobalLock _exclusiveOpLock = GlobalLock.getInternLock("vmware.exclusive.op");
@ -349,9 +359,9 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
_serviceConsoleName = "Service Console";
}
_managemetPortGroupName = _configDao.getValue(Config.VmwareManagementPortGroup.key());
if (_managemetPortGroupName == null) {
_managemetPortGroupName = "Management Network";
_managementPortGroupName = _configDao.getValue(Config.VmwareManagementPortGroup.key());
if (_managementPortGroupName == null) {
_managementPortGroupName = "Management Network";
}
_defaultSystemVmNicAdapterType = _configDao.getValue(Config.VmwareSystemVmNicDeviceType.key());
@ -450,7 +460,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
s_logger.info("Preparing network on host " + hostMo.getContext().toString() + " for " + privateTrafficLabel);
VirtualSwitchType vsType = VirtualSwitchType.getType(vSwitchType);
//The management network is probably always going to be a physical network with islation type of vlans, so assume BroadcastDomainType VLAN
//The management network is probably always going to be a physical network with isolation type of vlans, so assume BroadcastDomainType VLAN
if (VirtualSwitchType.StandardVirtualSwitch == vsType) {
HypervisorHostHelper.prepareNetwork(vSwitchName, "cloud.private", hostMo, vlanId, null, null, 180000, false, BroadcastDomainType.Vlan, null, null);
}
@ -459,7 +469,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
AboutInfo about = hostMo.getHostAboutInfo();
if (about != null) {
String version = about.getApiVersion();
if (version != null && (version.equals("4.0") || version.equals("4.1")) && _portsPerDvPortGroup < DEFAULT_PORTS_PER_DV_PORT_GROUP_VSPHERE4_x) {
if (version != null && (version.equals("4.0") || version.equals("4.1")) ) { // && _portsPerDvPortGroup < DEFAULT_PORTS_PER_DV_PORT_GROUP_VSPHERE4_x)
portsPerDvPortGroup = DEFAULT_PORTS_PER_DV_PORT_GROUP_VSPHERE4_x;
}
}
@ -482,7 +492,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
}
URI uriForHost = new URI(UriUtils.encodeURIComponent(clusterDetails.get("url") + "/" + host.getName()));
morSrcHost = serviceContext.getHostMorByPath(URLDecoder.decode(uriForHost.getPath(), "UTF-8"));
morSrcHost = serviceContext.getHostMorByPath(URLDecoder.decode(uriForHost.getPath(), StandardCharsets.UTF_8));
if (morSrcHost == null) {
return null;
}
@ -498,19 +508,18 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
throw new CloudRuntimeException("Invalid serviceContext");
}
ManagedObjectReference mor = serviceContext.getHostMorByPath(hostInventoryPath);
String privateTrafficLabel = null;
String privateTrafficLabel;
privateTrafficLabel = serviceContext.getStockObject("privateTrafficLabel");
if (privateTrafficLabel == null) {
privateTrafficLabel = _privateNetworkVSwitchName;
}
if (mor != null) {
List<ManagedObjectReference> returnedHostList = new ArrayList<ManagedObjectReference>();
List<ManagedObjectReference> returnedHostList = new ArrayList<>();
if (mor.getType().equals("ComputeResource")) {
List<ManagedObjectReference> hosts = serviceContext.getVimClient().getDynamicProperty(mor, "host");
assert (hosts != null && hosts.size() > 0);
assert (CollectionUtils.isNullOrEmpty(hosts));
// For ESX host, we need to enable host firewall to allow VNC access
HostMO hostMo = new HostMO(serviceContext, hosts.get(0));
@ -521,8 +530,8 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
List<ManagedObjectReference> hosts = serviceContext.getVimClient().getDynamicProperty(mor, "host");
assert (hosts != null);
if (hosts.size() > 0) {
AboutInfo about = (AboutInfo)(serviceContext.getVimClient().getDynamicProperty(hosts.get(0), "config.product"));
if (!hosts.isEmpty()) {
AboutInfo about = serviceContext.getVimClient().getDynamicProperty(hosts.get(0), "config.product");
String version = about.getApiVersion();
int maxHostsPerCluster = _hvCapabilitiesDao.getMaxHostsPerCluster(HypervisorType.VMware, version);
if (hosts.size() > maxHostsPerCluster) {
@ -551,7 +560,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
returnedHostList.add(mor);
return returnedHostList;
} else {
s_logger.error("Unsupport host type " + mor.getType() + ":" + mor.getValue() + " from inventory path: " + hostInventoryPath);
s_logger.error("Unsupported host type " + mor.getType() + ":" + mor.getValue() + " from inventory path: " + hostInventoryPath);
return null;
}
}
@ -616,13 +625,13 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
@Override
public String getManagementPortGroupName() {
return _managemetPortGroupName;
return _managementPortGroupName;
}
@Override
public String getManagementPortGroupByHost(HostMO hostMo) throws Exception {
if (hostMo.getHostType() == VmwareHostType.ESXi) {
return _managemetPortGroupName;
return _managementPortGroupName;
}
return _serviceConsoleName;
}
@ -632,7 +641,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
params.put("vmware.create.full.clone", _fullCloneFlag);
params.put("vm.instancename.flag", _instanceNameFlag);
params.put("service.console.name", _serviceConsoleName);
params.put("management.portgroup.name", _managemetPortGroupName);
params.put("management.portgroup.name", _managementPortGroupName);
params.put("vmware.root.disk.controller", _rootDiskController);
params.put("vmware.data.disk.controller", _dataDiskController);
params.put("vmware.recycle.hung.wokervm", _recycleHungWorker);
@ -659,25 +668,25 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
return false;
}
String tokens[] = workerTag.split("-");
String[] tokens = workerTag.split("-");
if (tokens.length != 3) {
s_logger.error("Invalid worker VM tag " + workerTag);
return false;
}
long startTick = Long.parseLong(tokens[0]);
long msid = Long.parseLong(tokens[1]);
long runid = Long.parseLong(tokens[2]);
long msId = Long.parseLong(tokens[1]);
long runId = Long.parseLong(tokens[2]);
if (msHostPeerDao.countStateSeenInPeers(msid, runid, ManagementServerHost.State.Down) > 0) {
if (msHostPeerDao.countStateSeenInPeers(msId, runId, ManagementServerHost.State.Down) > 0) {
if (s_logger.isInfoEnabled())
s_logger.info("Worker VM's owner management server node has been detected down from peer nodes, recycle it");
return true;
}
if (runid != clusterManager.getManagementRunId(msid)) {
if (runId != clusterManager.getManagementRunId(msId)) {
if (s_logger.isInfoEnabled())
s_logger.info("Worker VM's owner management server has changed runid, recycle it");
s_logger.info("Worker VM's owner management server has changed runId, recycle it");
return true;
}
@ -712,7 +721,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
File patchFolder = new File(mountPoint + "/systemvm");
if (!patchFolder.exists()) {
if (!patchFolder.mkdirs()) {
String msg = "Unable to create systemvm folder on secondary storage. location: " + patchFolder.toString();
String msg = "Unable to create systemvm folder on secondary storage. location: " + patchFolder;
s_logger.error(msg);
throw new CloudRuntimeException(msg);
}
@ -731,7 +740,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
} catch (IOException e) {
s_logger.error("Unexpected exception ", e);
String msg = "Unable to copy systemvm ISO on secondary storage. src location: " + srcIso.toString() + ", dest location: " + destIso;
String msg = "Unable to copy systemvm ISO on secondary storage. src location: " + srcIso + ", dest location: " + destIso;
s_logger.error(msg);
throw new CloudRuntimeException(msg);
}
@ -773,9 +782,8 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
isoFile = new File("/usr/share/cloudstack-common/vms/systemvm.iso");
}
assert (isoFile != null);
if (!isoFile.exists()) {
s_logger.error("Unable to locate systemvm.iso in your setup at " + isoFile.toString());
s_logger.error("Unable to locate systemvm.iso in your setup at " + isoFile);
}
return isoFile;
}
@ -790,16 +798,16 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
if (keyFile == null || !keyFile.exists()) {
keyFile = new File("/usr/share/cloudstack-common/scripts/vm/systemvm/id_rsa.cloud");
}
assert (keyFile != null);
if (!keyFile.exists()) {
s_logger.error("Unable to locate id_rsa.cloud in your setup at " + keyFile.toString());
s_logger.error("Unable to locate id_rsa.cloud in your setup at " + keyFile);
}
return keyFile;
}
@Override
public String getMountPoint(String storageUrl, String nfsVersion) {
String mountPoint = null;
String mountPoint;
synchronized (_storageMounts) {
mountPoint = _storageMounts.get(storageUrl);
if (mountPoint != null) {
@ -829,7 +837,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
String mountPoint = null;
long mshostId = ManagementServerNode.getManagementServerId();
for (int i = 0; i < 10; i++) {
String mntPt = parent + File.separator + String.valueOf(mshostId) + "." + Integer.toHexString(_rand.nextInt(Integer.MAX_VALUE));
String mntPt = parent + File.separator + mshostId + "." + Integer.toHexString(_rand.nextInt(Integer.MAX_VALUE));
File file = new File(mntPt);
if (!file.exists()) {
if (_storage.mkdir(mntPt)) {
@ -854,10 +862,9 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
for (String mountPoint : mounts) {
s_logger.info("umount NFS mount from previous session: " + mountPoint);
String result = null;
Script command = new Script(true, "umount", _timeout, s_logger);
command.add(mountPoint);
result = command.execute();
String result = command.execute();
if (result != null) {
s_logger.warn("Unable to umount " + mountPoint + " due to " + result);
}
@ -875,7 +882,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
for (String mountPoint : _storageMounts.values()) {
s_logger.info("umount NFS mount: " + mountPoint);
String result = null;
String result;
Script command = new Script(true, "umount", _timeout, s_logger);
command.add(mountPoint);
result = command.execute();
@ -896,8 +903,8 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
return null;
}
Script script = null;
String result = null;
Script script;
String result;
Script command = new Script(true, "mount", _timeout, s_logger);
command.add("-t", "nfs");
if (nfsVersion != null){
@ -984,40 +991,15 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
@Override
public void processConnect(Host host, StartupCommand cmd, boolean forRebalance) {
if (cmd instanceof StartupCommand) {
if (cmd != null) {
if (host.getHypervisorType() == HypervisorType.VMware) {
updateClusterNativeHAState(host, cmd);
} else {
return;
}
}
}
protected final static int DEFAULT_DOMR_SSHPORT = 3922;
protected boolean shutdownRouterVM(DomainRouterVO router) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Try to shutdown router VM " + router.getInstanceName() + " directly.");
}
Pair<Boolean, String> result;
try {
result = SshHelper.sshExecute(router.getPrivateIpAddress(), DEFAULT_DOMR_SSHPORT, "root", getSystemVMKeyFile(), null, "poweroff -f");
if (!result.first()) {
s_logger.debug("Unable to shutdown " + router.getInstanceName() + " directly");
return false;
}
} catch (Throwable e) {
s_logger.warn("Unable to shutdown router " + router.getInstanceName() + " directly.");
return false;
}
if (s_logger.isDebugEnabled()) {
s_logger.debug("Shutdown router " + router.getInstanceName() + " successful.");
}
return true;
}
@Override
public boolean processDisconnect(long agentId, Status state) {
return false;
@ -1058,16 +1040,16 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
@Override
public Pair<Integer, Integer> getAddiionalVncPortRange() {
return new Pair<Integer, Integer>(_additionalPortRangeStart, _additionalPortRangeSize);
return new Pair<>(_additionalPortRangeStart, _additionalPortRangeSize);
}
@Override
public Map<String, String> getNexusVSMCredentialsByClusterId(Long clusterId) {
CiscoNexusVSMDeviceVO nexusVSM = null;
ClusterVSMMapVO vsmMapVO = null;
CiscoNexusVSMDeviceVO nexusVSM;
ClusterVSMMapVO vsmMapVO;
vsmMapVO = _vsmMapDao.findByClusterId(clusterId);
long vsmId = 0;
long vsmId;
if (vsmMapVO != null) {
vsmId = vsmMapVO.getVsmId();
s_logger.info("vsmId is " + vsmId);
@ -1078,7 +1060,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
return null;
}
Map<String, String> nexusVSMCredentials = new HashMap<String, String>();
Map<String, String> nexusVSMCredentials = new HashMap<>();
if (nexusVSM != null) {
nexusVSMCredentials.put("vsmip", nexusVSM.getipaddr());
nexusVSMCredentials.put("vsmusername", nexusVSM.getUserName());
@ -1105,7 +1087,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
@Override
public List<Class<?>> getCommands() {
List<Class<?>> cmdList = new ArrayList<Class<?>>();
List<Class<?>> cmdList = new ArrayList<>();
cmdList.add(AddVmwareDcCmd.class);
cmdList.add(UpdateVmwareDcCmd.class);
cmdList.add(RemoveVmwareDcCmd.class);
@ -1114,13 +1096,14 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
cmdList.add(ListVsphereStoragePoliciesCmd.class);
cmdList.add(ListVsphereStoragePolicyCompatiblePoolsCmd.class);
cmdList.add(ListVmwareDcVmsCmd.class);
cmdList.add(ListVmwareDcHostsCmd.class);
return cmdList;
}
@Override
@DB
public VmwareDatacenterVO addVmwareDatacenter(AddVmwareDcCmd cmd) throws ResourceInUseException {
VmwareDatacenterVO vmwareDc = null;
VmwareDatacenterVO vmwareDc;
Long zoneId = cmd.getZoneId();
String userName = cmd.getUsername();
String password = cmd.getPassword();
@ -1176,10 +1159,10 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
checkIfDcIsUsed(vCenterHost, vmwareDcName, zoneId);
VmwareContext context = null;
DatacenterMO dcMo = null;
DatacenterMO dcMo;
String dcCustomFieldValue;
boolean addDcCustomFieldDef = false;
boolean dcInUse = false;
boolean dcInUse;
String guid;
ManagedObjectReference dcMor;
try {
@ -1212,7 +1195,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
// Map zone with vmware datacenter
vmwareDcZoneMap = new VmwareDatacenterZoneMapVO(zoneId, vmwareDc.getId());
vmwareDcZoneMap = vmwareDatacenterZoneMapDao.persist(vmwareDcZoneMap);
vmwareDatacenterZoneMapDao.persist(vmwareDcZoneMap);
// Set custom field for this DC
if (addDcCustomFieldDef) {
@ -1232,7 +1215,6 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
if (context != null) {
context.close();
}
context = null;
}
importVsphereStoragePoliciesInternal(zoneId, vmwareDc.getId());
return vmwareDc;
@ -1257,9 +1239,9 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
* Check if DC is already part of zone
* In that case vmware_data_center table should have the DC and a dc zone mapping should exist
*
* @param vCenterHost
* @param vmwareDcName
* @param zoneId
* @param vCenterHost the vcenter appliance hostname
* @param vmwareDcName the name of the vmware DC
* @param zoneId zone that the DC should be connected to
* @throws ResourceInUseException if the DC can not be used.
*/
private void checkIfDcIsUsed(String vCenterHost, String vmwareDcName, Long zoneId) throws ResourceInUseException {
@ -1267,7 +1249,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
vmwareDc = vmwareDcDao.getVmwareDatacenterByGuid(vmwareDcName + "@" + vCenterHost);
if (vmwareDc != null) {
VmwareDatacenterZoneMapVO mapping = vmwareDatacenterZoneMapDao.findByVmwareDcId(vmwareDc.getId());
if (mapping != null && Long.compare(zoneId, mapping.getZoneId()) == 0) {
if (mapping != null && zoneId == mapping.getZoneId()) {
throw new ResourceInUseException(String.format("This DC (%s) is already part of other CloudStack zone (%d). Cannot add this DC to more zones.", vmwareDc.getUuid(), zoneId));
}
}
@ -1276,7 +1258,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
@Override
@ActionEvent(eventType = EventTypes.EVENT_ZONE_EDIT, eventDescription = "updating VMware datacenter")
public VmwareDatacenter updateVmwareDatacenter(UpdateVmwareDcCmd cmd) {
final Long zoneId = cmd.getZoneId();
final long zoneId = cmd.getZoneId();
final String userName = cmd.getUsername();
final String password = cmd.getPassword();
final String vCenterHost = cmd.getVcenter();
@ -1304,7 +1286,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
}
vmwareDc.setGuid(String.format("%s@%s", vmwareDc.getVmwareDatacenterName(), vmwareDc.getVcenterHost()));
return Transaction.execute(new TransactionCallback<VmwareDatacenter>() {
return Transaction.execute(new TransactionCallback<>() {
@Override
public VmwareDatacenter doInTransaction(TransactionStatus status) {
if (vmwareDcDao.update(vmwareDc.getId(), vmwareDc)) {
@ -1353,7 +1335,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
String vCenterHost;
String userName;
String password;
DatacenterMO dcMo = null;
DatacenterMO dcMo;
final VmwareDatacenterZoneMapVO vmwareDcZoneMap = vmwareDatacenterZoneMapDao.findByZoneId(zoneId);
// Check if zone is associated with VMware DC
if (vmwareDcZoneMap == null) {
@ -1390,11 +1372,9 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
throw new DiscoveryException(msg);
}
assert (dcMo != null);
// Reset custom field property cloud.zone over this DC
dcMo.setCustomFieldValue(CustomFieldConstants.CLOUD_ZONE, "false");
s_logger.info("Sucessfully reset custom field property cloud.zone over DC " + vmwareDcName);
s_logger.info("Successfully reset custom field property cloud.zone over DC " + vmwareDcName);
} catch (Exception e) {
String msg = "Unable to reset custom field property cloud.zone over DC " + vmwareDcName + " due to : " + VmwareHelper.getExceptionMessage(e);
s_logger.error(msg);
@ -1403,7 +1383,6 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
if (context != null) {
context.close();
}
context = null;
}
return true;
}
@ -1424,7 +1403,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
private void validateZoneWithResources(Long zoneId, String errStr) throws ResourceInUseException {
// Check if zone has resources? - For now look for clusters
List<ClusterVO> clusters = clusterDao.listByZoneId(zoneId);
if (clusters != null && clusters.size() > 0) {
if (!CollectionUtils.isNullOrEmpty(clusters)) {
// Look for VMware hypervisor.
for (ClusterVO cluster : clusters) {
if (cluster.getHypervisorType().equals(HypervisorType.VMware)) {
@ -1445,9 +1424,9 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
}
@Override
public List<? extends VmwareDatacenter> listVmwareDatacenters(ListVmwareDcsCmd cmd) throws CloudRuntimeException, InvalidParameterValueException {
public List<? extends VmwareDatacenter> listVmwareDatacenters(ListVmwareDcsCmd cmd) throws CloudRuntimeException {
Long zoneId = cmd.getZoneId();
List<VmwareDatacenterVO> vmwareDcList = new ArrayList<VmwareDatacenterVO>();
List<VmwareDatacenterVO> vmwareDcList = new ArrayList<>();
VmwareDatacenterZoneMapVO vmwareDcZoneMap;
VmwareDatacenterVO vmwareDatacenter;
long vmwareDcId;
@ -1505,7 +1484,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
String vCenterHost = vmwareDatacenter.getVcenterHost();
String userName = vmwareDatacenter.getUser();
String password = vmwareDatacenter.getPassword();
List<PbmProfile> storageProfiles = null;
List<PbmProfile> storageProfiles;
try {
s_logger.debug(String.format("Importing vSphere Storage Policies for the vmware DC %d in zone %d", vmwareDcId, zoneId));
VmwareContext context = VmwareContextFactory.getContext(vCenterHost, userName, password);
@ -1533,16 +1512,15 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
List<VsphereStoragePolicyVO> allStoragePolicies = vsphereStoragePolicyDao.listAll();
List<PbmProfile> finalStorageProfiles = storageProfiles;
List<VsphereStoragePolicyVO> needToMarkRemoved = allStoragePolicies.stream()
.filter(existingPolicy -> !finalStorageProfiles.stream()
.anyMatch(storageProfile -> storageProfile.getProfileId().getUniqueId().equals(existingPolicy.getPolicyId())))
.filter(existingPolicy -> finalStorageProfiles.stream()
.noneMatch(storageProfile -> storageProfile.getProfileId().getUniqueId().equals(existingPolicy.getPolicyId())))
.collect(Collectors.toList());
for (VsphereStoragePolicyVO storagePolicy : needToMarkRemoved) {
vsphereStoragePolicyDao.remove(storagePolicy.getId());
}
List<VsphereStoragePolicyVO> storagePolicies = vsphereStoragePolicyDao.listAll();
return storagePolicies;
return vsphereStoragePolicyDao.listAll();
}
@Override
@ -1588,13 +1566,87 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
}
@Override
public List<UnmanagedInstanceTO> listVMsInDatacenter(ListVmwareDcVmsCmd cmd) {
public List<HostMO> listHostsInDatacenter(ListVmwareDcHostsCmd cmd) {
VcenterData vmwaredc = getVcenterData(cmd);
try {
VmwareContext context = getVmwareContext(vmwaredc);
DatacenterMO dcMo = getDatacenterMO(context, vmwaredc);
return dcMo.getAllHostsOnDatacenter();
} catch (RuntimeFaultFaultMsg | URISyntaxException | VmwareClientException | InvalidLocaleFaultMsg |
InvalidLoginFaultMsg | InvalidPropertyFaultMsg e) {
String errorMsg = String.format("Error retrieving stopped VMs from the VMware VC %s datacenter %s: %s",
vmwaredc.vcenter, vmwaredc.datacenterName, e.getMessage());
s_logger.error(errorMsg, e);
throw new CloudRuntimeException(errorMsg);
}
}
@Override
public Pair<String, List<UnmanagedInstanceTO>> listVMsInDatacenter(ListVmwareDcVmsCmd cmd) {
Integer maxObjects = cmd.getBatchSize();
String token = cmd.getToken();
String host = cmd.getHost();
VcenterData vmwaredc = getVcenterData(cmd);
try {
VmwareContext context = getVmwareContext(vmwaredc);
DatacenterMO dcMo = getDatacenterMO(context, vmwaredc);
if (com.cloud.utils.StringUtils.isNotBlank(host)) {
ManagedObjectReference hostMor = dcMo.findHost(host);
if (hostMor == null) {
throw new VmwareClientException(String.format("No host '%s' found on DC: %s.", host, dcMo.getName()));
}
HostMO hostMo = new HostMO(context, hostMor);
return hostMo.getVms(maxObjects, token);
} else {
return dcMo.getVms(maxObjects, token);
}
} catch (InvalidParameterValueException | VmwareClientException | InvalidLocaleFaultMsg | InvalidLoginFaultMsg |
RuntimeFaultFaultMsg | URISyntaxException | InvalidPropertyFaultMsg | InvocationTargetException |
NoSuchMethodException | IllegalAccessException e) {
String errorMsg = String.format("Error retrieving stopped VMs from the VMware VC %s datacenter %s: %s",
vmwaredc.vcenter, vmwaredc.datacenterName, e.getMessage());
s_logger.error(errorMsg, e);
throw new CloudRuntimeException(errorMsg);
}
}
@NotNull
private static DatacenterMO getDatacenterMO(VmwareContext context, VcenterData vmwaredc) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
DatacenterMO dcMo = new DatacenterMO(context, vmwaredc.datacenterName);
ManagedObjectReference dcMor = dcMo.getMor();
if (dcMor == null) {
String msg = String.format("Unable to find VMware datacenter %s in vCenter %s",
vmwaredc.datacenterName, vmwaredc.vcenter);
s_logger.error(msg);
throw new InvalidParameterValueException(msg);
}
return dcMo;
}
@NotNull
private static VmwareContext getVmwareContext(VcenterData vmwaredc) throws RuntimeFaultFaultMsg, URISyntaxException, VmwareClientException, InvalidLocaleFaultMsg, InvalidLoginFaultMsg {
s_logger.debug(String.format("Connecting to the VMware datacenter %s at vCenter %s to retrieve VMs",
vmwaredc.datacenterName, vmwaredc.vcenter));
String serviceUrl = String.format("https://%s/sdk/vimService", vmwaredc.vcenter);
VmwareClient vimClient = new VmwareClient(vmwaredc.vcenter);
vimClient.connect(serviceUrl, vmwaredc.username, vmwaredc.password);
VmwareContext context = new VmwareContext(vimClient, vmwaredc.vcenter);
return context;
}
@NotNull
private VcenterData getVcenterData(ListVmwareDcItems cmd) {
String vcenter = cmd.getVcenter();
String datacenterName = cmd.getDatacenterName();
String username = cmd.getUsername();
String password = cmd.getPassword();
Long existingVcenterId = cmd.getExistingVcenterId();
String keyword = cmd.getKeyword();
if ((existingVcenterId == null && StringUtils.isBlank(vcenter)) ||
(existingVcenterId != null && StringUtils.isNotBlank(vcenter))) {
@ -1615,37 +1667,27 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
username = vmwareDc.getUser();
password = vmwareDc.getPassword();
}
try {
s_logger.debug(String.format("Connecting to the VMware datacenter %s at vCenter %s to retrieve VMs",
datacenterName, vcenter));
String serviceUrl = String.format("https://%s/sdk/vimService", vcenter);
VmwareClient vimClient = new VmwareClient(vcenter);
vimClient.connect(serviceUrl, username, password);
VmwareContext context = new VmwareContext(vimClient, vcenter);
DatacenterMO dcMo = new DatacenterMO(context, datacenterName);
ManagedObjectReference dcMor = dcMo.getMor();
if (dcMor == null) {
String msg = String.format("Unable to find VMware datacenter %s in vCenter %s",
datacenterName, vcenter);
s_logger.error(msg);
throw new InvalidParameterValueException(msg);
VcenterData vmwaredc = new VcenterData(vcenter, datacenterName, username, password);
return vmwaredc;
}
List<UnmanagedInstanceTO> instances = dcMo.getAllVmsOnDatacenter();
return StringUtils.isBlank(keyword) ? instances :
instances.stream().filter(x -> x.getName().toLowerCase().contains(keyword.toLowerCase())).collect(Collectors.toList());
} catch (Exception e) {
String errorMsg = String.format("Error retrieving stopped VMs from the VMware VC %s datacenter %s: %s",
vcenter, datacenterName, e.getMessage());
s_logger.error(errorMsg, e);
throw new CloudRuntimeException(errorMsg);
private static class VcenterData {
public final String vcenter;
public final String datacenterName;
public final String username;
public final String password;
public VcenterData(String vcenter, String datacenterName, String username, String password) {
this.vcenter = vcenter;
this.datacenterName = datacenterName;
this.username = username;
this.password = password;
}
}
@Override
public boolean hasNexusVSM(Long clusterId) {
ClusterVSMMapVO vsmMapVo = null;
ClusterVSMMapVO vsmMapVo;
vsmMapVo = _vsmMapDao.findByClusterId(clusterId);
if (vsmMapVo == null) {
@ -1695,7 +1737,7 @@ public class VmwareManagerImpl extends ManagerBase implements VmwareManager, Vmw
}
/**
* This task is to cleanup templates from primary storage that are otherwise not cleaned by the {@link com.cloud.storage.StorageManagerImpl.StorageGarbageCollector}.
* This task is to clean-up templates from primary storage that are otherwise not cleaned by the {@see com.cloud.storage.StorageManagerImpl.StorageGarbageCollector}.
* it is called at regular intervals when storage.template.cleanup.enabled == true
* It collect all templates that
* - are deleted from cloudstack

View File

@ -37,8 +37,8 @@ import com.cloud.dc.VmwareDatacenterVO;
import com.cloud.user.Account;
import com.cloud.utils.exception.CloudRuntimeException;
@APICommand(name = "addVmwareDc", description = "Adds a VMware datacenter to specified zone", responseObject = VmwareDatacenterResponse.class,
requestHasSensitiveInfo = true, responseHasSensitiveInfo = false)
@APICommand(name = "addVmwareDc", description = "Adds a Vmware datacenter to specified zone",
responseObject = VmwareDatacenterResponse.class, responseHasSensitiveInfo = false)
public class AddVmwareDcCmd extends BaseCmd {
@Inject
@ -47,7 +47,7 @@ public class AddVmwareDcCmd extends BaseCmd {
public static final Logger s_logger = Logger.getLogger(AddVmwareDcCmd.class.getName());
@Parameter(name = ApiConstants.NAME, type = CommandType.STRING, required = true, description = "Name of VMware datacenter to be added to specified zone.")
@Parameter(name = ApiConstants.NAME, type = CommandType.STRING, required = true, description = "Name of Vmware datacenter to be added to specified zone.")
private String name;
@Parameter(name = ApiConstants.VCENTER,
@ -56,10 +56,10 @@ public class AddVmwareDcCmd extends BaseCmd {
description = "The name/ip of vCenter. Make sure it is IP address or full qualified domain name for host running vCenter server.")
private String vCenter;
@Parameter(name = ApiConstants.USERNAME, type = CommandType.STRING, required = false, description = "The Username required to connect to resource.")
@Parameter(name = ApiConstants.USERNAME, type = CommandType.STRING, description = "The Username required to connect to resource.")
private String username;
@Parameter(name = ApiConstants.PASSWORD, type = CommandType.STRING, required = false, description = "The password for specified username.")
@Parameter(name = ApiConstants.PASSWORD, type = CommandType.STRING, description = "The password for specified username.")
private String password;
@Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, required = true, description = "The Zone ID.")
@ -101,7 +101,7 @@ public class AddVmwareDcCmd extends BaseCmd {
response.setResponseName(getCommandName());
response.setObjectName("vmwaredc");
} else {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add VMware Datacenter to zone.");
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add Vmware Datacenter to zone.");
}
this.setResponseObject(response);
} catch (DiscoveryException ex) {

View File

@ -37,7 +37,6 @@ import org.apache.cloudstack.api.response.VsphereStoragePoliciesResponse;
import org.apache.cloudstack.api.response.ListResponse;
import org.apache.cloudstack.api.response.ZoneResponse;
import org.apache.cloudstack.context.CallContext;
import org.apache.log4j.Logger;
import javax.inject.Inject;
import java.util.ArrayList;
@ -49,9 +48,6 @@ import java.util.List;
authorized = {RoleType.Admin})
public class ImportVsphereStoragePoliciesCmd extends BaseCmd {
public static final Logger LOGGER = Logger.getLogger(ImportVsphereStoragePoliciesCmd.class.getName());
@Inject
public VmwareDatacenterService _vmwareDatacenterService;
@ -76,6 +72,13 @@ public class ImportVsphereStoragePoliciesCmd extends BaseCmd {
List<? extends VsphereStoragePolicy> storagePolicies = _vmwareDatacenterService.importVsphereStoragePolicies(this);
final ListResponse<VsphereStoragePoliciesResponse> responseList = new ListResponse<>();
final List<VsphereStoragePoliciesResponse> storagePoliciesResponseList = getVsphereStoragePoliciesResponses(storagePolicies, dataCenter);
responseList.setResponses(storagePoliciesResponseList);
responseList.setResponseName(getCommandName());
setResponseObject(responseList);
}
private static List<VsphereStoragePoliciesResponse> getVsphereStoragePoliciesResponses(List<? extends VsphereStoragePolicy> storagePolicies, DataCenter dataCenter) {
final List<VsphereStoragePoliciesResponse> storagePoliciesResponseList = new ArrayList<>();
for (VsphereStoragePolicy storagePolicy : storagePolicies) {
final VsphereStoragePoliciesResponse storagePoliciesResponse = new VsphereStoragePoliciesResponse();
@ -88,9 +91,7 @@ public class ImportVsphereStoragePoliciesCmd extends BaseCmd {
storagePoliciesResponseList.add(storagePoliciesResponse);
}
responseList.setResponses(storagePoliciesResponseList);
responseList.setResponseName(getCommandName());
setResponseObject(responseList);
return storagePoliciesResponseList;
}
@Override

View File

@ -0,0 +1,144 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.cloudstack.api.command.admin.zone;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.NetworkRuleConflictException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.hypervisor.Hypervisor;
import com.cloud.hypervisor.vmware.VmwareDatacenterService;
import com.cloud.hypervisor.vmware.mo.HostMO;
import com.cloud.user.Account;
import com.cloud.utils.exception.CloudRuntimeException;
import com.vmware.vim25.InvalidPropertyFaultMsg;
import com.vmware.vim25.RuntimeFaultFaultMsg;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.ApiErrorCode;
import org.apache.cloudstack.api.BaseCmd;
import org.apache.cloudstack.api.BaseResponse;
import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.response.HostResponse;
import org.apache.cloudstack.api.response.VmwareDatacenterResponse;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import javax.inject.Inject;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
@APICommand(name = "listVmwareDcHosts", responseObject = VmwareRequestResponse.class,
description = "Lists the VMs in a Vmware Datacenter",
requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
public class ListVmwareDcHostsCmd extends BaseCmd implements ListVmwareDcItems {
@Inject
public VmwareDatacenterService _vmwareDatacenterService;
@Parameter(name = ApiConstants.EXISTING_VCENTER_ID,
type = CommandType.UUID,
entityType = VmwareDatacenterResponse.class,
description = "UUID of a linked existing vCenter")
private Long existingVcenterId;
@Parameter(name = ApiConstants.VCENTER,
type = CommandType.STRING,
description = "The name/ip of vCenter. Make sure it is IP address or full qualified domain name for host running vCenter server.")
private String vcenter;
@Parameter(name = ApiConstants.DATACENTER_NAME, type = CommandType.STRING, description = "Name of Vmware datacenter.")
private String datacenterName;
@Parameter(name = ApiConstants.USERNAME, type = CommandType.STRING, description = "The Username required to connect to resource.")
private String username;
@Parameter(name = ApiConstants.PASSWORD, type = CommandType.STRING, description = "The password for specified username.")
private String password;
public String getVcenter() {
return vcenter;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getDatacenterName() {
return datacenterName;
}
public Long getExistingVcenterId() {
return existingVcenterId;
}
@Override
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException {
checkParameters();
try {
List<HostMO> hosts = _vmwareDatacenterService.listHostsInDatacenter(this);
List<BaseResponse> baseResponseList = new ArrayList<>();
if (CollectionUtils.isNotEmpty(hosts)) {
for (HostMO vmwareHost : hosts) {
HostResponse resp = createHostResponse(vmwareHost);
baseResponseList.add(resp);
}
}
VmwareRequestResponse<BaseResponse> response = new VmwareRequestResponse<>();
response.setResponses(baseResponseList, baseResponseList.size());
response.setResponseName(getCommandName());
setResponseObject(response);
} catch (CloudRuntimeException | InvalidPropertyFaultMsg | RuntimeFaultFaultMsg | InvocationTargetException |
NoSuchMethodException | IllegalAccessException e) {
String errorMsg = String.format("Error retrieving VMs from Vmware VC: %s", e.getMessage());
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, errorMsg);
}
}
private HostResponse createHostResponse(HostMO hostInstance) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, InvocationTargetException, NoSuchMethodException, IllegalAccessException {
HostResponse response = new HostResponse();
response.setHypervisor(Hypervisor.HypervisorType.VMware.toString());
response.setName(hostInstance.getHostName());
response.setObjectName("host");
return response;
}
private void checkParameters() {
if ((existingVcenterId == null && vcenter == null) || (existingVcenterId != null && vcenter != null)) {
throw new ServerApiException(ApiErrorCode.PARAM_ERROR,
"Please provide an existing vCenter ID or a vCenter IP/Name, parameters are mutually exclusive");
}
if (existingVcenterId == null && StringUtils.isAnyBlank(vcenter, datacenterName, username, password)) {
throw new ServerApiException(ApiErrorCode.PARAM_ERROR,
"Please set all the information for a vCenter IP/Name, datacenter, username and password");
}
}
@Override
public long getEntityOwnerId() {
return Account.ACCOUNT_ID_SYSTEM;
}
}

View File

@ -0,0 +1,29 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.cloudstack.api.command.admin.zone;
public interface ListVmwareDcItems {
String getVcenter();
String getDatacenterName();
String getUsername();
String getPassword();
Long getExistingVcenterId();
}

View File

@ -23,15 +23,15 @@ import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.hypervisor.vmware.VmwareDatacenterService;
import com.cloud.user.Account;
import com.cloud.utils.Pair;
import com.cloud.utils.exception.CloudRuntimeException;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.ApiErrorCode;
import org.apache.cloudstack.api.BaseListCmd;
import org.apache.cloudstack.api.BaseCmd;
import org.apache.cloudstack.api.BaseResponse;
import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.response.ListResponse;
import org.apache.cloudstack.api.response.UnmanagedInstanceResponse;
import org.apache.cloudstack.api.response.VmwareDatacenterResponse;
import org.apache.cloudstack.vm.UnmanagedInstanceTO;
@ -42,10 +42,10 @@ import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
@APICommand(name = "listVmwareDcVms", responseObject = UnmanagedInstanceResponse.class,
description = "Lists the VMs in a VMware Datacenter",
@APICommand(name = "listVmwareDcVms", responseObject = VmwareRequestResponse.class,
description = "Lists the VMs in a Vmware Datacenter",
requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
public class ListVmwareDcVmsCmd extends BaseListCmd {
public class ListVmwareDcVmsCmd extends BaseCmd implements ListVmwareDcItems {
@Inject
public VmwareDatacenterService _vmwareDatacenterService;
@ -61,7 +61,7 @@ public class ListVmwareDcVmsCmd extends BaseListCmd {
description = "The name/ip of vCenter. Make sure it is IP address or full qualified domain name for host running vCenter server.")
private String vcenter;
@Parameter(name = ApiConstants.DATACENTER_NAME, type = CommandType.STRING, description = "Name of VMware datacenter.")
@Parameter(name = ApiConstants.DATACENTER_NAME, type = CommandType.STRING, description = "Name of Vmware datacenter.")
private String datacenterName;
@Parameter(name = ApiConstants.USERNAME, type = CommandType.STRING, description = "The Username required to connect to resource.")
@ -70,6 +70,18 @@ public class ListVmwareDcVmsCmd extends BaseListCmd {
@Parameter(name = ApiConstants.PASSWORD, type = CommandType.STRING, description = "The password for specified username.")
private String password;
@Parameter(name = ApiConstants.HOST, type = CommandType.STRING, description = "get only the VMs from the specified host.")
private String host;
@Parameter(name = ApiConstants.BATCH_SIZE, type = CommandType.INTEGER, description = "The maximum number of results to return.")
private Integer batchSize;
@Parameter(name = ApiConstants.TOKEN, type = CommandType.STRING,
description = "For listVmwareDcVms, if the maximum number of results (the `batchsize`) is exceeded, " +
" a token is returned. This token can be used in subsequent calls to retrieve more results." +
" As long as a token is returned, more results can be retrieved.")
private String token;
public String getVcenter() {
return vcenter;
}
@ -82,6 +94,18 @@ public class ListVmwareDcVmsCmd extends BaseListCmd {
return password;
}
public Integer getBatchSize() {
return batchSize;
}
public String getHost() {
return host;
}
public String getToken() {
return token;
}
public String getDatacenterName() {
return datacenterName;
}
@ -94,7 +118,8 @@ public class ListVmwareDcVmsCmd extends BaseListCmd {
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException {
checkParameters();
try {
List<UnmanagedInstanceTO> vms = _vmwareDatacenterService.listVMsInDatacenter(this);
Pair<String, List<UnmanagedInstanceTO>> results = _vmwareDatacenterService.listVMsInDatacenter(this);
List<UnmanagedInstanceTO> vms = results.second();
List<BaseResponse> baseResponseList = new ArrayList<>();
if (CollectionUtils.isNotEmpty(vms)) {
for (UnmanagedInstanceTO vmwareVm : vms) {
@ -102,16 +127,13 @@ public class ListVmwareDcVmsCmd extends BaseListCmd {
baseResponseList.add(resp);
}
}
List<BaseResponse> pagingList = com.cloud.utils.StringUtils.applyPagination(baseResponseList, this.getStartIndex(), this.getPageSizeVal());
if (CollectionUtils.isEmpty(pagingList)) {
pagingList = baseResponseList;
}
ListResponse<BaseResponse> response = new ListResponse<>();
response.setResponses(pagingList, baseResponseList.size());
VmwareRequestResponse<BaseResponse> response = new VmwareRequestResponse<>();
response.setResponses(baseResponseList, baseResponseList.size());
response.setResponseName(getCommandName());
response.setToken(results.first());
setResponseObject(response);
} catch (CloudRuntimeException e) {
String errorMsg = String.format("Error retrieving VMs from VMware VC: %s", e.getMessage());
String errorMsg = String.format("Error retrieving VMs from Vmware VC: %s", e.getMessage());
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, errorMsg);
}
}
@ -134,6 +156,6 @@ public class ListVmwareDcVmsCmd extends BaseListCmd {
@Override
public String getCommandName() {
return "listvmwaredcvmsresponse";
return "listVmwareDcVmsResponse".toLowerCase();
}
}

View File

@ -43,7 +43,7 @@ import com.cloud.dc.VmwareDatacenter;
import com.cloud.hypervisor.vmware.VmwareDatacenterService;
import com.cloud.user.Account;
@APICommand(name = "listVmwareDcs", responseObject = VmwareDatacenterResponse.class, description = "Retrieves VMware DC(s) associated with a zone.",
@APICommand(name = "listVmwareDcs", responseObject = VmwareDatacenterResponse.class, description = "Retrieves Vmware DC(s) associated with a zone.",
requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
public class ListVmwareDcsCmd extends BaseListCmd {
@ -52,7 +52,6 @@ public class ListVmwareDcsCmd extends BaseListCmd {
public static final Logger s_logger = Logger.getLogger(ListVmwareDcsCmd.class.getName());
/////////////////////////////////////////////////////
//////////////// API parameters /////////////////////
/////////////////////////////////////////////////////
@ -75,20 +74,27 @@ public class ListVmwareDcsCmd extends BaseListCmd {
@Override
public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException,
ResourceAllocationException {
List<? extends VmwareDatacenter> vmwareDcList = null;
List<? extends VmwareDatacenter> vmwareDcList;
try {
vmwareDcList = _vmwareDatacenterService.listVmwareDatacenters(this);
} catch (InvalidParameterValueException ie) {
throw new InvalidParameterValueException("Invalid zone id " + getZoneId());
} catch (Exception e) {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to find associated VMware DCs associated with zone " + getZoneId());
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to find associated Vmware DCs associated with zone " + getZoneId());
}
ListResponse<VmwareDatacenterResponse> response = new ListResponse<VmwareDatacenterResponse>();
List<VmwareDatacenterResponse> vmwareDcResponses = new ArrayList<VmwareDatacenterResponse>();
ListResponse<VmwareDatacenterResponse> response = new ListResponse<>();
List<VmwareDatacenterResponse> vmwareDcResponses = getVmwareDatacenterResponses(vmwareDcList);
response.setResponses(vmwareDcResponses);
response.setResponseName(getCommandName());
setResponseObject(response);
}
if (vmwareDcList != null && vmwareDcList.size() > 0) {
private List<VmwareDatacenterResponse> getVmwareDatacenterResponses(List<? extends VmwareDatacenter> vmwareDcList) {
List<VmwareDatacenterResponse> vmwareDcResponses = new ArrayList<>();
if (vmwareDcList != null && !vmwareDcList.isEmpty()) {
for (VmwareDatacenter vmwareDc : vmwareDcList) {
VmwareDatacenterResponse vmwareDcResponse = new VmwareDatacenterResponse();
@ -96,14 +102,12 @@ public class ListVmwareDcsCmd extends BaseListCmd {
vmwareDcResponse.setVcenter(vmwareDc.getVcenterHost());
vmwareDcResponse.setName(vmwareDc.getVmwareDatacenterName());
vmwareDcResponse.setZoneId(getZoneId());
vmwareDcResponse.setObjectName("VMwareDC");
vmwareDcResponse.setObjectName(ApiConstants.VMWARE_DC);
vmwareDcResponses.add(vmwareDcResponse);
}
}
response.setResponses(vmwareDcResponses);
response.setResponseName(getCommandName());
setResponseObject(response);
return vmwareDcResponses;
}
@Override

View File

@ -36,7 +36,6 @@ import org.apache.cloudstack.api.response.ListResponse;
import org.apache.cloudstack.api.response.VsphereStoragePoliciesResponse;
import org.apache.cloudstack.api.response.ZoneResponse;
import org.apache.cloudstack.context.CallContext;
import org.apache.log4j.Logger;
import javax.inject.Inject;
import java.util.ArrayList;
@ -48,9 +47,6 @@ import java.util.List;
authorized = {RoleType.Admin})
public class ListVsphereStoragePoliciesCmd extends BaseCmd {
public static final Logger LOGGER = Logger.getLogger(ListVsphereStoragePoliciesCmd.class.getName());
@Inject
public VmwareDatacenterService _vmwareDatacenterService;
@ -75,6 +71,13 @@ public class ListVsphereStoragePoliciesCmd extends BaseCmd {
List<? extends VsphereStoragePolicy> storagePolicies = _vmwareDatacenterService.listVsphereStoragePolicies(this);
final ListResponse<VsphereStoragePoliciesResponse> responseList = new ListResponse<>();
final List<VsphereStoragePoliciesResponse> storagePoliciesResponseList = getVsphereStoragePoliciesResponses(storagePolicies, dataCenter);
responseList.setResponses(storagePoliciesResponseList);
responseList.setResponseName(getCommandName());
setResponseObject(responseList);
}
private static List<VsphereStoragePoliciesResponse> getVsphereStoragePoliciesResponses(List<? extends VsphereStoragePolicy> storagePolicies, DataCenter dataCenter) {
final List<VsphereStoragePoliciesResponse> storagePoliciesResponseList = new ArrayList<>();
for (VsphereStoragePolicy storagePolicy : storagePolicies) {
final VsphereStoragePoliciesResponse storagePoliciesResponse = new VsphereStoragePoliciesResponse();
@ -83,13 +86,11 @@ public class ListVsphereStoragePoliciesCmd extends BaseCmd {
storagePoliciesResponse.setName(storagePolicy.getName());
storagePoliciesResponse.setPolicyId(storagePolicy.getPolicyId());
storagePoliciesResponse.setDescription(storagePolicy.getDescription());
storagePoliciesResponse.setObjectName("StoragePolicy");
storagePoliciesResponse.setObjectName(ApiConstants.STORAGE_POLICY);
storagePoliciesResponseList.add(storagePoliciesResponse);
}
responseList.setResponses(storagePoliciesResponseList);
responseList.setResponseName(getCommandName());
setResponseObject(responseList);
return storagePoliciesResponseList;
}
@Override

View File

@ -68,7 +68,7 @@ public class ListVsphereStoragePolicyCompatiblePoolsCmd extends BaseListCmd {
List<StoragePoolResponse> poolResponses = new ArrayList<>();
for (StoragePool pool : pools) {
StoragePoolResponse poolResponse = _responseGenerator.createStoragePoolForMigrationResponse(pool);
poolResponse.setObjectName("storagepool");
poolResponse.setObjectName(ApiConstants.STORAGE_POOL);
poolResponses.add(poolResponse);
}
response.setResponses(poolResponses);

View File

@ -35,7 +35,7 @@ import com.cloud.hypervisor.vmware.VmwareDatacenterService;
import com.cloud.user.Account;
import com.cloud.utils.exception.CloudRuntimeException;
@APICommand(name = "removeVmwareDc", responseObject = SuccessResponse.class, description = "Remove a VMware datacenter from a zone.",
@APICommand(name = "removeVmwareDc", responseObject = SuccessResponse.class, description = "Remove a Vmware datacenter from a zone.",
requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
public class RemoveVmwareDcCmd extends BaseCmd {
@ -49,7 +49,7 @@ public class RemoveVmwareDcCmd extends BaseCmd {
type = CommandType.UUID,
entityType = ZoneResponse.class,
required = true,
description = "The id of Zone from which VMware datacenter has to be removed.")
description = "The id of Zone from which Vmware datacenter has to be removed.")
private Long zoneId;
public Long getZoneId() {
@ -65,10 +65,10 @@ public class RemoveVmwareDcCmd extends BaseCmd {
response.setResponseName(getCommandName());
setResponseObject(response);
} else {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to remove VMware datacenter from zone");
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to remove Vmware datacenter from zone");
}
} catch (ResourceInUseException ex) {
s_logger.warn("The zone has one or more resources (like cluster), hence not able to remove VMware datacenter from zone."
s_logger.warn("The zone has one or more resources (like cluster), hence not able to remove Vmware datacenter from zone."
+ " Please remove all resource from zone, and retry. Exception: ", ex);
ServerApiException e = new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage());
for (String proxyObj : ex.getIdProxyList()) {

View File

@ -28,18 +28,15 @@ import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.response.VmwareDatacenterResponse;
import org.apache.cloudstack.api.response.ZoneResponse;
import org.apache.log4j.Logger;
import com.cloud.dc.VmwareDatacenter;
import com.cloud.hypervisor.vmware.VmwareDatacenterService;
import com.cloud.user.Account;
@APICommand(name = "updateVmwareDc", description = "Updates a VMware datacenter details for a zone",
@APICommand(name = "updateVmwareDc", description = "Updates a Vmware datacenter details for a zone",
responseObject = VmwareDatacenterResponse.class, responseHasSensitiveInfo = false,
since = "4.12.0", authorized = {RoleType.Admin})
public class UpdateVmwareDcCmd extends BaseCmd {
public static final Logger LOG = Logger.getLogger(UpdateVmwareDcCmd.class);
@Inject
public VmwareDatacenterService vmwareDatacenterService;
@ -53,7 +50,7 @@ public class UpdateVmwareDcCmd extends BaseCmd {
private Long zoneId;
@Parameter(name = ApiConstants.NAME, type = CommandType.STRING,
description = "VMware datacenter name.")
description = "Vmware datacenter name.")
private String name;
@Parameter(name = ApiConstants.VCENTER, type = CommandType.STRING,
@ -108,13 +105,13 @@ public class UpdateVmwareDcCmd extends BaseCmd {
public void execute() {
final VmwareDatacenter vmwareDatacenter = vmwareDatacenterService.updateVmwareDatacenter(this);
if (vmwareDatacenter == null) {
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update VMware datacenter");
throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update Vmware datacenter");
}
final VmwareDatacenterResponse response = new VmwareDatacenterResponse();
response.setId(vmwareDatacenter.getUuid());
response.setName(vmwareDatacenter.getVmwareDatacenterName());
response.setResponseName(getCommandName());
response.setObjectName("vmwaredc");
response.setObjectName(ApiConstants.VMWARE_DC);
setResponseObject(response);
}

View File

@ -0,0 +1,38 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.cloudstack.api.command.admin.zone;
import com.cloud.serializer.Param;
import com.google.gson.annotations.SerializedName;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.ResponseObject;
import org.apache.cloudstack.api.response.ListResponse;
public class VmwareRequestResponse<T extends ResponseObject> extends ListResponse<T> {
@SerializedName(ApiConstants.TOKEN)
@Param(description = "The Vmware API token to use for retrieving further responses with")
private String token;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}

View File

@ -73,6 +73,7 @@ class TestData(object):
"listApis": "allow",
"listAccounts": "allow",
"listClusters": "deny",
"*VmwareDc*": "allow",
"*VM*": "allow",
"*Host*": "deny"
}

View File

@ -3006,6 +3006,7 @@
"message.license.agreements.not.accepted": "License agreements not accepted.",
"message.linstor.resourcegroup.description": "Linstor resource group to use for primary storage.",
"message.list.zone.vmware.datacenter.empty": "No VMware Datacenter exists in the selected Zone",
"message.list.zone.vmware.hosts.empty": "No VMware hosts were found in the selected Datacenter",
"message.listnsp.not.return.providerid": "error: listNetworkServiceProviders API doesn't return VirtualRouter provider ID.",
"message.load.host.failed": "Failed to load hosts.",
"message.loadbalancer.stickypolicy.configuration": "Customize the load balancer stickiness policy:",

View File

@ -1184,6 +1184,7 @@ export default {
} else {
params.existingvcenterid = this.selectedVmwareVcenter.existingvcenterid
}
params.host = this.selectedVmwareVcenter.host
}
api(apiName, params).then(json => {

View File

@ -89,6 +89,7 @@
<a-input
v-model:value="vcenter"
:placeholder="apiParams.vcenter.description"
@change="onSelectExternalVmwareDatacenter"
/>
</a-form-item>
<a-form-item ref="datacenter" name="datacenter">
@ -98,6 +99,7 @@
<a-input
v-model:value="datacenter"
:placeholder="apiParams.datacentername.description"
@change="onSelectExternalVmwareDatacenter"
/>
</a-form-item>
<a-form-item ref="username" name="username">
@ -107,6 +109,7 @@
<a-input
v-model:value="username"
:placeholder="apiParams.username.description"
@change="onSelectExternalVmwareDatacenter"
/>
</a-form-item>
<a-form-item ref="password" name="password">
@ -116,14 +119,36 @@
<a-input-password
v-model:value="password"
:placeholder="apiParams.password.description"
@change="onSelectExternalVmwareDatacenter"
/>
</a-form-item>
</div>
<div
v-if="selectedExistingVcenterId || (vcenterSelectedOption === 'new')">
<a-form-item :label="$t('label.vcenter.host')" ref="host" name="host" v-if="hosts.length > 0">
<a-select
v-model:value="form.host"
:loading="loading"
optionFilterProp="label"
:filterOption="(input, option) => {
return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
}"
:placeholder="$t('label.vcenter.host')"
@change="onSelectExistingVmwareHost">
<a-select-option v-for="opt in hosts" :key="opt.name">
{{ 'ESXi: ' + opt.name }}
</a-select-option>
</a-select>
</a-form-item>
<div v-else>
{{ $t('message.list.zone.vmware.hosts.empty') }}
</div>
</div>
<div class="card-footer">
<a-button
v-if="vcenterSelectedOption == 'existing' || vcenterSelectedOption == 'new'"
:disabled="(vcenterSelectedOption === 'new' && (vcenter === '' || datacentername === '' || username === '' || password === '')) ||
(vcenterSelectedOption === 'existing' && selectedExistingVcenterId === '')"
(vcenterSelectedOption === 'existing' && selectedExistingVcenterId === '') && host === ''"
:loading="loading"
type="primary"
@click="listVmwareDatacenterVms">{{ $t('label.list.vmware.vcenter.vms') }}</a-button>
@ -154,6 +179,8 @@ export default {
zones: {},
vcenterSelectedOption: '',
existingvcenter: [],
hosts: [],
selectedHost: '',
selectedExistingVcenterId: '',
selectedPoweredOnVm: false,
vmwareDcVms: [],
@ -217,6 +244,7 @@ export default {
} else {
params.existingvcenterid = this.selectedExistingVcenterId
}
params.host = this.selectedHost
api('listVmwareDcVms', params).then(json => {
const obj = {
params: params,
@ -246,8 +274,29 @@ export default {
listZoneVmwareDcs () {
this.loading = true
api('listVmwareDcs', { zoneid: this.sourcezoneid }).then(response => {
if (response.listvmwaredcsresponse.VMwareDC && response.listvmwaredcsresponse.VMwareDC.length > 0) {
this.existingvcenter = response.listvmwaredcsresponse.VMwareDC
if (response.listvmwaredcsresponse.vmwaredc && response.listvmwaredcsresponse.vmwaredc.length > 0) {
this.existingvcenter = response.listvmwaredcsresponse.vmwaredc
}
}).catch(error => {
this.$notifyError(error)
}).finally(() => {
this.loading = false
})
},
listZoneVmwareDcHosts () {
this.loading = true
const params = {}
if (this.vcenterSelectedOption === 'new') {
params.datacentername = this.datacenter
params.vcenter = this.vcenter
params.username = this.username
params.password = this.password
} else {
params.existingvcenterid = this.selectedExistingVcenterId
}
api('listVmwareDcHosts', params).then(response => {
if (response.listvmwaredchostsresponse.host && response.listvmwaredchostsresponse.host.length > 0) {
this.hosts = response.listvmwaredchostsresponse.host
}
}).catch(error => {
this.$notifyError(error)
@ -257,6 +306,15 @@ export default {
},
onSelectExistingVmwareDatacenter (value) {
this.selectedExistingVcenterId = value
this.listZoneVmwareDcHosts()
},
onSelectExternalVmwareDatacenter (value) {
if (this.vcenterSelectedOption === 'new' && !(this.vcenter === '' || this.datacentername === '' || this.username === '' || this.password === '')) {
this.listZoneVmwareDcHosts()
}
},
onSelectExistingVmwareHost (value) {
this.selectedHost = value
},
onVcenterTypeChange () {
this.$emit('onVcenterTypeChanged', this.vcenterSelectedOption)

View File

@ -16,13 +16,24 @@
// under the License.
package com.cloud.hypervisor.vmware.mo;
import com.cloud.hypervisor.vmware.util.VmwareHelper;
import com.cloud.hypervisor.vmware.util.VmwareContext;
import com.cloud.utils.Pair;
import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils;
import org.apache.cloudstack.vm.UnmanagedInstanceTO;
import org.apache.log4j.Logger;
import com.vmware.vim25.CustomFieldDef;
import com.vmware.vim25.CustomFieldStringValue;
import com.vmware.vim25.ManagedObjectReference;
import com.vmware.vim25.InvalidPropertyFaultMsg;
import com.vmware.vim25.RuntimeFaultFaultMsg;
import com.vmware.vim25.ObjectContent;
import com.vmware.vim25.RetrieveResult;
import com.cloud.hypervisor.vmware.util.VmwareContext;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
public class BaseMO {
private static final Logger s_logger = Logger.getLogger(BaseMO.class);
@ -50,6 +61,15 @@ public class BaseMO {
_mor.setValue(morValue);
}
protected static Pair<String, List<ObjectContent>> createReturnObjectPair(RetrieveResult result) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("vmware result : " + ReflectionToStringBuilderUtils.reflectCollection(result));
}
String tokenForRetrievingNewResults = result.getToken();
List<ObjectContent> listOfObjects = result.getObjects();
return new Pair<>(tokenForRetrievingNewResults, listOfObjects);
}
public VmwareContext getContext() {
return _context;
}
@ -137,11 +157,11 @@ public class BaseMO {
return null;
}
public int getCustomFieldKey(String fieldName) throws Exception {
public int getCustomFieldKey(String fieldName) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, InvocationTargetException, NoSuchMethodException, IllegalAccessException {
return getCustomFieldKey(getMor().getType(), fieldName);
}
public int getCustomFieldKey(String morType, String fieldName) throws Exception {
public int getCustomFieldKey(String morType, String fieldName) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, InvocationTargetException, NoSuchMethodException, IllegalAccessException {
assert (morType != null);
ManagedObjectReference cfmMor = _context.getServiceContent().getCustomFieldsManager();
@ -153,4 +173,30 @@ public class BaseMO {
return cfmMo.getCustomFieldKey(morType, fieldName);
}
protected Pair<String, List<ObjectContent>> retrieveNextSetOfProperties(String tokenForPriorQuery) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
RetrieveResult result = _context.getService().continueRetrievePropertiesEx(_context.getPropertyCollector(), tokenForPriorQuery);
return BaseMO.createReturnObjectPair(result);
}
protected void objectContentToUnmanagedInstanceTO(Pair<String, List<ObjectContent>> objectContents, List<UnmanagedInstanceTO> vms) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, InvocationTargetException, NoSuchMethodException, IllegalAccessException {
List<ObjectContent> ocs = objectContents.second();
if (ocs != null) {
for (ObjectContent oc : ocs) {
ManagedObjectReference vmMor = oc.getObj();
if (vmMor != null) {
VirtualMachineMO vmMo = new VirtualMachineMO(_context, vmMor);
try {
if (!vmMo.isTemplate()) {
HostMO hostMO = vmMo.getRunningHost();
UnmanagedInstanceTO unmanagedInstance = VmwareHelper.getUnmanagedInstance(hostMO, vmMo);
vms.add(unmanagedInstance);
}
} catch (Exception e) {
s_logger.debug(String.format("Unexpected error checking unmanaged instance %s, excluding it: %s", vmMo.getVmName(), e.getMessage()), e);
}
}
}
}
}
}

View File

@ -16,11 +16,14 @@
// under the License.
package com.cloud.hypervisor.vmware.mo;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import com.vmware.vim25.CustomFieldDef;
import com.vmware.vim25.ManagedObjectReference;
import com.vmware.vim25.PrivilegePolicyDef;
import com.vmware.vim25.InvalidPropertyFaultMsg;
import com.vmware.vim25.RuntimeFaultFaultMsg;
import com.cloud.hypervisor.vmware.util.VmwareContext;
@ -50,12 +53,12 @@ public class CustomFieldsManagerMO extends BaseMO {
_context.getService().setField(getMor(), morEntity, key, value);
}
public List<CustomFieldDef> getFields() throws Exception {
public List<CustomFieldDef> getFields() throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, InvocationTargetException, NoSuchMethodException, IllegalAccessException {
return _context.getVimClient().getDynamicProperty(getMor(), "field");
}
@Override
public int getCustomFieldKey(String morType, String fieldName) throws Exception {
public int getCustomFieldKey(String morType, String fieldName) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, InvocationTargetException, NoSuchMethodException, IllegalAccessException {
List<CustomFieldDef> fields = getFields();
if (fields != null) {
for (CustomFieldDef field : fields) {

View File

@ -17,11 +17,12 @@
package com.cloud.hypervisor.vmware.mo;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.cloud.hypervisor.vmware.util.VmwareHelper;
import com.cloud.utils.StringUtils;
import org.apache.cloudstack.vm.UnmanagedInstanceTO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
@ -39,6 +40,10 @@ import com.vmware.vim25.PropertySpec;
import com.vmware.vim25.SelectionSpec;
import com.vmware.vim25.TraversalSpec;
import com.vmware.vim25.VirtualEthernetCardDistributedVirtualPortBackingInfo;
import com.vmware.vim25.RetrieveOptions;
import com.vmware.vim25.RetrieveResult;
import com.vmware.vim25.InvalidPropertyFaultMsg;
import com.vmware.vim25.RuntimeFaultFaultMsg;
import com.cloud.hypervisor.vmware.util.VmwareContext;
import com.cloud.utils.Pair;
@ -54,7 +59,7 @@ public class DatacenterMO extends BaseMO {
super(context, morType, morValue);
}
public DatacenterMO(VmwareContext context, String dcName) throws Exception {
public DatacenterMO(VmwareContext context, String dcName) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
super(context, null);
_mor = _context.getVimClient().getDecendentMoRef(_context.getRootFolder(), "Datacenter", dcName);
@ -64,25 +69,8 @@ public class DatacenterMO extends BaseMO {
}
@Override
public String getName() throws Exception {
return (String)_context.getVimClient().getDynamicProperty(_mor, "name");
}
public void registerTemplate(ManagedObjectReference morHost, String datastoreName, String templateName, String templateFileName) throws Exception {
ManagedObjectReference morFolder = (ManagedObjectReference)_context.getVimClient().getDynamicProperty(_mor, "vmFolder");
assert (morFolder != null);
ManagedObjectReference morTask =
_context.getService()
.registerVMTask(morFolder, String.format("[%s] %s/%s", datastoreName, templateName, templateFileName), templateName, true, null, morHost);
boolean result = _context.getVimClient().waitForTask(morTask);
if (!result) {
throw new Exception("Unable to register template due to " + TaskMO.getTaskFailureInfo(_context, morTask));
} else {
_context.waitForTaskProgressDone(morTask);
}
public String getName() throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, InvocationTargetException, NoSuchMethodException, IllegalAccessException {
return _context.getVimClient().getDynamicProperty(_mor, "name");
}
public VirtualMachineMO findVm(String vmName) throws Exception {
@ -91,7 +79,7 @@ public class DatacenterMO extends BaseMO {
s_logger.warn("Custom field " + CustomFieldConstants.CLOUD_VM_INTERNAL_NAME + " is not registered ?!");
}
String instanceNameCustomField = "value[" + key + "]";
List<ObjectContent> ocs = getVmPropertiesOnDatacenterVmFolder(new String[] {"name", instanceNameCustomField});
List<ObjectContent> ocs = getVmProperties(new String[] {"name", instanceNameCustomField});
return HypervisorHostHelper.findVmFromObjectContent(_context, ocs.toArray(new ObjectContent[0]), vmName, instanceNameCustomField);
}
@ -100,10 +88,10 @@ public class DatacenterMO extends BaseMO {
int key = cfmMo.getCustomFieldKey("VirtualMachine", CustomFieldConstants.CLOUD_UUID);
assert (key != 0);
List<VirtualMachineMO> list = new ArrayList<VirtualMachineMO>();
List<VirtualMachineMO> list = new ArrayList<>();
List<ObjectContent> ocs = getVmPropertiesOnDatacenterVmFolder(new String[] {"name", String.format("value[%d]", key)});
if (ocs != null && ocs.size() > 0) {
List<ObjectContent> ocs = getVmProperties(new String[] {"name", String.format("value[%d]", key)});
if (CollectionUtils.isNotEmpty(ocs)) {
for (ObjectContent oc : ocs) {
List<DynamicProperty> props = oc.getPropSet();
if (props != null) {
@ -135,8 +123,8 @@ public class DatacenterMO extends BaseMO {
s_logger.warn("Custom field " + CustomFieldConstants.CLOUD_VM_INTERNAL_NAME + " is not registered ?!");
}
List<ObjectContent> ocs = getVmPropertiesOnDatacenterVmFolder(new String[] {"name", String.format("value[%d]", key)});
if (ocs != null && ocs.size() > 0) {
List<ObjectContent> ocs = getVmProperties(new String[] {"name", String.format("value[%d]", key)});
if (CollectionUtils.isNotEmpty(ocs)) {
for (ObjectContent oc : ocs) {
List<DynamicProperty> props = oc.getPropSet();
if (props != null) {
@ -161,31 +149,20 @@ public class DatacenterMO extends BaseMO {
return null;
}
public List<UnmanagedInstanceTO> getAllVmsOnDatacenter() throws Exception {
public Pair<String, List<UnmanagedInstanceTO>> getVms(Integer maxObjects, String token) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, InvocationTargetException, NoSuchMethodException, IllegalAccessException {
List<UnmanagedInstanceTO> vms = new ArrayList<>();
List<ObjectContent> ocs = getVmPropertiesOnDatacenterVmFolder(new String[] {"name"});
if (ocs != null) {
for (ObjectContent oc : ocs) {
ManagedObjectReference vmMor = oc.getObj();
if (vmMor != null) {
VirtualMachineMO vmMo = new VirtualMachineMO(_context, vmMor);
try {
if (!vmMo.isTemplate()) {
HostMO hostMO = vmMo.getRunningHost();
UnmanagedInstanceTO unmanagedInstance = VmwareHelper.getUnmanagedInstance(hostMO, vmMo);
vms.add(unmanagedInstance);
}
} catch (Exception e) {
s_logger.debug(String.format("Unexpected error checking unmanaged instance %s, excluding it: %s", vmMo.getVmName(), e.getMessage()), e);
}
}
Pair<String, List<ObjectContent>> objectContents = getVmProperties(new String[] {"name"}, maxObjects, token);
if (s_logger.isDebugEnabled()) {
s_logger.debug(String.format("returning token %s for future retrievals, currently %d objects retrieved.", objectContents.first(), objectContents.second().size()));
}
Pair<String, List<UnmanagedInstanceTO>> retval = new Pair<>(objectContents.first(), vms);
objectContentToUnmanagedInstanceTO(objectContents, vms);
return retval;
}
return vms;
}
public List<HostMO> getAllHostsOnDatacenter() throws Exception {
public List<HostMO> getAllHostsOnDatacenter() throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
List<HostMO> hosts = new ArrayList<>();
List<ObjectContent> ocs = getHostPropertiesOnDatacenterHostFolder(new String[] {"name"});
@ -212,21 +189,7 @@ public class DatacenterMO extends BaseMO {
return null;
}
public ManagedObjectReference listDatastore(String name) throws Exception {
assert (name != null);
List<ObjectContent> ocs = getDatastorePropertiesOnDatacenter(new String[] {"name"});
if (ocs != null) {
for (ObjectContent oc : ocs) {
if (oc.getPropSet().get(0).getVal().toString().equals(name)) {
return oc.getObj();
}
}
}
return null;
}
public ManagedObjectReference findHost(String name) throws Exception {
public ManagedObjectReference findHost(String name) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
List<ObjectContent> ocs = getHostPropertiesOnDatacenterHostFolder(new String[] {"name"});
if (ocs != null) {
@ -240,10 +203,10 @@ public class DatacenterMO extends BaseMO {
}
public ManagedObjectReference getVmFolder() throws Exception {
return (ManagedObjectReference)_context.getVimClient().getDynamicProperty(_mor, "vmFolder");
return _context.getVimClient().getDynamicProperty(_mor, "vmFolder");
}
public List<ObjectContent> getHostPropertiesOnDatacenterHostFolder(String[] propertyPaths) throws Exception {
public List<ObjectContent> getHostPropertiesOnDatacenterHostFolder(String[] propertyPaths) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
PropertySpec pSpec = new PropertySpec();
pSpec.setType("HostSystem");
pSpec.getPathSet().addAll(Arrays.asList(propertyPaths));
@ -277,7 +240,7 @@ public class DatacenterMO extends BaseMO {
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
pfSpec.getPropSet().add(pSpec);
pfSpec.getObjectSet().add(oSpec);
List<PropertyFilterSpec> pfSpecArr = new ArrayList<PropertyFilterSpec>();
List<PropertyFilterSpec> pfSpecArr = new ArrayList<>();
pfSpecArr.add(pfSpec);
return _context.getService().retrieveProperties(_context.getPropertyCollector(), pfSpecArr);
@ -303,14 +266,41 @@ public class DatacenterMO extends BaseMO {
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
pfSpec.getPropSet().add(pSpec);
pfSpec.getObjectSet().add(oSpec);
List<PropertyFilterSpec> pfSpecArr = new ArrayList<PropertyFilterSpec>();
List<PropertyFilterSpec> pfSpecArr = new ArrayList<>();
pfSpecArr.add(pfSpec);
return _context.getService().retrieveProperties(_context.getPropertyCollector(), pfSpecArr);
}
public List<ObjectContent> getVmPropertiesOnDatacenterVmFolder(String[] propertyPaths) throws Exception {
public List<ObjectContent> getVmProperties(String[] propertyPaths) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
return getVmProperties(propertyPaths, null, null).second();
}
/**
*
* @param propertyPaths Vmware side property names to query, for instance {"name"}
* @param maxObjects the number of objects to retrieve
* @param tokenForPriorQuery restart the query or continue a previous query
* @return The propertyPaths requested for the objects of type "VirtualMachine" in a list are found/returned by the DC
* @throws InvalidPropertyFaultMsg property does not exist as thrown by Vmware.
* @throws RuntimeFaultFaultMsg generic vmware runtime exception
*/
public Pair<String, List<ObjectContent>> getVmProperties(String[] propertyPaths, Integer maxObjects, String tokenForPriorQuery) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
if(StringUtils.isNotBlank(tokenForPriorQuery)) {
if (s_logger.isDebugEnabled()) {
s_logger.debug(String.format("running repeat query with token \'%s\'", tokenForPriorQuery));
}
return retrieveNextSetOfProperties(tokenForPriorQuery);
} else {
if (s_logger.isDebugEnabled()) {
s_logger.debug(String.format("running query for %d propertypaths and max %d objects", propertyPaths.length, maxObjects));
}
return retrieveNextSetOfProperties(propertyPaths, maxObjects);
}
}
private Pair<String, List<ObjectContent>> retrieveNextSetOfProperties(String[] propertyPaths, Integer maxObjects) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
PropertySpec pSpec = new PropertySpec();
pSpec.setType("VirtualMachine");
pSpec.getPathSet().addAll(Arrays.asList(propertyPaths));
@ -338,10 +328,16 @@ public class DatacenterMO extends BaseMO {
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
pfSpec.getPropSet().add(pSpec);
pfSpec.getObjectSet().add(oSpec);
List<PropertyFilterSpec> pfSpecArr = new ArrayList<PropertyFilterSpec>();
List<PropertyFilterSpec> pfSpecArr = new ArrayList<>();
pfSpecArr.add(pfSpec);
return _context.getService().retrieveProperties(_context.getPropertyCollector(), pfSpecArr);
RetrieveOptions ro = new RetrieveOptions();
if (maxObjects != null && maxObjects > 0) {
ro.setMaxObjects(maxObjects);
}
RetrieveResult result = _context.getService().retrievePropertiesEx(_context.getPropertyCollector(), pfSpecArr, ro);
return createReturnObjectPair(result);
}
public static Pair<DatacenterMO, String> getOwnerDatacenter(VmwareContext context, ManagedObjectReference morEntity) throws Exception {
@ -366,18 +362,18 @@ public class DatacenterMO extends BaseMO {
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
pfSpec.getPropSet().add(pSpec);
pfSpec.getObjectSet().add(oSpec);
List<PropertyFilterSpec> pfSpecArr = new ArrayList<PropertyFilterSpec>();
List<PropertyFilterSpec> pfSpecArr = new ArrayList<>();
pfSpecArr.add(pfSpec);
List<ObjectContent> ocs = context.getService().retrieveProperties(context.getPropertyCollector(), pfSpecArr);
assert (ocs != null && ocs.size() > 0);
assert (CollectionUtils.isNotEmpty(ocs));
assert (ocs.get(0).getObj() != null);
assert (ocs.get(0).getPropSet().get(0) != null);
assert (ocs.get(0).getPropSet().get(0).getVal() != null);
String dcName = ocs.get(0).getPropSet().get(0).getVal().toString();
return new Pair<DatacenterMO, String>(new DatacenterMO(context, ocs.get(0).getObj()), dcName);
return new Pair<>(new DatacenterMO(context, ocs.get(0).getObj()), dcName);
}
public ManagedObjectReference getDvPortGroupMor(String dvPortGroupName) throws Exception {
@ -398,7 +394,7 @@ public class DatacenterMO extends BaseMO {
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
pfSpec.getPropSet().add(pSpec);
pfSpec.getObjectSet().add(oSpec);
List<PropertyFilterSpec> pfSpecArr = new ArrayList<PropertyFilterSpec>();
List<PropertyFilterSpec> pfSpecArr = new ArrayList<>();
pfSpecArr.add(pfSpec);
List<ObjectContent> ocs = _context.getService().retrieveProperties(_context.getPropertyCollector(), pfSpecArr);
@ -419,9 +415,7 @@ public class DatacenterMO extends BaseMO {
public boolean hasDvPortGroup(String dvPortGroupName) throws Exception {
ManagedObjectReference morNetwork = getDvPortGroupMor(dvPortGroupName);
if (morNetwork != null)
return true;
return false;
return morNetwork != null;
}
public DVPortgroupConfigInfo getDvPortGroupSpec(String dvPortGroupName) throws Exception {
@ -445,7 +439,7 @@ public class DatacenterMO extends BaseMO {
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
pfSpec.getPropSet().add(pSpec);
pfSpec.getObjectSet().add(oSpec);
List<PropertyFilterSpec> pfSpecArr = new ArrayList<PropertyFilterSpec>();
List<PropertyFilterSpec> pfSpecArr = new ArrayList<>();
pfSpecArr.add(pfSpec);
List<ObjectContent> ocs = _context.getService().retrieveProperties(_context.getPropertyCollector(), pfSpecArr);
@ -462,7 +456,7 @@ public class DatacenterMO extends BaseMO {
nameProperty = prop.getVal().toString();
}
}
if (nameProperty.equalsIgnoreCase(dvPortGroupName)) {
if (nameProperty != null && nameProperty.equalsIgnoreCase(dvPortGroupName)) {
return configSpec;
}
}
@ -492,7 +486,7 @@ public class DatacenterMO extends BaseMO {
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
pfSpec.getPropSet().add(pSpec);
pfSpec.getObjectSet().add(oSpec);
List<PropertyFilterSpec> pfSpecArr = new ArrayList<PropertyFilterSpec>();
List<PropertyFilterSpec> pfSpecArr = new ArrayList<>();
pfSpecArr.add(pfSpec);
List<ObjectContent> ocs = _context.getService().retrieveProperties(_context.getPropertyCollector(), pfSpecArr);
@ -520,7 +514,7 @@ public class DatacenterMO extends BaseMO {
public String getDvSwitchUuid(ManagedObjectReference dvSwitchMor) throws Exception {
assert (dvSwitchMor != null);
return (String)_context.getVimClient().getDynamicProperty(dvSwitchMor, "uuid");
return _context.getVimClient().getDynamicProperty(dvSwitchMor, "uuid");
}
public VirtualEthernetCardDistributedVirtualPortBackingInfo getDvPortBackingInfo(Pair<ManagedObjectReference, String> networkInfo) throws Exception {
@ -538,8 +532,8 @@ public class DatacenterMO extends BaseMO {
}
public ManagedObjectReference getDvSwitchMor(String dvSwitchName) throws Exception {
ManagedObjectReference dvSwitchMor = null;
ManagedObjectReference networkFolderMor = null;
ManagedObjectReference dvSwitchMor;
ManagedObjectReference networkFolderMor;
networkFolderMor = _context.getVimClient().getMoRefProp(_mor, "networkFolder");
dvSwitchMor = _context.getVimClient().getDecendentMoRef(networkFolderMor, "VmwareDistributedVirtualSwitch", dvSwitchName);
return dvSwitchMor;
@ -551,7 +545,6 @@ public class DatacenterMO extends BaseMO {
}
public DatacenterConfigInfo getDatacenterConfigInfo() throws Exception {
DatacenterConfigInfo configInfo = (DatacenterConfigInfo)_context.getVimClient().getDynamicProperty(_mor, "configuration");
return configInfo;
return _context.getVimClient().getDynamicProperty(_mor, "configuration");
}
}

View File

@ -16,6 +16,7 @@
// under the License.
package com.cloud.hypervisor.vmware.mo;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@ -24,11 +25,20 @@ import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.apache.cloudstack.vm.UnmanagedInstanceTO;
import com.cloud.hypervisor.vmware.util.VmwareClientException;
import com.cloud.hypervisor.vmware.util.VmwareContext;
import com.cloud.hypervisor.vmware.util.VmwareHelper;
import com.cloud.utils.LogUtils;
import com.cloud.utils.Pair;
import com.cloud.utils.StringUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import com.google.gson.Gson;
import com.vmware.vim25.AboutInfo;
import com.vmware.vim25.AlreadyExistsFaultMsg;
import com.vmware.vim25.ClusterDasConfigInfo;
@ -58,6 +68,7 @@ import com.vmware.vim25.HostRuntimeInfo;
import com.vmware.vim25.HostSystemConnectionState;
import com.vmware.vim25.HostVirtualNic;
import com.vmware.vim25.HostVirtualSwitch;
import com.vmware.vim25.InvalidPropertyFaultMsg;
import com.vmware.vim25.ManagedObjectReference;
import com.vmware.vim25.NasDatastoreInfo;
import com.vmware.vim25.ObjectContent;
@ -65,13 +76,12 @@ import com.vmware.vim25.ObjectSpec;
import com.vmware.vim25.OptionValue;
import com.vmware.vim25.PropertyFilterSpec;
import com.vmware.vim25.PropertySpec;
import com.vmware.vim25.RetrieveOptions;
import com.vmware.vim25.RetrieveResult;
import com.vmware.vim25.RuntimeFaultFaultMsg;
import com.vmware.vim25.TraversalSpec;
import com.vmware.vim25.VirtualMachineConfigSpec;
import com.vmware.vim25.VirtualNicManagerNetConfig;
import com.cloud.hypervisor.vmware.util.VmwareContext;
import com.cloud.hypervisor.vmware.util.VmwareHelper;
import com.cloud.utils.LogUtils;
import com.cloud.utils.Pair;
public class HostMO extends BaseMO implements VmwareHypervisorHost {
private static final Logger s_logger = Logger.getLogger(HostMO.class);
@ -535,19 +545,23 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
return null;
}
public String getHostName() throws Exception {
public String getHostName() throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, InvocationTargetException, NoSuchMethodException, IllegalAccessException {
return (String)_context.getVimClient().getDynamicProperty(_mor, "name");
}
@Override
public synchronized List<VirtualMachineMO> listVmsOnHyperHostWithHypervisorName(String vmName) throws Exception {
public synchronized List<VirtualMachineMO> listVmsOnHyperHostWithHypervisorName(String vmName) throws VmwareClientException {
List<VirtualMachineMO> vms = new ArrayList<>();
try {
if (StringUtils.isNotEmpty(vmName)) {
vms.add(findVmOnHyperHostWithHypervisorName(vmName));
} else {
loadVmCache();
vms.addAll(_vmCache.values());
}
} catch (InvalidPropertyFaultMsg | RuntimeFaultFaultMsg | InvocationTargetException | NoSuchMethodException | IllegalAccessException e) {
throw new VmwareClientException("problem loading vm cache.", e);
}
return vms;
}
@ -582,7 +596,7 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
}
}
private void loadVmCache() throws Exception {
private void loadVmCache() throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, InvocationTargetException, NoSuchMethodException, IllegalAccessException {
if (s_logger.isDebugEnabled())
s_logger.debug("load VM cache on host");
@ -704,11 +718,16 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
}
@Override
public ObjectContent[] getVmPropertiesOnHyperHost(String[] propertyPaths) throws Exception {
if (s_logger.isTraceEnabled())
public ObjectContent[] getVmPropertiesOnHyperHost(String[] propertyPaths) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
List<ObjectContent> properties = getVmProperties(propertyPaths, null, null).second();
return properties.toArray(new ObjectContent[properties.size()]);
}
public Pair<String, List<ObjectContent>> getVmProperties(String[] propertyPaths, Integer maxObjects) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
if (s_logger.isTraceEnabled()) {
s_logger.trace("vCenter API trace - retrieveProperties() for VM properties. target MOR: " + _mor.getValue() + ", properties: " +
new Gson().toJson(propertyPaths));
}
PropertySpec pSpec = new PropertySpec();
pSpec.setType("VirtualMachine");
pSpec.getPathSet().addAll(Arrays.asList(propertyPaths));
@ -726,14 +745,19 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
pfSpec.getPropSet().add(pSpec);
pfSpec.getObjectSet().add(oSpec);
List<PropertyFilterSpec> pfSpecArr = new ArrayList<PropertyFilterSpec>();
List<PropertyFilterSpec> pfSpecArr = new ArrayList<>();
pfSpecArr.add(pfSpec);
List<ObjectContent> properties = _context.getService().retrieveProperties(_context.getPropertyCollector(), pfSpecArr);
RetrieveOptions ro = new RetrieveOptions();
if (maxObjects != null && maxObjects > 0) {
ro.setMaxObjects(maxObjects);
}
RetrieveResult result = _context.getService().retrievePropertiesEx(_context.getPropertyCollector(), pfSpecArr, ro);
if (s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - retrieveProperties() done");
return properties.toArray(new ObjectContent[properties.size()]);
return createReturnObjectPair(result);
}
@Override
@ -759,7 +783,7 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
pfSpec.getPropSet().add(pSpec);
pfSpec.getObjectSet().add(oSpec);
List<PropertyFilterSpec> pfSpecArr = new ArrayList<PropertyFilterSpec>();
List<PropertyFilterSpec> pfSpecArr = new ArrayList<>();
pfSpecArr.add(pfSpec);
List<ObjectContent> properties = _context.getService().retrieveProperties(_context.getPropertyCollector(), pfSpecArr);
@ -1318,7 +1342,7 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
return false;
}
private synchronized VirtualMachineMO findVmOnHyperHostWithHypervisorName(String vmName) throws Exception {
private synchronized VirtualMachineMO findVmOnHyperHostWithHypervisorName(String vmName) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, InvocationTargetException, NoSuchMethodException, IllegalAccessException {
if (s_logger.isDebugEnabled())
s_logger.debug("find VM hypervisor name: " + vmName + " on host");
@ -1350,4 +1374,29 @@ public class HostMO extends BaseMO implements VmwareHypervisorHost {
return null;
}
public Pair<String, List<UnmanagedInstanceTO>> getVms(Integer maxObjects, String token) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, InvocationTargetException, NoSuchMethodException, IllegalAccessException {
List<UnmanagedInstanceTO> vms = new ArrayList<>();
Pair<String, List<ObjectContent>> objectContents = getVmProperties(new String[] {"name"}, maxObjects, token);
if (s_logger.isDebugEnabled()) {
s_logger.debug(String.format("returning token %s for future retrievals, currently %d objects retrieved.", objectContents.first(), objectContents.second().size()));
}
Pair<String, List<UnmanagedInstanceTO>> retval = new Pair<>(objectContents.first(), vms);
objectContentToUnmanagedInstanceTO(objectContents, vms);
return retval;
}
public Pair<String, List<ObjectContent>> getVmProperties(String[] propertyPaths, Integer maxObjects, String tokenForPriorQuery) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
if(com.cloud.utils.StringUtils.isNotBlank(tokenForPriorQuery)) {
if (s_logger.isDebugEnabled()) {
s_logger.debug(String.format("running repeat query with token \'%s\'", tokenForPriorQuery));
}
return retrieveNextSetOfProperties(tokenForPriorQuery);
} else {
if (s_logger.isDebugEnabled()) {
s_logger.debug(String.format("running query for %d propertypaths and max %d objects", propertyPaths.length, maxObjects));
}
return getVmProperties(propertyPaths, maxObjects);
}
}
}

View File

@ -16,8 +16,10 @@
// under the License.
package com.cloud.hypervisor.vmware.util;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@ -36,19 +38,23 @@ import javax.xml.ws.handler.Handler;
import javax.xml.ws.handler.HandlerResolver;
import javax.xml.ws.handler.PortInfo;
import org.apache.cloudstack.utils.security.SSLUtils;
import org.apache.cloudstack.utils.security.SecureSSLSocketFactory;
import com.cloud.utils.StringUtils;
import org.apache.log4j.Logger;
import org.w3c.dom.Element;
import com.vmware.pbm.PbmPortType;
import com.vmware.pbm.PbmService;
import com.vmware.pbm.PbmServiceInstanceContent;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.w3c.dom.Element;
import com.vmware.vim25.DynamicProperty;
import com.vmware.vim25.InvalidCollectorVersionFaultMsg;
import com.vmware.vim25.InvalidLocaleFaultMsg;
import com.vmware.vim25.InvalidLoginFaultMsg;
import com.vmware.vim25.InvalidPropertyFaultMsg;
import com.vmware.vim25.LocalizedMethodFault;
import com.vmware.vim25.ManagedObjectReference;
@ -158,7 +164,7 @@ public class VmwareClient {
* @throws Exception
* the exception
*/
public void connect(String url, String userName, String password) throws Exception {
public void connect(String url, String userName, String password) throws RuntimeFaultFaultMsg, URISyntaxException, VmwareClientException, InvalidLocaleFaultMsg, InvalidLoginFaultMsg {
svcInstRef.setType(SVC_INST_NAME);
svcInstRef.setValue(SVC_INST_NAME);
@ -188,7 +194,7 @@ public class VmwareClient {
if (cookies == null) {
String msg = "Login successful, but failed to get server cookies from url :[" + url + "]";
s_logger.error(msg);
throw new Exception(msg);
throw new VmwareClientException(msg);
}
}
@ -204,7 +210,7 @@ public class VmwareClient {
isConnected = true;
}
private void pbmConnect(String url, String cookieValue) throws Exception {
private void pbmConnect(String url, String cookieValue) throws URISyntaxException {
URI uri = new URI(url);
String pbmurl = "https://" + uri.getHost() + "/pbm";
String[] tokens = cookieValue.split("=");
@ -348,8 +354,8 @@ public class VmwareClient {
* in case of error.
*/
@SuppressWarnings("unchecked")
public <T> T getDynamicProperty(ManagedObjectReference mor, String propertyName) throws Exception {
List<String> props = new ArrayList<String>();
public <T> T getDynamicProperty(ManagedObjectReference mor, String propertyName) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
List<String> props = new ArrayList<>();
props.add(propertyName);
List<ObjectContent> objContent = retrieveMoRefProperties(mor, props);
@ -379,7 +385,7 @@ public class VmwareClient {
return (T)propertyValue;
}
private List<ObjectContent> retrieveMoRefProperties(ManagedObjectReference mObj, List<String> props) throws Exception {
private List<ObjectContent> retrieveMoRefProperties(ManagedObjectReference mObj, List<String> props) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
PropertySpec pSpec = new PropertySpec();
pSpec.setAll(false);
pSpec.setType(mObj.getType());
@ -704,7 +710,7 @@ public class VmwareClient {
*
* @return First ManagedObjectReference of the type / name pair found
*/
public ManagedObjectReference getDecendentMoRef(ManagedObjectReference root, String type, String name) throws Exception {
public ManagedObjectReference getDecendentMoRef(ManagedObjectReference root, String type, String name) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg {
if (name == null || name.length() == 0) {
return null;
}

View File

@ -0,0 +1,33 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.hypervisor.vmware.util;
import com.cloud.exception.CloudException;
public class VmwareClientException extends CloudException {
public VmwareClientException(String message, Throwable cause) {
super(message, cause);
}
public VmwareClientException(String msg) {
super(msg);
}
// TODO embed vmware classes in this one for use downstream
public VmwareClientException(String msg, Exception embedded) {
super(msg, embedded);
}
}