use of com.vmware.vim25.VirtualMachineRuntimeInfo in project CloudStack-archive by CloudStack-extras.
the class VirtualMachineMO method exportVm.
public void exportVm(String exportDir, String exportName, boolean packToOva, boolean leaveOvaFileOnly) throws Exception {
ManagedObjectReference morOvf = _context.getServiceContent().getOvfManager();
VirtualMachineRuntimeInfo runtimeInfo = getRuntimeInfo();
HostMO hostMo = new HostMO(_context, runtimeInfo.getHost());
String hostName = hostMo.getHostName();
String vmName = getVmName();
DatacenterMO dcMo = new DatacenterMO(_context, hostMo.getHyperHostDatacenter());
if (runtimeInfo.getPowerState() != VirtualMachinePowerState.poweredOff) {
String msg = "Unable to export VM because it is not at powerdOff state. vmName: " + vmName + ", host: " + hostName;
s_logger.error(msg);
throw new Exception(msg);
}
ManagedObjectReference morLease = _context.getService().exportVm(getMor());
if (morLease == null) {
s_logger.error("exportVm() failed");
throw new Exception("exportVm() failed");
}
HttpNfcLeaseMO leaseMo = new HttpNfcLeaseMO(_context, morLease);
HttpNfcLeaseState state = leaseMo.waitState(new HttpNfcLeaseState[] { HttpNfcLeaseState.ready, HttpNfcLeaseState.error });
try {
if (state == HttpNfcLeaseState.ready) {
final HttpNfcLeaseMO.ProgressReporter progressReporter = leaseMo.createProgressReporter();
boolean success = false;
List<String> fileNames = new ArrayList<String>();
try {
HttpNfcLeaseInfo leaseInfo = leaseMo.getLeaseInfo();
final long totalBytes = leaseInfo.getTotalDiskCapacityInKB() * 1024;
long totalBytesDownloaded = 0;
HttpNfcLeaseDeviceUrl[] deviceUrls = leaseInfo.getDeviceUrl();
if (deviceUrls != null) {
OvfFile[] ovfFiles = new OvfFile[deviceUrls.length];
for (int i = 0; i < deviceUrls.length; i++) {
String deviceId = deviceUrls[i].getKey();
String deviceUrlStr = deviceUrls[i].getUrl();
String orgDiskFileName = deviceUrlStr.substring(deviceUrlStr.lastIndexOf("/") + 1);
String diskFileName = String.format("%s-disk%d%s", exportName, i, VmwareHelper.getFileExtension(orgDiskFileName, ".vmdk"));
String diskUrlStr = deviceUrlStr.replace("*", hostName);
diskUrlStr = HypervisorHostHelper.resolveHostNameInUrl(dcMo, diskUrlStr);
String diskLocalPath = exportDir + File.separator + diskFileName;
fileNames.add(diskLocalPath);
if (s_logger.isInfoEnabled()) {
s_logger.info("Download VMDK file for export. url: " + deviceUrlStr);
}
long lengthOfDiskFile = _context.downloadVmdkFile(diskUrlStr, diskLocalPath, totalBytesDownloaded, new ActionDelegate<Long>() {
@Override
public void action(Long param) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Download progress " + param + "/" + totalBytes);
}
progressReporter.reportProgress((int) (param * 100 / totalBytes));
}
});
totalBytesDownloaded += lengthOfDiskFile;
OvfFile ovfFile = new OvfFile();
ovfFile.setPath(diskFileName);
ovfFile.setDeviceId(deviceId);
ovfFile.setSize(lengthOfDiskFile);
ovfFiles[i] = ovfFile;
}
// write OVF descriptor file
OvfCreateDescriptorParams ovfDescParams = new OvfCreateDescriptorParams();
ovfDescParams.setOvfFiles(ovfFiles);
OvfCreateDescriptorResult ovfCreateDescriptorResult = _context.getService().createDescriptor(morOvf, getMor(), ovfDescParams);
String ovfPath = exportDir + File.separator + exportName + ".ovf";
fileNames.add(ovfPath);
FileWriter out = new FileWriter(ovfPath);
out.write(ovfCreateDescriptorResult.getOvfDescriptor());
out.close();
// tar files into OVA
if (packToOva) {
// Important! we need to sync file system before we can safely use tar to work around a linux kernal bug(or feature)
s_logger.info("Sync file system before we package OVA...");
Script commandSync = new Script(true, "sync", 0, s_logger);
commandSync.execute();
Script command = new Script(false, "tar", 0, s_logger);
command.setWorkDir(exportDir);
command.add("-cf", exportName + ".ova");
// OVF file should be the first file in OVA archive
command.add(exportName + ".ovf");
for (String name : fileNames) {
command.add((new File(name).getName()));
}
s_logger.info("Package OVA with commmand: " + command.toString());
command.execute();
// to be safe, physically test existence of the target OVA file
if ((new File(exportDir + File.separator + exportName + ".ova")).exists()) {
success = true;
} else {
s_logger.error(exportDir + File.separator + exportName + ".ova is not created as expected");
}
}
}
} catch (Throwable e) {
s_logger.error("Unexpected exception ", e);
} finally {
progressReporter.close();
if (leaveOvaFileOnly) {
for (String name : fileNames) {
new File(name).delete();
}
}
if (!success)
throw new Exception("Unable to finish the whole process to package as a OVA file");
}
}
} finally {
leaseMo.updateLeaseProgress(100);
leaseMo.completeLease();
}
}
use of com.vmware.vim25.VirtualMachineRuntimeInfo in project cloudstack by apache.
the class VirtualMachineMO method detachIso.
public void detachIso(String isoDatastorePath) throws Exception {
if (s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - detachIso(). target MOR: " + _mor.getValue() + ", isoDatastorePath: " + isoDatastorePath);
VirtualDevice device = getIsoDevice();
if (device == null) {
if (s_logger.isTraceEnabled())
s_logger.trace("vCenter API trace - detachIso() done(failed)");
throw new Exception("Unable to find a CDROM device");
}
VirtualCdromRemotePassthroughBackingInfo backingInfo = new VirtualCdromRemotePassthroughBackingInfo();
backingInfo.setDeviceName("");
device.setBacking(backingInfo);
VirtualMachineConfigSpec reConfigSpec = new VirtualMachineConfigSpec();
//VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1];
VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec();
deviceConfigSpec.setDevice(device);
deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.EDIT);
//deviceConfigSpecArray[0] = deviceConfigSpec;
reConfigSpec.getDeviceChange().add(deviceConfigSpec);
ManagedObjectReference morTask = _context.getService().reconfigVMTask(_mor, reConfigSpec);
// Monitor VM questions
final Boolean[] flags = { false };
final VirtualMachineMO vmMo = this;
Future<?> future = MonitorServiceExecutor.submit(new Runnable() {
@Override
public void run() {
s_logger.info("VM Question monitor started...");
while (!flags[0]) {
try {
VirtualMachineRuntimeInfo runtimeInfo = vmMo.getRuntimeInfo();
VirtualMachineQuestionInfo question = runtimeInfo.getQuestion();
if (question != null) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Question id: " + question.getId());
s_logger.trace("Question text: " + question.getText());
}
if (question.getMessage() != null) {
for (VirtualMachineMessage msg : question.getMessage()) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("msg id: " + msg.getId());
s_logger.trace("msg text: " + msg.getText());
}
if ("msg.cdromdisconnect.locked".equalsIgnoreCase(msg.getId())) {
s_logger.info("Found that VM has a pending question that we need to answer programmatically, question id: " + msg.getId() + ", for safe operation we will automatically decline it");
vmMo.answerVM(question.getId(), "1");
break;
}
}
} else if (question.getText() != null) {
String text = question.getText();
String msgId;
String msgText;
if (s_logger.isDebugEnabled()) {
s_logger.debug("question text : " + text);
}
String[] tokens = text.split(":");
msgId = tokens[0];
msgText = tokens[1];
if ("msg.cdromdisconnect.locked".equalsIgnoreCase(msgId)) {
s_logger.info("Found that VM has a pending question that we need to answer programmatically, question id: " + question.getId() + ". Message id : " + msgId + ". Message text : " + msgText + ", for safe operation we will automatically decline it.");
vmMo.answerVM(question.getId(), "1");
}
}
ChoiceOption choice = question.getChoice();
if (choice != null) {
for (ElementDescription info : choice.getChoiceInfo()) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Choice option key: " + info.getKey());
s_logger.trace("Choice option label: " + info.getLabel());
}
}
}
}
} catch (Throwable e) {
s_logger.error("Unexpected exception: ", e);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
s_logger.debug("[ignored] interupted while handling vm question about iso detach.");
}
}
s_logger.info("VM Question monitor stopped");
}
});
try {
boolean result = _context.getVimClient().waitForTask(morTask);
if (!result) {
if (s_logger.isDebugEnabled())
s_logger.trace("vCenter API trace - detachIso() done(failed)");
throw new Exception("Failed to detachIso due to " + TaskMO.getTaskFailureInfo(_context, morTask));
}
_context.waitForTaskProgressDone(morTask);
s_logger.trace("vCenter API trace - detachIso() done(successfully)");
} finally {
flags[0] = true;
future.cancel(true);
}
}
use of com.vmware.vim25.VirtualMachineRuntimeInfo in project opennms by OpenNMS.
the class VmwareMonitor method poll.
/**
* This method queries the Vmware vCenter server for sensor data.
*
* @param svc the monitored service
* @param parameters the parameter map
* @return the poll status for this system
*/
@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
final boolean ignoreStandBy = getKeyedBoolean(parameters, "ignoreStandBy", false);
final String vmwareManagementServer = getKeyedString(parameters, VMWARE_MANAGEMENT_SERVER_KEY, null);
final String vmwareManagedEntityType = getKeyedString(parameters, VMWARE_MANAGED_ENTITY_TYPE_KEY, null);
final String vmwareManagedObjectId = getKeyedString(parameters, VMWARE_MANAGED_OBJECT_ID_KEY, null);
final String vmwareMangementServerUsername = getKeyedString(parameters, VMWARE_MANAGEMENT_SERVER_USERNAME_KEY, null);
final String vmwareMangementServerPassword = getKeyedString(parameters, VMWARE_MANAGEMENT_SERVER_PASSWORD_KEY, null);
final TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
PollStatus serviceStatus = PollStatus.unknown();
for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) {
final VmwareViJavaAccess vmwareViJavaAccess = new VmwareViJavaAccess(vmwareManagementServer, vmwareMangementServerUsername, vmwareMangementServerPassword);
try {
vmwareViJavaAccess.connect();
} catch (MalformedURLException e) {
logger.warn("Error connecting VMware management server '{}': '{}' exception: {} cause: '{}'", vmwareManagementServer, e.getMessage(), e.getClass().getName(), e.getCause());
return PollStatus.unavailable("Error connecting VMware management server '" + vmwareManagementServer + "'");
} catch (RemoteException e) {
logger.warn("Error connecting VMware management server '{}': '{}' exception: {} cause: '{}'", vmwareManagementServer, e.getMessage(), e.getClass().getName(), e.getCause());
return PollStatus.unavailable("Error connecting VMware management server '" + vmwareManagementServer + "'");
}
if (!vmwareViJavaAccess.setTimeout(tracker.getConnectionTimeout())) {
logger.warn("Error setting connection timeout for VMware management server '{}'", vmwareManagementServer);
}
String powerState = "unknown";
if ("HostSystem".equals(vmwareManagedEntityType)) {
HostSystem hostSystem = vmwareViJavaAccess.getHostSystemByManagedObjectId(vmwareManagedObjectId);
if (hostSystem == null) {
return PollStatus.unknown("hostSystem=null");
} else {
HostRuntimeInfo hostRuntimeInfo = hostSystem.getRuntime();
if (hostRuntimeInfo == null) {
return PollStatus.unknown("hostRuntimeInfo=null");
} else {
HostSystemPowerState hostSystemPowerState = hostRuntimeInfo.getPowerState();
if (hostSystemPowerState == null) {
return PollStatus.unknown("hostSystemPowerState=null");
} else {
powerState = hostSystemPowerState.toString();
}
}
}
} else {
if ("VirtualMachine".equals(vmwareManagedEntityType)) {
VirtualMachine virtualMachine = vmwareViJavaAccess.getVirtualMachineByManagedObjectId(vmwareManagedObjectId);
if (virtualMachine == null) {
return PollStatus.unknown("virtualMachine=null");
} else {
VirtualMachineRuntimeInfo virtualMachineRuntimeInfo = virtualMachine.getRuntime();
if (virtualMachineRuntimeInfo == null) {
return PollStatus.unknown("virtualMachineRuntimeInfo=null");
} else {
VirtualMachinePowerState virtualMachinePowerState = virtualMachineRuntimeInfo.getPowerState();
if (virtualMachinePowerState == null) {
return PollStatus.unknown("virtualMachinePowerState=null");
} else {
powerState = virtualMachinePowerState.toString();
}
}
}
} else {
logger.warn("Error getting '{}' for '{}'", vmwareManagedEntityType, vmwareManagedObjectId);
vmwareViJavaAccess.disconnect();
return serviceStatus;
}
}
if ("poweredOn".equals(powerState)) {
serviceStatus = PollStatus.available();
} else {
if (ignoreStandBy && "standBy".equals(powerState)) {
serviceStatus = PollStatus.up();
} else {
serviceStatus = PollStatus.unavailable("The system's state is '" + powerState + "'");
}
}
vmwareViJavaAccess.disconnect();
}
return serviceStatus;
}
use of com.vmware.vim25.VirtualMachineRuntimeInfo in project opennms by OpenNMS.
the class VmwareImporter method createRequisitionNode.
/**
* Creates a requisition node for the given managed entity and type.
*
* @param ipAddresses the set of Ip addresses
* @param managedEntity the managed entity
* @return the generated requisition node
*/
private RequisitionNode createRequisitionNode(Set<String> ipAddresses, ManagedEntity managedEntity, int apiVersion, VmwareViJavaAccess vmwareViJavaAccess) {
RequisitionNode requisitionNode = new RequisitionNode();
// Setting the node label
requisitionNode.setNodeLabel(managedEntity.getName());
// Foreign Id consisting of managed entity Id
requisitionNode.setForeignId(managedEntity.getMOR().getVal());
/*
* Original version:
*
* Foreign Id consisting of VMware management server's hostname and managed entity id
*
* requisitionNode.setForeignId(m_hostname + "/" + managedEntity.getMOR().getVal());
*/
logger.debug("Start primary interface search for managed entity '{}' (ID: {})", managedEntity.getName(), managedEntity.getMOR().getVal());
if (managedEntity instanceof VirtualMachine) {
boolean firstInterface = true;
// add all given interfaces
for (String ipAddress : ipAddresses) {
try {
if ((request.isPersistIPv4() && InetAddressUtils.isIPv4Address(ipAddress)) || (request.isPersistIPv6() && InetAddressUtils.isIPv6Address(ipAddress))) {
InetAddress inetAddress = InetAddress.getByName(ipAddress);
if (!inetAddress.isLoopbackAddress()) {
RequisitionInterface requisitionInterface = new RequisitionInterface();
requisitionInterface.setIpAddr(ipAddress);
// the first one will be primary
if (firstInterface) {
requisitionInterface.setSnmpPrimary(PrimaryType.PRIMARY);
for (String service : request.getVirtualMachineServices()) {
requisitionInterface.insertMonitoredService(new RequisitionMonitoredService(service.trim()));
}
firstInterface = false;
} else {
requisitionInterface.setSnmpPrimary(PrimaryType.SECONDARY);
}
requisitionInterface.setManaged(Boolean.TRUE);
requisitionInterface.setStatus(Integer.valueOf(1));
requisitionNode.putInterface(requisitionInterface);
}
}
} catch (UnknownHostException unknownHostException) {
logger.warn("Invalid IP address '{}'", unknownHostException.getMessage());
}
}
} else {
if (managedEntity instanceof HostSystem) {
boolean reachableInterfaceFound = false, firstInterface = true;
List<RequisitionInterface> requisitionInterfaceList = new ArrayList<>();
RequisitionInterface primaryInterfaceCandidate = null;
// add all given interfaces
for (String ipAddress : ipAddresses) {
try {
if ((request.isPersistIPv4() && InetAddressUtils.isIPv4Address(ipAddress)) || (request.isPersistIPv6() && InetAddressUtils.isIPv6Address(ipAddress))) {
InetAddress inetAddress = InetAddress.getByName(ipAddress);
if (!inetAddress.isLoopbackAddress()) {
RequisitionInterface requisitionInterface = new RequisitionInterface();
requisitionInterface.setIpAddr(ipAddress);
if (firstInterface) {
primaryInterfaceCandidate = requisitionInterface;
firstInterface = false;
}
if (!reachableInterfaceFound && reachableCimService(vmwareViJavaAccess, (HostSystem) managedEntity, ipAddress)) {
primaryInterfaceCandidate = requisitionInterface;
reachableInterfaceFound = true;
}
requisitionInterface.setManaged(Boolean.TRUE);
requisitionInterface.setStatus(Integer.valueOf(1));
requisitionInterface.setSnmpPrimary(PrimaryType.SECONDARY);
requisitionInterfaceList.add(requisitionInterface);
}
}
} catch (UnknownHostException unknownHostException) {
logger.warn("Invalid IP address '{}'", unknownHostException.getMessage());
}
}
if (primaryInterfaceCandidate != null) {
if (reachableInterfaceFound) {
logger.warn("Found reachable primary interface '{}'", primaryInterfaceCandidate.getIpAddr());
} else {
logger.warn("Only non-reachable interfaces found, using first one for primary interface '{}'", primaryInterfaceCandidate.getIpAddr());
}
primaryInterfaceCandidate.setSnmpPrimary(PrimaryType.PRIMARY);
for (String service : request.getHostSystemServices()) {
if (reachableInterfaceFound || !"VMwareCim-HostSystem".equals(service)) {
primaryInterfaceCandidate.insertMonitoredService(new RequisitionMonitoredService(service.trim()));
}
}
} else {
logger.warn("No primary interface found");
}
for (RequisitionInterface requisitionInterface : requisitionInterfaceList) {
requisitionNode.putInterface(requisitionInterface);
}
} else {
logger.error("Undefined type of managedEntity '{}'", managedEntity.getMOR().getType());
return null;
}
}
/*
* For now we use displaycategory, notifycategory and pollercategory for storing
* the vcenter Ip address, the username and the password
*/
String powerState = "unknown";
final StringBuilder vmwareTopologyInfo = new StringBuilder();
// putting parents to topology information
ManagedEntity parentEntity = managedEntity.getParent();
do {
if (vmwareTopologyInfo.length() > 0) {
vmwareTopologyInfo.append(", ");
}
try {
if (parentEntity != null && parentEntity.getMOR() != null) {
vmwareTopologyInfo.append(parentEntity.getMOR().getVal() + "/" + URLEncoder.encode(parentEntity.getName(), StandardCharsets.UTF_8.name()));
} else {
logger.warn("Can't add topologyInformation because either the parentEntity or the MOR is null for " + managedEntity.getName());
}
} catch (UnsupportedEncodingException e) {
logger.warn("Unsupported encoding '{}'", e.getMessage());
}
parentEntity = parentEntity == null ? null : parentEntity.getParent();
} while (parentEntity != null);
if (managedEntity instanceof HostSystem) {
HostSystem hostSystem = (HostSystem) managedEntity;
HostRuntimeInfo hostRuntimeInfo = hostSystem.getRuntime();
if (hostRuntimeInfo == null) {
logger.debug("hostRuntimeInfo=null");
} else {
HostSystemPowerState hostSystemPowerState = hostRuntimeInfo.getPowerState();
if (hostSystemPowerState == null) {
logger.debug("hostSystemPowerState=null");
} else {
powerState = hostSystemPowerState.toString();
}
}
try {
if (request.isTopologyDatastores()) {
for (Datastore datastore : hostSystem.getDatastores()) {
if (vmwareTopologyInfo.length() > 0) {
vmwareTopologyInfo.append(", ");
}
try {
vmwareTopologyInfo.append(datastore.getMOR().getVal() + "/" + URLEncoder.encode(datastore.getSummary().getName(), StandardCharsets.UTF_8.name()));
} catch (UnsupportedEncodingException e) {
logger.warn("Unsupported encoding '{}'", e.getMessage());
}
}
}
} catch (RemoteException e) {
logger.warn("Cannot retrieve datastores for managedEntity '{}': '{}'", managedEntity.getMOR().getVal(), e.getMessage());
}
try {
if (request.isTopologyNetworks()) {
for (Network network : hostSystem.getNetworks()) {
if (vmwareTopologyInfo.length() > 0) {
vmwareTopologyInfo.append(", ");
}
try {
if (network instanceof DistributedVirtualPortgroup ? request.isTopologyPortGroups() : true) {
vmwareTopologyInfo.append(network.getMOR().getVal() + "/" + URLEncoder.encode(network.getSummary().getName(), StandardCharsets.UTF_8.name()));
}
} catch (UnsupportedEncodingException e) {
logger.warn("Unsupported encoding '{}'", e.getMessage());
}
}
}
} catch (RemoteException e) {
logger.warn("Cannot retrieve networks for managedEntity '{}': '{}'", managedEntity.getMOR().getVal(), e.getMessage());
}
} else {
if (managedEntity instanceof VirtualMachine) {
VirtualMachine virtualMachine = (VirtualMachine) managedEntity;
VirtualMachineRuntimeInfo virtualMachineRuntimeInfo = virtualMachine.getRuntime();
if (virtualMachineRuntimeInfo == null) {
logger.debug("virtualMachineRuntimeInfo=null");
} else {
VirtualMachinePowerState virtualMachinePowerState = virtualMachineRuntimeInfo.getPowerState();
if (virtualMachinePowerState == null) {
logger.debug("virtualMachinePowerState=null");
} else {
powerState = virtualMachinePowerState.toString();
}
}
try {
if (request.isTopologyDatastores()) {
for (Datastore datastore : virtualMachine.getDatastores()) {
if (vmwareTopologyInfo.length() > 0) {
vmwareTopologyInfo.append(", ");
}
try {
vmwareTopologyInfo.append(datastore.getMOR().getVal() + "/" + URLEncoder.encode(datastore.getSummary().getName(), StandardCharsets.UTF_8.name()));
} catch (UnsupportedEncodingException e) {
logger.warn("Unsupported encoding '{}'", e.getMessage());
}
}
}
} catch (RemoteException e) {
logger.warn("Cannot retrieve datastores for managedEntity '{}': '{}'", managedEntity.getMOR().getVal(), e.getMessage());
}
try {
if (request.isTopologyNetworks()) {
for (Network network : virtualMachine.getNetworks()) {
if (vmwareTopologyInfo.length() > 0) {
vmwareTopologyInfo.append(", ");
}
try {
if (network instanceof DistributedVirtualPortgroup ? request.isTopologyPortGroups() : true) {
vmwareTopologyInfo.append(network.getMOR().getVal() + "/" + URLEncoder.encode(network.getSummary().getName(), StandardCharsets.UTF_8.name()));
}
} catch (UnsupportedEncodingException e) {
logger.warn("Unsupported encoding '{}'", e.getMessage());
}
}
}
} catch (RemoteException e) {
logger.warn("Cannot retrieve networks for managedEntity '{}': '{}'", managedEntity.getMOR().getVal(), e.getMessage());
}
if (vmwareTopologyInfo.length() > 0) {
vmwareTopologyInfo.append(", ");
}
try {
if (m_hostSystemMap.get(virtualMachine.getRuntime().getHost().getVal()) != null) {
vmwareTopologyInfo.append(virtualMachine.getRuntime().getHost().getVal() + "/" + URLEncoder.encode(m_hostSystemMap.get(virtualMachine.getRuntime().getHost().getVal()), StandardCharsets.UTF_8.name()));
} else {
logger.warn("Problem building topology information for virtual machine '{}' with power state '{}' running on host system '{}'", virtualMachine.getMOR().getVal(), powerState, virtualMachine.getRuntime().getHost().getVal());
}
} catch (UnsupportedEncodingException e) {
logger.warn("Unsupported encoding '{}'", e.getMessage());
}
} else {
logger.error("Undefined type of managedEntity '{}'", managedEntity.getMOR().getType());
return null;
}
}
RequisitionAsset requisitionAssetHostname = new RequisitionAsset("vmwareManagementServer", request.getHostname());
requisitionNode.putAsset(requisitionAssetHostname);
RequisitionAsset requisitionAssetType = new RequisitionAsset("vmwareManagedEntityType", (managedEntity instanceof HostSystem ? "HostSystem" : "VirtualMachine"));
requisitionNode.putAsset(requisitionAssetType);
RequisitionAsset requisitionAssetId = new RequisitionAsset("vmwareManagedObjectId", managedEntity.getMOR().getVal());
requisitionNode.putAsset(requisitionAssetId);
RequisitionAsset requisitionAssetTopologyInfo = new RequisitionAsset("vmwareTopologyInfo", vmwareTopologyInfo.toString());
requisitionNode.putAsset(requisitionAssetTopologyInfo);
RequisitionAsset requisitionAssetState = new RequisitionAsset("vmwareState", powerState);
requisitionNode.putAsset(requisitionAssetState);
requisitionNode.putCategory(new RequisitionCategory("VMware" + apiVersion));
return requisitionNode;
}
use of com.vmware.vim25.VirtualMachineRuntimeInfo in project cloudstack by apache.
the class VMwareGuru method importVirtualMachineFromBackup.
@Override
public VirtualMachine importVirtualMachineFromBackup(long zoneId, long domainId, long accountId, long userId, String vmInternalName, Backup backup) throws Exception {
s_logger.debug(String.format("Trying to import VM [vmInternalName: %s] from Backup [%s].", vmInternalName, ReflectionToStringBuilderUtils.reflectOnlySelectedFields(backup, "id", "uuid", "vmId", "externalId", "backupType")));
DatacenterMO dcMo = getDatacenterMO(zoneId);
VirtualMachineMO vmToImport = dcMo.findVm(vmInternalName);
if (vmToImport == null) {
throw new CloudRuntimeException("Error finding VM: " + vmInternalName);
}
VirtualMachineConfigSummary configSummary = vmToImport.getConfigSummary();
VirtualMachineRuntimeInfo runtimeInfo = vmToImport.getRuntimeInfo();
List<VirtualDisk> virtualDisks = vmToImport.getVirtualDisks();
String[] vmNetworkNames = vmToImport.getNetworks();
VirtualDevice[] nicDevices = vmToImport.getNicDevices();
Map<VirtualDisk, VolumeVO> disksMapping = getDisksMapping(backup, virtualDisks);
Map<String, NetworkVO> networksMapping = getNetworksMapping(vmNetworkNames, accountId, zoneId, domainId);
long guestOsId = getImportingVMGuestOs(configSummary);
long serviceOfferingId = getImportingVMServiceOffering(configSummary, runtimeInfo);
long templateId = getImportingVMTemplate(virtualDisks, dcMo, vmInternalName, guestOsId, accountId, disksMapping, backup);
VMInstanceVO vm = getVM(vmInternalName, templateId, guestOsId, serviceOfferingId, zoneId, accountId, userId, domainId);
syncVMVolumes(vm, virtualDisks, disksMapping, vmToImport, backup);
syncVMNics(nicDevices, dcMo, networksMapping, vm);
return vm;
}
Aggregations