Connection conn = getConnection();
Set<VM> vms = VM.getByNameLabel(conn, vmName);
// stop vm which is running on this host or is in halted state
Iterator<VM> iter = vms.iterator();
while ( iter.hasNext() ) {
VM vm = iter.next();
VM.Record vmr = vm.getRecord(conn);
if (vmr.powerState != VmPowerState.RUNNING) {
continue;
}
if (isRefNull(vmr.residentOn)) {
continue;
}
if (vmr.residentOn.getUuid(conn).equals(_host.uuid)) {
continue;
}
iter.remove();
}
if (vms.size() == 0) {
synchronized (_cluster.intern()) {
s_logger.info("VM does not exist on XenServer" + _host.uuid);
s_vms.remove(_cluster, _name, vmName);
}
return new StopAnswer(cmd, "VM does not exist", true);
}
for (VM vm : vms) {
VM.Record vmr = vm.getRecord(conn);
platformstring = StringUtils.mapToString(vmr.platform);
if (vmr.isControlDomain) {
String msg = "Tring to Shutdown control domain";
s_logger.warn(msg);
return new StopAnswer(cmd, msg, false);
}
if (vmr.powerState == VmPowerState.RUNNING && !isRefNull(vmr.residentOn) && !vmr.residentOn.getUuid(conn).equals(_host.uuid)) {
String msg = "Stop Vm " + vmName + " failed due to this vm is not running on this host: " + _host.uuid + " but host:" + vmr.residentOn.getUuid(conn);
s_logger.warn(msg);
return new StopAnswer(cmd, msg, platformstring, false);
}
State state = s_vms.getState(_cluster, vmName);
synchronized (_cluster.intern()) {
s_vms.put(_cluster, _name, vmName, State.Stopping);
}
s_logger.debug("9. The VM " + vmName + " is in Stopping state");
try {
if (vmr.powerState == VmPowerState.RUNNING) {
/* when stop a vm, set affinity to current xenserver */
vm.setAffinity(conn, vm.getResidentOn(conn));
if (_canBridgeFirewall) {
String result = callHostPlugin(conn, "vmops", "destroy_network_rules_for_vm", "vmName", cmd
.getVmName());
if (result == null || result.isEmpty() || !Boolean.parseBoolean(result)) {
s_logger.warn("Failed to remove network rules for vm " + cmd.getVmName());
} else {
s_logger.info("Removed network rules for vm " + cmd.getVmName());
}
}
shutdownVM(conn, vm, vmName);
}
} catch (Exception e) {
String msg = "Catch exception " + e.getClass().getName() + " when stop VM:" + cmd.getVmName() + " due to " + e.toString();
s_logger.debug(msg);
return new StopAnswer(cmd, msg, platformstring, false);
} finally {
try {
if (vm.getPowerState(conn) == VmPowerState.HALTED) {
Set<VIF> vifs = vm.getVIFs(conn);
List<Network> networks = new ArrayList<Network>();
for (VIF vif : vifs) {
networks.add(vif.getNetwork(conn));
}
vm.destroy(conn);
state = State.Stopped;
SR sr = getISOSRbyVmName(conn, cmd.getVmName());
removeSR(conn, sr);
// Disable any VLAN networks that aren't used
// anymore