use of com.vmware.vim25.mo.Network in project cloudstack by apache.
the class VmwareResource method execute.
private ReplugNicAnswer execute(ReplugNicCommand 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 ReplugNic 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"));
}
NicTO nicTo = cmd.getNic();
VirtualDevice nic = findVirtualNicDevice(vmMo, nicTo.getMac());
if (nic == null) {
return new ReplugNicAnswer(cmd, false, "Nic to replug not found");
}
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);
VmwareHelper.updateDvNicDevice(nic, networkInfo.first(), dvSwitchUuid);
} else {
s_logger.info("Preparing NIC device on network " + networkInfo.second());
VmwareHelper.updateNicDevice(nic, networkInfo.first(), networkInfo.second());
}
configureNicDevice(vmMo, nic, VirtualDeviceConfigSpecOperation.EDIT, "ReplugNicCommand");
return new ReplugNicAnswer(cmd, true, "success");
} catch (Exception e) {
s_logger.error("Unexpected exception: ", e);
return new ReplugNicAnswer(cmd, false, "Unable to execute ReplugNicCommand due to " + e.toString());
}
}
use of com.vmware.vim25.mo.Network in project cloudstack by apache.
the class VmwareResource method configure.
@Override
public boolean configure(String name, Map<String, Object> params) throws ConfigurationException {
try {
_name = name;
_url = (String) params.get("url");
_username = (String) params.get("username");
_password = (String) params.get("password");
_dcId = (String) params.get("zone");
_pod = (String) params.get("pod");
_cluster = (String) params.get("cluster");
_guid = (String) params.get("guid");
String[] tokens = _guid.split("@");
_vCenterAddress = tokens[1];
_morHyperHost = new ManagedObjectReference();
String[] hostTokens = tokens[0].split(":");
_morHyperHost.setType(hostTokens[0]);
_morHyperHost.setValue(hostTokens[1]);
_guestTrafficInfo = (VmwareTrafficLabel) params.get("guestTrafficInfo");
_publicTrafficInfo = (VmwareTrafficLabel) params.get("publicTrafficInfo");
VmwareContext context = getServiceContext();
VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
if (mgr == null) {
throw new ConfigurationException("Invalid vmwareContext: vmwareMgr stock object is not set or cleared.");
}
mgr.setupResourceStartupParams(params);
CustomFieldsManagerMO cfmMo = new CustomFieldsManagerMO(context, context.getServiceContent().getCustomFieldsManager());
cfmMo.ensureCustomFieldDef("Datastore", CustomFieldConstants.CLOUD_UUID);
cfmMo.ensureCustomFieldDef("StoragePod", CustomFieldConstants.CLOUD_UUID);
if (_publicTrafficInfo != null && _publicTrafficInfo.getVirtualSwitchType() != VirtualSwitchType.StandardVirtualSwitch || _guestTrafficInfo != null && _guestTrafficInfo.getVirtualSwitchType() != VirtualSwitchType.StandardVirtualSwitch) {
cfmMo.ensureCustomFieldDef("DistributedVirtualPortgroup", CustomFieldConstants.CLOUD_GC_DVP);
}
cfmMo.ensureCustomFieldDef("Network", CustomFieldConstants.CLOUD_GC);
cfmMo.ensureCustomFieldDef("VirtualMachine", CustomFieldConstants.CLOUD_UUID);
cfmMo.ensureCustomFieldDef("VirtualMachine", CustomFieldConstants.CLOUD_NIC_MASK);
cfmMo.ensureCustomFieldDef("VirtualMachine", CustomFieldConstants.CLOUD_VM_INTERNAL_NAME);
cfmMo.ensureCustomFieldDef("VirtualMachine", CustomFieldConstants.CLOUD_WORKER);
cfmMo.ensureCustomFieldDef("VirtualMachine", CustomFieldConstants.CLOUD_WORKER_TAG);
VmwareHypervisorHost hostMo = this.getHyperHost(context);
_hostName = hostMo.getHyperHostName();
if (_guestTrafficInfo.getVirtualSwitchType() == VirtualSwitchType.NexusDistributedVirtualSwitch || _publicTrafficInfo.getVirtualSwitchType() == VirtualSwitchType.NexusDistributedVirtualSwitch) {
_privateNetworkVSwitchName = mgr.getPrivateVSwitchName(Long.parseLong(_dcId), HypervisorType.VMware);
_vsmCredentials = mgr.getNexusVSMCredentialsByClusterId(Long.parseLong(_cluster));
}
if (_privateNetworkVSwitchName == null) {
_privateNetworkVSwitchName = (String) params.get("private.network.vswitch.name");
}
String value = (String) params.get("vmware.recycle.hung.wokervm");
if (value != null && value.equalsIgnoreCase("true"))
_recycleHungWorker = true;
value = (String) params.get("vmware.root.disk.controller");
if (value != null && value.equalsIgnoreCase("scsi"))
_rootDiskController = DiskControllerType.scsi;
else if (value != null && value.equalsIgnoreCase("ide"))
_rootDiskController = DiskControllerType.ide;
else
_rootDiskController = DiskControllerType.osdefault;
Integer intObj = (Integer) params.get("ports.per.dvportgroup");
if (intObj != null)
_portsPerDvPortGroup = intObj.intValue();
s_logger.info("VmwareResource network configuration info." + " private traffic over vSwitch: " + _privateNetworkVSwitchName + ", public traffic over " + _publicTrafficInfo.getVirtualSwitchType() + " : " + _publicTrafficInfo.getVirtualSwitchName() + ", guest traffic over " + _guestTrafficInfo.getVirtualSwitchType() + " : " + _guestTrafficInfo.getVirtualSwitchName());
Boolean boolObj = (Boolean) params.get("vmware.create.full.clone");
if (boolObj != null && boolObj.booleanValue()) {
_fullCloneFlag = true;
} else {
_fullCloneFlag = false;
}
boolObj = (Boolean) params.get("vm.instancename.flag");
if (boolObj != null && boolObj.booleanValue()) {
_instanceNameFlag = true;
} else {
_instanceNameFlag = false;
}
value = (String) params.get("scripts.timeout");
int timeout = NumbersUtil.parseInt(value, 1440) * 1000;
storageNfsVersion = NfsSecondaryStorageResource.retrieveNfsVersionFromParams(params);
_storageProcessor = new VmwareStorageProcessor((VmwareHostService) this, _fullCloneFlag, (VmwareStorageMount) mgr, timeout, this, _shutdownWaitMs, null, storageNfsVersion);
storageHandler = new VmwareStorageSubsystemCommandHandler(_storageProcessor, storageNfsVersion);
_vrResource = new VirtualRoutingResource(this);
if (!_vrResource.configure(name, params)) {
throw new ConfigurationException("Unable to configure VirtualRoutingResource");
}
if (s_logger.isTraceEnabled()) {
s_logger.trace("Successfully configured VmwareResource.");
}
return true;
} catch (Exception e) {
s_logger.error("Unexpected Exception ", e);
throw new ConfigurationException("Failed to configure VmwareResource due to unexpect exception.");
} finally {
recycleServiceContext();
}
}
use of com.vmware.vim25.mo.Network in project cloudstack by apache.
the class HypervisorHostHelper method prepareNetwork.
/**
* Prepares network (for non-standard virtual switch) for the VM NIC based on the parameters.
* Can create a new portgroup or update an existing.
* @return Pair of network's ManagedObjectReference and name
* @throws Exception
*/
public static Pair<ManagedObjectReference, String> prepareNetwork(String physicalNetwork, String namePrefix, HostMO hostMo, String vlanId, String secondaryvlanId, Integer networkRateMbps, Integer networkRateMulticastMbps, long timeOutMs, VirtualSwitchType vSwitchType, int numPorts, String gateway, boolean configureVServiceInNexus, BroadcastDomainType broadcastDomainType, Map<String, String> vsmCredentials, Map<NetworkOffering.Detail, String> details) throws Exception {
ManagedObjectReference morNetwork = null;
VmwareContext context = hostMo.getContext();
ManagedObjectReference dcMor = hostMo.getHyperHostDatacenter();
DatacenterMO dataCenterMo = new DatacenterMO(context, dcMor);
DistributedVirtualSwitchMO dvSwitchMo = null;
ManagedObjectReference morEthernetPortProfile = null;
String ethPortProfileName = null;
ManagedObjectReference morDvSwitch = null;
String dvSwitchName = null;
boolean bWaitPortGroupReady = false;
boolean createGCTag = false;
String vcApiVersion;
String minVcApiVersionSupportingAutoExpand;
boolean autoExpandSupported;
String networkName;
Integer vid = null;
// secondary pvlan id
Integer spvlanid = null;
/**
* This is the list of BroadcastDomainTypes we can actually
* prepare networks for in this function.
*/
BroadcastDomainType[] supportedBroadcastTypes = new BroadcastDomainType[] { BroadcastDomainType.Lswitch, BroadcastDomainType.LinkLocal, BroadcastDomainType.Native, BroadcastDomainType.Pvlan, BroadcastDomainType.Storage, BroadcastDomainType.UnDecided, BroadcastDomainType.Vlan };
if (!Arrays.asList(supportedBroadcastTypes).contains(broadcastDomainType)) {
throw new InvalidParameterException("BroadcastDomainType " + broadcastDomainType + " it not supported on a VMWare hypervisor at this time.");
}
if (broadcastDomainType == BroadcastDomainType.Lswitch) {
if (vSwitchType == VirtualSwitchType.NexusDistributedVirtualSwitch) {
throw new InvalidParameterException("Nexus Distributed Virtualswitch is not supported with BroadcastDomainType " + broadcastDomainType);
}
/**
* Nicira NVP requires all vms to be connected to a single port-group.
* A unique vlan needs to be set per port. This vlan is specific to
* this implementation and has no reference to other vlans in CS
*/
// FIXME Should be set via a configuration item in CS
networkName = "br-int";
// No doubt about this, depending on vid=null to avoid lots of code below
vid = null;
} else {
if (vlanId != null) {
vlanId = vlanId.replace("vlan://", "");
}
networkName = composeCloudNetworkName(namePrefix, vlanId, secondaryvlanId, networkRateMbps, physicalNetwork);
if (vlanId != null && !UNTAGGED_VLAN_NAME.equalsIgnoreCase(vlanId) && !StringUtils.containsAny(vlanId, ",-")) {
createGCTag = true;
vid = Integer.parseInt(vlanId);
}
if (vlanId != null && StringUtils.containsAny(vlanId, ",-")) {
createGCTag = true;
}
if (secondaryvlanId != null) {
spvlanid = Integer.parseInt(secondaryvlanId);
}
}
if (vSwitchType == VirtualSwitchType.VMwareDistributedVirtualSwitch) {
vcApiVersion = getVcenterApiVersion(context);
minVcApiVersionSupportingAutoExpand = "5.0";
autoExpandSupported = isFeatureSupportedInVcenterApiVersion(vcApiVersion, minVcApiVersionSupportingAutoExpand);
dvSwitchName = physicalNetwork;
// and switch types.
if (dvSwitchName == null) {
s_logger.warn("Detected null dvSwitch. Defaulting to dvSwitch0");
dvSwitchName = "dvSwitch0";
}
morDvSwitch = dataCenterMo.getDvSwitchMor(dvSwitchName);
if (morDvSwitch == null) {
String msg = "Unable to find distributed vSwitch " + dvSwitchName;
s_logger.error(msg);
throw new Exception(msg);
}
dvSwitchMo = new DistributedVirtualSwitchMO(context, morDvSwitch);
String dvSwitchVersion = dvSwitchMo.getDVSProductVersion(morDvSwitch);
s_logger.debug(String.format("Found distributed vSwitch: %s with product version: %s", dvSwitchName, dvSwitchVersion));
if (broadcastDomainType == BroadcastDomainType.Lswitch) {
if (!dataCenterMo.hasDvPortGroup(networkName)) {
throw new InvalidParameterException("NVP integration port-group " + networkName + " does not exist on the DVS " + dvSwitchName);
}
bWaitPortGroupReady = false;
} else {
boolean dvSwitchSupportNewPolicies = (isFeatureSupportedInVcenterApiVersion(vcApiVersion, MINIMUM_VCENTER_API_VERSION_WITH_DVS_NEW_POLICIES_SUPPORT) && isVersionEqualOrHigher(dvSwitchVersion, MINIMUM_DVS_VERSION_WITH_NEW_POLICIES_SUPPORT));
DVSTrafficShapingPolicy shapingPolicy = getDVSShapingPolicy(networkRateMbps);
DVSSecurityPolicy secPolicy = createDVSSecurityPolicy(details);
DVSMacManagementPolicy macManagementPolicy = createDVSMacManagementPolicy(details);
// First, if both vlan id and pvlan id are provided, we need to
// reconfigure the DVSwitch to have a tuple <vlan id, pvlan id> of
// type isolated.
String pvlanType = MapUtils.isNotEmpty(details) ? details.get(NetworkOffering.Detail.pvlanType) : null;
if (vid != null && spvlanid != null) {
setupPVlanPair(dvSwitchMo, morDvSwitch, vid, spvlanid, pvlanType);
}
VMwareDVSPortgroupPolicy portGroupPolicy = null;
// Next, create the port group. For this, we need to create a VLAN spec.
createPortGroup(physicalNetwork, networkName, vlanId, vid, spvlanid, dataCenterMo, shapingPolicy, secPolicy, macManagementPolicy, portGroupPolicy, dvSwitchMo, numPorts, autoExpandSupported, dvSwitchSupportNewPolicies);
bWaitPortGroupReady = true;
}
} else if (vSwitchType == VirtualSwitchType.NexusDistributedVirtualSwitch) {
ethPortProfileName = physicalNetwork;
// and switch types.
if (ethPortProfileName == null) {
s_logger.warn("Detected null ethrenet port profile. Defaulting to epp0.");
ethPortProfileName = "epp0";
}
morEthernetPortProfile = dataCenterMo.getDvPortGroupMor(ethPortProfileName);
if (morEthernetPortProfile == null) {
String msg = "Unable to find Ethernet port profile " + ethPortProfileName;
s_logger.error(msg);
throw new Exception(msg);
} else {
s_logger.info("Found Ethernet port profile " + ethPortProfileName);
}
long averageBandwidth = 0L;
if (networkRateMbps != null && networkRateMbps.intValue() > 0) {
averageBandwidth = networkRateMbps.intValue() * 1024L * 1024L;
}
// We chose 50% higher allocation than average bandwidth.
// TODO(sateesh): Optionally let user specify the peak coefficient
long peakBandwidth = (long) (averageBandwidth * 1.5);
// TODO(sateesh): Optionally let user specify the burst coefficient
long burstSize = 5 * averageBandwidth / 8;
if (vsmCredentials != null) {
s_logger.info("Stocking credentials of Nexus VSM");
context.registerStockObject("vsmcredentials", vsmCredentials);
}
if (!dataCenterMo.hasDvPortGroup(networkName)) {
s_logger.info("Port profile " + networkName + " not found.");
createPortProfile(context, physicalNetwork, networkName, vid, networkRateMbps, peakBandwidth, burstSize, gateway, configureVServiceInNexus);
bWaitPortGroupReady = true;
} else {
s_logger.info("Port profile " + networkName + " found.");
updatePortProfile(context, physicalNetwork, networkName, vid, networkRateMbps, peakBandwidth, burstSize);
}
}
// Wait for dvPortGroup on vCenter
if (bWaitPortGroupReady)
morNetwork = waitForDvPortGroupReady(dataCenterMo, networkName, timeOutMs);
else
morNetwork = dataCenterMo.getDvPortGroupMor(networkName);
if (morNetwork == null) {
String msg = "Failed to create guest network " + networkName;
s_logger.error(msg);
throw new Exception(msg);
}
if (createGCTag) {
NetworkMO networkMo = new NetworkMO(hostMo.getContext(), morNetwork);
networkMo.setCustomFieldValue(CustomFieldConstants.CLOUD_GC_DVP, "true");
s_logger.debug("Added custom field : " + CustomFieldConstants.CLOUD_GC_DVP);
}
return new Pair<ManagedObjectReference, String>(morNetwork, networkName);
}
use of com.vmware.vim25.mo.Network in project cloudstack by apache.
the class HypervisorHostHelper method prepareNetwork.
public static Pair<ManagedObjectReference, String> prepareNetwork(String vSwitchName, String namePrefix, HostMO hostMo, String vlanId, Integer networkRateMbps, Integer networkRateMulticastMbps, long timeOutMs, boolean syncPeerHosts, BroadcastDomainType broadcastDomainType, String nicUuid, Map<NetworkOffering.Detail, String> nicDetails) throws Exception {
HostVirtualSwitch vSwitch;
if (vSwitchName == null) {
s_logger.info("Detected vswitch name as undefined. Defaulting to vSwitch0");
vSwitchName = "vSwitch0";
}
vSwitch = hostMo.getHostVirtualSwitchByName(vSwitchName);
if (vSwitch == null) {
String msg = "Unable to find vSwitch" + vSwitchName;
s_logger.error(msg);
throw new Exception(msg);
}
boolean createGCTag = false;
String networkName;
Integer vid = null;
/**
* This is the list of BroadcastDomainTypes we can actually
* prepare networks for in this function.
*/
BroadcastDomainType[] supportedBroadcastTypes = new BroadcastDomainType[] { BroadcastDomainType.Lswitch, BroadcastDomainType.LinkLocal, BroadcastDomainType.Native, BroadcastDomainType.Pvlan, BroadcastDomainType.Storage, BroadcastDomainType.UnDecided, BroadcastDomainType.Vlan };
if (!Arrays.asList(supportedBroadcastTypes).contains(broadcastDomainType)) {
throw new InvalidParameterException("BroadcastDomainType " + broadcastDomainType + " it not supported on a VMWare hypervisor at this time.");
}
if (broadcastDomainType == BroadcastDomainType.Lswitch) {
/**
* Nicira NVP requires each vm to have its own port-group with a dedicated
* vlan. We'll set the name of the pg to the uuid of the nic.
*/
networkName = nicUuid;
// No doubt about this, depending on vid=null to avoid lots of code below
vid = null;
} else {
networkName = composeCloudNetworkName(namePrefix, vlanId, null, networkRateMbps, vSwitchName);
if (vlanId != null && !UNTAGGED_VLAN_NAME.equalsIgnoreCase(vlanId)) {
createGCTag = true;
vid = Integer.parseInt(vlanId);
}
}
HostNetworkSecurityPolicy secPolicy = createVSSecurityPolicy(nicDetails);
HostNetworkTrafficShapingPolicy shapingPolicy = null;
if (networkRateMbps != null && networkRateMbps.intValue() > 0) {
shapingPolicy = new HostNetworkTrafficShapingPolicy();
shapingPolicy.setEnabled(true);
shapingPolicy.setAverageBandwidth(networkRateMbps.intValue() * 1024L * 1024L);
//
// TODO : people may have different opinion on how to set the following
//
// give 50% premium to peek
shapingPolicy.setPeakBandwidth((long) (shapingPolicy.getAverageBandwidth() * 1.5));
// allow 5 seconds of burst transfer
shapingPolicy.setBurstSize(5 * shapingPolicy.getAverageBandwidth() / 8);
}
boolean bWaitPortGroupReady = false;
if (broadcastDomainType == BroadcastDomainType.Lswitch) {
// if NSX API VERSION >= 4.2, connect to br-int (nsx.network), do not create portgroup else previous behaviour
if (NiciraNvpApiVersion.isApiVersionLowerThan("4.2")) {
// Previous behaviour
if (!hostMo.hasPortGroup(vSwitch, networkName)) {
createNvpPortGroup(hostMo, vSwitch, networkName, shapingPolicy);
bWaitPortGroupReady = true;
} else {
bWaitPortGroupReady = false;
}
}
} else {
if (!hostMo.hasPortGroup(vSwitch, networkName)) {
hostMo.createPortGroup(vSwitch, networkName, vid, secPolicy, shapingPolicy, timeOutMs);
// Setting flag "bWaitPortGroupReady" to false.
// This flag indicates whether we need to wait for portgroup on vCenter.
// Above createPortGroup() method itself ensures creation of portgroup as well as wait for portgroup.
bWaitPortGroupReady = false;
} else {
HostPortGroupSpec spec = hostMo.getPortGroupSpec(networkName);
if (!isSpecMatch(spec, vid, secPolicy, shapingPolicy)) {
hostMo.updatePortGroup(vSwitch, networkName, vid, secPolicy, shapingPolicy);
bWaitPortGroupReady = true;
}
}
}
ManagedObjectReference morNetwork = null;
if (broadcastDomainType != BroadcastDomainType.Lswitch || (broadcastDomainType == BroadcastDomainType.Lswitch && NiciraNvpApiVersion.isApiVersionLowerThan("4.2"))) {
if (bWaitPortGroupReady)
morNetwork = waitForNetworkReady(hostMo, networkName, timeOutMs);
else
morNetwork = hostMo.getNetworkMor(networkName);
if (morNetwork == null) {
String msg = "Failed to create guest network " + networkName;
s_logger.error(msg);
throw new Exception(msg);
}
if (createGCTag) {
NetworkMO networkMo = new NetworkMO(hostMo.getContext(), morNetwork);
networkMo.setCustomFieldValue(CustomFieldConstants.CLOUD_GC, "true");
}
}
if (syncPeerHosts) {
ManagedObjectReference morParent = hostMo.getParentMor();
if (morParent != null && morParent.getType().equals("ClusterComputeResource")) {
// to be conservative, lock cluster
GlobalLock lock = GlobalLock.getInternLock("ClusterLock." + morParent.getValue());
try {
if (lock.lock(DEFAULT_LOCK_TIMEOUT_SECONDS)) {
try {
List<ManagedObjectReference> hosts = hostMo.getContext().getVimClient().getDynamicProperty(morParent, "host");
if (hosts != null) {
for (ManagedObjectReference otherHost : hosts) {
if (!otherHost.getValue().equals(hostMo.getMor().getValue())) {
HostMO otherHostMo = new HostMO(hostMo.getContext(), otherHost);
try {
if (s_logger.isDebugEnabled())
s_logger.debug("Prepare network on other host, vlan: " + vlanId + ", host: " + otherHostMo.getHostName());
prepareNetwork(vSwitchName, namePrefix, otherHostMo, vlanId, networkRateMbps, networkRateMulticastMbps, timeOutMs, false, broadcastDomainType, nicUuid, nicDetails);
} catch (Exception e) {
s_logger.warn("Unable to prepare network on other host, vlan: " + vlanId + ", host: " + otherHostMo.getHostName());
}
}
}
}
} finally {
lock.unlock();
}
} else {
s_logger.warn("Unable to lock cluster to prepare guest network, vlan: " + vlanId);
}
} finally {
lock.releaseRef();
}
}
}
s_logger.info("Network " + networkName + " is ready on vSwitch " + vSwitchName);
return new Pair<ManagedObjectReference, String>(morNetwork, networkName);
}
use of com.vmware.vim25.mo.Network in project cloudstack by apache.
the class HypervisorHostHelper method importVmFromOVF.
/**
* deploys a new VM from a ovf spec. It ignores network, defaults locale to 'US'
* @throws Exception shoud be a VmwareResourceException
*/
public static void importVmFromOVF(VmwareHypervisorHost host, String ovfFilePath, String vmName, DatastoreMO dsMo, String diskOption, ManagedObjectReference morRp, ManagedObjectReference morHost, String configurationId) throws CloudRuntimeException, IOException {
assert (morRp != null);
OvfCreateImportSpecParams importSpecParams = new OvfCreateImportSpecParams();
importSpecParams.setHostSystem(morHost);
importSpecParams.setLocale("US");
importSpecParams.setEntityName(vmName);
String deploymentOption = StringUtils.isNotBlank(configurationId) ? configurationId : "";
importSpecParams.setDeploymentOption(deploymentOption);
// diskOption: thin, thick, etc
importSpecParams.setDiskProvisioning(diskOption);
String ovfDescriptor = removeOVFNetwork(HttpNfcLeaseMO.readOvfContent(ovfFilePath));
VmwareContext context = host.getContext();
OvfCreateImportSpecResult ovfImportResult = null;
try {
ovfImportResult = context.getService().createImportSpec(context.getServiceContent().getOvfManager(), ovfDescriptor, morRp, dsMo.getMor(), importSpecParams);
} catch (ConcurrentAccessFaultMsg | FileFaultFaultMsg | InvalidDatastoreFaultMsg | InvalidStateFaultMsg | RuntimeFaultFaultMsg | TaskInProgressFaultMsg | VmConfigFaultFaultMsg error) {
throw new CloudRuntimeException("ImportSpec creation failed", error);
}
if (ovfImportResult == null) {
String msg = "createImportSpec() failed. ovfFilePath: " + ovfFilePath + ", vmName: " + vmName + ", diskOption: " + diskOption;
s_logger.error(msg);
throw new CloudRuntimeException(msg);
}
if (!ovfImportResult.getError().isEmpty()) {
for (LocalizedMethodFault fault : ovfImportResult.getError()) {
s_logger.error("createImportSpec error: " + fault.getLocalizedMessage());
}
throw new CloudRuntimeException("Failed to create an import spec from " + ovfFilePath + ". Check log for details.");
}
if (!ovfImportResult.getWarning().isEmpty()) {
for (LocalizedMethodFault fault : ovfImportResult.getError()) {
s_logger.warn("createImportSpec warning: " + fault.getLocalizedMessage());
}
}
DatacenterMO dcMo = null;
try {
dcMo = new DatacenterMO(context, host.getHyperHostDatacenter());
} catch (Exception e) {
throw new CloudRuntimeException(String.format("no datacenter for host '%s' available in context", context.getServerAddress()), e);
}
ManagedObjectReference folderMO = null;
try {
folderMO = dcMo.getVmFolder();
} catch (Exception e) {
throw new CloudRuntimeException("no management handle for VmFolder", e);
}
ManagedObjectReference morLease = null;
try {
morLease = context.getService().importVApp(morRp, ovfImportResult.getImportSpec(), folderMO, morHost);
} catch (DuplicateNameFaultMsg | FileFaultFaultMsg | InsufficientResourcesFaultFaultMsg | InvalidDatastoreFaultMsg | InvalidNameFaultMsg | OutOfBoundsFaultMsg | RuntimeFaultFaultMsg | VmConfigFaultFaultMsg fault) {
throw new CloudRuntimeException("import vApp failed", fault);
}
if (morLease == null) {
String msg = "importVApp() failed. ovfFilePath: " + ovfFilePath + ", vmName: " + vmName + ", diskOption: " + diskOption;
s_logger.error(msg);
throw new CloudRuntimeException(msg);
}
boolean importSuccess = true;
final HttpNfcLeaseMO leaseMo = new HttpNfcLeaseMO(context, morLease);
HttpNfcLeaseState state = null;
try {
state = leaseMo.waitState(new HttpNfcLeaseState[] { HttpNfcLeaseState.READY, HttpNfcLeaseState.ERROR });
} catch (Exception e) {
throw new CloudRuntimeException("exception while waiting for leaseMO", e);
}
try {
if (state == HttpNfcLeaseState.READY) {
final long totalBytes = HttpNfcLeaseMO.calcTotalBytes(ovfImportResult);
File ovfFile = new File(ovfFilePath);
HttpNfcLeaseInfo httpNfcLeaseInfo = null;
try {
httpNfcLeaseInfo = leaseMo.getLeaseInfo();
} catch (Exception e) {
throw new CloudRuntimeException("error waiting for lease info", e);
}
List<HttpNfcLeaseDeviceUrl> deviceUrls = httpNfcLeaseInfo.getDeviceUrl();
long bytesAlreadyWritten = 0;
final HttpNfcLeaseMO.ProgressReporter progressReporter = leaseMo.createProgressReporter();
try {
for (HttpNfcLeaseDeviceUrl deviceUrl : deviceUrls) {
String deviceKey = deviceUrl.getImportKey();
for (OvfFileItem ovfFileItem : ovfImportResult.getFileItem()) {
if (deviceKey.equals(ovfFileItem.getDeviceId())) {
String absoluteFile = ovfFile.getParent() + File.separator + ovfFileItem.getPath();
s_logger.info("Uploading file: " + absoluteFile);
File f = new File(absoluteFile);
if (f.exists()) {
String urlToPost = deviceUrl.getUrl();
urlToPost = resolveHostNameInUrl(dcMo, urlToPost);
context.uploadVmdkFile(ovfFileItem.isCreate() ? "PUT" : "POST", urlToPost, absoluteFile, bytesAlreadyWritten, new ActionDelegate<Long>() {
@Override
public void action(Long param) {
progressReporter.reportProgress((int) (param * 100 / totalBytes));
}
});
bytesAlreadyWritten += ovfFileItem.getSize();
}
}
}
}
} catch (Exception e) {
String erroMsg = "File upload task failed to complete due to: " + e.getMessage();
s_logger.error(erroMsg);
// Set flag to cleanup the stale template left due to failed import operation, if any
importSuccess = false;
throw new CloudRuntimeException(erroMsg, e);
} catch (Throwable th) {
String errorMsg = "throwable caught during file upload task: " + th.getMessage();
s_logger.error(errorMsg);
// Set flag to cleanup the stale template left due to failed import operation, if any
importSuccess = false;
throw new CloudRuntimeException(errorMsg, th);
} finally {
progressReporter.close();
}
if (bytesAlreadyWritten == totalBytes) {
try {
leaseMo.updateLeaseProgress(100);
} catch (Exception e) {
throw new CloudRuntimeException("error while waiting for lease update", e);
}
}
} else if (state == HttpNfcLeaseState.ERROR) {
LocalizedMethodFault error = null;
try {
error = leaseMo.getLeaseError();
} catch (Exception e) {
throw new CloudRuntimeException("error getting lease error", e);
}
MethodFault fault = error.getFault();
String erroMsg = "Object creation on vCenter failed due to: Exception: " + fault.getClass().getName() + ", message: " + error.getLocalizedMessage();
s_logger.error(erroMsg);
throw new CloudRuntimeException(erroMsg);
}
} finally {
try {
if (!importSuccess) {
s_logger.error("Aborting the lease on " + vmName + " after import operation failed.");
leaseMo.abortLease();
} else {
leaseMo.completeLease();
}
} catch (Exception e) {
throw new CloudRuntimeException("error completing lease", e);
}
}
}
Aggregations