use of com.vmware.vim25.mo.Network in project photon-model by vmware.
the class NetworkDeviceBackingFactory method getOpaqueNetworkBackingInfo.
/**
* Backing info for an opaque network which is managed by a management plane outside vSphere.
*/
private static VirtualEthernetCardOpaqueNetworkBackingInfo getOpaqueNetworkBackingInfo(CustomProperties props) {
VirtualEthernetCardOpaqueNetworkBackingInfo backing = new VirtualEthernetCardOpaqueNetworkBackingInfo();
backing.setOpaqueNetworkId(props.getString(NsxProperties.OPAQUE_NET_ID));
backing.setOpaqueNetworkType(props.getString(NsxProperties.OPAQUE_NET_TYPE));
return backing;
}
use of com.vmware.vim25.mo.Network in project vsphere-cloud-plugin by jenkinsci.
the class ReconfigureNetworkAdapters method reconfigureNetwork.
public boolean reconfigureNetwork(final Run<?, ?> run, final Launcher launcher, final TaskListener listener) throws VSphereException {
PrintStream jLogger = listener.getLogger();
String expandedDeviceLabel = deviceLabel;
String expandedMacAddress = macAddress;
String expandedPortGroup = portGroup;
String expandedDistributedPortGroup = distributedPortGroup;
String expandedDistributedPortId = distributedPortId;
EnvVars env;
try {
env = run.getEnvironment(listener);
} catch (Exception e) {
throw new VSphereException(e);
}
if (run instanceof AbstractBuild) {
// Add in matrix axes..
env.overrideAll(((AbstractBuild) run).getBuildVariables());
expandedDeviceLabel = env.expand(deviceLabel);
expandedMacAddress = env.expand(macAddress);
expandedPortGroup = env.expand(portGroup);
expandedDistributedPortGroup = env.expand(distributedPortGroup);
expandedDistributedPortId = env.expand(distributedPortId);
}
VSphereLogger.vsLogger(jLogger, "Preparing reconfigure: " + deviceAction.getLabel() + " Network Adapter \"" + expandedDeviceLabel + "\"");
VirtualEthernetCard vEth = null;
if (deviceAction == DeviceAction.ADD) {
vEth = new VirtualE1000();
vEth.setBacking(new VirtualEthernetCardNetworkBackingInfo());
Description description = vEth.getDeviceInfo();
if (description == null) {
description = new Description();
}
description.setLabel(expandedDeviceLabel);
vEth.setDeviceInfo(description);
} else {
vEth = findNetworkDeviceByLabel(vm.getConfig().getHardware().getDevice(), expandedDeviceLabel);
}
if (vEth == null) {
throw new VSphereException("Could not find network device named " + expandedDeviceLabel);
}
// change mac address
if (!expandedMacAddress.isEmpty()) {
VSphereLogger.vsLogger(jLogger, "Reconfiguring MAC Address -> " + expandedMacAddress);
vEth.setMacAddress(expandedMacAddress);
}
// extract backing from ethernet virtual card, always available
VirtualDeviceBackingInfo virtualDeviceBackingInfo = vEth.getBacking();
// change our port group
if (standardSwitch && !expandedPortGroup.isEmpty()) {
VSphereLogger.vsLogger(jLogger, "Reconfiguring Network Port Group -> " + expandedPortGroup);
if (virtualDeviceBackingInfo instanceof VirtualEthernetCardNetworkBackingInfo) {
VirtualEthernetCardNetworkBackingInfo backing = (VirtualEthernetCardNetworkBackingInfo) virtualDeviceBackingInfo;
Network networkPortGroup = getVsphere().getNetworkPortGroupByName(getVM(), expandedPortGroup);
if (networkPortGroup != null) {
backing.deviceName = expandedPortGroup;
} else {
VSphereLogger.vsLogger(jLogger, "Failed to find Network for Port Group -> " + expandedPortGroup);
}
} else {
VSphereLogger.vsLogger(jLogger, "Network Device -> " + expandedDeviceLabel + " isn't standard switch");
}
} else // change out distributed switch port group
if (distributedSwitch && !expandedDistributedPortGroup.isEmpty()) {
VSphereLogger.vsLogger(jLogger, "Reconfiguring Distributed Switch Port Group -> " + expandedDistributedPortGroup + " Port Id -> " + expandedDistributedPortId);
if (virtualDeviceBackingInfo instanceof VirtualEthernetCardDistributedVirtualPortBackingInfo) {
VirtualEthernetCardDistributedVirtualPortBackingInfo virtualEthernetCardDistributedVirtualPortBackingInfo = (VirtualEthernetCardDistributedVirtualPortBackingInfo) virtualDeviceBackingInfo;
DistributedVirtualPortgroup distributedVirtualPortgroup = getVsphere().getDistributedVirtualPortGroupByName(getVM(), expandedDistributedPortGroup);
if (distributedVirtualPortgroup != null) {
DistributedVirtualSwitch distributedVirtualSwitch = getVsphere().getDistributedVirtualSwitchByPortGroup(distributedVirtualPortgroup);
DistributedVirtualSwitchPortConnection distributedVirtualSwitchPortConnection = new DistributedVirtualSwitchPortConnection();
distributedVirtualSwitchPortConnection.setSwitchUuid(distributedVirtualSwitch.getUuid());
distributedVirtualSwitchPortConnection.setPortgroupKey(distributedVirtualPortgroup.getKey());
distributedVirtualSwitchPortConnection.setPortKey(expandedDistributedPortId);
virtualEthernetCardDistributedVirtualPortBackingInfo.setPort(distributedVirtualSwitchPortConnection);
VSphereLogger.vsLogger(jLogger, "Distributed Switch Port Group -> " + expandedDistributedPortGroup + "Port Id -> " + expandedDistributedPortId + " successfully configured!");
} else {
VSphereLogger.vsLogger(jLogger, "Failed to find Distributed Virtual Portgroup for Port Group -> " + expandedDistributedPortGroup);
}
} else {
VSphereLogger.vsLogger(jLogger, "Network Device -> " + expandedDeviceLabel + " isn't distributed switch");
}
}
VirtualDeviceConfigSpec vdspec = new VirtualDeviceConfigSpec();
vdspec.setDevice(vEth);
if (deviceAction == DeviceAction.EDIT) {
vdspec.setOperation(VirtualDeviceConfigSpecOperation.edit);
} else if (deviceAction == DeviceAction.REMOVE) {
vdspec.setOperation(VirtualDeviceConfigSpecOperation.remove);
}
// add change into config spec
VirtualDeviceConfigSpec[] deviceConfigSpecs = spec.getDeviceChange();
if (deviceConfigSpecs == null) {
deviceConfigSpecs = new VirtualDeviceConfigSpec[1];
} else {
deviceConfigSpecs = Arrays.copyOf(deviceConfigSpecs, deviceConfigSpecs.length + 1);
}
deviceConfigSpecs[deviceConfigSpecs.length - 1] = vdspec;
spec.setDeviceChange(deviceConfigSpecs);
VSphereLogger.vsLogger(jLogger, "Finished!");
return true;
}
use of com.vmware.vim25.mo.Network in project cloudstack by apache.
the class VmwareResource method execute.
protected StartAnswer execute(StartCommand cmd) {
VirtualMachineTO vmSpec = cmd.getVirtualMachine();
boolean vmAlreadyExistsInVcenter = false;
String existingVmName = null;
VirtualMachineFileInfo existingVmFileInfo = null;
VirtualMachineFileLayoutEx existingVmFileLayout = null;
List<DatastoreMO> existingDatastores = new ArrayList<DatastoreMO>();
String diskStoragePolicyId = null;
String vmStoragePolicyId = null;
VirtualMachineDefinedProfileSpec diskProfileSpec = null;
VirtualMachineDefinedProfileSpec vmProfileSpec = null;
DeployAsIsInfoTO deployAsIsInfo = vmSpec.getDeployAsIsInfo();
boolean deployAsIs = deployAsIsInfo != null;
Pair<String, String> names = composeVmNames(vmSpec);
String vmInternalCSName = names.first();
String vmNameOnVcenter = names.second();
DiskTO rootDiskTO = null;
String bootMode = getBootModeFromVmSpec(vmSpec, deployAsIs);
Pair<String, String> controllerInfo = getControllerInfoFromVmSpec(vmSpec);
Boolean systemVm = vmSpec.getType().isUsedBySystem();
// Thus, vmInternalCSName always holds i-x-y, the cloudstack generated internal VM name.
VmwareContext context = getServiceContext();
DatacenterMO dcMo = null;
try {
VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
VmwareHypervisorHost hyperHost = getHyperHost(context);
dcMo = new DatacenterMO(hyperHost.getContext(), hyperHost.getHyperHostDatacenter());
// Validate VM name is unique in Datacenter
VirtualMachineMO vmInVcenter = dcMo.checkIfVmAlreadyExistsInVcenter(vmNameOnVcenter, vmInternalCSName);
if (vmInVcenter != null) {
vmAlreadyExistsInVcenter = true;
String msg = "VM with name: " + vmNameOnVcenter + " already exists in vCenter.";
s_logger.error(msg);
throw new Exception(msg);
}
DiskTO[] specDisks = vmSpec.getDisks();
String guestOsId = getGuestOsIdFromVmSpec(vmSpec, deployAsIs);
DiskTO[] disks = validateDisks(vmSpec.getDisks());
assert (disks.length > 0);
NicTO[] nics = vmSpec.getNics();
HashMap<String, Pair<ManagedObjectReference, DatastoreMO>> dataStoresDetails = inferDatastoreDetailsFromDiskInfo(hyperHost, context, disks, cmd);
if ((dataStoresDetails == null) || (dataStoresDetails.isEmpty())) {
String msg = "Unable to locate datastore details of the volumes to be attached";
s_logger.error(msg);
throw new Exception(msg);
}
VirtualMachineDiskInfoBuilder diskInfoBuilder = null;
VirtualDevice[] nicDevices = null;
VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmInternalCSName);
DiskControllerType systemVmScsiControllerType = DiskControllerType.lsilogic;
int firstScsiControllerBusNum = 0;
int numScsiControllerForSystemVm = 1;
boolean hasSnapshot = false;
List<Pair<Integer, ManagedObjectReference>> diskDatastores = null;
if (vmMo != null) {
s_logger.info("VM " + vmInternalCSName + " already exists, tear down devices for reconfiguration");
if (getVmPowerState(vmMo) != PowerState.PowerOff)
vmMo.safePowerOff(_shutdownWaitMs);
// retrieve disk information before we tear down
diskDatastores = vmMo.getAllDiskDatastores();
diskInfoBuilder = vmMo.getDiskInfoBuilder();
hasSnapshot = vmMo.hasSnapshot();
nicDevices = vmMo.getNicDevices();
tearDownVmDevices(vmMo, hasSnapshot, deployAsIs);
ensureDiskControllersInternal(vmMo, systemVm, controllerInfo, systemVmScsiControllerType, numScsiControllerForSystemVm, firstScsiControllerBusNum, deployAsIs);
} else {
ManagedObjectReference morDc = hyperHost.getHyperHostDatacenter();
assert (morDc != null);
vmMo = hyperHost.findVmOnPeerHyperHost(vmInternalCSName);
if (vmMo != null) {
if (s_logger.isInfoEnabled()) {
s_logger.info("Found vm " + vmInternalCSName + " at other host, relocate to " + hyperHost.getHyperHostName());
}
takeVmFromOtherHyperHost(hyperHost, vmInternalCSName);
if (getVmPowerState(vmMo) != PowerState.PowerOff)
vmMo.safePowerOff(_shutdownWaitMs);
diskInfoBuilder = vmMo.getDiskInfoBuilder();
hasSnapshot = vmMo.hasSnapshot();
diskDatastores = vmMo.getAllDiskDatastores();
tearDownVmDevices(vmMo, hasSnapshot, deployAsIs);
ensureDiskControllersInternal(vmMo, systemVm, controllerInfo, systemVmScsiControllerType, numScsiControllerForSystemVm, firstScsiControllerBusNum, deployAsIs);
} else {
// If a VM with the same name is found in a different cluster in the DC, unregister the old VM and configure a new VM (cold-migration).
VirtualMachineMO existingVmInDc = dcMo.findVm(vmInternalCSName);
if (existingVmInDc != null) {
s_logger.debug("Found VM: " + vmInternalCSName + " on a host in a different cluster. Unregistering the exisitng VM.");
existingVmName = existingVmInDc.getName();
existingVmFileInfo = existingVmInDc.getFileInfo();
existingVmFileLayout = existingVmInDc.getFileLayout();
existingDatastores = existingVmInDc.getAllDatastores();
existingVmInDc.unregisterVm();
}
if (deployAsIs) {
vmMo = hyperHost.findVmOnHyperHost(vmInternalCSName);
if (vmMo == null) {
s_logger.info("Cloned deploy-as-is VM " + vmInternalCSName + " is not in this host, relocating it");
vmMo = takeVmFromOtherHyperHost(hyperHost, vmInternalCSName);
}
} else {
DiskTO rootDisk = null;
for (DiskTO vol : disks) {
if (vol.getType() == Volume.Type.ROOT) {
rootDisk = vol;
}
}
Pair<ManagedObjectReference, DatastoreMO> rootDiskDataStoreDetails = getDatastoreThatDiskIsOn(dataStoresDetails, rootDisk);
assert (vmSpec.getMinSpeed() != null) && (rootDiskDataStoreDetails != null);
DatastoreMO dsRootVolumeIsOn = rootDiskDataStoreDetails.second();
if (dsRootVolumeIsOn == null) {
String msg = "Unable to locate datastore details of root volume";
s_logger.error(msg);
throw new Exception(msg);
}
if (rootDisk.getDetails().get(DiskTO.PROTOCOL_TYPE) != null && rootDisk.getDetails().get(DiskTO.PROTOCOL_TYPE).equalsIgnoreCase(Storage.StoragePoolType.DatastoreCluster.toString())) {
if (diskInfoBuilder != null) {
DatastoreMO diskDatastoreMofromVM = getDataStoreWhereDiskExists(hyperHost, context, diskInfoBuilder, rootDisk, diskDatastores);
if (diskDatastoreMofromVM != null) {
String actualPoolUuid = diskDatastoreMofromVM.getCustomFieldValue(CustomFieldConstants.CLOUD_UUID);
if (!actualPoolUuid.equalsIgnoreCase(rootDisk.getData().getDataStore().getUuid())) {
dsRootVolumeIsOn = diskDatastoreMofromVM;
}
}
}
}
boolean vmFolderExists = dsRootVolumeIsOn.folderExists(String.format("[%s]", dsRootVolumeIsOn.getName()), vmNameOnVcenter);
String vmxFileFullPath = dsRootVolumeIsOn.searchFileInSubFolders(vmNameOnVcenter + ".vmx", false, VmwareManager.s_vmwareSearchExcludeFolder.value());
if (vmFolderExists && vmxFileFullPath != null) {
// VM can be registered only if .vmx is present.
registerVm(vmNameOnVcenter, dsRootVolumeIsOn);
vmMo = hyperHost.findVmOnHyperHost(vmInternalCSName);
if (vmMo != null) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Found registered vm " + vmInternalCSName + " at host " + hyperHost.getHyperHostName());
}
}
tearDownVm(vmMo);
} else if (!hyperHost.createBlankVm(vmNameOnVcenter, vmInternalCSName, vmSpec.getCpus(), vmSpec.getMaxSpeed().intValue(), getReservedCpuMHZ(vmSpec), vmSpec.getLimitCpuUse(), (int) (vmSpec.getMaxRam() / ResourceType.bytesToMiB), getReservedMemoryMb(vmSpec), guestOsId, rootDiskDataStoreDetails.first(), false, controllerInfo, systemVm)) {
throw new Exception("Failed to create VM. vmName: " + vmInternalCSName);
}
}
}
vmMo = hyperHost.findVmOnHyperHost(vmInternalCSName);
if (vmMo == null) {
throw new Exception("Failed to find the newly create or relocated VM. vmName: " + vmInternalCSName);
}
}
if (deployAsIs) {
s_logger.info("Mapping VM disks to spec disks and tearing down datadisks (if any)");
mapSpecDisksToClonedDisksAndTearDownDatadisks(vmMo, vmInternalCSName, specDisks);
}
int disksChanges = getDisksChangesNumberFromDisksSpec(disks, deployAsIs);
int totalChangeDevices = disksChanges + nics.length;
if (deployAsIsInfo != null && deployAsIsInfo.getProperties() != null) {
totalChangeDevices++;
}
DiskTO volIso = null;
if (vmSpec.getType() != VirtualMachine.Type.User) {
// system VM needs a patch ISO
totalChangeDevices++;
} else {
volIso = getIsoDiskTO(disks);
if (volIso == null && !deployAsIs) {
totalChangeDevices++;
}
}
VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();
int i = 0;
int ideUnitNumber = !deployAsIs ? 0 : vmMo.getNextIDEDeviceNumber();
int scsiUnitNumber = !deployAsIs ? 0 : vmMo.getNextScsiDiskDeviceNumber();
int ideControllerKey = vmMo.getIDEDeviceControllerKey();
int scsiControllerKey = vmMo.getScsiDeviceControllerKeyNoException();
VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[totalChangeDevices];
DiskTO[] sortedDisks = sortVolumesByDeviceId(disks);
VmwareHelper.setBasicVmConfig(vmConfigSpec, vmSpec.getCpus(), vmSpec.getMaxSpeed(), getReservedCpuMHZ(vmSpec), (int) (vmSpec.getMaxRam() / (1024 * 1024)), getReservedMemoryMb(vmSpec), guestOsId, vmSpec.getLimitCpuUse(), deployAsIs);
// Check for multi-cores per socket settings
int numCoresPerSocket = 1;
String coresPerSocket = vmSpec.getDetails().get(VmDetailConstants.CPU_CORE_PER_SOCKET);
if (coresPerSocket != null) {
String apiVersion = HypervisorHostHelper.getVcenterApiVersion(vmMo.getContext());
// Property 'numCoresPerSocket' is supported since vSphere API 5.0
if (apiVersion.compareTo("5.0") >= 0) {
numCoresPerSocket = NumbersUtil.parseInt(coresPerSocket, 1);
vmConfigSpec.setNumCoresPerSocket(numCoresPerSocket);
}
}
// Check for hotadd settings
vmConfigSpec.setMemoryHotAddEnabled(vmMo.isMemoryHotAddSupported(guestOsId) && vmSpec.isEnableDynamicallyScaleVm());
String hostApiVersion = ((HostMO) hyperHost).getHostAboutInfo().getApiVersion();
if (numCoresPerSocket > 1 && hostApiVersion.compareTo("5.0") < 0) {
s_logger.warn("Dynamic scaling of CPU is not supported for Virtual Machines with multi-core vCPUs in case of ESXi hosts 4.1 and prior. Hence CpuHotAdd will not be" + " enabled for Virtual Machine: " + vmInternalCSName);
vmConfigSpec.setCpuHotAddEnabled(false);
} else {
vmConfigSpec.setCpuHotAddEnabled(vmMo.isCpuHotAddSupported(guestOsId) && vmSpec.isEnableDynamicallyScaleVm());
}
if (!vmMo.isMemoryHotAddSupported(guestOsId) && vmSpec.isEnableDynamicallyScaleVm()) {
s_logger.warn("hotadd of memory is not supported, dynamic scaling feature can not be applied to vm: " + vmInternalCSName);
}
if (!vmMo.isCpuHotAddSupported(guestOsId) && vmSpec.isEnableDynamicallyScaleVm()) {
s_logger.warn("hotadd of cpu is not supported, dynamic scaling feature can not be applied to vm: " + vmInternalCSName);
}
configNestedHVSupport(vmMo, vmSpec, vmConfigSpec);
// prepare systemvm patch ISO
if (vmSpec.getType() != VirtualMachine.Type.User) {
// attach ISO (for patching of system VM)
Pair<String, Long> secStoreUrlAndId = mgr.getSecondaryStorageStoreUrlAndId(Long.parseLong(_dcId));
String secStoreUrl = secStoreUrlAndId.first();
Long secStoreId = secStoreUrlAndId.second();
if (secStoreUrl == null) {
String msg = "secondary storage for dc " + _dcId + " is not ready yet?";
throw new Exception(msg);
}
mgr.prepareSecondaryStorageStore(secStoreUrl, secStoreId);
ManagedObjectReference morSecDs = prepareSecondaryDatastoreOnHost(secStoreUrl);
if (morSecDs == null) {
String msg = "Failed to prepare secondary storage on host, secondary store url: " + secStoreUrl;
throw new Exception(msg);
}
DatastoreMO secDsMo = new DatastoreMO(hyperHost.getContext(), morSecDs);
deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec();
Pair<VirtualDevice, Boolean> isoInfo = VmwareHelper.prepareIsoDevice(vmMo, String.format("[%s] systemvm/%s", secDsMo.getName(), mgr.getSystemVMIsoFileNameOnDatastore()), secDsMo.getMor(), true, true, ideUnitNumber++, i + 1);
deviceConfigSpecArray[i].setDevice(isoInfo.first());
if (isoInfo.second()) {
if (s_logger.isDebugEnabled())
s_logger.debug("Prepare ISO volume at new device " + _gson.toJson(isoInfo.first()));
deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.ADD);
} else {
if (s_logger.isDebugEnabled())
s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first()));
deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.EDIT);
}
i++;
} else if (!deployAsIs) {
// Note: we will always plug a CDROM device
if (volIso != null) {
for (DiskTO vol : disks) {
if (vol.getType() == Volume.Type.ISO) {
configureIso(hyperHost, vmMo, vol, deviceConfigSpecArray, ideUnitNumber++, i);
i++;
}
}
} else {
deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec();
Pair<VirtualDevice, Boolean> isoInfo = VmwareHelper.prepareIsoDevice(vmMo, null, null, true, true, ideUnitNumber++, i + 1);
deviceConfigSpecArray[i].setDevice(isoInfo.first());
if (isoInfo.second()) {
if (s_logger.isDebugEnabled())
s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first()));
deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.ADD);
} else {
if (s_logger.isDebugEnabled())
s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first()));
deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.EDIT);
}
i++;
}
}
int controllerKey;
//
if (multipleIsosAtached(sortedDisks) && deployAsIs) {
sortedDisks = getDisks(sortedDisks);
}
for (DiskTO vol : sortedDisks) {
if (vol.getType() == Volume.Type.ISO) {
if (deployAsIs) {
configureIso(hyperHost, vmMo, vol, deviceConfigSpecArray, ideUnitNumber++, i);
i++;
}
continue;
}
if (deployAsIs && vol.getType() == Volume.Type.ROOT) {
rootDiskTO = vol;
resizeRootDiskOnVMStart(vmMo, rootDiskTO, hyperHost, context);
continue;
}
VirtualMachineDiskInfo matchingExistingDisk = getMatchingExistingDisk(diskInfoBuilder, vol, hyperHost, context);
String diskController = getDiskController(vmMo, matchingExistingDisk, vol, controllerInfo, deployAsIs);
if (DiskControllerType.getType(diskController) == DiskControllerType.osdefault) {
diskController = vmMo.getRecommendedDiskController(null);
}
if (DiskControllerType.getType(diskController) == DiskControllerType.ide) {
controllerKey = vmMo.getIDEControllerKey(ideUnitNumber);
if (vol.getType() == Volume.Type.DATADISK) {
// Ensure maximum of 2 data volumes over IDE controller, 3 includeing root volume
if (vmMo.getNumberOfVirtualDisks() > 3) {
throw new CloudRuntimeException("Found more than 3 virtual disks attached to this VM [" + vmMo.getVmName() + "]. Unable to implement the disks over " + diskController + " controller, as maximum number of devices supported over IDE controller is 4 includeing CDROM device.");
}
}
} else {
if (VmwareHelper.isReservedScsiDeviceNumber(scsiUnitNumber)) {
scsiUnitNumber++;
}
controllerKey = vmMo.getScsiDiskControllerKeyNoException(diskController, scsiUnitNumber);
if (controllerKey == -1) {
// This may happen for ROOT legacy VMs which doesn't have recommended disk controller when global configuration parameter 'vmware.root.disk.controller' is set to "osdefault"
// Retrieve existing controller and use.
Ternary<Integer, Integer, DiskControllerType> vmScsiControllerInfo = vmMo.getScsiControllerInfo();
DiskControllerType existingControllerType = vmScsiControllerInfo.third();
controllerKey = vmMo.getScsiDiskControllerKeyNoException(existingControllerType.toString(), scsiUnitNumber);
}
}
if (!hasSnapshot) {
deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec();
VolumeObjectTO volumeTO = (VolumeObjectTO) vol.getData();
DataStoreTO primaryStore = volumeTO.getDataStore();
Map<String, String> details = vol.getDetails();
boolean managed = false;
String iScsiName = null;
if (details != null) {
managed = Boolean.parseBoolean(details.get(DiskTO.MANAGED));
iScsiName = details.get(DiskTO.IQN);
}
String primaryStoreUuid = primaryStore.getUuid();
// if the storage is managed, iScsiName should not be null
String datastoreName = managed ? VmwareResource.getDatastoreName(iScsiName) : primaryStoreUuid;
Pair<ManagedObjectReference, DatastoreMO> volumeDsDetails = dataStoresDetails.get(datastoreName);
assert (volumeDsDetails != null);
if (volumeDsDetails == null) {
throw new Exception("Primary datastore " + primaryStore.getUuid() + " is not mounted on host.");
}
if (vol.getDetails().get(DiskTO.PROTOCOL_TYPE) != null && vol.getDetails().get(DiskTO.PROTOCOL_TYPE).equalsIgnoreCase("DatastoreCluster")) {
if (diskInfoBuilder != null && matchingExistingDisk != null) {
String[] diskChain = matchingExistingDisk.getDiskChain();
if (diskChain != null && diskChain.length > 0) {
DatastoreFile file = new DatastoreFile(diskChain[0]);
if (!file.getFileBaseName().equalsIgnoreCase(volumeTO.getPath())) {
if (s_logger.isInfoEnabled())
s_logger.info("Detected disk-chain top file change on volume: " + volumeTO.getId() + " " + volumeTO.getPath() + " -> " + file.getFileBaseName());
volumeTO.setPath(file.getFileBaseName());
}
}
DatastoreMO diskDatastoreMofromVM = getDataStoreWhereDiskExists(hyperHost, context, diskInfoBuilder, vol, diskDatastores);
if (diskDatastoreMofromVM != null) {
String actualPoolUuid = diskDatastoreMofromVM.getCustomFieldValue(CustomFieldConstants.CLOUD_UUID);
if (actualPoolUuid != null && !actualPoolUuid.equalsIgnoreCase(primaryStore.getUuid())) {
volumeDsDetails = new Pair<>(diskDatastoreMofromVM.getMor(), diskDatastoreMofromVM);
if (s_logger.isInfoEnabled())
s_logger.info("Detected datastore uuid change on volume: " + volumeTO.getId() + " " + primaryStore.getUuid() + " -> " + actualPoolUuid);
((PrimaryDataStoreTO) primaryStore).setUuid(actualPoolUuid);
}
}
}
}
String[] diskChain = syncDiskChain(dcMo, vmMo, vol, matchingExistingDisk, volumeDsDetails.second());
int deviceNumber = -1;
if (controllerKey == vmMo.getIDEControllerKey(ideUnitNumber)) {
deviceNumber = ideUnitNumber % VmwareHelper.MAX_ALLOWED_DEVICES_IDE_CONTROLLER;
ideUnitNumber++;
} else {
deviceNumber = scsiUnitNumber % VmwareHelper.MAX_ALLOWED_DEVICES_SCSI_CONTROLLER;
scsiUnitNumber++;
}
VirtualDevice device = VmwareHelper.prepareDiskDevice(vmMo, null, controllerKey, diskChain, volumeDsDetails.first(), deviceNumber, i + 1);
diskStoragePolicyId = volumeTO.getvSphereStoragePolicyId();
if (StringUtils.isNotEmpty(diskStoragePolicyId)) {
PbmProfileManagerMO profMgrMo = new PbmProfileManagerMO(context);
diskProfileSpec = profMgrMo.getProfileSpec(diskStoragePolicyId);
deviceConfigSpecArray[i].getProfile().add(diskProfileSpec);
if (s_logger.isDebugEnabled()) {
s_logger.debug(String.format("Adding vSphere storage profile: %s to virtual disk [%s]", diskStoragePolicyId, _gson.toJson(device)));
}
}
if (vol.getType() == Volume.Type.ROOT) {
rootDiskTO = vol;
vmStoragePolicyId = diskStoragePolicyId;
vmProfileSpec = diskProfileSpec;
}
deviceConfigSpecArray[i].setDevice(device);
deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.ADD);
if (s_logger.isDebugEnabled())
s_logger.debug("Prepare volume at new device " + _gson.toJson(device));
i++;
} else {
if (controllerKey == vmMo.getIDEControllerKey(ideUnitNumber))
ideUnitNumber++;
else
scsiUnitNumber++;
}
}
//
if (StringUtils.isNotBlank(guestOsId) && guestOsId.startsWith("darwin")) {
// Mac OS
VirtualDevice[] devices = vmMo.getMatchedDevices(new Class<?>[] { VirtualUSBController.class });
if (devices.length == 0) {
s_logger.debug("No USB Controller device on VM Start. Add USB Controller device for Mac OS VM " + vmInternalCSName);
// For Mac OS X systems, the EHCI+UHCI controller is enabled by default and is required for USB mouse and keyboard access.
VirtualDevice usbControllerDevice = VmwareHelper.prepareUSBControllerDevice();
deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec();
deviceConfigSpecArray[i].setDevice(usbControllerDevice);
deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.ADD);
if (s_logger.isDebugEnabled())
s_logger.debug("Prepare USB controller at new device " + _gson.toJson(deviceConfigSpecArray[i]));
i++;
} else {
s_logger.debug("USB Controller device exists on VM Start for Mac OS VM " + vmInternalCSName);
}
}
//
// Setup NIC devices
//
VirtualDevice nic;
int nicMask = 0;
int nicCount = 0;
VirtualEthernetCardType nicDeviceType;
NiciraNvpApiVersion.logNiciraApiVersion();
Map<String, String> nicUuidToDvSwitchUuid = new HashMap<String, String>();
for (NicTO nicTo : sortNicsByDeviceId(nics)) {
s_logger.info("Prepare NIC device based on NicTO: " + _gson.toJson(nicTo));
String adapterTypeStr = deployAsIs ? mapAdapterType(deployAsIsInfo.getNicAdapterMap().get(nicTo.getDeviceId())) : vmSpec.getDetails().get(VmDetailConstants.NIC_ADAPTER);
nicDeviceType = VirtualEthernetCardType.valueOf(adapterTypeStr);
if (s_logger.isDebugEnabled()) {
s_logger.debug("VM " + vmInternalCSName + " will be started with NIC device type: " + nicDeviceType + " on NIC device " + nicTo.getDeviceId());
}
boolean configureVServiceInNexus = (nicTo.getType() == TrafficType.Guest) && (vmSpec.getDetails().containsKey("ConfigureVServiceInNexus"));
VirtualMachine.Type vmType = cmd.getVirtualMachine().getType();
Pair<ManagedObjectReference, String> networkInfo = prepareNetworkFromNicInfo(vmMo.getRunningHost(), nicTo, configureVServiceInNexus, vmType);
if ((nicTo.getBroadcastType() != BroadcastDomainType.Lswitch) || (nicTo.getBroadcastType() == BroadcastDomainType.Lswitch && NiciraNvpApiVersion.isApiVersionLowerThan("4.2"))) {
if (VmwareHelper.isDvPortGroup(networkInfo.first())) {
String dvSwitchUuid;
ManagedObjectReference dcMor = hyperHost.getHyperHostDatacenter();
DatacenterMO dataCenterMo = new DatacenterMO(context, dcMor);
ManagedObjectReference dvsMor = dataCenterMo.getDvSwitchMor(networkInfo.first());
dvSwitchUuid = dataCenterMo.getDvSwitchUuid(dvsMor);
s_logger.info("Preparing NIC device on dvSwitch : " + dvSwitchUuid);
nic = VmwareHelper.prepareDvNicDevice(vmMo, networkInfo.first(), nicDeviceType, networkInfo.second(), dvSwitchUuid, nicTo.getMac(), i + 1, true, true);
if (nicTo.getUuid() != null) {
nicUuidToDvSwitchUuid.put(nicTo.getUuid(), dvSwitchUuid);
}
} else {
s_logger.info("Preparing NIC device on network " + networkInfo.second());
nic = VmwareHelper.prepareNicDevice(vmMo, networkInfo.first(), nicDeviceType, networkInfo.second(), nicTo.getMac(), i + 1, true, true);
}
} else {
// if NSX API VERSION >= 4.2, connect to br-int (nsx.network), do not create portgroup else previous behaviour
nic = VmwareHelper.prepareNicOpaque(vmMo, nicDeviceType, networkInfo.second(), nicTo.getMac(), i + 1, true, true);
}
deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec();
deviceConfigSpecArray[i].setDevice(nic);
deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.ADD);
if (s_logger.isDebugEnabled())
s_logger.debug("Prepare NIC at new device " + _gson.toJson(deviceConfigSpecArray[i]));
// this is really a hacking for DomR, upon DomR startup, we will reset all the NIC allocation after eth3
if (nicCount < 3)
nicMask |= (1 << nicCount);
i++;
nicCount++;
}
for (int j = 0; j < i; j++) vmConfigSpec.getDeviceChange().add(deviceConfigSpecArray[j]);
//
// Setup VM options
//
// pass boot arguments through machine.id & perform customized options to VMX
ArrayList<OptionValue> extraOptions = new ArrayList<OptionValue>();
configBasicExtraOption(extraOptions, vmSpec);
if (deployAsIs) {
setDeployAsIsProperties(vmMo, deployAsIsInfo, vmConfigSpec, hyperHost);
}
configNvpExtraOption(extraOptions, vmSpec, nicUuidToDvSwitchUuid);
configCustomExtraOption(extraOptions, vmSpec);
// config for NCC
VirtualMachine.Type vmType = cmd.getVirtualMachine().getType();
if (vmType.equals(VirtualMachine.Type.NetScalerVm)) {
NicTO mgmtNic = vmSpec.getNics()[0];
OptionValue option = new OptionValue();
option.setKey("machine.id");
option.setValue("ip=" + mgmtNic.getIp() + "&netmask=" + mgmtNic.getNetmask() + "&gateway=" + mgmtNic.getGateway());
extraOptions.add(option);
}
configureVNC(vmSpec, extraOptions, vmConfigSpec, hyperHost, vmInternalCSName);
// config video card
configureVideoCard(vmMo, vmSpec, vmConfigSpec);
setBootOptions(vmSpec, bootMode, vmConfigSpec);
if (StringUtils.isNotEmpty(vmStoragePolicyId)) {
vmConfigSpec.getVmProfile().add(vmProfileSpec);
if (s_logger.isTraceEnabled()) {
s_logger.trace(String.format("Configuring the VM %s with storage policy: %s", vmInternalCSName, vmStoragePolicyId));
}
}
//
if (!vmMo.configureVm(vmConfigSpec)) {
throw new Exception("Failed to configure VM before start. vmName: " + vmInternalCSName);
}
if (vmSpec.getType() == VirtualMachine.Type.DomainRouter) {
hyperHost.setRestartPriorityForVM(vmMo, DasVmPriority.HIGH.value());
}
// Resizing root disk only when explicit requested by user
final Map<String, String> vmDetails = cmd.getVirtualMachine().getDetails();
if (!deployAsIs && rootDiskTO != null && !hasSnapshot && (vmDetails != null && vmDetails.containsKey(ApiConstants.ROOT_DISK_SIZE))) {
resizeRootDiskOnVMStart(vmMo, rootDiskTO, hyperHost, context);
}
//
// Post Configuration
//
vmMo.setCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK, String.valueOf(nicMask));
postNvpConfigBeforeStart(vmMo, vmSpec);
Map<String, Map<String, String>> iqnToData = new HashMap<>();
postDiskConfigBeforeStart(vmMo, vmSpec, sortedDisks, ideControllerKey, scsiControllerKey, iqnToData, hyperHost, context);
//
if (!vmMo.powerOn()) {
throw new Exception("Failed to start VM. vmName: " + vmInternalCSName + " with hostname " + vmNameOnVcenter);
}
StartAnswer startAnswer = new StartAnswer(cmd);
startAnswer.setIqnToData(iqnToData);
// Since VM was successfully powered-on, if there was an existing VM in a different cluster that was unregistered, delete all the files associated with it.
if (existingVmName != null && existingVmFileLayout != null) {
List<String> vmDatastoreNames = new ArrayList<String>();
for (DatastoreMO vmDatastore : vmMo.getAllDatastores()) {
vmDatastoreNames.add(vmDatastore.getName());
}
// Don't delete files that are in a datastore that is being used by the new VM as well (zone-wide datastore).
List<String> skipDatastores = new ArrayList<String>();
for (DatastoreMO existingDatastore : existingDatastores) {
if (vmDatastoreNames.contains(existingDatastore.getName())) {
skipDatastores.add(existingDatastore.getName());
}
}
deleteUnregisteredVmFiles(existingVmFileLayout, dcMo, true, skipDatastores);
}
return startAnswer;
} catch (Throwable e) {
StartAnswer startAnswer = new StartAnswer(cmd, createLogMessageException(e, cmd));
if (vmAlreadyExistsInVcenter) {
startAnswer.setContextParam("stopRetry", "true");
}
if (existingVmName != null && existingVmFileInfo != null) {
s_logger.debug(String.format("Since VM start failed, registering back an existing VM: [%s] that was unregistered.", existingVmName));
try {
DatastoreFile fileInDatastore = new DatastoreFile(existingVmFileInfo.getVmPathName());
DatastoreMO existingVmDsMo = new DatastoreMO(dcMo.getContext(), dcMo.findDatastore(fileInDatastore.getDatastoreName()));
registerVm(existingVmName, existingVmDsMo);
} catch (Exception ex) {
String message = String.format("Failed to register an existing VM: [%s] due to [%s].", existingVmName, VmwareHelper.getExceptionMessage(ex));
s_logger.error(message, ex);
}
}
return startAnswer;
}
}
use of com.vmware.vim25.mo.Network in project cloudstack by apache.
the class VmwareServerDiscoverer method find.
@Override
public Map<? extends ServerResource, Map<String, String>> find(long dcId, Long podId, Long clusterId, URI url, String username, String password, List<String> hostTags) throws DiscoveryException {
if (s_logger.isInfoEnabled())
s_logger.info("Discover host. dc: " + dcId + ", pod: " + podId + ", cluster: " + clusterId + ", uri host: " + url.getHost());
if (podId == null) {
if (s_logger.isInfoEnabled())
s_logger.info("No pod is assigned, assuming that it is not for vmware and skip it to next discoverer");
return null;
}
boolean failureInClusterDiscovery = true;
String vsmIp = "";
ClusterVO cluster = _clusterDao.findById(clusterId);
if (cluster == null || cluster.getHypervisorType() != HypervisorType.VMware) {
if (s_logger.isInfoEnabled())
s_logger.info("invalid cluster id or cluster is not for VMware hypervisors");
return null;
}
Map<String, String> clusterDetails = _clusterDetailsDao.findDetails(clusterId);
boolean legacyZone = _vmwareMgr.isLegacyZone(dcId);
boolean usernameNotProvided = (username == null || username.isEmpty());
boolean passwordNotProvided = (password == null || password.isEmpty());
// Check if NOT a legacy zone.
if (!legacyZone) {
// Retrieve VMware DC associated with specified zone
VmwareDatacenterVO vmwareDc = fetchVmwareDatacenterByZone(dcId);
// If either or both not provided, try to retrieve & use the credentials from database, which are provided earlier while adding VMware DC to zone.
if (usernameNotProvided || passwordNotProvided) {
// Retrieve credentials associated with VMware DC
s_logger.info("Username and/or Password not provided while adding cluster to cloudstack zone. " + "Hence using both username & password provided while adding VMware DC to CloudStack zone.");
username = vmwareDc.getUser();
password = vmwareDc.getPassword();
clusterDetails.put("username", username);
clusterDetails.put("password", password);
_clusterDetailsDao.persist(clusterId, clusterDetails);
}
String updatedInventoryPath = validateCluster(url, vmwareDc);
try {
if (!URLDecoder.decode(url.getPath(), "UTF-8").equals(updatedInventoryPath)) {
// If url from API doesn't specify DC then update url in database with DC associated with this zone.
clusterDetails.put("url", url.getScheme() + "://" + url.getHost() + updatedInventoryPath);
_clusterDetailsDao.persist(clusterId, clusterDetails);
}
} catch (UnsupportedEncodingException e) {
throw new DiscoveredWithErrorException("Unable to decode URL path, URL path : " + url.getPath(), e);
}
} else {
// For legacy zones insist on the old model of asking for credentials for each cluster being added.
if (usernameNotProvided) {
if (passwordNotProvided) {
throw new InvalidParameterValueException("Please provide username & password to add this cluster to zone");
} else {
throw new InvalidParameterValueException("Please provide username to add this cluster to zone");
}
} else if (passwordNotProvided) {
throw new InvalidParameterValueException("Please provide password to add this cluster to zone");
}
}
List<HostVO> hosts = _resourceMgr.listAllHostsInCluster(clusterId);
if (hosts != null && hosts.size() > 0) {
int maxHostsPerCluster = _hvCapabilitiesDao.getMaxHostsPerCluster(hosts.get(0).getHypervisorType(), hosts.get(0).getHypervisorVersion());
if (hosts.size() >= maxHostsPerCluster) {
String msg = "VMware cluster " + cluster.getName() + " is too big to add new host, current size: " + hosts.size() + ", max. size: " + maxHostsPerCluster;
s_logger.error(msg);
throw new DiscoveredWithErrorException(msg);
}
}
String privateTrafficLabel = null;
String publicTrafficLabel = null;
String guestTrafficLabel = null;
Map<String, String> vsmCredentials = null;
VirtualSwitchType defaultVirtualSwitchType = VirtualSwitchType.StandardVirtualSwitch;
String paramGuestVswitchType = null;
String paramGuestVswitchName = null;
String paramPublicVswitchType = null;
String paramPublicVswitchName = null;
VmwareTrafficLabel guestTrafficLabelObj = new VmwareTrafficLabel(TrafficType.Guest);
VmwareTrafficLabel publicTrafficLabelObj = new VmwareTrafficLabel(TrafficType.Public);
DataCenterVO zone = _dcDao.findById(dcId);
NetworkType zoneType = zone.getNetworkType();
_readGlobalConfigParameters();
// Private traffic will be only on standard vSwitch for now.
if (useDVS) {
// Parse url parameters for type of vswitch and name of vswitch specified at cluster level
paramGuestVswitchType = _urlParams.get(ApiConstants.VSWITCH_TYPE_GUEST_TRAFFIC);
paramGuestVswitchName = _urlParams.get(ApiConstants.VSWITCH_NAME_GUEST_TRAFFIC);
paramPublicVswitchType = _urlParams.get(ApiConstants.VSWITCH_TYPE_PUBLIC_TRAFFIC);
paramPublicVswitchName = _urlParams.get(ApiConstants.VSWITCH_NAME_PUBLIC_TRAFFIC);
defaultVirtualSwitchType = getDefaultVirtualSwitchType();
}
// Zone level vSwitch Type depends on zone level traffic labels
//
// User can override Zone wide vswitch type (for public and guest) by providing following optional parameters in addClusterCmd
// param "guestvswitchtype" with valid values vmwaredvs, vmwaresvs, nexusdvs
// param "publicvswitchtype" with valid values vmwaredvs, vmwaresvs, nexusdvs
//
// Format of label is <VSWITCH>,<VLANID>,<VSWITCHTYPE>
// If a field <VLANID> OR <VSWITCHTYPE> is not present leave it empty.
// Ex: 1) vswitch0
// 2) dvswitch0,200,vmwaredvs
// 3) nexusepp0,300,nexusdvs
// 4) vswitch1,400,vmwaresvs
// 5) vswitch0
// default vswitchtype is 'vmwaresvs'.
// <VSWITCHTYPE> 'vmwaresvs' is for vmware standard vswitch
// <VSWITCHTYPE> 'vmwaredvs' is for vmware distributed virtual switch
// <VSWITCHTYPE> 'nexusdvs' is for cisco nexus distributed virtual switch
// Get zone wide traffic labels for Guest traffic and Public traffic
guestTrafficLabel = _netmgr.getDefaultGuestTrafficLabel(dcId, HypervisorType.VMware);
// Process traffic label information provided at zone level and cluster level
guestTrafficLabelObj = getTrafficInfo(TrafficType.Guest, guestTrafficLabel, defaultVirtualSwitchType, paramGuestVswitchType, paramGuestVswitchName, clusterId);
if (zoneType == NetworkType.Advanced) {
// Get zone wide traffic label for Public traffic
publicTrafficLabel = _netmgr.getDefaultPublicTrafficLabel(dcId, HypervisorType.VMware);
// Process traffic label information provided at zone level and cluster level
publicTrafficLabelObj = getTrafficInfo(TrafficType.Public, publicTrafficLabel, defaultVirtualSwitchType, paramPublicVswitchType, paramPublicVswitchName, clusterId);
// Configuration Check: A physical network cannot be shared by different types of virtual switches.
//
// Check if different vswitch types are chosen for same physical network
// 1. Get physical network for guest traffic - multiple networks
// 2. Get physical network for public traffic - single network
// See if 2 is in 1
// if no - pass
// if yes - compare publicTrafficLabelObj.getVirtualSwitchType() == guestTrafficLabelObj.getVirtualSwitchType()
// true - pass
// false - throw exception - fail cluster add operation
List<? extends PhysicalNetwork> pNetworkListGuestTraffic = _netmgr.getPhysicalNtwksSupportingTrafficType(dcId, TrafficType.Guest);
List<? extends PhysicalNetwork> pNetworkListPublicTraffic = _netmgr.getPhysicalNtwksSupportingTrafficType(dcId, TrafficType.Public);
// Public network would be on single physical network hence getting first object of the list would suffice.
PhysicalNetwork pNetworkPublic = pNetworkListPublicTraffic.get(0);
if (pNetworkListGuestTraffic.contains(pNetworkPublic)) {
if (publicTrafficLabelObj.getVirtualSwitchType() != guestTrafficLabelObj.getVirtualSwitchType()) {
String msg = "Both public traffic and guest traffic is over same physical network " + pNetworkPublic + ". And virtual switch type chosen for each traffic is different" + ". A physical network cannot be shared by different types of virtual switches.";
s_logger.error(msg);
throw new InvalidParameterValueException(msg);
}
}
}
privateTrafficLabel = _netmgr.getDefaultManagementTrafficLabel(dcId, HypervisorType.VMware);
if (privateTrafficLabel != null) {
s_logger.info("Detected private network label : " + privateTrafficLabel);
}
Pair<Boolean, Long> vsmInfo = new Pair<Boolean, Long>(false, 0L);
if (nexusDVS && (guestTrafficLabelObj.getVirtualSwitchType() == VirtualSwitchType.NexusDistributedVirtualSwitch) || ((zoneType == NetworkType.Advanced) && (publicTrafficLabelObj.getVirtualSwitchType() == VirtualSwitchType.NexusDistributedVirtualSwitch))) {
// 2) Atleast 1 traffic type uses Nexus distributed virtual switch as backend.
if (zoneType != NetworkType.Basic) {
publicTrafficLabel = _netmgr.getDefaultPublicTrafficLabel(dcId, HypervisorType.VMware);
if (publicTrafficLabel != null) {
s_logger.info("Detected public network label : " + publicTrafficLabel);
}
}
// Get physical network label
guestTrafficLabel = _netmgr.getDefaultGuestTrafficLabel(dcId, HypervisorType.VMware);
if (guestTrafficLabel != null) {
s_logger.info("Detected guest network label : " + guestTrafficLabel);
}
// Before proceeding with validation of Nexus 1000v VSM check if an instance of Nexus 1000v VSM is already associated with this cluster.
boolean clusterHasVsm = _vmwareMgr.hasNexusVSM(clusterId);
if (!clusterHasVsm) {
vsmIp = _urlParams.get("vsmipaddress");
String vsmUser = _urlParams.get("vsmusername");
String vsmPassword = _urlParams.get("vsmpassword");
String clusterName = cluster.getName();
try {
vsmInfo = _nexusElement.validateAndAddVsm(vsmIp, vsmUser, vsmPassword, clusterId, clusterName);
} catch (ResourceInUseException ex) {
DiscoveryException discEx = new DiscoveryException(ex.getLocalizedMessage() + ". The resource is " + ex.getResourceName());
throw discEx;
}
}
vsmCredentials = _vmwareMgr.getNexusVSMCredentialsByClusterId(clusterId);
}
VmwareContext context = null;
try {
context = VmwareContextFactory.create(url.getHost(), username, password);
if (privateTrafficLabel != null)
context.registerStockObject("privateTrafficLabel", privateTrafficLabel);
if (nexusDVS) {
if (vsmCredentials != null) {
s_logger.info("Stocking credentials of Nexus VSM");
context.registerStockObject("vsmcredentials", vsmCredentials);
}
}
List<ManagedObjectReference> morHosts = _vmwareMgr.addHostToPodCluster(context, dcId, podId, clusterId, URLDecoder.decode(url.getPath(), "UTF-8"));
if (morHosts == null)
s_logger.info("Found 0 hosts.");
if (privateTrafficLabel != null)
context.uregisterStockObject("privateTrafficLabel");
if (morHosts == null) {
s_logger.error("Unable to find host or cluster based on url: " + URLDecoder.decode(url.getPath(), "UTF-8"));
return null;
}
ManagedObjectReference morCluster = null;
clusterDetails = _clusterDetailsDao.findDetails(clusterId);
if (clusterDetails.get("url") != null) {
URI uriFromCluster = new URI(UriUtils.encodeURIComponent(clusterDetails.get("url")));
morCluster = context.getHostMorByPath(URLDecoder.decode(uriFromCluster.getPath(), "UTF-8"));
if (morCluster == null || !morCluster.getType().equalsIgnoreCase("ClusterComputeResource")) {
s_logger.warn("Cluster url does not point to a valid vSphere cluster, url: " + clusterDetails.get("url"));
return null;
} else {
ClusterMO clusterMo = new ClusterMO(context, morCluster);
if (clusterMo.isHAEnabled()) {
clusterDetails.put("NativeHA", "true");
_clusterDetailsDao.persist(clusterId, clusterDetails);
}
}
}
if (!validateDiscoveredHosts(context, morCluster, morHosts)) {
if (morCluster == null)
s_logger.warn("The discovered host is not standalone host, can not be added to a standalone cluster");
else
s_logger.warn("The discovered host does not belong to the cluster");
return null;
}
Map<VmwareResource, Map<String, String>> resources = new HashMap<VmwareResource, Map<String, String>>();
for (ManagedObjectReference morHost : morHosts) {
Map<String, String> details = new HashMap<String, String>();
Map<String, Object> params = new HashMap<String, Object>();
HostMO hostMo = new HostMO(context, morHost);
details.put("url", hostMo.getHostName());
details.put("username", username);
details.put("password", password);
boolean uefiLegacySupported = hostMo.isUefiLegacySupported();
if (uefiLegacySupported) {
details.put(Host.HOST_UEFI_ENABLE, "true");
}
String guid = morHost.getType() + ":" + morHost.getValue() + "@" + url.getHost();
details.put("guid", guid);
params.put("url", hostMo.getHostName());
params.put("username", username);
params.put("password", password);
params.put("zone", Long.toString(dcId));
params.put("pod", Long.toString(podId));
params.put("cluster", Long.toString(clusterId));
params.put("guid", guid);
if (privateTrafficLabel != null) {
params.put("private.network.vswitch.name", privateTrafficLabel);
}
params.put("guestTrafficInfo", guestTrafficLabelObj);
params.put("publicTrafficInfo", publicTrafficLabelObj);
params.put("router.aggregation.command.each.timeout", _configDao.getValue(Config.RouterAggregationCommandEachTimeout.toString()));
VmwareResource resource = new VmwareResource();
try {
resource.configure("VMware", params);
} catch (ConfigurationException e) {
_alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_HOST, dcId, podId, "Unable to add " + url.getHost(), "Error is " + e.getMessage());
s_logger.warn("Unable to instantiate " + url.getHost(), e);
}
resource.start();
resources.put(resource, details);
}
// place a place holder guid derived from cluster ID
try {
cluster.setGuid(UUID.nameUUIDFromBytes(String.valueOf(clusterId).getBytes("UTF-8")).toString());
} catch (UnsupportedEncodingException e) {
throw new DiscoveredWithErrorException("Unable to create UUID based on string " + String.valueOf(clusterId) + ". Bad clusterId or UTF-8 encoding error.");
}
_clusterDao.update(clusterId, cluster);
// Flag cluster discovery success
failureInClusterDiscovery = false;
return resources;
} catch (DiscoveredWithErrorException e) {
throw e;
} catch (Exception e) {
s_logger.warn("Unable to connect to Vmware vSphere server. service address: " + url.getHost() + ". " + e);
return null;
} finally {
if (context != null)
context.close();
if (failureInClusterDiscovery && vsmInfo.first()) {
try {
s_logger.debug("Deleting Nexus 1000v VSM " + vsmIp + " because cluster discovery and addition to zone has failed.");
_nexusElement.deleteCiscoNexusVSM(vsmInfo.second().longValue());
} catch (Exception e) {
s_logger.warn("Deleting Nexus 1000v VSM " + vsmIp + " failed.");
}
}
}
}
use of com.vmware.vim25.mo.Network in project cloudstack by apache.
the class VmwareResource method areVMsOnNetwork.
private boolean areVMsOnNetwork(DatacenterMO dcMO, NetworkDetails netDetails) throws Exception {
if (netDetails == null || netDetails.getName() == null) {
throw new CloudRuntimeException("Unspecified network details / port group, couldn't check VMs on network port group");
}
List<HostMO> hosts = dcMO.getAllHostsOnDatacenter();
if (!CollectionUtils.isEmpty(hosts)) {
for (HostMO host : hosts) {
NetworkMO networkMo = new NetworkMO(host.getContext(), netDetails.getNetworkMor());
List<ManagedObjectReference> vms = networkMo.getVMsOnNetwork();
if (!CollectionUtils.isEmpty(vms)) {
s_logger.debug("Network port group: " + netDetails.getName() + " is in use");
return true;
}
}
}
return false;
}
Aggregations