You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cloudstack.apache.org by al...@apache.org on 2012/08/07 20:39:57 UTC
[2/61] [abbrv] Merge branch 'master' into vpc
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/95449da4/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
----------------------------------------------------------------------
diff --cc plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
index 6862e14,026b914..7bff023
--- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
+++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java
@@@ -1694,960 -1695,959 +1695,961 @@@ public class LibvirtComputingResource e
templFo.close();
}
- Map<String, Object> params = new HashMap<String, Object>();
- params.put(StorageLayer.InstanceConfigKey, _storage);
- Processor qcow2Processor = new QCOW2Processor();
-
- qcow2Processor.configure("QCOW2 Processor", params);
-
- FormatInfo info = qcow2Processor.process(tmpltPath, null,
- cmd.getUniqueName());
-
- TemplateLocation loc = new TemplateLocation(_storage, tmpltPath);
- loc.create(1, true, cmd.getUniqueName());
- loc.addFormat(info);
- loc.save();
-
- return new CreatePrivateTemplateAnswer(cmd, true, null,
- templateInstallFolder + cmd.getUniqueName() + ".qcow2",
- info.virtualSize, info.size, cmd.getUniqueName(),
- ImageFormat.QCOW2);
- } catch (LibvirtException e) {
- s_logger.debug("Failed to get secondary storage pool: "
- + e.toString());
- return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
- } catch (InternalErrorException e) {
- return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
- } catch (IOException e) {
- return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
- } catch (ConfigurationException e) {
- return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
- } catch (CloudRuntimeException e) {
- return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
- } finally {
- if (secondaryStorage != null) {
- secondaryStorage.delete();
- }
- }
- }
-
- protected PrimaryStorageDownloadAnswer execute(
- final PrimaryStorageDownloadCommand cmd) {
- String tmplturl = cmd.getUrl();
- int index = tmplturl.lastIndexOf("/");
- String mountpoint = tmplturl.substring(0, index);
- String tmpltname = null;
- if (index < tmplturl.length() - 1) {
- tmpltname = tmplturl.substring(index + 1);
- }
-
- KVMPhysicalDisk tmplVol = null;
- KVMStoragePool secondaryPool = null;
- try {
- secondaryPool = _storagePoolMgr.getStoragePoolByURI(mountpoint);
-
- /* Get template vol */
- if (tmpltname == null) {
- secondaryPool.refresh();
- List<KVMPhysicalDisk> disks = secondaryPool.listPhysicalDisks();
- if (disks == null || disks.isEmpty()) {
- return new PrimaryStorageDownloadAnswer(
- "Failed to get volumes from pool: "
- + secondaryPool.getUuid());
- }
- for (KVMPhysicalDisk disk : disks) {
- if (disk.getName().endsWith("qcow2")) {
- tmplVol = disk;
- break;
- }
- }
- if (tmplVol == null) {
- return new PrimaryStorageDownloadAnswer(
- "Failed to get template from pool: "
- + secondaryPool.getUuid());
- }
- } else {
- tmplVol = secondaryPool.getPhysicalDisk(tmpltname);
- }
-
- /* Copy volume to primary storage */
- KVMStoragePool primaryPool = _storagePoolMgr.getStoragePool(cmd
- .getPoolUuid());
-
- KVMPhysicalDisk primaryVol = _storagePoolMgr.copyPhysicalDisk(
- tmplVol, UUID.randomUUID().toString(), primaryPool);
-
- return new PrimaryStorageDownloadAnswer(primaryVol.getName(),
- primaryVol.getSize());
- } catch (CloudRuntimeException e) {
- return new PrimaryStorageDownloadAnswer(e.toString());
- } finally {
- if (secondaryPool != null) {
- secondaryPool.delete();
- }
- }
- }
-
- protected Answer execute(CreateStoragePoolCommand cmd) {
- return new Answer(cmd, true, "success");
- }
-
- protected Answer execute(ModifyStoragePoolCommand cmd) {
- KVMStoragePool storagepool = _storagePoolMgr.createStoragePool(cmd
+ Map<String, Object> params = new HashMap<String, Object>();
+ params.put(StorageLayer.InstanceConfigKey, _storage);
+ Processor qcow2Processor = new QCOW2Processor();
+
+ qcow2Processor.configure("QCOW2 Processor", params);
+
+ FormatInfo info = qcow2Processor.process(tmpltPath, null,
+ cmd.getUniqueName());
+
+ TemplateLocation loc = new TemplateLocation(_storage, tmpltPath);
+ loc.create(1, true, cmd.getUniqueName());
+ loc.addFormat(info);
+ loc.save();
+
+ return new CreatePrivateTemplateAnswer(cmd, true, null,
+ templateInstallFolder + cmd.getUniqueName() + ".qcow2",
+ info.virtualSize, info.size, cmd.getUniqueName(),
+ ImageFormat.QCOW2);
+ } catch (LibvirtException e) {
+ s_logger.debug("Failed to get secondary storage pool: "
+ + e.toString());
+ return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
+ } catch (InternalErrorException e) {
+ return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
+ } catch (IOException e) {
+ return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
+ } catch (ConfigurationException e) {
+ return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
+ } catch (CloudRuntimeException e) {
+ return new CreatePrivateTemplateAnswer(cmd, false, e.toString());
+ } finally {
+ if (secondaryStorage != null) {
+ secondaryStorage.delete();
+ }
+ }
+ }
+
+ protected PrimaryStorageDownloadAnswer execute(
+ final PrimaryStorageDownloadCommand cmd) {
+ String tmplturl = cmd.getUrl();
+ int index = tmplturl.lastIndexOf("/");
+ String mountpoint = tmplturl.substring(0, index);
+ String tmpltname = null;
+ if (index < tmplturl.length() - 1) {
+ tmpltname = tmplturl.substring(index + 1);
+ }
+
+ KVMPhysicalDisk tmplVol = null;
+ KVMStoragePool secondaryPool = null;
+ try {
+ secondaryPool = _storagePoolMgr.getStoragePoolByURI(mountpoint);
+
+ /* Get template vol */
+ if (tmpltname == null) {
+ secondaryPool.refresh();
+ List<KVMPhysicalDisk> disks = secondaryPool.listPhysicalDisks();
+ if (disks == null || disks.isEmpty()) {
+ return new PrimaryStorageDownloadAnswer(
+ "Failed to get volumes from pool: "
+ + secondaryPool.getUuid());
+ }
+ for (KVMPhysicalDisk disk : disks) {
+ if (disk.getName().endsWith("qcow2")) {
+ tmplVol = disk;
+ break;
+ }
+ }
+ if (tmplVol == null) {
+ return new PrimaryStorageDownloadAnswer(
+ "Failed to get template from pool: "
+ + secondaryPool.getUuid());
+ }
+ } else {
+ tmplVol = secondaryPool.getPhysicalDisk(tmpltname);
+ }
+
+ /* Copy volume to primary storage */
+ KVMStoragePool primaryPool = _storagePoolMgr.getStoragePool(cmd
+ .getPoolUuid());
+
+ KVMPhysicalDisk primaryVol = _storagePoolMgr.copyPhysicalDisk(
+ tmplVol, UUID.randomUUID().toString(), primaryPool);
+
+ return new PrimaryStorageDownloadAnswer(primaryVol.getName(),
+ primaryVol.getSize());
+ } catch (CloudRuntimeException e) {
+ return new PrimaryStorageDownloadAnswer(e.toString());
+ } finally {
+ if (secondaryPool != null) {
+ secondaryPool.delete();
+ }
+ }
+ }
+
+ protected Answer execute(CreateStoragePoolCommand cmd) {
+ return new Answer(cmd, true, "success");
+ }
+
+ protected Answer execute(ModifyStoragePoolCommand cmd) {
+ KVMStoragePool storagepool = _storagePoolMgr.createStoragePool(cmd
.getPool().getUuid(), cmd.getPool().getHost(), cmd.getPool().getPort(),
cmd.getPool().getPath(), cmd.getPool().getUserInfo(), cmd.getPool().getType());
- if (storagepool == null) {
- return new Answer(cmd, false, " Failed to create storage pool");
- }
-
- Map<String, TemplateInfo> tInfo = new HashMap<String, TemplateInfo>();
- ModifyStoragePoolAnswer answer = new ModifyStoragePoolAnswer(cmd,
- storagepool.getCapacity(), storagepool.getUsed(), tInfo);
-
- return answer;
- }
-
- private Answer execute(SecurityGroupRulesCmd cmd) {
- String vif = null;
- String brname = null;
- try {
- Connect conn = LibvirtConnection.getConnection();
- List<InterfaceDef> nics = getInterfaces(conn, cmd.getVmName());
- vif = nics.get(0).getDevName();
- brname = nics.get(0).getBrName();
- } catch (LibvirtException e) {
- return new SecurityGroupRuleAnswer(cmd, false, e.toString());
- }
-
- boolean result = add_network_rules(cmd.getVmName(),
- Long.toString(cmd.getVmId()), cmd.getGuestIp(),
- cmd.getSignature(), Long.toString(cmd.getSeqNum()),
- cmd.getGuestMac(), cmd.stringifyRules(), vif, brname);
-
- if (!result) {
- s_logger.warn("Failed to program network rules for vm "
- + cmd.getVmName());
- return new SecurityGroupRuleAnswer(cmd, false,
- "programming network rules failed");
- } else {
- s_logger.debug("Programmed network rules for vm " + cmd.getVmName()
- + " guestIp=" + cmd.getGuestIp() + ",ingress numrules="
- + cmd.getIngressRuleSet().length + ",egress numrules="
- + cmd.getEgressRuleSet().length);
- return new SecurityGroupRuleAnswer(cmd);
- }
- }
-
- private Answer execute(CleanupNetworkRulesCmd cmd) {
- boolean result = cleanup_rules();
- return new Answer(cmd, result, "");
- }
-
- protected GetVncPortAnswer execute(GetVncPortCommand cmd) {
- try {
- Connect conn = LibvirtConnection.getConnection();
- Integer vncPort = getVncPort(conn, cmd.getName());
- return new GetVncPortAnswer(cmd, _privateIp, 5900 + vncPort);
- } catch (Exception e) {
- return new GetVncPortAnswer(cmd, e.toString());
- }
- }
-
- protected Answer execute(final CheckConsoleProxyLoadCommand cmd) {
- return executeProxyLoadScan(cmd, cmd.getProxyVmId(),
- cmd.getProxyVmName(), cmd.getProxyManagementIp(),
- cmd.getProxyCmdPort());
- }
-
- protected Answer execute(final WatchConsoleProxyLoadCommand cmd) {
- return executeProxyLoadScan(cmd, cmd.getProxyVmId(),
- cmd.getProxyVmName(), cmd.getProxyManagementIp(),
- cmd.getProxyCmdPort());
- }
-
- protected MaintainAnswer execute(MaintainCommand cmd) {
- return new MaintainAnswer(cmd);
- }
-
- private Answer executeProxyLoadScan(final Command cmd,
- final long proxyVmId, final String proxyVmName,
- final String proxyManagementIp, final int cmdPort) {
- String result = null;
-
- final StringBuffer sb = new StringBuffer();
- sb.append("http://").append(proxyManagementIp).append(":" + cmdPort)
- .append("/cmd/getstatus");
-
- boolean success = true;
- try {
- final URL url = new URL(sb.toString());
- final URLConnection conn = url.openConnection();
-
- final InputStream is = conn.getInputStream();
- final BufferedReader reader = new BufferedReader(
- new InputStreamReader(is));
- final StringBuilder sb2 = new StringBuilder();
- String line = null;
- try {
- while ((line = reader.readLine()) != null) {
- sb2.append(line + "\n");
- }
- result = sb2.toString();
- } catch (final IOException e) {
- success = false;
- } finally {
- try {
- is.close();
- } catch (final IOException e) {
- s_logger.warn("Exception when closing , console proxy address : "
- + proxyManagementIp);
- success = false;
- }
- }
- } catch (final IOException e) {
- s_logger.warn("Unable to open console proxy command port url, console proxy address : "
- + proxyManagementIp);
- success = false;
- }
-
- return new ConsoleProxyLoadAnswer(cmd, proxyVmId, proxyVmName, success,
- result);
- }
-
- private Answer execute(AttachIsoCommand cmd) {
- try {
- Connect conn = LibvirtConnection.getConnection();
- attachOrDetachISO(conn, cmd.getVmName(), cmd.getIsoPath(),
- cmd.isAttach());
- } catch (LibvirtException e) {
- return new Answer(cmd, false, e.toString());
- } catch (URISyntaxException e) {
- return new Answer(cmd, false, e.toString());
- } catch (InternalErrorException e) {
- return new Answer(cmd, false, e.toString());
- }
-
- return new Answer(cmd);
- }
-
- private AttachVolumeAnswer execute(AttachVolumeCommand cmd) {
- try {
- Connect conn = LibvirtConnection.getConnection();
- KVMStoragePool primary = _storagePoolMgr.getStoragePool(cmd
- .getPoolUuid());
- KVMPhysicalDisk disk = primary.getPhysicalDisk(cmd.getVolumePath());
- attachOrDetachDisk(conn, cmd.getAttach(), cmd.getVmName(), disk,
- cmd.getDeviceId().intValue());
- } catch (LibvirtException e) {
- return new AttachVolumeAnswer(cmd, e.toString());
- } catch (InternalErrorException e) {
- return new AttachVolumeAnswer(cmd, e.toString());
- }
-
- return new AttachVolumeAnswer(cmd, cmd.getDeviceId());
- }
-
- private Answer execute(ReadyCommand cmd) {
- return new ReadyAnswer(cmd);
- }
-
- protected State convertToState(DomainInfo.DomainState ps) {
- final State state = s_statesTable.get(ps);
- return state == null ? State.Unknown : state;
- }
-
- protected State getVmState(Connect conn, final String vmName) {
- int retry = 3;
- Domain vms = null;
- while (retry-- > 0) {
- try {
- vms = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
- .getBytes()));
- State s = convertToState(vms.getInfo().state);
- return s;
- } catch (final LibvirtException e) {
- s_logger.warn("Can't get vm state " + vmName + e.getMessage()
- + "retry:" + retry);
- } catch (Exception e) {
- s_logger.warn("Can't get vm state " + vmName + e.getMessage()
- + "retry:" + retry);
- } finally {
- try {
- if (vms != null) {
- vms.free();
- }
- } catch (final LibvirtException e) {
-
- }
- }
- }
- return State.Stopped;
- }
-
- private Answer execute(CheckVirtualMachineCommand cmd) {
- try {
- Connect conn = LibvirtConnection.getConnection();
- final State state = getVmState(conn, cmd.getVmName());
- Integer vncPort = null;
- if (state == State.Running) {
- vncPort = getVncPort(conn, cmd.getVmName());
-
- synchronized (_vms) {
- _vms.put(cmd.getVmName(), State.Running);
- }
- }
-
- return new CheckVirtualMachineAnswer(cmd, state, vncPort);
- } catch (LibvirtException e) {
- return new CheckVirtualMachineAnswer(cmd, e.getMessage());
- }
- }
-
- private Answer execute(PingTestCommand cmd) {
- String result = null;
- final String computingHostIp = cmd.getComputingHostIp(); // TODO, split
- // the
- // command
- // into 2
- // types
-
- if (computingHostIp != null) {
- result = doPingTest(computingHostIp);
- } else if (cmd.getRouterIp() != null && cmd.getPrivateIp() != null) {
- result = doPingTest(cmd.getRouterIp(), cmd.getPrivateIp());
- } else {
- return new Answer(cmd, false, "routerip and private ip is null");
- }
-
- if (result != null) {
- return new Answer(cmd, false, result);
- }
- return new Answer(cmd);
- }
-
- private String doPingTest(final String computingHostIp) {
- final Script command = new Script(_pingTestPath, 10000, s_logger);
- command.add("-h", computingHostIp);
- return command.execute();
- }
-
- private String doPingTest(final String domRIp, final String vmIp) {
- final Script command = new Script(_pingTestPath, 10000, s_logger);
- command.add("-i", domRIp);
- command.add("-p", vmIp);
- return command.execute();
- }
-
- private synchronized Answer execute(MigrateCommand cmd) {
- String vmName = cmd.getVmName();
-
- State state = null;
- String result = null;
- synchronized (_vms) {
- state = _vms.get(vmName);
- _vms.put(vmName, State.Stopping);
- }
-
- Domain dm = null;
- Connect dconn = null;
- Domain destDomain = null;
- Connect conn = null;
- try {
- conn = LibvirtConnection.getConnection();
- dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
- .getBytes()));
- dconn = new Connect("qemu+tcp://" + cmd.getDestinationIp()
- + "/system");
- /*
- * Hard code lm flags: VIR_MIGRATE_LIVE(1<<0) and
- * VIR_MIGRATE_PERSIST_DEST(1<<3)
- */
- destDomain = dm.migrate(dconn, (1 << 0) | (1 << 3), vmName, "tcp:"
- + cmd.getDestinationIp(), _migrateSpeed);
- } catch (LibvirtException e) {
- s_logger.debug("Can't migrate domain: " + e.getMessage());
- result = e.getMessage();
- } catch (Exception e) {
- s_logger.debug("Can't migrate domain: " + e.getMessage());
- result = e.getMessage();
- } finally {
- try {
- if (dm != null) {
- dm.free();
- }
- if (dconn != null) {
- dconn.close();
- }
- if (destDomain != null) {
- destDomain.free();
- }
- } catch (final LibvirtException e) {
-
- }
- }
-
- if (result != null) {
- synchronized (_vms) {
- _vms.put(vmName, state);
- }
- } else {
- destroy_network_rules_for_vm(conn, vmName);
- cleanupVM(conn, vmName,
- getVnetId(VirtualMachineName.getVnet(vmName)));
- }
-
- return new MigrateAnswer(cmd, result == null, result, null);
- }
-
- private synchronized Answer execute(PrepareForMigrationCommand cmd) {
-
- VirtualMachineTO vm = cmd.getVirtualMachine();
- if (s_logger.isDebugEnabled()) {
- s_logger.debug("Preparing host for migrating " + vm);
- }
-
- NicTO[] nics = vm.getNics();
- try {
- Connect conn = LibvirtConnection.getConnection();
- for (NicTO nic : nics) {
- String vlanId = null;
- if (nic.getBroadcastType() == BroadcastDomainType.Vlan) {
- URI broadcastUri = nic.getBroadcastUri();
- vlanId = broadcastUri.getHost();
- }
- if (nic.getType() == TrafficType.Guest) {
- if (nic.getBroadcastType() == BroadcastDomainType.Vlan
- && !vlanId.equalsIgnoreCase("untagged")) {
- createVlanBr(vlanId, _pifs.first());
- }
- } else if (nic.getType() == TrafficType.Control) {
- /* Make sure the network is still there */
+ if (storagepool == null) {
+ return new Answer(cmd, false, " Failed to create storage pool");
+ }
+
+ Map<String, TemplateInfo> tInfo = new HashMap<String, TemplateInfo>();
+ ModifyStoragePoolAnswer answer = new ModifyStoragePoolAnswer(cmd,
+ storagepool.getCapacity(), storagepool.getUsed(), tInfo);
+
+ return answer;
+ }
+
+ private Answer execute(SecurityGroupRulesCmd cmd) {
+ String vif = null;
+ String brname = null;
+ try {
+ Connect conn = LibvirtConnection.getConnection();
+ List<InterfaceDef> nics = getInterfaces(conn, cmd.getVmName());
+ vif = nics.get(0).getDevName();
+ brname = nics.get(0).getBrName();
+ } catch (LibvirtException e) {
+ return new SecurityGroupRuleAnswer(cmd, false, e.toString());
+ }
+
+ boolean result = add_network_rules(cmd.getVmName(),
+ Long.toString(cmd.getVmId()), cmd.getGuestIp(),
+ cmd.getSignature(), Long.toString(cmd.getSeqNum()),
+ cmd.getGuestMac(), cmd.stringifyRules(), vif, brname);
+
+ if (!result) {
+ s_logger.warn("Failed to program network rules for vm "
+ + cmd.getVmName());
+ return new SecurityGroupRuleAnswer(cmd, false,
+ "programming network rules failed");
+ } else {
+ s_logger.debug("Programmed network rules for vm " + cmd.getVmName()
+ + " guestIp=" + cmd.getGuestIp() + ",ingress numrules="
+ + cmd.getIngressRuleSet().length + ",egress numrules="
+ + cmd.getEgressRuleSet().length);
+ return new SecurityGroupRuleAnswer(cmd);
+ }
+ }
+
+ private Answer execute(CleanupNetworkRulesCmd cmd) {
+ boolean result = cleanup_rules();
+ return new Answer(cmd, result, "");
+ }
+
+ protected GetVncPortAnswer execute(GetVncPortCommand cmd) {
+ try {
+ Connect conn = LibvirtConnection.getConnection();
+ Integer vncPort = getVncPort(conn, cmd.getName());
+ return new GetVncPortAnswer(cmd, _privateIp, 5900 + vncPort);
+ } catch (Exception e) {
+ return new GetVncPortAnswer(cmd, e.toString());
+ }
+ }
+
+ protected Answer execute(final CheckConsoleProxyLoadCommand cmd) {
+ return executeProxyLoadScan(cmd, cmd.getProxyVmId(),
+ cmd.getProxyVmName(), cmd.getProxyManagementIp(),
+ cmd.getProxyCmdPort());
+ }
+
+ protected Answer execute(final WatchConsoleProxyLoadCommand cmd) {
+ return executeProxyLoadScan(cmd, cmd.getProxyVmId(),
+ cmd.getProxyVmName(), cmd.getProxyManagementIp(),
+ cmd.getProxyCmdPort());
+ }
+
+ protected MaintainAnswer execute(MaintainCommand cmd) {
+ return new MaintainAnswer(cmd);
+ }
+
+ private Answer executeProxyLoadScan(final Command cmd,
+ final long proxyVmId, final String proxyVmName,
+ final String proxyManagementIp, final int cmdPort) {
+ String result = null;
+
+ final StringBuffer sb = new StringBuffer();
+ sb.append("http://").append(proxyManagementIp).append(":" + cmdPort)
+ .append("/cmd/getstatus");
+
+ boolean success = true;
+ try {
+ final URL url = new URL(sb.toString());
+ final URLConnection conn = url.openConnection();
+
+ final InputStream is = conn.getInputStream();
+ final BufferedReader reader = new BufferedReader(
+ new InputStreamReader(is));
+ final StringBuilder sb2 = new StringBuilder();
+ String line = null;
+ try {
+ while ((line = reader.readLine()) != null) {
+ sb2.append(line + "\n");
+ }
+ result = sb2.toString();
+ } catch (final IOException e) {
+ success = false;
+ } finally {
+ try {
+ is.close();
+ } catch (final IOException e) {
+ s_logger.warn("Exception when closing , console proxy address : "
+ + proxyManagementIp);
+ success = false;
+ }
+ }
+ } catch (final IOException e) {
+ s_logger.warn("Unable to open console proxy command port url, console proxy address : "
+ + proxyManagementIp);
+ success = false;
+ }
+
+ return new ConsoleProxyLoadAnswer(cmd, proxyVmId, proxyVmName, success,
+ result);
+ }
+
+ private Answer execute(AttachIsoCommand cmd) {
+ try {
+ Connect conn = LibvirtConnection.getConnection();
+ attachOrDetachISO(conn, cmd.getVmName(), cmd.getIsoPath(),
+ cmd.isAttach());
+ } catch (LibvirtException e) {
+ return new Answer(cmd, false, e.toString());
+ } catch (URISyntaxException e) {
+ return new Answer(cmd, false, e.toString());
+ } catch (InternalErrorException e) {
+ return new Answer(cmd, false, e.toString());
+ }
+
+ return new Answer(cmd);
+ }
+
+ private AttachVolumeAnswer execute(AttachVolumeCommand cmd) {
+ try {
+ Connect conn = LibvirtConnection.getConnection();
+ KVMStoragePool primary = _storagePoolMgr.getStoragePool(cmd
+ .getPoolUuid());
+ KVMPhysicalDisk disk = primary.getPhysicalDisk(cmd.getVolumePath());
+ attachOrDetachDisk(conn, cmd.getAttach(), cmd.getVmName(), disk,
+ cmd.getDeviceId().intValue());
+ } catch (LibvirtException e) {
+ return new AttachVolumeAnswer(cmd, e.toString());
+ } catch (InternalErrorException e) {
+ return new AttachVolumeAnswer(cmd, e.toString());
+ }
+
+ return new AttachVolumeAnswer(cmd, cmd.getDeviceId());
+ }
+
+ private Answer execute(ReadyCommand cmd) {
+ return new ReadyAnswer(cmd);
+ }
+
+ protected State convertToState(DomainInfo.DomainState ps) {
+ final State state = s_statesTable.get(ps);
+ return state == null ? State.Unknown : state;
+ }
+
+ protected State getVmState(Connect conn, final String vmName) {
+ int retry = 3;
+ Domain vms = null;
+ while (retry-- > 0) {
+ try {
+ vms = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
+ .getBytes()));
+ State s = convertToState(vms.getInfo().state);
+ return s;
+ } catch (final LibvirtException e) {
+ s_logger.warn("Can't get vm state " + vmName + e.getMessage()
+ + "retry:" + retry);
+ } catch (Exception e) {
+ s_logger.warn("Can't get vm state " + vmName + e.getMessage()
+ + "retry:" + retry);
+ } finally {
+ try {
+ if (vms != null) {
+ vms.free();
+ }
+ } catch (final LibvirtException e) {
+
+ }
+ }
+ }
+ return State.Stopped;
+ }
+
+ private Answer execute(CheckVirtualMachineCommand cmd) {
+ try {
+ Connect conn = LibvirtConnection.getConnection();
+ final State state = getVmState(conn, cmd.getVmName());
+ Integer vncPort = null;
+ if (state == State.Running) {
+ vncPort = getVncPort(conn, cmd.getVmName());
+
+ synchronized (_vms) {
+ _vms.put(cmd.getVmName(), State.Running);
+ }
+ }
+
+ return new CheckVirtualMachineAnswer(cmd, state, vncPort);
+ } catch (LibvirtException e) {
+ return new CheckVirtualMachineAnswer(cmd, e.getMessage());
+ }
+ }
+
+ private Answer execute(PingTestCommand cmd) {
+ String result = null;
+ final String computingHostIp = cmd.getComputingHostIp(); // TODO, split
+ // the
+ // command
+ // into 2
+ // types
+
+ if (computingHostIp != null) {
+ result = doPingTest(computingHostIp);
+ } else if (cmd.getRouterIp() != null && cmd.getPrivateIp() != null) {
+ result = doPingTest(cmd.getRouterIp(), cmd.getPrivateIp());
+ } else {
+ return new Answer(cmd, false, "routerip and private ip is null");
+ }
+
+ if (result != null) {
+ return new Answer(cmd, false, result);
+ }
+ return new Answer(cmd);
+ }
+
+ private String doPingTest(final String computingHostIp) {
+ final Script command = new Script(_pingTestPath, 10000, s_logger);
+ command.add("-h", computingHostIp);
+ return command.execute();
+ }
+
+ private String doPingTest(final String domRIp, final String vmIp) {
+ final Script command = new Script(_pingTestPath, 10000, s_logger);
+ command.add("-i", domRIp);
+ command.add("-p", vmIp);
+ return command.execute();
+ }
+
+ private synchronized Answer execute(MigrateCommand cmd) {
+ String vmName = cmd.getVmName();
+
+ State state = null;
+ String result = null;
+ synchronized (_vms) {
+ state = _vms.get(vmName);
+ _vms.put(vmName, State.Stopping);
+ }
+
+ Domain dm = null;
+ Connect dconn = null;
+ Domain destDomain = null;
+ Connect conn = null;
+ try {
+ conn = LibvirtConnection.getConnection();
+ dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName
+ .getBytes()));
+ dconn = new Connect("qemu+tcp://" + cmd.getDestinationIp()
+ + "/system");
+ /*
+ * Hard code lm flags: VIR_MIGRATE_LIVE(1<<0) and
+ * VIR_MIGRATE_PERSIST_DEST(1<<3)
+ */
+ destDomain = dm.migrate(dconn, (1 << 0) | (1 << 3), vmName, "tcp:"
+ + cmd.getDestinationIp(), _migrateSpeed);
+ } catch (LibvirtException e) {
+ s_logger.debug("Can't migrate domain: " + e.getMessage());
+ result = e.getMessage();
+ } catch (Exception e) {
+ s_logger.debug("Can't migrate domain: " + e.getMessage());
+ result = e.getMessage();
+ } finally {
+ try {
+ if (dm != null) {
+ dm.free();
+ }
+ if (dconn != null) {
+ dconn.close();
+ }
+ if (destDomain != null) {
+ destDomain.free();
+ }
+ } catch (final LibvirtException e) {
+
+ }
+ }
+
+ if (result != null) {
+ synchronized (_vms) {
+ _vms.put(vmName, state);
+ }
+ } else {
+ destroy_network_rules_for_vm(conn, vmName);
+ cleanupVM(conn, vmName,
+ getVnetId(VirtualMachineName.getVnet(vmName)));
+ }
+
+ return new MigrateAnswer(cmd, result == null, result, null);
+ }
+
+ private synchronized Answer execute(PrepareForMigrationCommand cmd) {
+
+ VirtualMachineTO vm = cmd.getVirtualMachine();
+ if (s_logger.isDebugEnabled()) {
+ s_logger.debug("Preparing host for migrating " + vm);
+ }
+
+ NicTO[] nics = vm.getNics();
+ try {
+ Connect conn = LibvirtConnection.getConnection();
+ for (NicTO nic : nics) {
+ String vlanId = null;
+ if (nic.getBroadcastType() == BroadcastDomainType.Vlan) {
+ URI broadcastUri = nic.getBroadcastUri();
+ vlanId = broadcastUri.getHost();
+ }
+ if (nic.getType() == TrafficType.Guest) {
+ if (nic.getBroadcastType() == BroadcastDomainType.Vlan
+ && !vlanId.equalsIgnoreCase("untagged")) {
+ createVlanBr(vlanId, _pifs.first());
+ }
+ } else if (nic.getType() == TrafficType.Control) {
+ /* Make sure the network is still there */
createControlNetwork();
- } else if (nic.getType() == TrafficType.Public) {
- if (nic.getBroadcastType() == BroadcastDomainType.Vlan
- && !vlanId.equalsIgnoreCase("untagged")) {
- createVlanBr(vlanId, _pifs.second());
- }
- }
- }
-
- /* setup disks, e.g for iso */
- VolumeTO[] volumes = vm.getDisks();
- for (VolumeTO volume : volumes) {
- if (volume.getType() == Volume.Type.ISO) {
- getVolumePath(conn, volume);
- }
- }
-
- synchronized (_vms) {
- _vms.put(vm.getName(), State.Migrating);
- }
-
- return new PrepareForMigrationAnswer(cmd);
- } catch (LibvirtException e) {
- return new PrepareForMigrationAnswer(cmd, e.toString());
- } catch (InternalErrorException e) {
- return new PrepareForMigrationAnswer(cmd, e.toString());
- } catch (URISyntaxException e) {
- return new PrepareForMigrationAnswer(cmd, e.toString());
- }
- }
-
- public void createVnet(String vnetId, String pif)
- throws InternalErrorException {
- final Script command = new Script(_modifyVlanPath, _timeout, s_logger);
- command.add("-v", vnetId);
- command.add("-p", pif);
- command.add("-o", "add");
-
- final String result = command.execute();
- if (result != null) {
- throw new InternalErrorException("Failed to create vnet " + vnetId
- + ": " + result);
- }
- }
-
- private Answer execute(CheckHealthCommand cmd) {
- return new CheckHealthAnswer(cmd, true);
- }
-
- private Answer execute(GetHostStatsCommand cmd) {
- final Script cpuScript = new Script("/bin/bash", s_logger);
- cpuScript.add("-c");
- cpuScript
- .add("idle=$(top -b -n 1|grep Cpu\\(s\\):|cut -d% -f4|cut -d, -f2);echo $idle");
-
- final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser();
- String result = cpuScript.execute(parser);
- if (result != null) {
- s_logger.debug("Unable to get the host CPU state: " + result);
- return new Answer(cmd, false, result);
- }
- double cpuUtil = (100.0D - Double.parseDouble(parser.getLine()));
-
- long freeMem = 0;
- final Script memScript = new Script("/bin/bash", s_logger);
- memScript.add("-c");
- memScript
- .add("freeMem=$(free|grep cache:|awk '{print $4}');echo $freeMem");
- final OutputInterpreter.OneLineParser Memparser = new OutputInterpreter.OneLineParser();
- result = memScript.execute(Memparser);
- if (result != null) {
- s_logger.debug("Unable to get the host Mem state: " + result);
- return new Answer(cmd, false, result);
- }
- freeMem = Long.parseLong(Memparser.getLine());
-
- Script totalMem = new Script("/bin/bash", s_logger);
- totalMem.add("-c");
- totalMem.add("free|grep Mem:|awk '{print $2}'");
- final OutputInterpreter.OneLineParser totMemparser = new OutputInterpreter.OneLineParser();
- result = totalMem.execute(totMemparser);
- if (result != null) {
- s_logger.debug("Unable to get the host Mem state: " + result);
- return new Answer(cmd, false, result);
- }
- long totMem = Long.parseLong(totMemparser.getLine());
-
- Pair<Double, Double> nicStats = getNicStats(_publicBridgeName);
-
- HostStatsEntry hostStats = new HostStatsEntry(cmd.getHostId(), cpuUtil,
- nicStats.first() / 1000, nicStats.second() / 1000, "host",
- totMem, freeMem, 0, 0);
- return new GetHostStatsAnswer(cmd, hostStats);
- }
-
- protected String networkUsage(final String privateIpAddress,
- final String option, final String vif) {
- Script getUsage = new Script(_networkUsagePath, s_logger);
- if (option.equals("get")) {
- getUsage.add("-g");
- } else if (option.equals("create")) {
- getUsage.add("-c");
- } else if (option.equals("reset")) {
- getUsage.add("-r");
- } else if (option.equals("addVif")) {
- getUsage.add("-a", vif);
- } else if (option.equals("deleteVif")) {
- getUsage.add("-d", vif);
- }
-
- getUsage.add("-i", privateIpAddress);
- final OutputInterpreter.OneLineParser usageParser = new OutputInterpreter.OneLineParser();
- String result = getUsage.execute(usageParser);
- if (result != null) {
- s_logger.debug("Failed to execute networkUsage:" + result);
- return null;
- }
- return usageParser.getLine();
- }
-
- protected long[] getNetworkStats(String privateIP) {
- String result = networkUsage(privateIP, "get", null);
- long[] stats = new long[2];
- if (result != null) {
- String[] splitResult = result.split(":");
- int i = 0;
- while (i < splitResult.length - 1) {
- stats[0] += (new Long(splitResult[i++])).longValue();
- stats[1] += (new Long(splitResult[i++])).longValue();
- }
- }
- return stats;
- }
-
- private Answer execute(NetworkUsageCommand cmd) {
- if (cmd.getOption() != null && cmd.getOption().equals("create")) {
- String result = networkUsage(cmd.getPrivateIP(), "create", null);
- NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, result, 0L,
- 0L);
- return answer;
- }
- long[] stats = getNetworkStats(cmd.getPrivateIP());
- NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, "", stats[0],
- stats[1]);
- return answer;
- }
-
- private Answer execute(RebootCommand cmd) {
-
- synchronized (_vms) {
- _vms.put(cmd.getVmName(), State.Starting);
- }
-
- try {
- Connect conn = LibvirtConnection.getConnection();
- final String result = rebootVM(conn, cmd.getVmName());
- if (result == null) {
- Integer vncPort = null;
- try {
- vncPort = getVncPort(conn, cmd.getVmName());
- } catch (Exception e) {
-
- }
- get_rule_logs_for_vms();
+ } else if (nic.getType() == TrafficType.Public) {
+ if (nic.getBroadcastType() == BroadcastDomainType.Vlan
+ && !vlanId.equalsIgnoreCase("untagged")) {
+ createVlanBr(vlanId, _pifs.second());
+ }
+ }
+ }
+
+ /* setup disks, e.g for iso */
+ VolumeTO[] volumes = vm.getDisks();
+ for (VolumeTO volume : volumes) {
+ if (volume.getType() == Volume.Type.ISO) {
+ getVolumePath(conn, volume);
+ }
+ }
+
+ synchronized (_vms) {
+ _vms.put(vm.getName(), State.Migrating);
+ }
+
+ return new PrepareForMigrationAnswer(cmd);
+ } catch (LibvirtException e) {
+ return new PrepareForMigrationAnswer(cmd, e.toString());
+ } catch (InternalErrorException e) {
+ return new PrepareForMigrationAnswer(cmd, e.toString());
+ } catch (URISyntaxException e) {
+ return new PrepareForMigrationAnswer(cmd, e.toString());
+ }
+ }
+
+ public void createVnet(String vnetId, String pif)
+ throws InternalErrorException {
+ final Script command = new Script(_modifyVlanPath, _timeout, s_logger);
+ command.add("-v", vnetId);
+ command.add("-p", pif);
+ command.add("-o", "add");
+
+ final String result = command.execute();
+ if (result != null) {
+ throw new InternalErrorException("Failed to create vnet " + vnetId
+ + ": " + result);
+ }
+ }
+
+ private Answer execute(CheckHealthCommand cmd) {
+ return new CheckHealthAnswer(cmd, true);
+ }
+
+ private Answer execute(GetHostStatsCommand cmd) {
+ final Script cpuScript = new Script("/bin/bash", s_logger);
+ cpuScript.add("-c");
+ cpuScript
+ .add("idle=$(top -b -n 1|grep Cpu\\(s\\):|cut -d% -f4|cut -d, -f2);echo $idle");
+
+ final OutputInterpreter.OneLineParser parser = new OutputInterpreter.OneLineParser();
+ String result = cpuScript.execute(parser);
+ if (result != null) {
+ s_logger.debug("Unable to get the host CPU state: " + result);
+ return new Answer(cmd, false, result);
+ }
+ double cpuUtil = (100.0D - Double.parseDouble(parser.getLine()));
+
+ long freeMem = 0;
+ final Script memScript = new Script("/bin/bash", s_logger);
+ memScript.add("-c");
+ memScript
+ .add("freeMem=$(free|grep cache:|awk '{print $4}');echo $freeMem");
+ final OutputInterpreter.OneLineParser Memparser = new OutputInterpreter.OneLineParser();
+ result = memScript.execute(Memparser);
+ if (result != null) {
+ s_logger.debug("Unable to get the host Mem state: " + result);
+ return new Answer(cmd, false, result);
+ }
+ freeMem = Long.parseLong(Memparser.getLine());
+
+ Script totalMem = new Script("/bin/bash", s_logger);
+ totalMem.add("-c");
+ totalMem.add("free|grep Mem:|awk '{print $2}'");
+ final OutputInterpreter.OneLineParser totMemparser = new OutputInterpreter.OneLineParser();
+ result = totalMem.execute(totMemparser);
+ if (result != null) {
+ s_logger.debug("Unable to get the host Mem state: " + result);
+ return new Answer(cmd, false, result);
+ }
+ long totMem = Long.parseLong(totMemparser.getLine());
+
+ Pair<Double, Double> nicStats = getNicStats(_publicBridgeName);
+
+ HostStatsEntry hostStats = new HostStatsEntry(cmd.getHostId(), cpuUtil,
+ nicStats.first() / 1000, nicStats.second() / 1000, "host",
+ totMem, freeMem, 0, 0);
+ return new GetHostStatsAnswer(cmd, hostStats);
+ }
+
+ protected String networkUsage(final String privateIpAddress,
+ final String option, final String vif) {
+ Script getUsage = new Script(_routerProxyPath, s_logger);
+ getUsage.add("netusage.sh");
+ getUsage.add(privateIpAddress);
+ if (option.equals("get")) {
+ getUsage.add("-g");
+ } else if (option.equals("create")) {
+ getUsage.add("-c");
+ } else if (option.equals("reset")) {
+ getUsage.add("-r");
+ } else if (option.equals("addVif")) {
+ getUsage.add("-a", vif);
+ } else if (option.equals("deleteVif")) {
+ getUsage.add("-d", vif);
+ }
+
+
+ final OutputInterpreter.OneLineParser usageParser = new OutputInterpreter.OneLineParser();
+ String result = getUsage.execute(usageParser);
+ if (result != null) {
+ s_logger.debug("Failed to execute networkUsage:" + result);
+ return null;
+ }
+ return usageParser.getLine();
+ }
+
+ protected long[] getNetworkStats(String privateIP) {
+ String result = networkUsage(privateIP, "get", null);
+ long[] stats = new long[2];
+ if (result != null) {
+ String[] splitResult = result.split(":");
+ int i = 0;
+ while (i < splitResult.length - 1) {
+ stats[0] += (new Long(splitResult[i++])).longValue();
+ stats[1] += (new Long(splitResult[i++])).longValue();
+ }
+ }
+ return stats;
+ }
+
+ private Answer execute(NetworkUsageCommand cmd) {
+ if (cmd.getOption() != null && cmd.getOption().equals("create")) {
+ String result = networkUsage(cmd.getPrivateIP(), "create", null);
+ NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, result, 0L,
+ 0L);
+ return answer;
+ }
+ long[] stats = getNetworkStats(cmd.getPrivateIP());
+ NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, "", stats[0],
+ stats[1]);
+ return answer;
+ }
+
+ private Answer execute(RebootCommand cmd) {
+
+ synchronized (_vms) {
+ _vms.put(cmd.getVmName(), State.Starting);
+ }
+
+ try {
+ Connect conn = LibvirtConnection.getConnection();
+ final String result = rebootVM(conn, cmd.getVmName());
+ if (result == null) {
+ Integer vncPort = null;
+ try {
+ vncPort = getVncPort(conn, cmd.getVmName());
+ } catch (Exception e) {
+
+ }
+ get_rule_logs_for_vms();
return new RebootAnswer(cmd, null, vncPort);
- } else {
+ } else {
return new RebootAnswer(cmd, result, false);
- }
- } catch (LibvirtException e) {
+ }
+ } catch (LibvirtException e) {
return new RebootAnswer(cmd, e.getMessage(), false);
- } finally {
- synchronized (_vms) {
- _vms.put(cmd.getVmName(), State.Running);
- }
- }
- }
-
- protected Answer execute(RebootRouterCommand cmd) {
- RebootAnswer answer = (RebootAnswer) execute((RebootCommand) cmd);
- String result = _virtRouterResource.connect(cmd.getPrivateIpAddress());
- if (result == null) {
- networkUsage(cmd.getPrivateIpAddress(), "create", null);
- return answer;
- } else {
- return new Answer(cmd, false, result);
- }
- }
-
- protected GetVmStatsAnswer execute(GetVmStatsCommand cmd) {
- List<String> vmNames = cmd.getVmNames();
- try {
- HashMap<String, VmStatsEntry> vmStatsNameMap = new HashMap<String, VmStatsEntry>();
- Connect conn = LibvirtConnection.getConnection();
- for (String vmName : vmNames) {
- VmStatsEntry statEntry = getVmStat(conn, vmName);
- if (statEntry == null) {
- continue;
- }
-
- vmStatsNameMap.put(vmName, statEntry);
- }
- return new GetVmStatsAnswer(cmd, vmStatsNameMap);
- } catch (LibvirtException e) {
- s_logger.debug("Can't get vm stats: " + e.toString());
- return new GetVmStatsAnswer(cmd, null);
- }
- }
-
- protected Answer execute(StopCommand cmd) {
- final String vmName = cmd.getVmName();
-
- State state = null;
- synchronized (_vms) {
- state = _vms.get(vmName);
- _vms.put(vmName, State.Stopping);
- }
- try {
- Connect conn = LibvirtConnection.getConnection();
-
- List<DiskDef> disks = getDisks(conn, vmName);
- destroy_network_rules_for_vm(conn, vmName);
- String result = stopVM(conn, vmName, defineOps.UNDEFINE_VM);
- if (result == null) {
- for (DiskDef disk : disks) {
- if (disk.getDeviceType() == DiskDef.deviceType.CDROM
- && disk.getDiskPath() != null)
- cleanupDisk(conn, disk);
- }
- }
-
- final String result2 = cleanupVnet(conn, cmd.getVnet());
-
- if (result != null && result2 != null) {
- result = result2 + result;
- }
- state = State.Stopped;
+ } finally {
+ synchronized (_vms) {
+ _vms.put(cmd.getVmName(), State.Running);
+ }
+ }
+ }
+
+ protected Answer execute(RebootRouterCommand cmd) {
+ RebootAnswer answer = (RebootAnswer) execute((RebootCommand) cmd);
+ String result = _virtRouterResource.connect(cmd.getPrivateIpAddress());
+ if (result == null) {
+ networkUsage(cmd.getPrivateIpAddress(), "create", null);
+ return answer;
+ } else {
+ return new Answer(cmd, false, result);
+ }
+ }
+
+ protected GetVmStatsAnswer execute(GetVmStatsCommand cmd) {
+ List<String> vmNames = cmd.getVmNames();
+ try {
+ HashMap<String, VmStatsEntry> vmStatsNameMap = new HashMap<String, VmStatsEntry>();
+ Connect conn = LibvirtConnection.getConnection();
+ for (String vmName : vmNames) {
+ VmStatsEntry statEntry = getVmStat(conn, vmName);
+ if (statEntry == null) {
+ continue;
+ }
+
+ vmStatsNameMap.put(vmName, statEntry);
+ }
+ return new GetVmStatsAnswer(cmd, vmStatsNameMap);
+ } catch (LibvirtException e) {
+ s_logger.debug("Can't get vm stats: " + e.toString());
+ return new GetVmStatsAnswer(cmd, null);
+ }
+ }
+
+ protected Answer execute(StopCommand cmd) {
+ final String vmName = cmd.getVmName();
+
+ State state = null;
+ synchronized (_vms) {
+ state = _vms.get(vmName);
+ _vms.put(vmName, State.Stopping);
+ }
+ try {
+ Connect conn = LibvirtConnection.getConnection();
+
+ List<DiskDef> disks = getDisks(conn, vmName);
+ destroy_network_rules_for_vm(conn, vmName);
+ String result = stopVM(conn, vmName, defineOps.UNDEFINE_VM);
+ if (result == null) {
+ for (DiskDef disk : disks) {
+ if (disk.getDeviceType() == DiskDef.deviceType.CDROM
+ && disk.getDiskPath() != null)
+ cleanupDisk(conn, disk);
+ }
+ }
+
+ final String result2 = cleanupVnet(conn, cmd.getVnet());
+
+ if (result != null && result2 != null) {
+ result = result2 + result;
+ }
+ state = State.Stopped;
return new StopAnswer(cmd, result, 0, true);
- } catch (LibvirtException e) {
+ } catch (LibvirtException e) {
return new StopAnswer(cmd, e.getMessage(), false);
- } finally {
- synchronized (_vms) {
- if (state != null) {
- _vms.put(vmName, state);
- } else {
- _vms.remove(vmName);
- }
- }
- }
- }
-
- protected Answer execute(ModifySshKeysCommand cmd) {
- File sshKeysDir = new File(_SSHKEYSPATH);
- String result = null;
- if (!sshKeysDir.exists()) {
- sshKeysDir.mkdir();
- // Change permissions for the 600
- Script script = new Script("chmod", _timeout, s_logger);
- script.add("600", _SSHKEYSPATH);
- script.execute();
- }
-
- File pubKeyFile = new File(_SSHPUBKEYPATH);
- if (!pubKeyFile.exists()) {
- try {
- pubKeyFile.createNewFile();
- } catch (IOException e) {
- result = "Failed to create file: " + e.toString();
- s_logger.debug(result);
- }
- }
-
- if (pubKeyFile.exists()) {
- String pubKey = cmd.getPubKey();
- try {
- FileOutputStream pubkStream = new FileOutputStream(pubKeyFile);
- pubkStream.write(pubKey.getBytes());
- pubkStream.close();
- } catch (FileNotFoundException e) {
- result = "File" + _SSHPUBKEYPATH + "is not found:"
- + e.toString();
- s_logger.debug(result);
- } catch (IOException e) {
- result = "Write file " + _SSHPUBKEYPATH + ":" + e.toString();
- s_logger.debug(result);
- }
- }
-
- File prvKeyFile = new File(_SSHPRVKEYPATH);
- if (!prvKeyFile.exists()) {
- try {
- prvKeyFile.createNewFile();
- } catch (IOException e) {
- result = "Failed to create file: " + e.toString();
- s_logger.debug(result);
- }
- }
-
- if (prvKeyFile.exists()) {
- String prvKey = cmd.getPrvKey();
- try {
- FileOutputStream prvKStream = new FileOutputStream(prvKeyFile);
- prvKStream.write(prvKey.getBytes());
- prvKStream.close();
- } catch (FileNotFoundException e) {
- result = "File" + _SSHPRVKEYPATH + "is not found:"
- + e.toString();
- s_logger.debug(result);
- } catch (IOException e) {
- result = "Write file " + _SSHPRVKEYPATH + ":" + e.toString();
- s_logger.debug(result);
- }
-
- Script script = new Script("chmod", _timeout, s_logger);
- script.add("600", _SSHPRVKEYPATH);
- script.execute();
- }
-
- if (result != null) {
- return new Answer(cmd, false, result);
- } else {
- return new Answer(cmd, true, null);
- }
- }
-
- protected void handleVmStartFailure(Connect conn, String vmName,
- LibvirtVMDef vm) {
- if (vm != null && vm.getDevices() != null) {
- cleanupVMNetworks(conn, vm.getDevices().getInterfaces());
- }
- }
-
- protected LibvirtVMDef createVMFromSpec(VirtualMachineTO vmTO) {
- LibvirtVMDef vm = new LibvirtVMDef();
- vm.setHvsType(_hypervisorType);
- vm.setDomainName(vmTO.getName());
- vm.setDomUUID(UUID.nameUUIDFromBytes(vmTO.getName().getBytes())
- .toString());
- vm.setDomDescription(vmTO.getOs());
-
- GuestDef guest = new GuestDef();
- guest.setGuestType(GuestDef.guestType.KVM);
- guest.setGuestArch(vmTO.getArch());
- guest.setMachineType("pc");
- guest.setBootOrder(GuestDef.bootOrder.CDROM);
- guest.setBootOrder(GuestDef.bootOrder.HARDISK);
-
- vm.addComp(guest);
-
- GuestResourceDef grd = new GuestResourceDef();
- grd.setMemorySize(vmTO.getMinRam() / 1024);
- grd.setVcpuNum(vmTO.getCpus());
- vm.addComp(grd);
+ } finally {
+ synchronized (_vms) {
+ if (state != null) {
+ _vms.put(vmName, state);
+ } else {
+ _vms.remove(vmName);
+ }
+ }
+ }
+ }
+
+ protected Answer execute(ModifySshKeysCommand cmd) {
+ File sshKeysDir = new File(_SSHKEYSPATH);
+ String result = null;
+ if (!sshKeysDir.exists()) {
+ sshKeysDir.mkdir();
+ // Change permissions for the 600
+ Script script = new Script("chmod", _timeout, s_logger);
+ script.add("600", _SSHKEYSPATH);
+ script.execute();
+ }
+
+ File pubKeyFile = new File(_SSHPUBKEYPATH);
+ if (!pubKeyFile.exists()) {
+ try {
+ pubKeyFile.createNewFile();
+ } catch (IOException e) {
+ result = "Failed to create file: " + e.toString();
+ s_logger.debug(result);
+ }
+ }
+
+ if (pubKeyFile.exists()) {
+ String pubKey = cmd.getPubKey();
+ try {
+ FileOutputStream pubkStream = new FileOutputStream(pubKeyFile);
+ pubkStream.write(pubKey.getBytes());
+ pubkStream.close();
+ } catch (FileNotFoundException e) {
+ result = "File" + _SSHPUBKEYPATH + "is not found:"
+ + e.toString();
+ s_logger.debug(result);
+ } catch (IOException e) {
+ result = "Write file " + _SSHPUBKEYPATH + ":" + e.toString();
+ s_logger.debug(result);
+ }
+ }
+
+ File prvKeyFile = new File(_SSHPRVKEYPATH);
+ if (!prvKeyFile.exists()) {
+ try {
+ prvKeyFile.createNewFile();
+ } catch (IOException e) {
+ result = "Failed to create file: " + e.toString();
+ s_logger.debug(result);
+ }
+ }
+
+ if (prvKeyFile.exists()) {
+ String prvKey = cmd.getPrvKey();
+ try {
+ FileOutputStream prvKStream = new FileOutputStream(prvKeyFile);
+ prvKStream.write(prvKey.getBytes());
+ prvKStream.close();
+ } catch (FileNotFoundException e) {
+ result = "File" + _SSHPRVKEYPATH + "is not found:"
+ + e.toString();
+ s_logger.debug(result);
+ } catch (IOException e) {
+ result = "Write file " + _SSHPRVKEYPATH + ":" + e.toString();
+ s_logger.debug(result);
+ }
+
+ Script script = new Script("chmod", _timeout, s_logger);
+ script.add("600", _SSHPRVKEYPATH);
+ script.execute();
+ }
+
+ if (result != null) {
+ return new Answer(cmd, false, result);
+ } else {
+ return new Answer(cmd, true, null);
+ }
+ }
+
+ protected void handleVmStartFailure(Connect conn, String vmName,
+ LibvirtVMDef vm) {
+ if (vm != null && vm.getDevices() != null) {
+ cleanupVMNetworks(conn, vm.getDevices().getInterfaces());
+ }
+ }
+
+ protected LibvirtVMDef createVMFromSpec(VirtualMachineTO vmTO) {
+ LibvirtVMDef vm = new LibvirtVMDef();
+ vm.setHvsType(_hypervisorType);
+ vm.setDomainName(vmTO.getName());
+ vm.setDomUUID(UUID.nameUUIDFromBytes(vmTO.getName().getBytes())
+ .toString());
+ vm.setDomDescription(vmTO.getOs());
+
+ GuestDef guest = new GuestDef();
+ guest.setGuestType(GuestDef.guestType.KVM);
+ guest.setGuestArch(vmTO.getArch());
+ guest.setMachineType("pc");
+ guest.setBootOrder(GuestDef.bootOrder.CDROM);
+ guest.setBootOrder(GuestDef.bootOrder.HARDISK);
+
+ vm.addComp(guest);
+
+ GuestResourceDef grd = new GuestResourceDef();
+ grd.setMemorySize(vmTO.getMinRam() / 1024);
+ grd.setVcpuNum(vmTO.getCpus());
+ vm.addComp(grd);
+ CpuTuneDef ctd = new CpuTuneDef();
+ ctd.setShares(vmTO.getCpus() * vmTO.getSpeed());
+ vm.addComp(ctd);
+
- FeaturesDef features = new FeaturesDef();
- features.addFeatures("pae");
- features.addFeatures("apic");
- features.addFeatures("acpi");
- vm.addComp(features);
+ FeaturesDef features = new FeaturesDef();
+ features.addFeatures("pae");
+ features.addFeatures("apic");
+ features.addFeatures("acpi");
+ vm.addComp(features);
- TermPolicy term = new TermPolicy();
- term.setCrashPolicy("destroy");
- term.setPowerOffPolicy("destroy");
- term.setRebootPolicy("restart");
- vm.addComp(term);
+ TermPolicy term = new TermPolicy();
+ term.setCrashPolicy("destroy");
+ term.setPowerOffPolicy("destroy");
+ term.setRebootPolicy("restart");
+ vm.addComp(term);
- ClockDef clock = new ClockDef();
- if (vmTO.getOs().startsWith("Windows")) {
- clock.setClockOffset(ClockDef.ClockOffset.LOCALTIME);
- clock.setTimer("rtc", "catchup", null);
- }
+ ClockDef clock = new ClockDef();
+ if (vmTO.getOs().startsWith("Windows")) {
+ clock.setClockOffset(ClockDef.ClockOffset.LOCALTIME);
+ clock.setTimer("rtc", "catchup", null);
+ }
- vm.addComp(clock);
+ vm.addComp(clock);
- DevicesDef devices = new DevicesDef();
- devices.setEmulatorPath(_hypervisorPath);
+ DevicesDef devices = new DevicesDef();
+ devices.setEmulatorPath(_hypervisorPath);
- SerialDef serial = new SerialDef("pty", null, (short) 0);
- devices.addDevice(serial);
+ SerialDef serial = new SerialDef("pty", null, (short) 0);
+ devices.addDevice(serial);
- ConsoleDef console = new ConsoleDef("pty", null, null, (short) 0);
- devices.addDevice(console);
+ ConsoleDef console = new ConsoleDef("pty", null, null, (short) 0);
+ devices.addDevice(console);
GraphicDef grap = new GraphicDef("vnc", (short) 0, true, vmTO.getVncAddr(), null,
- null);
- devices.addDevice(grap);
+ null);
+ devices.addDevice(grap);
- InputDef input = new InputDef("tablet", "usb");
- devices.addDevice(input);
+ InputDef input = new InputDef("tablet", "usb");
+ devices.addDevice(input);
- vm.addComp(devices);
+ vm.addComp(devices);
- return vm;
- }
+ return vm;
+ }
protected void createVifs(VirtualMachineTO vmSpec,
- LibvirtVMDef vm) throws InternalErrorException, LibvirtException {
- NicTO[] nics = vmSpec.getNics();
- for (int i = 0; i < nics.length; i++) {
- for (NicTO nic : vmSpec.getNics()) {
- if (nic.getDeviceId() == i) {
+ LibvirtVMDef vm) throws InternalErrorException, LibvirtException {
+ NicTO[] nics = vmSpec.getNics();
+ for (int i = 0; i < nics.length; i++) {
+ for (NicTO nic : vmSpec.getNics()) {
+ if (nic.getDeviceId() == i) {
createVif(vm, nic);
- }
- }
- }
- }
+ }
+ }
+ }
+ }
- protected synchronized StartAnswer execute(StartCommand cmd) {
- VirtualMachineTO vmSpec = cmd.getVirtualMachine();
+ protected synchronized StartAnswer execute(StartCommand cmd) {
+ VirtualMachineTO vmSpec = cmd.getVirtualMachine();
vmSpec.setVncAddr(cmd.getHostIp());
- String vmName = vmSpec.getName();
- LibvirtVMDef vm = null;
-
- State state = State.Stopped;
- Connect conn = null;
- try {
- conn = LibvirtConnection.getConnection();
- synchronized (_vms) {
- _vms.put(vmName, State.Starting);
- }
+ String vmName = vmSpec.getName();
+ LibvirtVMDef vm = null;
- vm = createVMFromSpec(vmSpec);
+ State state = State.Stopped;
+ Connect conn = null;
+ try {
+ conn = LibvirtConnection.getConnection();
+ synchronized (_vms) {
+ _vms.put(vmName, State.Starting);
+ }
- createVbd(conn, vmSpec, vmName, vm);
-
- createVifs(vmSpec, vm);
-
- s_logger.debug("starting " + vmName + ": " + vm.toString());
- startDomain(conn, vmName, vm.toString());
-
- NicTO[] nics = vmSpec.getNics();
- for (NicTO nic : nics) {
- if (nic.getIsolationUri() != null
- && nic.getIsolationUri().getScheme()
- .equalsIgnoreCase(IsolationType.Ec2.toString())) {
- if (vmSpec.getType() != VirtualMachine.Type.User) {
- default_network_rules_for_systemvm(conn, vmName);
- break;
- } else {
- default_network_rules(conn, vmName, nic, vmSpec.getId());
- }
- }
- }
+ vm = createVMFromSpec(vmSpec);
- state = State.Running;
- return new StartAnswer(cmd);
- } catch (Exception e) {
- s_logger.warn("Exception ", e);
- if (conn != null) {
- handleVmStartFailure(conn, vmName, vm);
- }
- return new StartAnswer(cmd, e.getMessage());
- } finally {
- synchronized (_vms) {
- if (state != State.Stopped) {
- _vms.put(vmName, state);
- } else {
- _vms.remove(vmName);
- }
- }
- }
- }
-
- private String getVolumePath(Connect conn, VolumeTO volume)
- throws LibvirtException, URISyntaxException {
- if (volume.getType() == Volume.Type.ISO && volume.getPath() != null) {
- String isoPath = volume.getPath();
- int index = isoPath.lastIndexOf("/");
- String path = isoPath.substring(0, index);
- String name = isoPath.substring(index + 1);
- KVMStoragePool secondaryPool = _storagePoolMgr
- .getStoragePoolByURI(path);
- KVMPhysicalDisk isoVol = secondaryPool.getPhysicalDisk(name);
- return isoVol.getPath();
- } else {
- return volume.getPath();
- }
- }
-
- protected void createVbd(Connect conn, VirtualMachineTO vmSpec,
- String vmName, LibvirtVMDef vm) throws InternalErrorException,
- LibvirtException, URISyntaxException {
- List<VolumeTO> disks = Arrays.asList(vmSpec.getDisks());
- Collections.sort(disks, new Comparator<VolumeTO>() {
- @Override
- public int compare(VolumeTO arg0, VolumeTO arg1) {
- return arg0.getDeviceId() > arg1.getDeviceId() ? 1 : -1;
- }
- });
-
- for (VolumeTO volume : disks) {
- KVMPhysicalDisk physicalDisk = null;
- KVMStoragePool pool = null;
- if (volume.getType() == Volume.Type.ISO && volume.getPath() != null) {
- String volPath = volume.getPath();
- int index = volPath.lastIndexOf("/");
- String volDir = volPath.substring(0, index);
- String volName = volPath.substring(index + 1);
- KVMStoragePool secondaryStorage = _storagePoolMgr
- .getStoragePoolByURI(volDir);
- physicalDisk = secondaryStorage.getPhysicalDisk(volName);
- } else if (volume.getType() != Volume.Type.ISO) {
- pool = _storagePoolMgr.getStoragePool(volume.getPoolUuid());
- physicalDisk = pool.getPhysicalDisk(volume.getPath());
- }
+ createVbd(conn, vmSpec, vmName, vm);
- String volPath = null;
- if (physicalDisk != null) {
- volPath = physicalDisk.getPath();
- }
+ createVifs(vmSpec, vm);
- DiskDef.diskBus diskBusType = getGuestDiskModel(vmSpec.getOs());
- DiskDef disk = new DiskDef();
- if (volume.getType() == Volume.Type.ISO) {
- if (volPath == null) {
- /* Add iso as placeholder */
- disk.defISODisk(null);
- } else {
- disk.defISODisk(volPath);
- }
- } else {
- int devId = (int) volume.getDeviceId();
+ s_logger.debug("starting " + vmName + ": " + vm.toString());
+ startDomain(conn, vmName, vm.toString());
- Script.runSimpleBashScript("virsh schedinfo " + vmName
- + " --set cpu_shares=" + vmSpec.getCpus()
- * vmSpec.getSpeed());
+
+ NicTO[] nics = vmSpec.getNics();
+ for (NicTO nic : nics) {
+ if (nic.getIsolationUri() != null
+ && nic.getIsolationUri().getScheme()
+ .equalsIgnoreCase(IsolationType.Ec2.toString())) {
+ if (vmSpec.getType() != VirtualMachine.Type.User) {
+ default_network_rules_for_systemvm(conn, vmName);
+ break;
+ } else {
+ default_network_rules(conn, vmName, nic, vmSpec.getId());
+ }
+ }
+ }
+
+ state = State.Running;
+ return new StartAnswer(cmd);
+ } catch (Exception e) {
+ s_logger.warn("Exception ", e);
+ if (conn != null) {
+ handleVmStartFailure(conn, vmName, vm);
+ }
+ return new StartAnswer(cmd, e.getMessage());
+ } finally {
+ synchronized (_vms) {
+ if (state != State.Stopped) {
+ _vms.put(vmName, state);
+ } else {
+ _vms.remove(vmName);
+ }
+ }
+ }
+ }
+
+ private String getVolumePath(Connect conn, VolumeTO volume)
+ throws LibvirtException, URISyntaxException {
+ if (volume.getType() == Volume.Type.ISO && volume.getPath() != null) {
+ String isoPath = volume.getPath();
+ int index = isoPath.lastIndexOf("/");
+ String path = isoPath.substring(0, index);
+ String name = isoPath.substring(index + 1);
+ KVMStoragePool secondaryPool = _storagePoolMgr
+ .getStoragePoolByURI(path);
+ KVMPhysicalDisk isoVol = secondaryPool.getPhysicalDisk(name);
+ return isoVol.getPath();
+ } else {
+ return volume.getPath();
+ }
+ }
+
+ protected void createVbd(Connect conn, VirtualMachineTO vmSpec,
+ String vmName, LibvirtVMDef vm) throws InternalErrorException,
+ LibvirtException, URISyntaxException {
+ List<VolumeTO> disks = Arrays.asList(vmSpec.getDisks());
+ Collections.sort(disks, new Comparator<VolumeTO>() {
+ @Override
+ public int compare(VolumeTO arg0, VolumeTO arg1) {
+ return arg0.getDeviceId() > arg1.getDeviceId() ? 1 : -1;
+ }
+ });
+
+ for (VolumeTO volume : disks) {
+ KVMPhysicalDisk physicalDisk = null;
+ KVMStoragePool pool = null;
+ if (volume.getType() == Volume.Type.ISO && volume.getPath() != null) {
+ String volPath = volume.getPath();
+ int index = volPath.lastIndexOf("/");
+ String volDir = volPath.substring(0, index);
+ String volName = volPath.substring(index + 1);
+ KVMStoragePool secondaryStorage = _storagePoolMgr
+ .getStoragePoolByURI(volDir);
+ physicalDisk = secondaryStorage.getPhysicalDisk(volName);
+ } else if (volume.getType() != Volume.Type.ISO) {
+ pool = _storagePoolMgr.getStoragePool(volume.getPoolUuid());
+ physicalDisk = pool.getPhysicalDisk(volume.getPath());
+ }
+
+ String volPath = null;
+ if (physicalDisk != null) {
+ volPath = physicalDisk.getPath();
+ }
+
+ DiskDef.diskBus diskBusType = getGuestDiskModel(vmSpec.getOs());
+ DiskDef disk = new DiskDef();
+ if (volume.getType() == Volume.Type.ISO) {
+ if (volPath == null) {
+ /* Add iso as placeholder */
+ disk.defISODisk(null);
+ } else {
+ disk.defISODisk(volPath);
+ }
+ } else {
+ int devId = (int) volume.getDeviceId();
if (pool.getType() == StoragePoolType.RBD) {
/*
http://git-wip-us.apache.org/repos/asf/incubator-cloudstack/blob/95449da4/server/src/com/cloud/vm/UserVmManagerImpl.java
----------------------------------------------------------------------