use of com.vmware.vim25.VirtualDevice in project cloudstack by apache.
the class VmwareResource method plugPublicNic.
private void plugPublicNic(VirtualMachineMO vmMo, final String vlanId, final String vifMacAddress) throws Exception {
// TODO : probably need to set traffic shaping
Pair<ManagedObjectReference, String> networkInfo = null;
VirtualSwitchType vSwitchType = VirtualSwitchType.StandardVirtualSwitch;
if (_publicTrafficInfo != null) {
vSwitchType = _publicTrafficInfo.getVirtualSwitchType();
}
/** FIXME We have no clue which network this nic is on and that means that we can't figure out the BroadcastDomainType
* so we assume that it's VLAN for now
*/
if (VirtualSwitchType.StandardVirtualSwitch == vSwitchType) {
networkInfo = HypervisorHostHelper.prepareNetwork(_publicTrafficInfo.getVirtualSwitchName(), "cloud.public", vmMo.getRunningHost(), vlanId, null, null, _opsTimeout, true, BroadcastDomainType.Vlan, null);
} else {
networkInfo = HypervisorHostHelper.prepareNetwork(_publicTrafficInfo.getVirtualSwitchName(), "cloud.public", vmMo.getRunningHost(), vlanId, null, null, null, _opsTimeout, vSwitchType, _portsPerDvPortGroup, null, false, BroadcastDomainType.Vlan, _vsmCredentials);
}
int nicIndex = allocPublicNicIndex(vmMo);
try {
VirtualDevice[] nicDevices = vmMo.getNicDevices();
VirtualEthernetCard device = (VirtualEthernetCard) nicDevices[nicIndex];
if (VirtualSwitchType.StandardVirtualSwitch == vSwitchType) {
VirtualEthernetCardNetworkBackingInfo nicBacking = new VirtualEthernetCardNetworkBackingInfo();
nicBacking.setDeviceName(networkInfo.second());
nicBacking.setNetwork(networkInfo.first());
device.setBacking(nicBacking);
} else {
HostMO hostMo = vmMo.getRunningHost();
DatacenterMO dataCenterMo = new DatacenterMO(hostMo.getContext(), hostMo.getHyperHostDatacenter());
device.setBacking(dataCenterMo.getDvPortBackingInfo(networkInfo));
}
VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();
//VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1];
VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec();
deviceConfigSpec.setDevice(device);
deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.EDIT);
vmConfigSpec.getDeviceChange().add(deviceConfigSpec);
if (!vmMo.configureVm(vmConfigSpec)) {
throw new Exception("Failed to configure devices when plugPublicNic");
}
} catch (Exception e) {
// restore allocation mask in case of exceptions
String nicMasksStr = vmMo.getCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK);
int nicMasks = Integer.parseInt(nicMasksStr);
nicMasks &= ~(1 << nicIndex);
vmMo.setCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK, String.valueOf(nicMasks));
throw e;
}
}
use of com.vmware.vim25.VirtualDevice in project cloudstack by apache.
the class VmwareResource method postNvpConfigBeforeStart.
private static void postNvpConfigBeforeStart(VirtualMachineMO vmMo, VirtualMachineTO vmSpec) throws Exception {
/**
* We need to configure the port on the DV switch after the host is
* connected. So make this happen between the configure and start of
* the VM
*/
int nicIndex = 0;
for (NicTO nicTo : sortNicsByDeviceId(vmSpec.getNics())) {
if (nicTo.getBroadcastType() == BroadcastDomainType.Lswitch) {
// We need to create a port with a unique vlan and pass the key to the nic device
s_logger.trace("Nic " + nicTo.toString() + " is connected to an NVP logicalswitch");
VirtualDevice nicVirtualDevice = vmMo.getNicDeviceByIndex(nicIndex);
if (nicVirtualDevice == null) {
//FIXME Generic exceptions are bad
throw new Exception("Failed to find a VirtualDevice for nic " + nicIndex);
}
VirtualDeviceBackingInfo backing = nicVirtualDevice.getBacking();
if (backing instanceof VirtualEthernetCardDistributedVirtualPortBackingInfo) {
// This NIC is connected to a Distributed Virtual Switch
VirtualEthernetCardDistributedVirtualPortBackingInfo portInfo = (VirtualEthernetCardDistributedVirtualPortBackingInfo) backing;
DistributedVirtualSwitchPortConnection port = portInfo.getPort();
String portKey = port.getPortKey();
String portGroupKey = port.getPortgroupKey();
String dvSwitchUuid = port.getSwitchUuid();
s_logger.debug("NIC " + nicTo.toString() + " is connected to dvSwitch " + dvSwitchUuid + " pg " + portGroupKey + " port " + portKey);
ManagedObjectReference dvSwitchManager = vmMo.getContext().getVimClient().getServiceContent().getDvSwitchManager();
ManagedObjectReference dvSwitch = vmMo.getContext().getVimClient().getService().queryDvsByUuid(dvSwitchManager, dvSwitchUuid);
// Get all ports
DistributedVirtualSwitchPortCriteria criteria = new DistributedVirtualSwitchPortCriteria();
criteria.setInside(true);
criteria.getPortgroupKey().add(portGroupKey);
List<DistributedVirtualPort> dvPorts = vmMo.getContext().getVimClient().getService().fetchDVPorts(dvSwitch, criteria);
DistributedVirtualPort vmDvPort = null;
List<Integer> usedVlans = new ArrayList<Integer>();
for (DistributedVirtualPort dvPort : dvPorts) {
// Find the port for this NIC by portkey
if (portKey.equals(dvPort.getKey())) {
vmDvPort = dvPort;
}
VMwareDVSPortSetting settings = (VMwareDVSPortSetting) dvPort.getConfig().getSetting();
VmwareDistributedVirtualSwitchVlanIdSpec vlanId = (VmwareDistributedVirtualSwitchVlanIdSpec) settings.getVlan();
s_logger.trace("Found port " + dvPort.getKey() + " with vlan " + vlanId.getVlanId());
if (vlanId.getVlanId() > 0 && vlanId.getVlanId() < 4095) {
usedVlans.add(vlanId.getVlanId());
}
}
if (vmDvPort == null) {
throw new Exception("Empty port list from dvSwitch for nic " + nicTo.toString());
}
DVPortConfigInfo dvPortConfigInfo = vmDvPort.getConfig();
VMwareDVSPortSetting settings = (VMwareDVSPortSetting) dvPortConfigInfo.getSetting();
VmwareDistributedVirtualSwitchVlanIdSpec vlanId = (VmwareDistributedVirtualSwitchVlanIdSpec) settings.getVlan();
BoolPolicy blocked = settings.getBlocked();
if (blocked.isValue() == Boolean.TRUE) {
s_logger.trace("Port is blocked, set a vlanid and unblock");
DVPortConfigSpec dvPortConfigSpec = new DVPortConfigSpec();
VMwareDVSPortSetting edittedSettings = new VMwareDVSPortSetting();
// Unblock
blocked.setValue(Boolean.FALSE);
blocked.setInherited(Boolean.FALSE);
edittedSettings.setBlocked(blocked);
// Set vlan
int i;
for (i = 1; i < 4095; i++) {
if (!usedVlans.contains(i))
break;
}
// FIXME should be a determined
vlanId.setVlanId(i);
// based on usage
vlanId.setInherited(false);
edittedSettings.setVlan(vlanId);
dvPortConfigSpec.setSetting(edittedSettings);
dvPortConfigSpec.setOperation("edit");
dvPortConfigSpec.setKey(portKey);
List<DVPortConfigSpec> dvPortConfigSpecs = new ArrayList<DVPortConfigSpec>();
dvPortConfigSpecs.add(dvPortConfigSpec);
ManagedObjectReference task = vmMo.getContext().getVimClient().getService().reconfigureDVPortTask(dvSwitch, dvPortConfigSpecs);
if (!vmMo.getContext().getVimClient().waitForTask(task)) {
throw new Exception("Failed to configure the dvSwitch port for nic " + nicTo.toString());
}
s_logger.debug("NIC " + nicTo.toString() + " connected to vlan " + i);
} else {
s_logger.trace("Port already configured and set to vlan " + vlanId.getVlanId());
}
} else if (backing instanceof VirtualEthernetCardNetworkBackingInfo) {
// This NIC is connected to a Virtual Switch
// Nothing to do
} else if (backing instanceof VirtualEthernetCardOpaqueNetworkBackingInfo) {
//if NSX API VERSION >= 4.2, connect to br-int (nsx.network), do not create portgroup else previous behaviour
//OK, connected to OpaqueNetwork
} else {
s_logger.error("nic device backing is of type " + backing.getClass().getName());
//FIXME Generic exceptions are bad
throw new Exception("Incompatible backing for a VirtualDevice for nic " + nicIndex);
}
}
nicIndex++;
}
}
use of com.vmware.vim25.VirtualDevice in project cloudstack by apache.
the class VmwareResource method prepareNetworkElementCommand.
private ExecutionResult prepareNetworkElementCommand(IpAssocCommand cmd) {
VmwareContext context = getServiceContext();
try {
VmwareHypervisorHost hyperHost = getHyperHost(context);
IpAddressTO[] ips = cmd.getIpAddresses();
String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME);
String controlIp = VmwareResource.getRouterSshControlIp(cmd);
VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(routerName);
// the check and will try to find it within cluster
if (vmMo == null) {
if (hyperHost instanceof HostMO) {
ClusterMO clusterMo = new ClusterMO(hyperHost.getContext(), ((HostMO) hyperHost).getParentMor());
vmMo = clusterMo.findVmOnHyperHost(routerName);
}
}
if (vmMo == null) {
String msg = "Router " + routerName + " no longer exists to execute IPAssoc command";
s_logger.error(msg);
throw new Exception(msg);
}
for (IpAddressTO ip : ips) {
/**
* TODO support other networks
*/
URI broadcastUri = BroadcastDomainType.fromString(ip.getBroadcastUri());
if (BroadcastDomainType.getSchemeValue(broadcastUri) != BroadcastDomainType.Vlan) {
throw new InternalErrorException("Unable to assign a public IP to a VIF on network " + ip.getBroadcastUri());
}
String vlanId = BroadcastDomainType.getValue(broadcastUri);
String publicNeworkName = HypervisorHostHelper.getPublicNetworkNamePrefix(vlanId);
Pair<Integer, VirtualDevice> publicNicInfo = vmMo.getNicDeviceIndex(publicNeworkName);
if (s_logger.isDebugEnabled()) {
s_logger.debug("Find public NIC index, public network name: " + publicNeworkName + ", index: " + publicNicInfo.first());
}
boolean addVif = false;
if (ip.isAdd() && publicNicInfo.first().intValue() == -1) {
if (s_logger.isDebugEnabled()) {
s_logger.debug("Plug new NIC to associate" + controlIp + " to " + ip.getPublicIp());
}
addVif = true;
}
if (addVif) {
plugPublicNic(vmMo, vlanId, ip.getVifMacAddress());
publicNicInfo = vmMo.getNicDeviceIndex(publicNeworkName);
if (publicNicInfo.first().intValue() >= 0) {
networkUsage(controlIp, "addVif", "eth" + publicNicInfo.first());
}
}
if (publicNicInfo.first().intValue() < 0) {
String msg = "Failed to find DomR VIF to associate/disassociate IP with.";
s_logger.error(msg);
throw new InternalErrorException(msg);
}
ip.setNicDevId(publicNicInfo.first().intValue());
ip.setNewNic(addVif);
}
} catch (Throwable e) {
s_logger.error("Unexpected exception: " + e.toString() + " will shortcut rest of IPAssoc commands", e);
return new ExecutionResult(false, e.toString());
}
return new ExecutionResult(true, null);
}
use of com.vmware.vim25.VirtualDevice in project cloudstack by apache.
the class VmwareResource method execute.
private PlugNicAnswer execute(PlugNicCommand cmd) {
if (s_logger.isInfoEnabled()) {
s_logger.info("Executing resource PlugNicCommand " + _gson.toJson(cmd));
}
getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
VmwareContext context = getServiceContext();
try {
VmwareHypervisorHost hyperHost = getHyperHost(context);
String vmName = cmd.getVmName();
VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName);
if (vmMo == null) {
if (hyperHost instanceof HostMO) {
ClusterMO clusterMo = new ClusterMO(hyperHost.getContext(), ((HostMO) hyperHost).getParentMor());
vmMo = clusterMo.findVmOnHyperHost(vmName);
}
}
if (vmMo == null) {
String msg = "Router " + vmName + " no longer exists to execute PlugNic command";
s_logger.error(msg);
throw new Exception(msg);
}
/*
if(!isVMWareToolsInstalled(vmMo)){
String errMsg = "vmware tools is not installed or not running, cannot add nic to vm " + vmName;
s_logger.debug(errMsg);
return new PlugNicAnswer(cmd, false, "Unable to execute PlugNicCommand due to " + errMsg);
}
*/
// Fallback to E1000 if no specific nicAdapter is passed
VirtualEthernetCardType nicDeviceType = VirtualEthernetCardType.E1000;
Map<String, String> details = cmd.getDetails();
if (details != null) {
nicDeviceType = VirtualEthernetCardType.valueOf((String) details.get("nicAdapter"));
}
// find a usable device number in VMware environment
VirtualDevice[] nicDevices = vmMo.getNicDevices();
int deviceNumber = -1;
for (VirtualDevice device : nicDevices) {
if (device.getUnitNumber() > deviceNumber)
deviceNumber = device.getUnitNumber();
}
deviceNumber++;
NicTO nicTo = cmd.getNic();
VirtualDevice nic;
Pair<ManagedObjectReference, String> networkInfo = prepareNetworkFromNicInfo(vmMo.getRunningHost(), nicTo, false, cmd.getVMType());
String dvSwitchUuid = null;
if (VmwareHelper.isDvPortGroup(networkInfo.first())) {
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(), deviceNumber, deviceNumber + 1, true, true);
} else {
s_logger.info("Preparing NIC device on network " + networkInfo.second());
nic = VmwareHelper.prepareNicDevice(vmMo, networkInfo.first(), nicDeviceType, networkInfo.second(), nicTo.getMac(), deviceNumber, deviceNumber + 1, true, true);
}
VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec();
//VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1];
VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec();
deviceConfigSpec.setDevice(nic);
deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD);
vmConfigSpec.getDeviceChange().add(deviceConfigSpec);
setNuageVspVrIpInExtraConfig(vmConfigSpec.getExtraConfig(), nicTo, dvSwitchUuid);
if (!vmMo.configureVm(vmConfigSpec)) {
throw new Exception("Failed to configure devices when running PlugNicCommand");
}
return new PlugNicAnswer(cmd, true, "success");
} catch (Exception e) {
s_logger.error("Unexpected exception: ", e);
return new PlugNicAnswer(cmd, false, "Unable to execute PlugNicCommand due to " + e.toString());
}
}
use of com.vmware.vim25.VirtualDevice in project cloudstack by apache.
the class VmwareHelper method prepareDiskDevice.
// vmdkDatastorePath: [datastore name] vmdkFilePath
public static VirtualDevice prepareDiskDevice(VirtualMachineMO vmMo, VirtualDisk device, int controllerKey, String[] vmdkDatastorePathChain, ManagedObjectReference morDs, int deviceNumber, int contextNumber) throws Exception {
assert (vmdkDatastorePathChain != null);
assert (vmdkDatastorePathChain.length >= 1);
VirtualDisk disk;
VirtualDiskFlatVer2BackingInfo backingInfo;
if (device != null) {
disk = device;
backingInfo = (VirtualDiskFlatVer2BackingInfo) disk.getBacking();
} else {
disk = new VirtualDisk();
backingInfo = new VirtualDiskFlatVer2BackingInfo();
backingInfo.setDatastore(morDs);
backingInfo.setDiskMode(VirtualDiskMode.PERSISTENT.value());
disk.setBacking(backingInfo);
int ideControllerKey = vmMo.getIDEDeviceControllerKey();
if (controllerKey < 0)
controllerKey = ideControllerKey;
if (deviceNumber < 0) {
deviceNumber = vmMo.getNextDeviceNumber(controllerKey);
}
disk.setControllerKey(controllerKey);
disk.setKey(-contextNumber);
disk.setUnitNumber(deviceNumber);
VirtualDeviceConnectInfo connectInfo = new VirtualDeviceConnectInfo();
connectInfo.setConnected(true);
connectInfo.setStartConnected(true);
disk.setConnectable(connectInfo);
}
backingInfo.setFileName(vmdkDatastorePathChain[0]);
if (vmdkDatastorePathChain.length > 1) {
String[] parentDisks = new String[vmdkDatastorePathChain.length - 1];
for (int i = 0; i < vmdkDatastorePathChain.length - 1; i++) parentDisks[i] = vmdkDatastorePathChain[i + 1];
setParentBackingInfo(backingInfo, morDs, parentDisks);
}
return disk;
}
Aggregations