use of com.cloud.hypervisor.vmware.util.VmwareContext in project cloudstack by apache.
the class VmwareResource method execute.
protected Answer execute(CreateVMSnapshotCommand cmd) {
try {
VmwareContext context = getServiceContext();
VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME);
return mgr.getStorageManager().execute(this, cmd);
} catch (Exception e) {
e.printStackTrace();
return new CreateVMSnapshotAnswer(cmd, false, "");
}
}
use of com.cloud.hypervisor.vmware.util.VmwareContext in project CloudStack-archive by CloudStack-extras.
the class HypervisorHostHelper method importVmFromOVF.
public static void importVmFromOVF(VmwareHypervisorHost host, String ovfFilePath, String vmName, DatastoreMO dsMo, String diskOption, ManagedObjectReference morRp, ManagedObjectReference morHost) throws Exception {
assert (morRp != null);
OvfCreateImportSpecParams importSpecParams = new OvfCreateImportSpecParams();
importSpecParams.setHostSystem(morHost);
importSpecParams.setLocale("US");
importSpecParams.setEntityName(vmName);
importSpecParams.setDeploymentOption("");
// diskOption: thin, thick, etc
importSpecParams.setDiskProvisioning(diskOption);
importSpecParams.setPropertyMapping(null);
String ovfDescriptor = HttpNfcLeaseMO.readOvfContent(ovfFilePath);
VmwareContext context = host.getContext();
OvfCreateImportSpecResult ovfImportResult = context.getService().createImportSpec(context.getServiceContent().getOvfManager(), ovfDescriptor, morRp, dsMo.getMor(), importSpecParams);
if (ovfImportResult == null) {
String msg = "createImportSpec() failed. ovfFilePath: " + ovfFilePath + ", vmName: " + vmName + ", diskOption: " + diskOption;
s_logger.error(msg);
throw new Exception(msg);
}
DatacenterMO dcMo = new DatacenterMO(context, host.getHyperHostDatacenter());
ManagedObjectReference morLease = context.getService().importVApp(morRp, ovfImportResult.getImportSpec(), dcMo.getVmFolder(), morHost);
if (morLease == null) {
String msg = "importVApp() failed. ovfFilePath: " + ovfFilePath + ", vmName: " + vmName + ", diskOption: " + diskOption;
s_logger.error(msg);
throw new Exception(msg);
}
final HttpNfcLeaseMO leaseMo = new HttpNfcLeaseMO(context, morLease);
HttpNfcLeaseState state = leaseMo.waitState(new HttpNfcLeaseState[] { HttpNfcLeaseState.ready, HttpNfcLeaseState.error });
try {
if (state == HttpNfcLeaseState.ready) {
final long totalBytes = HttpNfcLeaseMO.calcTotalBytes(ovfImportResult);
File ovfFile = new File(ovfFilePath);
HttpNfcLeaseInfo httpNfcLeaseInfo = leaseMo.getLeaseInfo();
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();
String urlToPost = deviceUrl.getUrl();
urlToPost = resolveHostNameInUrl(dcMo, urlToPost);
context.uploadVmdkFile(ovfFileItem.isCreate() ? "PUT" : "POST", urlToPost, absoluteFile, bytesAlreadyWritten, new ActionDelegate<Long>() {
public void action(Long param) {
progressReporter.reportProgress((int) (param * 100 / totalBytes));
}
});
bytesAlreadyWritten += ovfFileItem.getSize();
}
}
}
} finally {
progressReporter.close();
}
leaseMo.updateLeaseProgress(100);
}
} finally {
leaseMo.completeLease();
}
}
use of com.cloud.hypervisor.vmware.util.VmwareContext in project CloudStack-archive by CloudStack-extras.
the class HypervisorHostHelper method prepareNetwork.
/**
* @param ethPortProfileName
* @param namePrefix
* @param hostMo
* @param vlanId
* @param networkRateMbps
* @param networkRateMulticastMbps
* @param timeOutMs
* @return
* @throws Exception
*/
public static Pair<ManagedObjectReference, String> prepareNetwork(String ethPortProfileName, String namePrefix, HostMO hostMo, String vlanId, Integer networkRateMbps, Integer networkRateMulticastMbps, long timeOutMs) throws Exception {
ManagedObjectReference morNetwork = null;
VmwareContext context = hostMo.getContext();
ManagedObjectReference dcMor = hostMo.getHyperHostDatacenter();
DatacenterMO dataCenterMo = new DatacenterMO(context, dcMor);
ManagedObjectReference 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);
}
boolean createGCTag = false;
String networkName;
Integer vid = null;
if (vlanId != null && !UNTAGGED_VLAN_NAME.equalsIgnoreCase(vlanId)) {
createGCTag = true;
vid = Integer.parseInt(vlanId);
}
networkName = composeCloudNetworkName(namePrefix, vlanId, networkRateMbps, ethPortProfileName);
// TODO(sateesh): Enable this for VMware DVS.
// DVSTrafficShapingPolicy shapingPolicy = null;
// if (networkRateMbps != null && networkRateMbps.intValue() > 0) {
// shapingPolicy = new DVSTrafficShapingPolicy();
// BoolPolicy isEnabled = new BoolPolicy();
// LongPolicy averageBandwidth = new LongPolicy();
// LongPolicy peakBandwidth = new LongPolicy();
// LongPolicy burstSize = new LongPolicy();
//
// isEnabled.setValue(true);
// averageBandwidth.setValue((long) networkRateMbps.intValue() * 1024L * 1024L);
// // We chose 50% higher allocation than average bandwidth.
// // TODO(sateesh): Also let user specify the peak coefficient
// peakBandwidth.setValue((long) (averageBandwidth.getValue() * 1.5));
// // TODO(sateesh): Also let user specify the burst coefficient
// burstSize.setValue((long) (5 * averageBandwidth.getValue() / 8));
//
// shapingPolicy.setEnabled(isEnabled);
// shapingPolicy.setAverageBandwidth(averageBandwidth);
// shapingPolicy.setPeakBandwidth(peakBandwidth);
// shapingPolicy.setBurstSize(burstSize);
// }
DVPortgroupConfigInfo spec = dataCenterMo.getDvPortGroupSpec(networkName);
long averageBandwidth = 0L;
if (networkRateMbps != null && networkRateMbps.intValue() > 0) {
averageBandwidth = (long) (networkRateMbps.intValue() * 1024L * 1024L);
}
// We chose 50% higher allocation than average bandwidth.
// TODO(sateesh): Also let user specify the peak coefficient
long peakBandwidth = (long) (averageBandwidth * 1.5);
// TODO(sateesh): Also let user specify the burst coefficient
long burstSize = 5 * averageBandwidth / 8;
boolean bWaitPortGroupReady = false;
if (!dataCenterMo.hasDvPortGroup(networkName)) {
s_logger.info("Port profile " + networkName + " not found.");
createPortProfile(context, ethPortProfileName, networkName, vid, networkRateMbps, peakBandwidth, burstSize);
bWaitPortGroupReady = true;
} else {
s_logger.info("Port profile " + networkName + " found.");
bWaitPortGroupReady = true;
updatePortProfile(context, ethPortProfileName, 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.cloud.hypervisor.vmware.util.VmwareContext in project cloudstack by apache.
the class HypervisorHostHelper method importVmFromOVF.
public static void importVmFromOVF(VmwareHypervisorHost host, String ovfFilePath, String vmName, DatastoreMO dsMo, String diskOption, ManagedObjectReference morRp, ManagedObjectReference morHost) throws Exception {
assert (morRp != null);
OvfCreateImportSpecParams importSpecParams = new OvfCreateImportSpecParams();
importSpecParams.setHostSystem(morHost);
importSpecParams.setLocale("US");
importSpecParams.setEntityName(vmName);
importSpecParams.setDeploymentOption("");
// diskOption: thin, thick, etc
importSpecParams.setDiskProvisioning(diskOption);
String ovfDescriptor = removeOVFNetwork(HttpNfcLeaseMO.readOvfContent(ovfFilePath));
VmwareContext context = host.getContext();
OvfCreateImportSpecResult ovfImportResult = context.getService().createImportSpec(context.getServiceContent().getOvfManager(), ovfDescriptor, morRp, dsMo.getMor(), importSpecParams);
if (ovfImportResult == null) {
String msg = "createImportSpec() failed. ovfFilePath: " + ovfFilePath + ", vmName: " + vmName + ", diskOption: " + diskOption;
s_logger.error(msg);
throw new Exception(msg);
}
if (!ovfImportResult.getError().isEmpty()) {
for (LocalizedMethodFault fault : ovfImportResult.getError()) {
s_logger.error("createImportSpec error: " + fault.getLocalizedMessage());
}
throw new CloudException("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 = new DatacenterMO(context, host.getHyperHostDatacenter());
ManagedObjectReference morLease = context.getService().importVApp(morRp, ovfImportResult.getImportSpec(), dcMo.getVmFolder(), morHost);
if (morLease == null) {
String msg = "importVApp() failed. ovfFilePath: " + ovfFilePath + ", vmName: " + vmName + ", diskOption: " + diskOption;
s_logger.error(msg);
throw new Exception(msg);
}
boolean importSuccess = true;
final HttpNfcLeaseMO leaseMo = new HttpNfcLeaseMO(context, morLease);
HttpNfcLeaseState state = leaseMo.waitState(new HttpNfcLeaseState[] { HttpNfcLeaseState.READY, HttpNfcLeaseState.ERROR });
try {
if (state == HttpNfcLeaseState.READY) {
final long totalBytes = HttpNfcLeaseMO.calcTotalBytes(ovfImportResult);
File ovfFile = new File(ovfFilePath);
HttpNfcLeaseInfo httpNfcLeaseInfo = leaseMo.getLeaseInfo();
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();
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 Exception(erroMsg);
} 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 Exception(errorMsg, th);
} finally {
progressReporter.close();
}
if (bytesAlreadyWritten == totalBytes) {
leaseMo.updateLeaseProgress(100);
}
} else if (state == HttpNfcLeaseState.ERROR) {
LocalizedMethodFault error = leaseMo.getLeaseError();
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 Exception(erroMsg);
}
} finally {
if (!importSuccess) {
s_logger.error("Aborting the lease on " + vmName + " after import operation failed.");
leaseMo.abortLease();
} else {
leaseMo.completeLease();
}
}
}
use of com.cloud.hypervisor.vmware.util.VmwareContext in project cloudstack by apache.
the class HypervisorHostHelper method prepareNetwork.
/**
* @param ethPortProfileName
* @param namePrefix
* @param hostMo
* @param vlanId
* @param networkRateMbps
* @param networkRateMulticastMbps
* @param timeOutMs
* @param vSwitchType
* @param numPorts
* @return
* @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) 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, BroadcastDomainType.Vsp };
if (!Arrays.asList(supportedBroadcastTypes).contains(broadcastDomainType)) {
throw new InvalidParameterException("BroadcastDomainType " + broadcastDomainType + " it not supported on a VMWare hypervisor at this time.");
}
if (broadcastDomainType == BroadcastDomainType.Lswitch) {
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 {
networkName = composeCloudNetworkName(namePrefix, vlanId, secondaryvlanId, networkRateMbps, physicalNetwork);
if (vlanId != null && !UNTAGGED_VLAN_NAME.equalsIgnoreCase(vlanId)) {
createGCTag = true;
vid = Integer.parseInt(vlanId);
}
if (secondaryvlanId != null) {
spvlanid = Integer.parseInt(secondaryvlanId);
}
}
if (vSwitchType == VirtualSwitchType.VMwareDistributedVirtualSwitch) {
DVSTrafficShapingPolicy shapingPolicy;
DVSSecurityPolicy secPolicy;
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);
} else {
s_logger.debug("Found distributed vSwitch " + dvSwitchName);
}
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 {
dvSwitchMo = new DistributedVirtualSwitchMO(context, morDvSwitch);
shapingPolicy = getDVSShapingPolicy(networkRateMbps);
secPolicy = createDVSSecurityPolicy();
// type isolated.
if (vid != null && spvlanid != null) {
setupPVlanPair(dvSwitchMo, morDvSwitch, vid, spvlanid);
}
VMwareDVSPortgroupPolicy portGroupPolicy = null;
if (broadcastDomainType == BroadcastDomainType.Vsp) {
//If the broadcastDomainType is Vsp, then set the VMwareDVSPortgroupPolicy
portGroupPolicy = new VMwareDVSPortgroupPolicy();
portGroupPolicy.setVlanOverrideAllowed(true);
portGroupPolicy.setBlockOverrideAllowed(true);
portGroupPolicy.setPortConfigResetAtDisconnect(true);
}
// Next, create the port group. For this, we need to create a VLAN spec.
createPortGroup(physicalNetwork, networkName, vid, spvlanid, dataCenterMo, shapingPolicy, secPolicy, portGroupPolicy, dvSwitchMo, numPorts, autoExpandSupported);
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);
}
Aggregations