use of com.cloud.agent.resource.kvm.xml.LibvirtVmDef in project cosmic by MissionCriticalCloud.
the class LibvirtComputingResource method createVmFromSpec.
public LibvirtVmDef createVmFromSpec(final VirtualMachineTO vmTo) {
final LibvirtVmDef vm = new LibvirtVmDef();
vm.setDomainName(vmTo.getName());
String uuid = vmTo.getUuid();
uuid = getUuid(uuid);
vm.setDomUuid(uuid);
vm.setDomDescription("This VM is optimised for: " + vmTo.getOptimiseFor().toString());
vm.setPlatformEmulator(vmTo.getPlatformEmulator());
final MetadataTO metadataTo = vmTo.getMetadata();
if (metadataTo != null) {
final MetadataDef metadata = new MetadataDef();
metadata.getNodes().put("cosmicDomainUuid", metadataTo.getDomainUuid());
metadata.getNodes().put("cosmicDomainName", metadataTo.getCosmicDomainName());
metadata.getNodes().put("cosmicDomainPath", metadataTo.getCosmicDomainPath());
metadata.getNodes().put("cosmicInternalVmId", metadataTo.getVmId());
metadata.getNodes().put("cosmicInstanceName", metadataTo.getInstanceName());
metadata.getNodes().put("cosmicXmlGeneratedInCosmicVersion", LibvirtComputingResource.class.getPackage().getImplementationVersion());
metadata.getNodes().put("cosmicXmlGeneratedDateTime", getCurrentLocalDateTimeStamp());
metadata.getNodes().put("cosmicXmlGeneratedEpoch", getCurrentEpoch());
metadata.getNodes().put("cosmicVmHostname", metadataTo.getHostname());
metadata.getNodes().put("cosmicOptimiseFor", vmTo.getOptimiseFor().toString());
final List<String> vpcNameList = metadataTo.getVpcNameList();
if (vpcNameList != null) {
for (final String vpcName : vpcNameList) {
metadata.getNodes().put("cosmicVPC", vpcName);
}
}
final Map<String, String> vmTags = metadataTo.getResourceTags();
if (vmTags != null) {
for (Map.Entry<String, String> vmTag : vmTags.entrySet()) {
metadata.getNodes().put("cosmicTag_" + vmTag.getKey(), vmTag.getValue());
}
}
vm.addComponent(metadata);
}
final GuestDef guest = new GuestDef();
guest.setGuestType(LibvirtVmDef.GuestType.KVM);
vm.setHvsType(HypervisorType.KVM.toString().toLowerCase());
vm.setLibvirtVersion(this.hypervisorLibvirtVersion);
vm.setQemuVersion(this.hypervisorQemuVersion);
guest.setGuestArch(vmTo.getArch());
guest.setMachineType("pc");
guest.setUuid(uuid);
guest.setManufacturer(vmTo.getManufacturer());
guest.setBootMenuTimeout(vmTo.getBootMenuTimeout());
if (vmTo.getBootOrder() != null) {
for (BootOrder device : vmTo.getBootOrder()) {
guest.setBootOrder(device);
}
} else {
guest.setBootOrder(BootOrder.CDROM);
guest.setBootOrder(BootOrder.HARDDISK);
}
vm.addComponent(guest);
final GuestResourceDef grd = new GuestResourceDef();
if (vmTo.getMinRam() != vmTo.getMaxRam() && !this.libvirtComputingResourceProperties.getVmMemballoonDisable()) {
grd.setMemBalloning(true);
grd.setCurrentMem(vmTo.getMinRam() / 1024);
grd.setMemorySize(vmTo.getMaxRam() / 1024);
} else {
grd.setMemorySize(vmTo.getMaxRam() / 1024);
}
final int vcpus = vmTo.getCpus();
grd.setVcpuNum(vcpus);
vm.addComponent(grd);
final CpuModeDef cmd = new CpuModeDef();
cmd.setMode(getGuestCpuMode());
cmd.setModel(getGuestCpuModel());
cmd.setCpuflags(vmTo.getCpuflags());
if (vmTo.getType() == VirtualMachineType.User) {
cmd.setFeatures(getCpuFeatures());
}
// But only when maintenance policy is live migrate
if (OptimiseFor.Windows.equals(vmTo.getOptimiseFor()) && MaintenancePolicy.LiveMigrate.equals(vmTo.getMaintenancePolicy())) {
String extended_cpu_flags = vmTo.getCpuflags();
if (extended_cpu_flags == null) {
extended_cpu_flags = "-hypervisor";
} else {
extended_cpu_flags += " -hypervisor";
}
cmd.setCpuflags(extended_cpu_flags);
}
// multi cores per socket, for larger core configs
if (vcpus % 6 == 0) {
final int sockets = vcpus / 6;
cmd.setTopology(6, sockets);
} else if (vcpus % 4 == 0) {
final int sockets = vcpus / 4;
cmd.setTopology(4, sockets);
}
vm.addComponent(cmd);
final CpuTuneDef ctd = new CpuTuneDef();
if (VirtualMachineType.DomainRouter.equals(vmTo.getType())) {
ctd.setShares(vmTo.getCpus() * this.libvirtComputingResourceProperties.getGuestCpuSharesRouter());
} else {
ctd.setShares(vmTo.getCpus() * this.libvirtComputingResourceProperties.getGuestCpuShares());
}
vm.addComponent(ctd);
final FeaturesDef features = new FeaturesDef();
features.addFeature("pae");
features.addFeature("apic");
features.addFeature("acpi");
vm.addComponent(features);
if (vmTo.getOptimiseFor() == OptimiseFor.Windows) {
final HyperVEnlightenmentFeatureDef hyperVFeatures = new HyperVEnlightenmentFeatureDef();
hyperVFeatures.addFeature("relaxed", true);
hyperVFeatures.addFeature("vapic", true);
hyperVFeatures.addFeature("spinlocks", true);
hyperVFeatures.setRetries(8191);
features.addHyperVFeature(hyperVFeatures);
}
final TermPolicy term = new TermPolicy();
if (VirtualMachineType.User.equals(vmTo.getType())) {
term.setCrashPolicy(getVmTermpolicyCrash());
term.setPowerOffPolicy(getVmTermpolicyPowerOff());
term.setRebootPolicy(getVmTermpolicyReboot());
} else {
term.setCrashPolicy(getSystemTermpolicyCrash());
term.setPowerOffPolicy(getSystemTermpolicyPowerOff());
term.setRebootPolicy(getSystemTermpolicyReboot());
}
vm.addComponent(term);
final ClockDef clock = new ClockDef();
Boolean kvmClockEnabled = !isKvmClockDisabled();
Boolean hypervClockEnabled = false;
Boolean trackGuest = false;
if (vmTo.getOptimiseFor() == OptimiseFor.Windows) {
clock.setClockOffset(ClockDef.ClockOffset.LOCALTIME);
kvmClockEnabled = false;
hypervClockEnabled = true;
trackGuest = true;
}
clock.addTimer("kvmclock", null, kvmClockEnabled, false);
clock.addTimer("hypervclock", null, hypervClockEnabled, false);
// Recommended default clock/timer settings - https://bugzilla.redhat.com/show_bug.cgi?id=1053847
// Important note for track="guest" in Windows VMs:
// https://docs.fedoraproject.org/en-US/Fedora_Draft_Documentation/0
// .1/html/Virtualization_Deployment_and_Administration_Guide/sect-Virtualization-Tips_and_tricks-Libvirt_Managed_Timers.html
clock.addTimer("rtc", "catchup", true, trackGuest);
clock.addTimer("pit", "delay", true, false);
clock.addTimer("hpet", null, false, false);
vm.addComponent(clock);
final DevicesDef devices = new DevicesDef();
devices.setEmulatorPath(this.hypervisorPath);
devices.setGuestType(guest.getGuestType());
final SerialDef serial = new SerialDef("pty", null, (short) 0);
devices.addDevice(serial);
final QemuGuestAgentDef guestagent = new QemuGuestAgentDef();
devices.addDevice(guestagent);
if (this.libvirtComputingResourceProperties.getVmRngEnable()) {
final RngDef rngDevice = new RngDef(this.rngPath, this.rngBackendModel);
devices.addDevice(rngDevice);
}
final WatchDogDef watchDog = new WatchDogDef(this.libvirtComputingResourceProperties.getVmWatchdogAction(), this.libvirtComputingResourceProperties.getVmWatchdogModel());
devices.addDevice(watchDog);
final VideoDef videoCard = new VideoDef(this.libvirtComputingResourceProperties.getVmVideoHardware(), this.libvirtComputingResourceProperties.getVmVideoRam());
devices.addDevice(videoCard);
final ConsoleDef console = new ConsoleDef("pty", null, null, (short) 0);
devices.addDevice(console);
// add the VNC port passwd here, get the passwd from the vmInstance.
final String passwd = vmTo.getVncPassword();
final GraphicDef grap = new GraphicDef("vnc", (short) 0, true, passwd, null);
devices.addDevice(grap);
final InputDef input = new InputDef("tablet", "usb");
devices.addDevice(input);
// Always add a virtio scsi controller
vmTo.getName();
final ScsiDef sd = new ScsiDef((short) 0, 0, 0, 9, 0, vcpus);
devices.addDevice(sd);
logger.debug("Adding SCSI definition for " + vmTo.getName() + ":\n" + sd.toString());
vm.addComponent(devices);
return vm;
}
use of com.cloud.agent.resource.kvm.xml.LibvirtVmDef in project cosmic by MissionCriticalCloud.
the class LibvirtComputingResourceTest method testcreateVmFromSpecWithTopology6.
/**
* This test verifies that CPU topology is properly set for hex-core
*/
@Test
public void testcreateVmFromSpecWithTopology6() {
final int id = this._random.nextInt(65534);
final String name = "test-instance-1";
final int cpus = 12;
final int minRam = 256 * 1024;
final int maxRam = 512 * 1024;
final String os = "Ubuntu";
final String vncPassword = "mySuperSecretPassword";
final LibvirtComputingResource lcr = new LibvirtComputingResource();
final VirtualMachineTO to = new VirtualMachineTO(id, name, VirtualMachineType.User, cpus, minRam, maxRam, BootloaderType.HVM, os, false, false, vncPassword);
to.setUuid("b0f0a72d-7efb-3cad-a8ff-70ebf30b3af9");
final LibvirtVmDef vm = lcr.createVmFromSpec(to);
vm.setHvsType(this._hyperVisorType);
verifyVm(to, vm);
}
use of com.cloud.agent.resource.kvm.xml.LibvirtVmDef in project cosmic by MissionCriticalCloud.
the class LibvirtStartCommandWrapper method execute.
@Override
public Answer execute(final StartCommand command, final LibvirtComputingResource libvirtComputingResource) {
final VirtualMachineTO vmSpec = command.getVirtualMachine();
final String vmName = vmSpec.getName();
LibvirtVmDef vm = null;
DomainState state = DomainState.VIR_DOMAIN_SHUTOFF;
final KvmStoragePoolManager storagePoolMgr = libvirtComputingResource.getStoragePoolMgr();
final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
Connect conn = null;
try {
vm = libvirtComputingResource.createVmFromSpec(vmSpec);
conn = libvirtUtilitiesHelper.getConnectionByType(vm.getHvsType());
final Long remainingMem = getFreeMemory(conn, libvirtComputingResource);
if (remainingMem == null) {
return new StartAnswer(command, "Failed to get free memory");
} else if (remainingMem < vmSpec.getMinRam()) {
return new StartAnswer(command, "Not enough memory on the host, remaining: " + remainingMem + ", asking: " + vmSpec.getMinRam());
}
final NicTO[] nics = vmSpec.getNics();
libvirtComputingResource.createVbd(conn, vmSpec, vmName, vm);
if (!storagePoolMgr.connectPhysicalDisksViaVmSpec(vmSpec)) {
return new StartAnswer(command, "Failed to connect physical disks to host");
}
libvirtComputingResource.createVifs(vmSpec, vm);
s_logger.debug("starting " + vmName + ": " + vm.toString());
libvirtComputingResource.startVm(conn, vmName, vm.toString());
// system vms
if (vmSpec.getType() != VirtualMachineType.User) {
// pass cmdline with config for the systemvm to configure itself
if (libvirtComputingResource.passCmdLine(vmName, vmSpec.getBootArgs())) {
s_logger.debug("Passing cmdline succeeded");
} else {
final String errorMessage = "Passing cmdline failed, aborting.";
s_logger.debug(errorMessage);
return new StartAnswer(command, errorMessage);
}
String controlIp = null;
for (final NicTO nic : nics) {
if (nic.getType() == TrafficType.Control) {
controlIp = nic.getIp();
break;
}
}
// connect to the router by using its linklocal address (that should now be configured)
s_logger.debug("Starting ssh attempts to " + controlIp);
final VirtualRoutingResource virtRouterResource = libvirtComputingResource.getVirtRouterResource();
if (!virtRouterResource.connect(controlIp, 30, 5000)) {
final String errorMessage = "Unable to login to router via linklocal address " + controlIp + " after 30 tries, aborting.";
s_logger.debug(errorMessage);
return new StartAnswer(command, errorMessage);
}
s_logger.debug("Successfully completed ssh attempts to " + controlIp);
}
state = DomainState.VIR_DOMAIN_RUNNING;
return new StartAnswer(command);
} catch (final LibvirtException | InternalErrorException | URISyntaxException e) {
s_logger.warn("Exception while starting VM: " + ExceptionUtils.getRootCauseMessage(e));
if (conn != null) {
libvirtComputingResource.handleVmStartFailure(vm);
}
return new StartAnswer(command, e.getMessage());
} finally {
if (state != DomainState.VIR_DOMAIN_RUNNING) {
storagePoolMgr.disconnectPhysicalDisksViaVmSpec(vmSpec);
}
}
}
use of com.cloud.agent.resource.kvm.xml.LibvirtVmDef in project cosmic by MissionCriticalCloud.
the class LibvirtComputingResourceTest method testStartCommand.
@Test
public void testStartCommand() {
final VirtualMachineTO vmSpec = Mockito.mock(VirtualMachineTO.class);
final Host host = Mockito.mock(Host.class);
final boolean executeInSequence = false;
final StartCommand command = new StartCommand(vmSpec, host, executeInSequence);
final KvmStoragePoolManager storagePoolMgr = Mockito.mock(KvmStoragePoolManager.class);
final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
final Connect conn = Mockito.mock(Connect.class);
final LibvirtVmDef vmDef = Mockito.mock(LibvirtVmDef.class);
final VirtualRoutingResource virtRouterResource = Mockito.mock(VirtualRoutingResource.class);
final NicTO nic = Mockito.mock(NicTO.class);
final NicTO[] nics = new NicTO[] { nic };
final int[] vms = new int[0];
final String vmName = "Test";
final String controlIp = "127.0.0.1";
when(this.libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
when(vmSpec.getNics()).thenReturn(nics);
when(vmSpec.getType()).thenReturn(VirtualMachineType.DomainRouter);
when(vmSpec.getName()).thenReturn(vmName);
when(this.libvirtComputingResource.createVmFromSpec(vmSpec)).thenReturn(vmDef);
when(this.libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
try {
when(libvirtUtilitiesHelper.getConnectionByType(vmDef.getHvsType())).thenReturn(conn);
when(conn.listDomains()).thenReturn(vms);
doNothing().when(this.libvirtComputingResource).createVbd(conn, vmSpec, vmName, vmDef);
} catch (final LibvirtException e) {
fail(e.getMessage());
} catch (final InternalErrorException e) {
fail(e.getMessage());
} catch (final URISyntaxException e) {
fail(e.getMessage());
}
when(storagePoolMgr.connectPhysicalDisksViaVmSpec(vmSpec)).thenReturn(true);
try {
doNothing().when(this.libvirtComputingResource).createVifs(vmSpec, vmDef);
when(this.libvirtComputingResource.startVm(conn, vmName, vmDef.toString())).thenReturn("SUCCESS");
when(vmSpec.getBootArgs()).thenReturn("ls -lart");
when(this.libvirtComputingResource.passCmdLine(vmName, vmSpec.getBootArgs())).thenReturn(true);
when(nic.getIp()).thenReturn(controlIp);
when(nic.getType()).thenReturn(TrafficType.Control);
when(this.libvirtComputingResource.getVirtRouterResource()).thenReturn(virtRouterResource);
when(virtRouterResource.connect(controlIp, 30, 5000)).thenReturn(true);
} catch (final InternalErrorException e) {
fail(e.getMessage());
} catch (final LibvirtException e) {
fail(e.getMessage());
}
final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
assertNotNull(wrapper);
final Answer answer = wrapper.execute(command, this.libvirtComputingResource);
assertTrue(answer.getResult());
verify(this.libvirtComputingResource, times(1)).getStoragePoolMgr();
verify(this.libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
try {
verify(libvirtUtilitiesHelper, times(1)).getConnectionByType(vmDef.getHvsType());
} catch (final LibvirtException e) {
fail(e.getMessage());
}
}
use of com.cloud.agent.resource.kvm.xml.LibvirtVmDef in project cosmic by MissionCriticalCloud.
the class LibvirtComputingResourceTest method testStartCommandInternalError.
@Test
public void testStartCommandInternalError() {
final VirtualMachineTO vmSpec = Mockito.mock(VirtualMachineTO.class);
final Host host = Mockito.mock(Host.class);
final boolean executeInSequence = false;
final StartCommand command = new StartCommand(vmSpec, host, executeInSequence);
final KvmStoragePoolManager storagePoolMgr = Mockito.mock(KvmStoragePoolManager.class);
final LibvirtUtilitiesHelper libvirtUtilitiesHelper = Mockito.mock(LibvirtUtilitiesHelper.class);
final Connect conn = Mockito.mock(Connect.class);
final LibvirtVmDef vmDef = Mockito.mock(LibvirtVmDef.class);
final NicTO nic = Mockito.mock(NicTO.class);
final NicTO[] nics = new NicTO[] { nic };
final String vmName = "Test";
when(this.libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolMgr);
when(vmSpec.getNics()).thenReturn(nics);
when(vmSpec.getType()).thenReturn(VirtualMachineType.DomainRouter);
when(vmSpec.getName()).thenReturn(vmName);
when(this.libvirtComputingResource.createVmFromSpec(vmSpec)).thenReturn(vmDef);
when(this.libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
try {
when(libvirtUtilitiesHelper.getConnectionByType(vmDef.getHvsType())).thenReturn(conn);
doThrow(InternalErrorException.class).when(this.libvirtComputingResource).createVbd(conn, vmSpec, vmName, vmDef);
} catch (final LibvirtException e) {
fail(e.getMessage());
} catch (final InternalErrorException e) {
fail(e.getMessage());
} catch (final URISyntaxException e) {
fail(e.getMessage());
}
final LibvirtRequestWrapper wrapper = LibvirtRequestWrapper.getInstance();
assertNotNull(wrapper);
final Answer answer = wrapper.execute(command, this.libvirtComputingResource);
assertFalse(answer.getResult());
verify(this.libvirtComputingResource, times(1)).getStoragePoolMgr();
verify(this.libvirtComputingResource, times(1)).getLibvirtUtilitiesHelper();
try {
verify(libvirtUtilitiesHelper, times(1)).getConnectionByType(vmDef.getHvsType());
} catch (final LibvirtException e) {
fail(e.getMessage());
}
}
Aggregations