use of org.libvirt.Connect in project cloudstack by apache.
the class LibvirtStartCommandWrapper method execute.
@Override
public Answer execute(final StartCommand command, final LibvirtComputingResource libvirtComputingResource) {
final VirtualMachineTO vmSpec = command.getVirtualMachine();
vmSpec.setVncAddr(command.getHostIp());
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());
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();
for (final NicTO nic : nics) {
if (vmSpec.getType() != VirtualMachine.Type.User) {
nic.setPxeDisable(true);
}
}
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());
for (final NicTO nic : nics) {
if (nic.isSecurityGroupEnabled() || nic.getIsolationUri() != null && nic.getIsolationUri().getScheme().equalsIgnoreCase(IsolationType.Ec2.toString())) {
if (vmSpec.getType() != VirtualMachine.Type.User) {
libvirtComputingResource.configureDefaultNetworkRulesForSystemVm(conn, vmName);
break;
} else {
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:";
}
libvirtComputingResource.defaultNetworkRules(conn, vmName, nic, vmSpec.getId(), secIpsStr);
}
}
}
// pass cmdline info to system vms
if (vmSpec.getType() != VirtualMachine.Type.User) {
//wait and try passCmdLine for 5 minutes at most for CLOUDSTACK-2823
String controlIp = null;
for (final NicTO nic : nics) {
if (nic.getType() == TrafficType.Control) {
controlIp = nic.getIp();
break;
}
}
for (int count = 0; count < 30; count++) {
libvirtComputingResource.passCmdLine(vmName, vmSpec.getBootArgs());
//check router is up?
final VirtualRoutingResource virtRouterResource = libvirtComputingResource.getVirtRouterResource();
final boolean result = virtRouterResource.connect(controlIp, 1, 5000);
if (result) {
break;
}
}
}
state = DomainState.VIR_DOMAIN_RUNNING;
return new StartAnswer(command);
} catch (final LibvirtException e) {
s_logger.warn("LibvirtException ", e);
if (conn != null) {
libvirtComputingResource.handleVmStartFailure(conn, vmName, vm);
}
return new StartAnswer(command, e.getMessage());
} catch (final InternalErrorException e) {
s_logger.warn("InternalErrorException ", e);
if (conn != null) {
libvirtComputingResource.handleVmStartFailure(conn, vmName, vm);
}
return new StartAnswer(command, e.getMessage());
} catch (final URISyntaxException e) {
s_logger.warn("URISyntaxException ", e);
if (conn != null) {
libvirtComputingResource.handleVmStartFailure(conn, vmName, vm);
}
return new StartAnswer(command, e.getMessage());
} finally {
if (state != DomainState.VIR_DOMAIN_RUNNING) {
storagePoolMgr.disconnectPhysicalDisksViaVmSpec(vmSpec);
}
}
}
use of org.libvirt.Connect in project cloudstack by apache.
the class LibvirtPrepareForMigrationCommandWrapper method execute.
@Override
public Answer execute(final PrepareForMigrationCommand command, final LibvirtComputingResource libvirtComputingResource) {
final VirtualMachineTO vm = command.getVirtualMachine();
if (s_logger.isDebugEnabled()) {
s_logger.debug("Preparing host for migrating " + vm);
}
final NicTO[] nics = vm.getNics();
boolean skipDisconnect = false;
final KVMStoragePoolManager storagePoolMgr = libvirtComputingResource.getStoragePoolMgr();
try {
final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(vm.getName());
for (final NicTO nic : nics) {
libvirtComputingResource.getVifDriver(nic.getType()).plug(nic, null, "");
}
/* setup disks, e.g for iso */
final DiskTO[] volumes = vm.getDisks();
for (final DiskTO volume : volumes) {
if (volume.getType() == Volume.Type.ISO) {
libvirtComputingResource.getVolumePath(conn, volume);
}
}
skipDisconnect = true;
if (!storagePoolMgr.connectPhysicalDisksViaVmSpec(vm)) {
return new PrepareForMigrationAnswer(command, "failed to connect physical disks to host");
}
return new PrepareForMigrationAnswer(command);
} catch (final LibvirtException e) {
return new PrepareForMigrationAnswer(command, e.toString());
} catch (final InternalErrorException e) {
return new PrepareForMigrationAnswer(command, e.toString());
} catch (final URISyntaxException e) {
return new PrepareForMigrationAnswer(command, e.toString());
} finally {
if (!skipDisconnect) {
storagePoolMgr.disconnectPhysicalDisksViaVmSpec(vm);
}
}
}
use of org.libvirt.Connect in project cloudstack by apache.
the class LibvirtRebootCommandWrapper method execute.
@Override
public Answer execute(final RebootCommand command, final LibvirtComputingResource libvirtComputingResource) {
final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
try {
final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName());
final String result = libvirtComputingResource.rebootVM(conn, command.getVmName());
if (result == null) {
Integer vncPort = null;
try {
vncPort = libvirtComputingResource.getVncPort(conn, command.getVmName());
} catch (final LibvirtException e) {
s_logger.trace("Ignoring libvirt error.", e);
}
libvirtComputingResource.getRuleLogsForVms();
return new RebootAnswer(command, null, vncPort);
} else {
return new RebootAnswer(command, result, false);
}
} catch (final LibvirtException e) {
return new RebootAnswer(command, e.getMessage(), false);
}
}
use of org.libvirt.Connect in project cloudstack by apache.
the class LibvirtNetworkRulesSystemVmCommandWrapper method execute.
@Override
public Answer execute(final NetworkRulesSystemVmCommand command, final LibvirtComputingResource libvirtComputingResource) {
boolean success = false;
try {
final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(command.getVmName());
success = libvirtComputingResource.configureDefaultNetworkRulesForSystemVm(conn, command.getVmName());
} catch (final LibvirtException e) {
s_logger.trace("Ignoring libvirt error.", e);
}
return new Answer(command, success, "");
}
use of org.libvirt.Connect in project cloudstack by apache.
the class LibvirtBackupSnapshotCommandWrapper method execute.
@Override
public Answer execute(final BackupSnapshotCommand command, final LibvirtComputingResource libvirtComputingResource) {
final Long dcId = command.getDataCenterId();
final Long accountId = command.getAccountId();
final Long volumeId = command.getVolumeId();
final String secondaryStoragePoolUrl = command.getSecondaryStorageUrl();
final String snapshotName = command.getSnapshotName();
String snapshotDestPath = null;
String snapshotRelPath = null;
final String vmName = command.getVmName();
KVMStoragePool secondaryStoragePool = null;
final KVMStoragePoolManager storagePoolMgr = libvirtComputingResource.getStoragePoolMgr();
try {
final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper();
final Connect conn = libvirtUtilitiesHelper.getConnectionByVmName(vmName);
secondaryStoragePool = storagePoolMgr.getStoragePoolByURI(secondaryStoragePoolUrl);
final String ssPmountPath = secondaryStoragePool.getLocalPath();
snapshotRelPath = File.separator + "snapshots" + File.separator + dcId + File.separator + accountId + File.separator + volumeId;
snapshotDestPath = ssPmountPath + File.separator + "snapshots" + File.separator + dcId + File.separator + accountId + File.separator + volumeId;
final KVMStoragePool primaryPool = storagePoolMgr.getStoragePool(command.getPool().getType(), command.getPrimaryStoragePoolNameLabel());
final KVMPhysicalDisk snapshotDisk = primaryPool.getPhysicalDisk(command.getVolumePath());
final String manageSnapshotPath = libvirtComputingResource.manageSnapshotPath();
final int cmdsTimeout = libvirtComputingResource.getCmdsTimeout();
/**
* RBD snapshots can't be copied using qemu-img, so we have to use
* the Java bindings for librbd here.
*
* These bindings will read the snapshot and write the contents to
* the secondary storage directly
*
* It will stop doing so if the amount of time spend is longer then
* cmds.timeout
*/
if (primaryPool.getType() == StoragePoolType.RBD) {
try {
final Rados r = new Rados(primaryPool.getAuthUserName());
r.confSet("mon_host", primaryPool.getSourceHost() + ":" + primaryPool.getSourcePort());
r.confSet("key", primaryPool.getAuthSecret());
r.confSet("client_mount_timeout", "30");
r.connect();
s_logger.debug("Succesfully connected to Ceph cluster at " + r.confGet("mon_host"));
final IoCTX io = r.ioCtxCreate(primaryPool.getSourceDir());
final Rbd rbd = new Rbd(io);
final RbdImage image = rbd.open(snapshotDisk.getName(), snapshotName);
final File fh = new File(snapshotDestPath);
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fh))) {
final int chunkSize = 4194304;
long offset = 0;
s_logger.debug("Backuping up RBD snapshot " + snapshotName + " to " + snapshotDestPath);
while (true) {
final byte[] buf = new byte[chunkSize];
final int bytes = image.read(offset, buf, chunkSize);
if (bytes <= 0) {
break;
}
bos.write(buf, 0, bytes);
offset += bytes;
}
s_logger.debug("Completed backing up RBD snapshot " + snapshotName + " to " + snapshotDestPath + ". Bytes written: " + offset);
} catch (final IOException ex) {
s_logger.error("BackupSnapshotAnswer:Exception:" + ex.getMessage());
}
r.ioCtxDestroy(io);
} catch (final RadosException e) {
s_logger.error("A RADOS operation failed. The error was: " + e.getMessage());
return new BackupSnapshotAnswer(command, false, e.toString(), null, true);
} catch (final RbdException e) {
s_logger.error("A RBD operation on " + snapshotDisk.getName() + " failed. The error was: " + e.getMessage());
return new BackupSnapshotAnswer(command, false, e.toString(), null, true);
}
} else {
final Script scriptCommand = new Script(manageSnapshotPath, cmdsTimeout, s_logger);
scriptCommand.add("-b", snapshotDisk.getPath());
scriptCommand.add("-n", snapshotName);
scriptCommand.add("-p", snapshotDestPath);
scriptCommand.add("-t", snapshotName);
final String result = scriptCommand.execute();
if (result != null) {
s_logger.debug("Failed to backup snaptshot: " + result);
return new BackupSnapshotAnswer(command, false, result, null, true);
}
}
/* Delete the snapshot on primary */
DomainState state = null;
Domain vm = null;
if (vmName != null) {
try {
vm = libvirtComputingResource.getDomain(conn, command.getVmName());
state = vm.getInfo().state;
} catch (final LibvirtException e) {
s_logger.trace("Ignoring libvirt error.", e);
}
}
final KVMStoragePool primaryStorage = storagePoolMgr.getStoragePool(command.getPool().getType(), command.getPool().getUuid());
if (state == DomainState.VIR_DOMAIN_RUNNING && !primaryStorage.isExternalSnapshot()) {
final MessageFormat snapshotXML = new MessageFormat(" <domainsnapshot>" + " <name>{0}</name>" + " <domain>" + " <uuid>{1}</uuid>" + " </domain>" + " </domainsnapshot>");
final String vmUuid = vm.getUUIDString();
final Object[] args = new Object[] { snapshotName, vmUuid };
final String snapshot = snapshotXML.format(args);
s_logger.debug(snapshot);
final DomainSnapshot snap = vm.snapshotLookupByName(snapshotName);
if (snap != null) {
snap.delete(0);
} else {
throw new CloudRuntimeException("Unable to find vm snapshot with name -" + snapshotName);
}
/*
* libvirt on RHEL6 doesn't handle resume event emitted from
* qemu
*/
vm = libvirtComputingResource.getDomain(conn, command.getVmName());
state = vm.getInfo().state;
if (state == DomainState.VIR_DOMAIN_PAUSED) {
vm.resume();
}
} else {
final Script scriptCommand = new Script(manageSnapshotPath, cmdsTimeout, s_logger);
scriptCommand.add("-d", snapshotDisk.getPath());
scriptCommand.add("-n", snapshotName);
final String result = scriptCommand.execute();
if (result != null) {
s_logger.debug("Failed to backup snapshot: " + result);
return new BackupSnapshotAnswer(command, false, "Failed to backup snapshot: " + result, null, true);
}
}
} catch (final LibvirtException e) {
return new BackupSnapshotAnswer(command, false, e.toString(), null, true);
} catch (final CloudRuntimeException e) {
return new BackupSnapshotAnswer(command, false, e.toString(), null, true);
} finally {
if (secondaryStoragePool != null) {
storagePoolMgr.deleteStoragePool(secondaryStoragePool.getType(), secondaryStoragePool.getUuid());
}
}
return new BackupSnapshotAnswer(command, true, null, snapshotRelPath + File.separator + snapshotName, true);
}
Aggregations