use of com.xensource.xenapi.Types.VmPowerState in project cloudstack by apache.
the class CitrixResourceBase method getHostVmStateReport.
protected HashMap<String, HostVmStateReportEntry> getHostVmStateReport(final Connection conn) {
// TODO : new VM sync model does not require a cluster-scope report, we
// need to optimize
// the report accordingly
final HashMap<String, HostVmStateReportEntry> vmStates = new HashMap<String, HostVmStateReportEntry>();
Map<VM, VM.Record> vm_map = null;
for (int i = 0; i < 2; i++) {
try {
// USE THIS TO GET ALL VMS FROM
vm_map = VM.getAllRecords(conn);
// A CLUSTER
break;
} catch (final Throwable e) {
s_logger.warn("Unable to get vms", e);
}
try {
Thread.sleep(1000);
} catch (final InterruptedException ex) {
}
}
if (vm_map == null) {
return vmStates;
}
for (final VM.Record record : vm_map.values()) {
if (record.isControlDomain || record.isASnapshot || record.isATemplate) {
// Skip DOM0
continue;
}
final VmPowerState ps = record.powerState;
final Host host = record.residentOn;
String host_uuid = null;
if (!isRefNull(host)) {
try {
host_uuid = host.getUuid(conn);
} catch (final BadServerResponse e) {
s_logger.error("Failed to get host uuid for host " + host.toWireString(), e);
} catch (final XenAPIException e) {
s_logger.error("Failed to get host uuid for host " + host.toWireString(), e);
} catch (final XmlRpcException e) {
s_logger.error("Failed to get host uuid for host " + host.toWireString(), e);
}
if (host_uuid.equalsIgnoreCase(_host.getUuid())) {
vmStates.put(record.nameLabel, new HostVmStateReportEntry(convertToPowerState(ps), host_uuid));
}
}
}
return vmStates;
}
use of com.xensource.xenapi.Types.VmPowerState in project cloudstack by apache.
the class CitrixResourceBase method shutdownVM.
public void shutdownVM(final Connection conn, final VM vm, final String vmName) throws XmlRpcException {
Task task = null;
try {
task = vm.cleanShutdownAsync(conn);
try {
// poll every 1 seconds , timeout after 10 minutes
waitForTask(conn, task, 1000, 10 * 60 * 1000);
checkForSuccess(conn, task);
} catch (final TimeoutException e) {
if (vm.getPowerState(conn) == VmPowerState.HALTED) {
task = null;
return;
}
throw new CloudRuntimeException("Shutdown VM catch HandleInvalid and VM is not in HALTED state");
}
} catch (final XenAPIException e) {
s_logger.debug("Unable to cleanShutdown VM(" + vmName + ") on host(" + _host.getUuid() + ") due to " + e.toString());
try {
VmPowerState state = vm.getPowerState(conn);
if (state == VmPowerState.RUNNING) {
try {
vm.hardShutdown(conn);
} catch (final Exception e1) {
s_logger.debug("Unable to hardShutdown VM(" + vmName + ") on host(" + _host.getUuid() + ") due to " + e.toString());
state = vm.getPowerState(conn);
if (state == VmPowerState.RUNNING) {
forceShutdownVM(conn, vm);
}
return;
}
} else if (state == VmPowerState.HALTED) {
return;
} else {
final String msg = "After cleanShutdown the VM status is " + state.toString() + ", that is not expected";
s_logger.warn(msg);
throw new CloudRuntimeException(msg);
}
} catch (final Exception e1) {
final String msg = "Unable to hardShutdown VM(" + vmName + ") on host(" + _host.getUuid() + ") due to " + e.toString();
s_logger.warn(msg, e1);
throw new CloudRuntimeException(msg);
}
} finally {
if (task != null) {
try {
task.destroy(conn);
} catch (final Exception e1) {
s_logger.debug("unable to destroy task(" + task.toString() + ") on host(" + _host.getUuid() + ") due to " + e1.toString());
}
}
}
}
use of com.xensource.xenapi.Types.VmPowerState in project cloudstack by apache.
the class CitrixStartCommandWrapper method execute.
@Override
public Answer execute(final StartCommand command, final CitrixResourceBase citrixResourceBase) {
final Connection conn = citrixResourceBase.getConnection();
final VirtualMachineTO vmSpec = command.getVirtualMachine();
final String vmName = vmSpec.getName();
VmPowerState state = VmPowerState.HALTED;
VM vm = null;
// if a VDI is created, record its UUID to send back to the CS MS
final Map<String, String> iqnToPath = new HashMap<String, String>();
try {
final Set<VM> vms = VM.getByNameLabel(conn, vmName);
if (vms != null) {
for (final VM v : vms) {
final VM.Record vRec = v.getRecord(conn);
if (vRec.powerState == VmPowerState.HALTED) {
v.destroy(conn);
} else if (vRec.powerState == VmPowerState.RUNNING) {
final String host = vRec.residentOn.getUuid(conn);
final String msg = "VM " + vmName + " is runing on host " + host;
s_logger.debug(msg);
return new StartAnswer(command, msg, host);
} else {
final String msg = "There is already a VM having the same name " + vmName + " vm record " + vRec.toString();
s_logger.warn(msg);
return new StartAnswer(command, msg);
}
}
}
s_logger.debug("1. The VM " + vmName + " is in Starting state.");
final Host host = Host.getByUuid(conn, citrixResourceBase.getHost().getUuid());
vm = citrixResourceBase.createVmFromTemplate(conn, vmSpec, host);
final GPUDeviceTO gpuDevice = vmSpec.getGpuDevice();
if (gpuDevice != null) {
s_logger.debug("Creating VGPU for of VGPU type: " + gpuDevice.getVgpuType() + " in GPU group " + gpuDevice.getGpuGroup() + " for VM " + vmName);
citrixResourceBase.createVGPU(conn, command, vm, gpuDevice);
}
if (vmSpec.getType() != VirtualMachine.Type.User) {
citrixResourceBase.createPatchVbd(conn, vmName, vm);
}
// put cdrom at the first place in the list
List<DiskTO> disks = new ArrayList<DiskTO>(vmSpec.getDisks().length);
int index = 0;
for (final DiskTO disk : vmSpec.getDisks()) {
if (Volume.Type.ISO.equals(disk.getType())) {
disks.add(0, disk);
} else {
disks.add(index, disk);
}
index++;
}
for (DiskTO disk : disks) {
final VDI newVdi = citrixResourceBase.prepareManagedDisk(conn, disk, vmSpec.getId(), vmSpec.getName());
if (newVdi != null) {
final String path = newVdi.getUuid(conn);
iqnToPath.put(disk.getDetails().get(DiskTO.IQN), path);
}
citrixResourceBase.createVbd(conn, disk, vmName, vm, vmSpec.getBootloader(), newVdi);
}
for (final NicTO nic : vmSpec.getNics()) {
citrixResourceBase.createVif(conn, vmName, vm, vmSpec, nic);
}
citrixResourceBase.startVM(conn, host, vm, vmName);
if (citrixResourceBase.isOvs()) {
// TODO(Salvatore-orlando): This code should go
for (final NicTO nic : vmSpec.getNics()) {
if (nic.getBroadcastType() == Networks.BroadcastDomainType.Vswitch) {
final HashMap<String, String> args = citrixResourceBase.parseDefaultOvsRuleComamnd(BroadcastDomainType.getValue(nic.getBroadcastUri()));
final OvsSetTagAndFlowCommand flowCmd = new OvsSetTagAndFlowCommand(args.get("vmName"), args.get("tag"), args.get("vlans"), args.get("seqno"), Long.parseLong(args.get("vmId")));
final CitrixRequestWrapper citrixRequestWrapper = CitrixRequestWrapper.getInstance();
final OvsSetTagAndFlowAnswer r = (OvsSetTagAndFlowAnswer) citrixRequestWrapper.execute(flowCmd, citrixResourceBase);
if (!r.getResult()) {
s_logger.warn("Failed to set flow for VM " + r.getVmId());
} else {
s_logger.info("Success to set flow for VM " + r.getVmId());
}
}
}
}
if (citrixResourceBase.canBridgeFirewall()) {
String result = null;
if (vmSpec.getType() != VirtualMachine.Type.User) {
final NicTO[] nics = vmSpec.getNics();
boolean secGrpEnabled = false;
for (final NicTO nic : nics) {
if (nic.isSecurityGroupEnabled() || nic.getIsolationUri() != null && nic.getIsolationUri().getScheme().equalsIgnoreCase(IsolationType.Ec2.toString())) {
secGrpEnabled = true;
break;
}
}
if (secGrpEnabled) {
result = citrixResourceBase.callHostPlugin(conn, "vmops", "default_network_rules_systemvm", "vmName", vmName);
if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) {
s_logger.warn("Failed to program default network rules for " + vmName);
} else {
s_logger.info("Programmed default network rules for " + vmName);
}
}
} else {
// For user vm, program the rules for each nic if the
// isolation uri scheme is ec2
final NicTO[] nics = vmSpec.getNics();
for (final NicTO nic : nics) {
if (nic.isSecurityGroupEnabled() || nic.getIsolationUri() != null && nic.getIsolationUri().getScheme().equalsIgnoreCase(IsolationType.Ec2.toString())) {
final List<String> nicSecIps = nic.getNicSecIps();
String secIpsStr;
final StringBuilder sb = new StringBuilder();
if (nicSecIps != null) {
for (final String ip : nicSecIps) {
sb.append(ip).append(":");
}
secIpsStr = sb.toString();
} else {
secIpsStr = "0:";
}
result = citrixResourceBase.callHostPlugin(conn, "vmops", "default_network_rules", "vmName", vmName, "vmIP", nic.getIp(), "vmMAC", nic.getMac(), "vmID", Long.toString(vmSpec.getId()), "secIps", secIpsStr);
if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) {
s_logger.warn("Failed to program default network rules for " + vmName + " on nic with ip:" + nic.getIp() + " mac:" + nic.getMac());
} else {
s_logger.info("Programmed default network rules for " + vmName + " on nic with ip:" + nic.getIp() + " mac:" + nic.getMac());
}
}
}
}
}
state = VmPowerState.RUNNING;
final StartAnswer startAnswer = new StartAnswer(command);
startAnswer.setIqnToPath(iqnToPath);
return startAnswer;
} catch (final Exception e) {
s_logger.warn("Catch Exception: " + e.getClass().toString() + " due to " + e.toString(), e);
final String msg = citrixResourceBase.handleVmStartFailure(conn, vmName, vm, "", e);
final StartAnswer startAnswer = new StartAnswer(command, msg);
startAnswer.setIqnToPath(iqnToPath);
return startAnswer;
} finally {
if (state != VmPowerState.HALTED) {
s_logger.debug("2. The VM " + vmName + " is in " + state + " state.");
} else {
s_logger.debug("The VM is in stopped state, detected problem during startup : " + vmName);
}
}
}
use of com.xensource.xenapi.Types.VmPowerState in project cloudstack by apache.
the class CitrixCreateVMSnapshotCommandWrapper method execute.
@Override
public Answer execute(final CreateVMSnapshotCommand command, final CitrixResourceBase citrixResourceBase) {
final String vmName = command.getVmName();
final String vmSnapshotName = command.getTarget().getSnapshotName();
final List<VolumeObjectTO> listVolumeTo = command.getVolumeTOs();
VmPowerState vmState = VmPowerState.HALTED;
final String guestOSType = command.getGuestOSType();
final String platformEmulator = command.getPlatformEmulator();
final boolean snapshotMemory = command.getTarget().getType() == VMSnapshot.Type.DiskAndMemory;
final long timeout = command.getWait();
final Connection conn = citrixResourceBase.getConnection();
VM vm = null;
VM vmSnapshot = null;
boolean success = false;
try {
// check if VM snapshot already exists
final Set<VM> vmSnapshots = VM.getByNameLabel(conn, command.getTarget().getSnapshotName());
if (vmSnapshots == null || vmSnapshots.size() > 0) {
return new CreateVMSnapshotAnswer(command, command.getTarget(), command.getVolumeTOs());
}
// check if there is already a task for this VM snapshot
Task task = null;
Set<Task> tasks = Task.getByNameLabel(conn, "Async.VM.snapshot");
if (tasks == null) {
tasks = new LinkedHashSet<>();
}
final Set<Task> tasksByName = Task.getByNameLabel(conn, "Async.VM.checkpoint");
if (tasksByName != null) {
tasks.addAll(tasksByName);
}
for (final Task taskItem : tasks) {
if (taskItem.getOtherConfig(conn).containsKey("CS_VM_SNAPSHOT_KEY")) {
final String vmSnapshotTaskName = taskItem.getOtherConfig(conn).get("CS_VM_SNAPSHOT_KEY");
if (vmSnapshotTaskName != null && vmSnapshotTaskName.equals(command.getTarget().getSnapshotName())) {
task = taskItem;
}
}
}
// create a new task if there is no existing task for this VM snapshot
if (task == null) {
try {
vm = citrixResourceBase.getVM(conn, vmName);
vmState = vm.getPowerState(conn);
} catch (final Exception e) {
if (!snapshotMemory) {
vm = citrixResourceBase.createWorkingVM(conn, vmName, guestOSType, platformEmulator, listVolumeTo);
}
}
if (vm == null) {
return new CreateVMSnapshotAnswer(command, false, "Creating VM Snapshot Failed due to can not find vm: " + vmName);
}
// call Xenserver API
if (!snapshotMemory) {
task = vm.snapshotAsync(conn, vmSnapshotName);
} else {
final Set<VBD> vbds = vm.getVBDs(conn);
final Pool pool = Pool.getByUuid(conn, citrixResourceBase.getHost().getPool());
for (final VBD vbd : vbds) {
final VBD.Record vbdr = vbd.getRecord(conn);
if (vbdr.userdevice.equals("0")) {
final VDI vdi = vbdr.VDI;
final SR sr = vdi.getSR(conn);
// store memory image on the same SR with ROOT volume
pool.setSuspendImageSR(conn, sr);
}
}
task = vm.checkpointAsync(conn, vmSnapshotName);
}
task.addToOtherConfig(conn, "CS_VM_SNAPSHOT_KEY", vmSnapshotName);
}
citrixResourceBase.waitForTask(conn, task, 1000, timeout * 1000);
citrixResourceBase.checkForSuccess(conn, task);
final String result = task.getResult(conn);
// extract VM snapshot ref from result
final String ref = result.substring("<value>".length(), result.length() - "</value>".length());
vmSnapshot = Types.toVM(ref);
try {
Thread.sleep(5000);
} catch (final InterruptedException ex) {
}
// calculate used capacity for this VM snapshot
for (final VolumeObjectTO volumeTo : command.getVolumeTOs()) {
final long size = citrixResourceBase.getVMSnapshotChainSize(conn, volumeTo, command.getVmName());
volumeTo.setSize(size);
}
success = true;
return new CreateVMSnapshotAnswer(command, command.getTarget(), command.getVolumeTOs());
} catch (final Exception e) {
String msg = "";
if (e instanceof Types.BadAsyncResult) {
final String licenseKeyWord = "LICENCE_RESTRICTION";
final Types.BadAsyncResult errorResult = (Types.BadAsyncResult) e;
if (errorResult.shortDescription != null && errorResult.shortDescription.contains(licenseKeyWord)) {
msg = licenseKeyWord;
}
} else {
msg = e.toString();
}
s_logger.warn("Creating VM Snapshot " + command.getTarget().getSnapshotName() + " failed due to: " + msg, e);
return new CreateVMSnapshotAnswer(command, false, msg);
} finally {
try {
if (!success) {
if (vmSnapshot != null) {
s_logger.debug("Delete exsisting VM Snapshot " + vmSnapshotName + " after making VolumeTO failed");
final Set<VBD> vbds = vmSnapshot.getVBDs(conn);
for (final VBD vbd : vbds) {
final VBD.Record vbdr = vbd.getRecord(conn);
if (vbdr.type == Types.VbdType.DISK) {
final VDI vdi = vbdr.VDI;
vdi.destroy(conn);
}
}
vmSnapshot.destroy(conn);
}
}
if (vmState == VmPowerState.HALTED) {
if (vm != null) {
vm.destroy(conn);
}
}
} catch (final Exception e2) {
s_logger.error("delete snapshot error due to " + e2.getMessage());
}
}
}
Aggregations